umzug
- Version 3.8.2
- Published
- 139 kB
- 5 dependencies
- MIT license
Install
npm i umzug
yarn add umzug
pnpm add umzug
Overview
Framework-agnostic migration tool for Node
Index
Variables
Functions
Classes
Type Aliases
- CommandLineParserOptions
- FileLockerOptions
- GlobInputMigrations
- InputMigrations
- JSONStorageConstructorOptions
- LogFn
- MergeExclusive
- MigrateDownOptions
- MigrateUpOptions
- MigrationFn
- MigrationMeta
- MigrationParams
- ModelClass
- MongoDBCollectionOptions
- MongoDBConnectionOptions
- MongoDBStorageConstructorOptions
- Promisable
- RerunBehavior
- Resolver
- RunnableMigration
- SequelizeStorageConstructorOptions
- SequelizeType
- UmzugEvents
- UmzugOptions
- UmzugStorage
Variables
variable RerunBehavior
const RerunBehavior: { readonly THROW: 'THROW'; readonly SKIP: 'SKIP'; readonly ALLOW: 'ALLOW';};
Functions
function isUmzugStorage
isUmzugStorage: (arg: Partial<UmzugStorage>) => arg is UmzugStorage<unknown>;
function memoryStorage
memoryStorage: () => UmzugStorage;
function verifyUmzugStorage
verifyUmzugStorage: (arg: Partial<UmzugStorage>) => UmzugStorage;
Classes
class CreateAction
class CreateAction extends cli.CommandLineAction {}
constructor
constructor(umzug: Umzug<object>);
property umzug
readonly umzug: Umzug<object>;
method onDefineParameters
onDefineParameters: () => void;
method onExecute
onExecute: () => Promise<void>;
class DownAction
class DownAction extends cli.CommandLineAction {}
constructor
constructor(umzug: Umzug<object>);
property umzug
protected umzug: Umzug<object>;
method onDefineParameters
onDefineParameters: () => void;
method onExecute
onExecute: () => Promise<void>;
class FileLocker
class FileLocker {}
Simple locker using the filesystem. Only one lock can be held per file. An error will be thrown if the lock file already exists.
Example 1
const umzug = new Umzug({ ... }) FileLocker.attach(umzug, { path: 'path/to/lockfile' })
To wait for the lock to be free instead of throwing, you could extend it (the below example uses
setInterval
, but depending on your use-case, you may want to use a library with retry/backoff):Example 2
class WaitingFileLocker extends FileLocker { async getLock() { return new Promise(resolve => setInterval( () => super.getLock().then(resolve).catch(), 500, ) } }
const locker = new WaitingFileLocker({ path: 'path/to/lockfile' }) locker.attachTo(umzug)
constructor
constructor(params: FileLockerOptions);
method attach
static attach: (umzug: Umzug, params: FileLockerOptions) => void;
Attach
beforeAll
andafterAll
events to an umzug instance which use the specified filepath
method attachTo
attachTo: (umzug: Umzug) => void;
Attach lock handlers to
beforeCommand
andafterCommand
events on an umzug instance
method getLock
getLock: () => Promise<void>;
method releaseLock
releaseLock: () => Promise<void>;
class JSONStorage
class JSONStorage implements UmzugStorage {}
constructor
constructor(options?: JSONStorageConstructorOptions);
property path
readonly path: string;
method executed
executed: () => Promise<string[]>;
method logMigration
logMigration: ({ name: migrationName }: { name: string }) => Promise<void>;
method unlogMigration
unlogMigration: ({ name: migrationName }: { name: string }) => Promise<void>;
class ListAction
class ListAction extends cli.CommandLineAction {}
constructor
constructor(action: 'pending' | 'executed', umzug: Umzug<object>);
method onDefineParameters
onDefineParameters: () => void;
method onExecute
onExecute: () => Promise<void>;
class MigrationError
class MigrationError extends errorCause.ErrorWithCause<unknown> {}
constructor
constructor(migration: MigrationErrorParams, original: {});
property info
readonly info: MigrationErrorParams;
property jse_cause
jse_cause: {};
property migration
migration: MigrationErrorParams;
property name
name: string;
class MongoDBStorage
class MongoDBStorage implements UmzugStorage {}
constructor
constructor(options: MongoDBStorageConstructorOptions);
property collection
readonly collection: AnyObject;
property collectionName
readonly collectionName: string;
property connection
readonly connection: any;
method executed
executed: () => Promise<string[]>;
method logMigration
logMigration: ({ name: migrationName }: { name: string }) => Promise<void>;
method unlogMigration
unlogMigration: ({ name: migrationName }: { name: string }) => Promise<void>;
class SequelizeStorage
class SequelizeStorage implements UmzugStorage {}
constructor
constructor(options: any);
Constructs Sequelize based storage. Migrations will be stored in a SequelizeMeta table using the given instance of Sequelize.
If a model is given, it will be used directly as the model for the SequelizeMeta table. Otherwise, it will be created automatically according to the given options.
If the table does not exist it will be created automatically upon the logging of the first migration.
property columnName
readonly columnName: string;
property columnType
readonly columnType: string;
property model
readonly model: ModelClassType;
property modelName
readonly modelName: string;
property schema
readonly schema: any;
property sequelize
readonly sequelize: SequelizeType;
property tableName
readonly tableName?: string;
property timestamps
readonly timestamps: boolean;
method executed
executed: () => Promise<string[]>;
method getModel
getModel: () => ModelClassType;
method logMigration
logMigration: ({ name: migrationName }: { name: string }) => Promise<void>;
method syncModel
protected syncModel: () => Promise<void>;
method unlogMigration
unlogMigration: ({ name: migrationName }: { name: string }) => Promise<void>;
class Umzug
class Umzug<Ctx extends object = object> extends emittery<UmzugEvents<Ctx>> {}
constructor
constructor(options: UmzugOptions<Ctx>);
creates a new Umzug instance
property defaultResolver
static defaultResolver: Resolver<unknown>;
property migrations
readonly migrations: ( ctx: Ctx) => Promise<ReadonlyArray<RunnableMigration<Ctx>>>;
property options
readonly options: UmzugOptions<Ctx>;
method create
create: (options: { name: string; folder?: string; prefix?: 'TIMESTAMP' | 'DATE' | 'NONE'; allowExtension?: string; allowConfusingOrdering?: boolean; skipVerify?: boolean; content?: string;}) => Promise<void>;
method down
down: ( options?: typeFest.MergeExclusive<A, typeFest.MergeExclusive<B, C>>) => Promise<MigrationMeta[]>;
Revert migrations. By default, the last executed migration is reverted.
See Also
MigrateDownOptions for other use cases using
to
,migrations
andrerun
.
method executed
executed: () => Promise<MigrationMeta[]>;
Get the list of migrations which have already been applied
method getCli
protected getCli: (options?: CommandLineParserOptions) => UmzugCLI;
Get an UmzugCLI instance. This can be overriden in a subclass to add/remove commands - only use if you really know you need this, and are OK to learn about/interact with the API of @rushstack/ts-command-line.
method pending
pending: () => Promise<MigrationMeta[]>;
Get the list of migrations which are yet to be applied
method runAsCLI
runAsCLI: (argv?: string[]) => Promise<boolean>;
'Run' an umzug instance as a CLI. This will read
process.argv
, execute commands based on that, and callprocess.exit
after running. If that isn't what you want, stick to the programmatic API. You probably want to run only if a file is executed as the process's 'main' module with something like:Example 1
if (require.main === module) { myUmzugInstance.runAsCLI() }
method runCommand
protected runCommand: <T>( command: string, cb: (commandParams: { context: Ctx }) => Promise<T>) => Promise<T>;
method up
up: ( options?: typeFest.MergeExclusive<A, typeFest.MergeExclusive<B, C>>) => Promise<MigrationMeta[]>;
Apply migrations. By default, runs all pending migrations.
See Also
MigrateUpOptions for other use cases using
to
,migrations
andrerun
.
class UmzugCLI
class UmzugCLI extends cli.CommandLineParser {}
constructor
constructor( umzug: Umzug<object>, commandLineParserOptions?: CommandLineParserOptions);
property umzug
readonly umzug: Umzug<object>;
method onDefineParameters
onDefineParameters: () => void;
class UpAction
class UpAction extends cli.CommandLineAction {}
constructor
constructor(umzug: Umzug<object>);
property umzug
protected umzug: Umzug<object>;
method onDefineParameters
onDefineParameters: () => void;
method onExecute
onExecute: () => Promise<void>;
Type Aliases
type CommandLineParserOptions
type CommandLineParserOptions = { toolFileName?: string; toolDescription?: string;};
type FileLockerOptions
type FileLockerOptions = { path: string; fs?: typeof fs;};
type GlobInputMigrations
type GlobInputMigrations<T> = { /** * A glob string for migration files. Can also be in the format `[path/to/migrations/*.js', {cwd: 'some/base/dir', ignore: '**ignoreme.js' }]` * See https://npmjs.com/package/glob for more details on the glob format - this package is used internally. */ glob: | string | [ string, { cwd?: string; ignore?: string | string[]; } ]; /** Will be supplied to every migration function. Can be a database client, for example */ /** A function which takes a migration name, path and context, and returns an object with `up` and `down` functions. */ resolve?: Resolver<T>;};
Glob instructions for migration files
type InputMigrations
type InputMigrations<T> = | GlobInputMigrations<T> | Array<RunnableMigration<T>> | ((context: T) => Promisable<InputMigrations<T>>);
Allowable inputs for migrations. Can be either glob instructions for migration files, a list of runnable migrations, or a function which receives a context and returns a list of migrations.
type JSONStorageConstructorOptions
type JSONStorageConstructorOptions = { /** Path to JSON file where the log is stored. @default './umzug.json' */ readonly path?: string;};
type LogFn
type LogFn = (message: Record<string, unknown>) => void;
type MergeExclusive
type MergeExclusive<A, B, C> = typeFest.MergeExclusive< A, typeFest.MergeExclusive<B, C>>;
Create a type that has mutually exclusive keys. Wrapper for
See Also
import('type-fest').MergeExclusive
that works for three types
type MigrateDownOptions
type MigrateDownOptions = MergeExclusive< { /** If specified, migrations down to and including this name will be revert. Otherwise, only the last executed will be reverted */ to?: string | 0; }, { /** Revert this many migrations. If not specified, only the most recent migration will be reverted */ step: number; }, { /** * If specified, only the migrations with these names migrations will be reverted. An error will be thrown if any of the names are not found in the list of executed migrations. * Note, migrations will be run in the order specified. */ migrations: string[]; /** What to do if a migration that has not been run is explicitly specified. Default is `THROW`. */ rerun?: RerunBehavior; }>;
type MigrateUpOptions
type MigrateUpOptions = MergeExclusive< { /** If specified, migrations up to and including this name will be run. Otherwise, all pending migrations will be run */ to?: string; }, { /** Only run this many migrations. If not specified, all pending migrations will be run */ step: number; }, { /** If specified, only the migrations with these names migrations will be run. An error will be thrown if any of the names are not found in the list of available migrations */ migrations: string[]; /** What to do if a migration that has already been run is explicitly specified. Default is `THROW`. */ rerun?: RerunBehavior; }>;
type MigrationFn
type MigrationFn<T = unknown> = (params: MigrationParams<T>) => Promise<unknown>;
A callable function for applying or reverting a migration
type MigrationMeta
type MigrationMeta = { /** Name - this is used as the migration unique identifier within storage */ name: string; /** An optional filepath for the migration. Note: this may be undefined, since not all migrations correspond to files on the filesystem */ path?: string;};
Serializeable metadata for a migration. The structure returned by the external-facing
pending()
andexecuted()
methods.
type MigrationParams
type MigrationParams<T> = { name: string; path?: string; context: T;};
type ModelClass
type ModelClass = { tableName: string; sequelize?: SequelizeType; getTableName(): string; sync(): Promise<void>; findAll(options?: {}): Promise<any[]>; create(options: {}): Promise<void>; destroy(options: {}): Promise<void>;};
Minimal structure of a sequelize model, defined here to avoid a hard dependency. The type expected is
import { Model } from 'sequelize'
type MongoDBCollectionOptions
type MongoDBCollectionOptions = { /** A reference to a MongoDB Driver collection */ readonly collection: AnyObject;};
type MongoDBConnectionOptions
type MongoDBConnectionOptions = { /** A connection to target database established with MongoDB Driver */ readonly connection: AnyObject; /** The name of the migration collection in MongoDB @default 'migrations' */ readonly collectionName?: string;};
type MongoDBStorageConstructorOptions
type MongoDBStorageConstructorOptions = | MongoDBConnectionOptions | MongoDBCollectionOptions;
type Promisable
type Promisable<T> = T | PromiseLike<T>;
type RerunBehavior
type RerunBehavior = keyof typeof RerunBehavior;
type Resolver
type Resolver<T> = (params: MigrationParams<T>) => RunnableMigration<T>;
A function which takes a migration name, path and context, and returns an object with
up
anddown
functions.
type RunnableMigration
type RunnableMigration<T> = { /** The effect of applying the migration */ up: MigrationFn<T>; /** The effect of reverting the migration */ down?: MigrationFn<T>;} & MigrationMeta;
A runnable migration. Represents a migration object with an
up
function which can be called directly, with no arguments, and an optionaldown
function to revert it.
type SequelizeStorageConstructorOptions
type SequelizeStorageConstructorOptions = | SetRequired<_SequelizeStorageConstructorOptions, 'sequelize'> | SetRequired<_SequelizeStorageConstructorOptions, 'model'>;
type SequelizeType
type SequelizeType = { getQueryInterface(): any; isDefined(modelName: string): boolean; model(modelName: string): any; define(modelName: string, columns: {}, options: {}): {}; dialect?: { name?: string; };};
Minimal structure of a sequelize model, defined here to avoid a hard dependency. The type expected is
import { Sequelize } from 'sequelize'
type UmzugEvents
type UmzugEvents<Ctx> = { migrating: MigrationParams<Ctx>; migrated: MigrationParams<Ctx>; reverting: MigrationParams<Ctx>; reverted: MigrationParams<Ctx>; beforeCommand: { command: string; context: Ctx; }; afterCommand: { command: string; context: Ctx; };};
Map of eventName -> eventData type, where the keys are the string events that are emitted by an umzug instances, and the values are the payload emitted with the corresponding event.
type UmzugOptions
type UmzugOptions<Ctx extends {} = Record<string, unknown>> = { /** The migrations that the Umzug instance should perform */ migrations: InputMigrations<Ctx>; /** A logging function. Pass `console` to use stdout, or pass in your own logger. Pass `undefined` explicitly to disable logging. */ logger: Record<'info' | 'warn' | 'error' | 'debug', LogFn> | undefined; /** The storage implementation. By default, `JSONStorage` will be used */ storage?: UmzugStorage<Ctx>; /** An optional context object, which will be passed to each migration function, if defined */ context?: Ctx | (() => Promise<Ctx> | Ctx); /** Options for file creation */ create?: { /** * A function for generating placeholder migration files. Specify to make sure files generated via CLI or using `.create` follow team conventions. * Should return an array of [filepath, content] pairs. Usually, only one pair is needed, but to put `down` migrations in a separate * file, more than one can be returned. */ template?: (filepath: string) => Promisable<Array<[string, string]>>; /** * The default folder that new migration files should be generated in. If this is not specified, the new migration file will be created * in the same folder as the last existing migration. The value here can be overriden by passing `folder` when calling `create`. */ folder?: string; };};
Constructor options for the Umzug class
type UmzugStorage
type UmzugStorage<Ctx = unknown> = { /** * Logs migration to be considered as executed. */ logMigration: (params: MigrationParams<Ctx>) => Promise<void>; /** * Unlogs migration (makes it to be considered as pending). */ unlogMigration: (params: MigrationParams<Ctx>) => Promise<void>; /** * Gets list of executed migrations. */ executed: (meta: Pick<MigrationParams<Ctx>, 'context'>) => Promise<string[]>;};
Package Files (10)
Dependencies (5)
Dev Dependencies (25)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/umzug
.
- Markdown[](https://www.jsdocs.io/package/umzug)
- HTML<a href="https://www.jsdocs.io/package/umzug"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 3116 ms. - Missing or incorrect documentation? Open an issue for this package.