### Install Postgrator CLI Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Installs the Postgrator command-line interface using npm. ```sh npm install postgrator ``` -------------------------------- ### Postgrator Node.js Integration Example Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Demonstrates how to integrate Postgrator into a Node.js application. It shows setting up a database client, initializing Postgrator with migration patterns and driver details, and performing migrations to a specific version or the latest version. Includes error handling and connection management. ```js import Postgrator from "postgrator"; import pg from "pg"; import { dirname } from "path"; import { fileURLToPath } from "url"; const __dirname = dirname(fileURLToPath(import.meta.url)); async function main() { // Create a client of your choice const client = new pg.Client({ host: "localhost", port: 5432, database: "postgrator", user: "postgrator", password: "postgrator", }); try { // Establish a database connection await client.connect(); // Create postgrator instance const postgrator = new Postgrator({ migrationPattern: __dirname + "/some/pattern/*", driver: "pg", database: "databasename", schemaTable: "schemaversion", execQuery: (query) => client.query(query), execSqlScript: (sqlScript) => client.sqlScript(sqlScript), }); // Migrate to specific version const appliedMigrations = await postgrator.migrate("002"); console.log(appliedMigrations); // Or migrate to max version (optionally can provide 'max') await postgrator.migrate(); } catch (error) { // If error happened partially through migrations, // error object is decorated with appliedMigrations console.error(error.appliedMigrations); // array of migration objects } // Once done migrating, close your connection. await client.end(); } main(); ``` -------------------------------- ### Running Postgrator Tests with Docker Compose Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Instructions for running Postgrator tests locally using Docker and Docker Compose. This involves starting the database containers, running the tests, and then cleaning up the containers. ```sh # In one terminal window docker-compose up # In another terminal once databases are up npm test # After tests, in docker session # control/command-c to quit docker-compose and remove containers docker-compose rm --force ``` -------------------------------- ### JavaScript Migration Script (CommonJS) Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Example of a JavaScript migration script using CommonJS module format. The script exports a generateSql function that returns the SQL string to be executed. This approach is useful for incorporating environment variables or dynamic logic into migrations. ```js module.exports.generateSql = function () { return ( "CREATE USER transaction_user WITH PASSWORD '" + process.env.TRANSACTION_USER_PASSWORD + "'" ); }; ``` -------------------------------- ### JavaScript Migration Script (ES Module with Async) Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Example of an asynchronous JavaScript migration script using ES Module format. The generateSql function can perform asynchronous operations, such as fetching data from an external API using libraries like axios, before returning the SQL string. ```js import axios from "axios"; module.exports.generateSql = async () => { const response = await axios({ method: "get", url: "https://api.example.org/person/1", }); return `INSERT INTO person (name, age) VALUES ('${response.data.name}', ${response.data.age});`; }; ``` -------------------------------- ### Postgrator Initialization Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Initializes Postgrator with a configuration object. The options object defines how Postgrator interacts with your database and migration files. ```javascript const postgrator = new Postgrator(options); ``` -------------------------------- ### Postgrator Configuration Options Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Details the various options available when initializing Postgrator. These options control migration patterns, database drivers, connection details, query execution, schema management, and checksum validation. ```APIDOC Options: - migrationPattern (Required): Glob pattern to migration files. e.g. `path.join(__dirname, '/migrations/*')` - driver (Required): Must be `pg`, `mysql`, `mssql`, or `sqlite3` - database (Required): Target database name. Optional for `sqlite3`. - execQuery (Required): Function to execute SQL. MUST return a promise containing an object with a rows array of objects. For example `{ rows: [{ column_name: 'column_value' }] }` - execSqlScript (Optional): Function to execute db migration script consisting of multiple SQL statements. MUST return a void promise. If not supplied, `execQuery` will be used. - schemaTable (Optional): Table created to track schema version. When using Postgres, you may specify schema as well, e.g. `schema_name.table_name`. Defaults to `schemaversion`. - validateChecksum (Optional): Validates checksum of existing SQL migration files already run prior to executing migrations. Set to `false` to disable. Unused for JS migrations. Defaults to `true`. - newline (Optional): Force line ending on file when generating checksum. Value should be either `CRLF` (windows) or `LF` (unix/mac). - currentSchema (Optional): For Postgres and MS SQL Server. Specifies schema to look to when validating schemaversion table columns. For Postgres, run's `SET search_path = currentSchema` prior to running queries against db. ``` -------------------------------- ### Postgrator Event Emitter for Logging Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Demonstrates how to use Postgrator's event emitter to hook into different stages of the migration process for custom logging. Events include validation and migration start/finish. ```javascript const postgrator = new Postgrator(options); postgrator.on("validation-started", (migration) => console.log(migration)); postgrator.on("validation-finished", (migration) => console.log(migration)); postgrator.on("migration-started", (migration) => console.log(migration)); postgrator.on("migration-finished", (migration) => console.log(migration)); ``` -------------------------------- ### Postgrator Utility Methods Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Provides utility methods for Postgrator to retrieve the maximum available migration version from the filesystem, the current database schema version, and all migrations from a directory with parsed metadata. ```javascript const maxVersionAvailable = await postgrator.getMaxVersion(); console.log(maxVersionAvailable); // "current" database schema version as number, not string const version = await postgrator.getDatabaseVersion(); console.log(version); // To get all migrations from directory and parse metadata const migrations = await postgrator.getMigrations(); console.log(migrations); ``` -------------------------------- ### Migration Object Structure Source: https://github.com/rickbergfalk/postgrator/blob/master/README.md Defines the structure of a migration object returned by Postgrator. It includes version, action, name, filename, MD5 checksum, and a function to retrieve the SQL content. ```javascript { version: versionNumber, action: 'do', name: 'first-table', filename: 'path/to/0001.up.first-table.sql', md5: 'checksumvalue', getSql: () => {} // function to get sql from file } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.