### Install node-pg-migrate with bun Source: https://salsita.github.io/node-pg-migrate/getting-started Install node-pg-migrate as a dev dependency using bun. ```sh $ bun add -D node-pg-migrate ``` -------------------------------- ### Install node-pg-migrate with yarn Source: https://salsita.github.io/node-pg-migrate/getting-started Install node-pg-migrate as a dev dependency using yarn. ```sh $ yarn add -D node-pg-migrate ``` -------------------------------- ### JSON configuration example Source: https://salsita.github.io/node-pg-migrate/cli Example of a JSON configuration file for node-pg-migrate, specifying schema, migrations directory, table names, and other options. ```jsonc { "schema": "public", "create-schema": false, "database-url-var": "SECRET_DB_URL", "migrations-dir": "migrations", "use-glob": false, "migrations-schema": "public", "create-migrations-schema": false, "migrations-table": "pgmigrations", "migration-filename-format": "utc", "migration-file-language": "js", "ignore-pattern": "/SKIP$/", "template-file-name": "templates/new-migration.js", "check-order": true, "verbose": true, "decamelize": false, "pretty": false, "tsconfig-paths": "./tsconfig.json", } ``` -------------------------------- ### Install node-pg-migrate with npm Source: https://salsita.github.io/node-pg-migrate/getting-started Install node-pg-migrate as a dev dependency using npm. ```sh $ npm add -D node-pg-migrate ``` -------------------------------- ### Install node-pg-migrate with pnpm Source: https://salsita.github.io/node-pg-migrate/getting-started Install node-pg-migrate as a dev dependency using pnpm. ```sh $ pnpm add -D node-pg-migrate ``` -------------------------------- ### Add pg dependency with bun Source: https://salsita.github.io/node-pg-migrate/getting-started Install the pg library using bun. ```sh $ bun add pg ``` -------------------------------- ### pgm.createIndex examples Source: https://salsita.github.io/node-pg-migrate/migrations/indexes Create an index on a table with optional column ordering and operator class. The first example creates a simple index on one column; the second on multiple columns; the third specifies ascending/descending sort; the fourth uses a schema-qualified operator class. Each call generates the corresponding CREATE INDEX statement. ```ts pgm.createIndex('table', 'column'); //expected output: CREATE INDEX ON "table" ("column") ``` ```ts pgm.createIndex('table', ['col1', 'col2']); //expected output: CREATE INDEX ON "table" ("col1", "col2") ``` ```ts pgm.createIndex('table', [ { name: 'col1', sort: 'ASC' }, { name: 'col2', sort: 'DESC' }, ]); //expected output: CREATE INDEX ON "table" ("col1" ASC, "col2" DESC) ``` ```ts pgm.createIndex('table', [ { name: 'col1', opclass: { schema: 'schema', name: 'opclass' }, sort: 'ASC' }, ]); //expected output: CREATE INDEX ON "table" ("col1" "schema"."opclass" ASC) ``` -------------------------------- ### JSON configuration with environment groups Source: https://salsita.github.io/node-pg-migrate/cli Example of a JSON configuration file with groups for different environments (dev and prod), used with the --config-value option. ```jsonc { "dev": { "migrations-schema": "public", "verbose": true, }, "prod": { "migrations-schema": "myapp", }, } ``` -------------------------------- ### pgm.createExtension( extension ) Source: https://salsita.github.io/node-pg-migrate/migrations/extensions Installs one or more PostgreSQL extensions. Use the alias addExtension. Options include ifNotExists and schema. ```APIDOC ## pgm.createExtension( extension ) ### Description Installs one or more PostgreSQL extensions. Alias: `addExtension`. ### Method `pgm.createExtension` ### Arguments - **extension** (string or array[string]) - Required - Name(s) of extensions to install. - **options** (object) - Optional - Check below for available options. #### Options - **ifNotExists** (boolean) - Optional - Install extension only if it does not exist (default `false`). - **schema** (string) - Optional - The name of the schema in which to install the extension's objects. ### Example ```js pgm.createExtension('hstore'); ``` ``` -------------------------------- ### Add pg dependency with pnpm Source: https://salsita.github.io/node-pg-migrate/getting-started Install the pg library using pnpm. ```sh $ pnpm add pg ``` -------------------------------- ### Add pg dependency with yarn Source: https://salsita.github.io/node-pg-migrate/getting-started Install the pg library using yarn. ```sh $ yarn add pg ``` -------------------------------- ### runner() with grouped SQL loader Source: https://salsita.github.io/node-pg-migrate/migration-loading-strategies Example of using the runner function with a migrationLoaderStrategies configuration to enable grouped .up.sql/.down.sql files. ```APIDOC ## runner() ### Description Runs migrations with the specified configuration. This example enables the grouped SQL loader for .sql files. ### Method N/A (SDK function) ### Endpoint N/A (SDK function) ### Parameters #### Configuration Object - **databaseUrl** (string) - Required - Database connection URL. - **dir** (string) - Required - Directory containing migration files. - **direction** (string) - Required - Migration direction: 'up' or 'down'. - **migrationsTable** (string) - Required - Name of the migrations table. - **migrationLoaderStrategies** (array) - Optional - Array of loader strategy objects. Each object has `extensions` (string[]) and `loader` (string or function). ### Request Example ts await runner({ databaseUrl: process.env.DATABASE_URL!, dir: 'migrations', direction: 'up', migrationsTable: 'pgmigrations', migrationLoaderStrategies: [{ extensions: ['.sql'], loader: 'sql' }], }); ### Response #### Success Response No return value (Promise). #### Response Example N/A ``` -------------------------------- ### Add pg dependency with npm Source: https://salsita.github.io/node-pg-migrate/getting-started Install the pg library as a direct or dev dependency if not already installed. ```sh $ npm add pg ``` -------------------------------- ### runner() with custom loader Source: https://salsita.github.io/node-pg-migrate/migration-loading-strategies Example of using the runner function with a custom loader function for specific file extensions. ```APIDOC ## runner() ### Description Runs migrations with a custom loader function for .mjs files, while using the built-in SQL loader for .sql files. ### Method N/A (SDK function) ### Endpoint N/A (SDK function) ### Parameters #### Configuration Object - **databaseUrl** (string) - Required - Database connection URL. - **dir** (string) - Required - Directory containing migration files. - **direction** (string) - Required - Migration direction: 'up' or 'down'. - **migrationsTable** (string) - Required - Name of the migrations table. - **migrationLoaderStrategies** (array) - Required - Array of loader strategy objects. Each object has `extensions` (string[]) and `loader` (string or function). ### Request Example ts import type { MigrationLoader } from 'node-pg-migrate'; import { runner } from 'node-pg-migrate'; const customLoader: MigrationLoader = async (filePaths) => { // map files to migration units return []; }; await runner({ databaseUrl: process.env.DATABASE_URL!, dir: 'migrations', direction: 'up', migrationsTable: 'pgmigrations', migrationLoaderStrategies: [ { extensions: ['.sql'], loader: 'sql' }, { extensions: ['.mjs'], loader: customLoader }, ], }); ### Response #### Success Response No return value (Promise). #### Response Example N/A ``` -------------------------------- ### Use grouped SQL loader with migrationLoaderStrategies Source: https://salsita.github.io/node-pg-migrate/migration-loading-strategies Configures runner to use the 'sql' loader for .sql files, enabling grouped .up.sql/.down.sql migrations. With this setup, 001_init.up.sql and 001_init.down.sql are treated as one migration, the id is normalized to 001_init.sql, single-file .sql still works, and mixing single and split files throws an error. ```typescript import { runner } from 'node-pg-migrate'; await runner({ databaseUrl: process.env.DATABASE_URL!, dir: 'migrations', direction: 'up', migrationsTable: 'pgmigrations', migrationLoaderStrategies: [{ extensions: ['.sql'], loader: 'sql' }], }); ``` -------------------------------- ### Custom loader function with migrationLoaderStrategies Source: https://salsita.github.io/node-pg-migrate/migration-loading-strategies Shows how to provide a custom MigrationLoader function alongside the 'sql' loader. The custom loader receives file paths and must return migration units; the example returns an empty array as a placeholder. ```typescript import type { MigrationLoader } from 'node-pg-migrate'; import { runner } from 'node-pg-migrate'; const customLoader: MigrationLoader = async (filePaths) => { // map files to migration units return []; }; await runner({ databaseUrl: process.env.DATABASE_URL!, dir: 'migrations', direction: 'up', migrationsTable: 'pgmigrations', migrationLoaderStrategies: [ { extensions: ['.sql'], loader: 'sql' }, { extensions: ['.mjs'], loader: customLoader }, ], }); ``` -------------------------------- ### package.json script migration for CLI subcommands Source: https://salsita.github.io/node-pg-migrate/upgrading Update package.json scripts to move options after the command. The example shows the old script (with '-j ts' before the command) and the new script (without it). ```jsonc { "scripts": { "migrate": "node-pg-migrate -j ts", "migrate": "node-pg-migrate", }, } ``` -------------------------------- ### Config file with database connection parameters Source: https://salsita.github.io/node-pg-migrate/cli Alternative way to specify database connection using individual fields like user, password, host, port, database. ```jsonc // config/default.json { "db": { "user": "postgres", "password": "", "host": "localhost", "port": 5432, "database": "database", }, } ``` -------------------------------- ### Run migrations with npm, pnpm, yarn, or bun Source: https://salsita.github.io/node-pg-migrate/faq/typescript Runs migrations using the package manager of your choice. These commands are equivalent alternatives for executing the migrate script. ```bash npm run migrate ``` ```bash pnpm run migrate ``` ```bash yarn migrate ``` ```bash bun run migrate ``` -------------------------------- ### Create migration file (JavaScript) Source: https://salsita.github.io/node-pg-migrate/getting-started Creates a new migration file with the default JavaScript language. The command outputs a file named migrations/xxx_my-first-migration.js. ```bash npm run migrate create my-first-migration # creates migrations/xxx_my-first-migration.js ``` -------------------------------- ### runner() with tsconfigPaths Source: https://salsita.github.io/node-pg-migrate/migration-loading-strategies Example of using the runner function with tsconfigPaths to resolve TypeScript path aliases in migration files. ```APIDOC ## runner() ### Description Runs migrations with TypeScript path alias resolution enabled via the tsconfigPaths option. ### Method N/A (SDK function) ### Endpoint N/A (SDK function) ### Parameters #### Configuration Object - **databaseUrl** (string) - Required - Database connection URL. - **dir** (string) - Required - Directory containing migration files. - **direction** (string) - Required - Migration direction: 'up' or 'down'. - **migrationsTable** (string) - Required - Name of the migrations table. - **tsconfigPaths** (string | boolean) - Optional - Path to tsconfig.json or true to auto-discover. Defaults to false/omitted. ### Request Example ts import { runner } from 'node-pg-migrate'; await runner({ databaseUrl: process.env.DATABASE_URL!, dir: 'migrations', direction: 'up', migrationsTable: 'pgmigrations', // resolve `compilerOptions.paths` aliases inside migration files tsconfigPaths: './tsconfig.json', }); ### Response #### Success Response No return value (Promise). #### Response Example N/A ``` -------------------------------- ### Initial migration up/down (JavaScript) Source: https://salsita.github.io/node-pg-migrate/getting-started Defines the up and down migrations for creating users and posts tables with indexes and foreign keys. The down migration is empty. ```js exports.up = (pgm) => { pgm.createTable('users', { id: 'id', name: { type: 'varchar(1000)', notNull: true }, createdAt: { type: 'timestamp', notNull: true, default: pgm.func('current_timestamp'), }, }); pgm.createTable('posts', { id: 'id', userId: { type: 'integer', notNull: true, references: '"users"', onDelete: 'CASCADE', }, body: { type: 'text', notNull: true }, createdAt: { type: 'timestamp', notNull: true, default: pgm.func('current_timestamp'), }, }); pgm.createIndex('posts', 'userId'); }; exports.down = (pgm) => {}; ``` -------------------------------- ### Async migration with run callback Source: https://salsita.github.io/node-pg-migrate/migrations Async migration using the `run` callback. Note that none of the pgm operations will be executed until `run()` is called. ```javascript export const up = function up(pgm, run) { doSomethingAsync(function () { run(); }); }; ``` -------------------------------- ### runner Source: https://salsita.github.io/node-pg-migrate/api Runs migrations from a specified directory using the provided options. ```APIDOC ## runner ### Description Runs migrations from a specified directory using the provided options. ### Method N/A (JavaScript function) ### Endpoint N/A (JavaScript function) ### Parameters #### Options - **databaseUrl** (string or object) - Optional - Connection string or client config which is passed to new pg.Client - **dbClient** (pg.Client) - Optional - Instance of new pg.Client. Instance should be connected to DB, and after finishing migration, user is responsible to close connection - **migrationsTable** (string) - Optional - The table storing which migrations have been run - **migrationsSchema** (string) - Optional - The schema storing table which migrations have been run (defaults to same value as `schema`) - **schema** (string or array[string]) - Optional - The schema on which migration will be run (defaults to `public`) - **schemaIsDefault** (boolean) - Optional - Only matters when `schema` is set: marks it as a default your code filled in, as the CLI does without `--schema` - **dir** (string or array[string]) - Optional - The directory containing your migration files. This path is resolved from `cwd()`. Alternatively, provide a glob pattern or an array of glob patterns and set `useGlob = true` - **useGlob** (boolean) - Optional - Use glob to find migration files. This will use `dir` _and_ `ignorePattern` to glob-search for migration files - **checkOrder** (boolean) - Optional - Check order of migrations before running them - **direction** (enum) - Optional - `up` or `down` - **count** (number) - Optional - Amount of migration to run - **timestamp** (boolean) - Optional - Treats `count` as timestamp - **ignorePattern** (string or array[string]) - Optional - Regex pattern for file names to ignore (ignores files starting with `.` by default). Alternatively, provide a glob pattern or an array of glob patterns and set `isGlob = true` - **file** (string) - Optional - Run-only migration with this name - **singleTransaction** (boolean) - Optional - Combines all pending migrations into a single transaction so that if any migration fails, all will be rolled back (defaults to `true`) - **createSchema** (boolean) - Optional - Creates the configured schema if it doesn't exist - **createMigrationsSchema** (boolean) - Optional - Creates the configured migration schema if it doesn't exist - **noLock** (boolean) - Optional - Disables locking mechanism and checks - **lockValue** (number) - Optional - Value to use for the lock - **advisoryLockMode** (fail or wait) - Optional - Controls behavior when the migration advisory lock is already held by another process. Use `fail` to throw immediately or `wait` to block until the lock becomes available (defaults to `fail`) - **fake** (boolean) - Optional - Mark migrations as run without actually performing them (use with caution!) - **dryRun** (boolean) - Optional - Print the SQL that would be run without applying anything. Runs inside a read-only transaction, so nothing is created, recorded or written, and no advisory lock is taken - **log** (function) - Optional - Redirect log messages to this function, rather than `console` - **logger** (object with debug/info/warn/error methods) - Optional - Redirect messages to this logger object, rather than `console` - **verbose** (boolean) - Optional - Print all debug messages like DB queries run (if you switch it on, it will disable `logger.debug` method) - **decamelize** (boolean) - Optional - Runs `decamelize` on table/column/etc. names used in migrations (not on `migrationsTable`, `migrationsSchema` or `schema`) - **pretty** (boolean) - Optional - Formats the generated SQL statements with linebreaks and indentation for better readability. When `false` (the default), each statement is emitted as a single line - **migrationLoaderStrategies** (MigrationLoaderStrategy[]) - Optional - Allows custom loading strategies based on file extensions. If omitted, default behavior is used. ### Request Example ```javascript import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { runner } from 'node-pg-migrate'; await runner({ databaseUrl: process.env.DATABASE_URL, dir: `${import.meta.dirname}/migrations`, migrationsTable: 'pgmigrations', direction: 'up', verbose: true, }); ``` ### Response #### Success Response No explicit response documented. #### Response Example No explicit response example documented. ``` -------------------------------- ### pgm.renameIndex example Source: https://salsita.github.io/node-pg-migrate/migrations/indexes Rename an index. The generated SQL is ALTER INDEX index_name RENAME TO new_index_name. Renaming preserves the source schema, including during automatic reversal, and does not move the index to another schema because PostgreSQL does not provide ALTER INDEX ... SET SCHEMA. ```ts pgm.renameIndex('index_name', 'new_index_name'); //expected output: ALTER INDEX index_name RENAME TO new_index_name; ``` -------------------------------- ### pgm.createTable( tablename, columns, options ) Source: https://salsita.github.io/node-pg-migrate/migrations/tables Creates a new table with the specified columns and options. Supports temporary tables, ifNotExists, inheritance, constraints, LIKE clause, comments, and unlogged setting. ```APIDOC ## pgm.createTable( tablename, columns, options ) ### Description Creates a new table with the specified columns and options. Supports temporary tables, ifNotExists, inheritance, constraints, LIKE clause, comments, and unlogged setting. ### Method pgm.createTable ### Arguments - **tablename** (Name) - Required - name for the new table - **columns** (object) - Required - column names / options -- see column definitions section - **options** (object) - Optional - table options ### Options - **temporary** (boolean) - Optional - default `false` - **ifNotExists** (boolean) - Optional - default `false` - **inherits** (Name) - Optional - table(s) to inherit from - **constraints** (object) - Optional - table constraints see `expression` of add constraint - **like** (Name or object) - Optional - table(s) to inherit from or object with `table` and `options` keys - **comment** (string) - Optional - adds comment on table - **unlogged** (boolean) - Optional - default `false` #### like options - **including** (string or array[string]) - Optional - 'COMMENTS', 'CONSTRAINTS', 'DEFAULTS', 'IDENTITY', 'INDEXES', 'STATISTICS', 'STORAGE', 'ALL' - **excluding** (string or array[string]) - Optional - 'COMMENTS', 'CONSTRAINTS', 'DEFAULTS', 'IDENTITY', 'INDEXES', 'STATISTICS', 'STORAGE', 'ALL' ``` -------------------------------- ### pgm.createView( viewName, options, definition ) Source: https://salsita.github.io/node-pg-migrate/migrations/views Creates a new view in the database. The definition must be a SQL SELECT statement. Options allow adding TEMPORARY, OR REPLACE, RECURSIVE clauses, specifying column names, view options, and check option. ```APIDOC ## pgm.createView( viewName, options, definition ) ### Description Creates a new view in the database. The definition must be a SQL SELECT statement. ### Arguments - **viewName** (string) - Required - Name of the new view. - **options** (object) - Required - Options for the view creation. - **definition** (string) - Required - SQL of SELECT statement. ### Options - **temporary** (boolean) - Optional - Adds `TEMPORARY` clause. - **replace** (boolean) - Optional - Adds `OR REPLACE` clause. - **recursive** (boolean) - Optional - Adds `RECURSIVE` clause. - **columns** (string or array) - Optional - Use if you want to name columns differently than inferred from definition. - **options** (object) - Optional - Key value pairs of View Options. - **checkOption** (string) - Optional - `CASCADED` or `LOCAL`. ### Reverse Operation `pgm.dropView( viewName, options )` ``` -------------------------------- ### SQL generated by pgm.createTable with shorthands Source: https://salsita.github.io/node-pg-migrate/migrations SQL produced by `pgm.createTable('test', { id: 'id', createdAt: 'createdAt' })` using the shorthands defined above. ```sql CREATE TABLE "test" ("id" uuid PRIMARY KEY, "createdAt" timestamp DEFAULT current_timestamp NOT NULL); ``` -------------------------------- ### Create users table with index (TypeScript, JavaScript, SQL) Source: https://salsita.github.io/node-pg-migrate Create a users table with an email column and an index on createdAt. The TypeScript and JavaScript versions use the pgm API; the SQL version includes both up and down migrations. The down migration is inferred when omitted in JS/TS. ```ts import type { MigrationBuilder } from 'node-pg-migrate'; export async function up ( pgm : MigrationBuilder ): Promise { pgm . createTable ('users', { id : 'id', email : { type : 'text', notNull : true, unique : true }, createdAt : { type : 'timestamptz', notNull : true, default : pgm . func ('now()'), }, }); pgm . createIndex ('users', 'createdAt'); } ``` ```js export const up = (pgm) => { pgm.createTable('users', { id: 'id', email: { type: 'text', notNull: true, unique: true }, createdAt: { type: 'timestamptz', notNull: true, default: pgm.func('now()'), }, }); pgm.createIndex('users', 'createdAt'); }; ``` ```sql -- Up Migration CREATE TABLE "users" ( "id" serial PRIMARY KEY, "email" text UNIQUE NOT NULL, "createdAt" timestamptz DEFAULT now() NOT NULL ); CREATE INDEX "users_createdAt_index" ON "users" ("createdAt"); -- Down Migration DROP INDEX "users_createdAt_index"; DROP TABLE "users"; ``` -------------------------------- ### Enable pretty option for multi-line SQL Source: https://salsita.github.io/node-pg-migrate/upgrading To restore the previous multi-line SQL formatting, use the new 'pretty' option when running the up command. ```bash node-pg-migrate up --pretty ``` -------------------------------- ### Enable pretty output with `pretty: true` Source: https://salsita.github.io/node-pg-migrate/upgrading Configuration option to enable pretty-printed SQL output. When using the programmatic API, pass `pretty: true` to `runner()`. ```jsonc { "pretty": true, } ``` -------------------------------- ### Setting DATABASE_URL environment variable Source: https://salsita.github.io/node-pg-migrate/cli Run node-pg-migrate by setting the DATABASE_URL environment variable. ```bash DATABASE_URL=postgres://postgres@localhost/database node-pg-migrate ``` -------------------------------- ### Run migrations with node-pg-migrate runner Source: https://salsita.github.io/node-pg-migrate/api Shows the expected directory layout and the JavaScript code to run migrations from the `migrations/` directory using the `runner` function from `node-pg-migrate`. The runner is called with `databaseUrl`, `dir`, `migrationsTable`, `direction`, and `verbose` options. ```text . ├── migrations │ ├── 00_init.sql │ └── 01_foobar.sql └── run_migrations.js ``` ```javascript import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { runner } from 'node-pg-migrate'; await runner({ databaseUrl: process.env.DATABASE_URL, dir: `${import.meta.dirname}/migrations`, migrationsTable: 'pgmigrations', direction: 'up', verbose: true, }); ``` -------------------------------- ### pgm.createRole( role_name, role_options ) Source: https://salsita.github.io/node-pg-migrate/migrations/roles Creates a new role with the specified name and options. Options include superuser, createdb, createrole, inherit, login, replication, bypassrls, limit, password, encrypted, valid, inRole, role, and admin. ```APIDOC ## pgm.createRole( role_name, role_options ) ### Description Creates a new role with the specified name and options. ### Method pgm.createRole ### Arguments - **role_name** (Name) - Required - Name of the new role. - **role_options** (object) - Required - Options for the role. See below. ### role_options - **superuser** (boolean) - Optional - Default `false`. - **createdb** (boolean) - Optional - Default `false`. - **createrole** (boolean) - Optional - Default `false`. - **inherit** (boolean) - Optional - Default `true`. - **login** (boolean) - Optional - Default `false`. - **replication** (boolean) - Optional - Default `false`. - **bypassrls** (boolean) - Optional - No default specified. - **limit** (number) - Optional - No default specified. - **password** (string) - Optional - No default specified. - **encrypted** (boolean) - Optional - Default `true`. - **valid** (string) - Optional - Timestamp. - **inRole** (string or array[string]) - Optional - Role or array of roles. - **role** (string or array[string]) - Optional - Role or array of roles. - **admin** (string or array[string]) - Optional - Role or array of roles. ### Request Example ```js pgm.createRole('new_role', { login: true, password: 'secret' }); ``` ### Response No return value documented. ``` -------------------------------- ### Add lead column migration (JavaScript) Source: https://salsita.github.io/node-pg-migrate/getting-started Adds a 'lead' column to the 'posts' table using pgm.addColumns. ```js export const up = (pgm) => { pgm.addColumns('posts', { lead: { type: 'text', notNull: true }, }); }; ``` -------------------------------- ### Config file with database URL Source: https://salsita.github.io/node-pg-migrate/cli Specify database connection URL in a JSON config file. ```jsonc // config/default.json { "db": { "url": "postgres://postgres:password@localhost:5432/database", }, } ``` -------------------------------- ### Custom JSON config file Source: https://salsita.github.io/node-pg-migrate/cli Pass a custom JSON file with database connection settings, same format as the db entry. ```jsonc // path/to/config.json { "user": "postgres", "password": "", "host": "localhost", "port": 5432, "database": "database", } ``` -------------------------------- ### Initial migration up/down (TypeScript) Source: https://salsita.github.io/node-pg-migrate/getting-started Defines the up and down migrations for creating users and posts tables with indexes and foreign keys. The down migration is an async function that does nothing. ```ts import { MigrationBuilder } from 'node-pg-migrate'; export const up = (pgm: MigrationBuilder) => { pgm.createTable('users', { id: 'id', name: { type: 'varchar(1000)', notNull: true }, createdAt: { type: 'timestamp', notNull: true, default: pgm.func('current_timestamp'), }, }); pgm.createTable('posts', { id: 'id', userId: { type: 'integer', notNull: true, references: '"users"', onDelete: 'CASCADE', }, body: { type: 'text', notNull: true }, createdAt: { type: 'timestamp', notNull: true, default: pgm.func('current_timestamp'), }, }); pgm.createIndex('posts', 'userId'); }; export async function down(pgm: MigrationBuilder): Promise {} ``` -------------------------------- ### Async migration returning a Promise Source: https://salsita.github.io/node-pg-migrate/migrations Async migration by returning a Promise from the `up` function. ```javascript export const up = function (pgm) { return new Promise((resolve) => { // doSomethingAsync resolve(); }); }; ``` -------------------------------- ### pgm.createSchema( schema_name, schema_options ) Source: https://salsita.github.io/node-pg-migrate/migrations/schemas Creates a new schema in the database with optional settings for existence checks and ownership. ```APIDOC ## pgm.createSchema( schema_name, schema_options ) ### Description Creates a new schema in the database. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Arguments - **schema_name** (string) - Required - Name of the new schema. - **schema_options** (object) - Optional - Options for creating the schema. #### schema_options - **ifNotExists** (boolean) - Optional - Adds `IF NOT EXISTS` clause. - **authorization** (string) - Optional - Alternative user to own new schema. ### Request Example N/A ### Response N/A ``` -------------------------------- ### CLI subcommand usage: options after command Source: https://salsita.github.io/node-pg-migrate/upgrading In v10, options must be passed after the command. The first line shows the correct usage; the second line shows the old, now-incorrect usage. ```bash node-pg-migrate up --pretty -m migrations node-pg-migrate --pretty up -m migrations ``` -------------------------------- ### Add node-pg-migrate script to package.json Source: https://salsita.github.io/node-pg-migrate/faq/typescript Adds a migrate script to package.json that runs node-pg-migrate. The comment placeholder indicates where other scripts may appear. ```jsonc { "scripts": { // .. "migrate": "node-pg-migrate", }, } ```