Skip to content

Migrations ​

Introduction ​

Migrations are version control for your database schema. Each migration is a small class that knows how to apply a change (up) and how to undo it (down). Plinth records which migrations have run, so every developer and every server can bring a database to the same state by running the pending ones in order.

The pieces fit together like this:

  • A Migration class describes one change using the Schema builder.
  • The Schema builder creates, alters and drops tables, columns, indexes and foreign keys, and compiles them to the SQL of whichever database you use.
  • A Migrator runs, rolls back and reports on a list of migrations, recording them in a migrations table.
  • Console commands (migrate, migrate:rollback, and others) wrap the Migrator for the command line.
bash
pnpm add @plinthjs/database

Writing migrations ​

A migration is a file that default-exports a class extending Migration. Both methods receive a Schema bound to the connection the migration runs on.

ts
import { Migration } from '@plinthjs/database'

import type { Schema } from '@plinthjs/database'

export default class extends Migration {
  async up(schema: Schema): Promise<void> {
    await schema.create('users', (table) => {
      table.id()
      table.string('name')
      table.string('email').unique()
      table.timestamps()
    })
  }

  async down(schema: Schema): Promise<void> {
    await schema.dropIfExists('users')
  }
}

Name files with a sortable timestamp prefix, such as 2024_01_05_090307_create_users_table.ts. Migrations run in filename order, and the filename without its extension is the name recorded in the ledger.

Generating a migration ​

make:migration writes a timestamped file from a stub. The stub depends on the name: create_widgets_table produces a schema.create('widgets', ...) stub, add_email_to_users_table produces a schema.table('users', ...) stub, and any other name produces an empty one. --create=widgets or --table=widgets set the table explicitly.

bash
npx plinth make:migration create_posts_table
npx plinth make:migration add_slug_to_posts_table

In a generated application the file lands in src/database/migrations/, and make:migration create_posts_table --create=posts (using --create to name the table) writes a create stub for posts. The command in @plinthjs/database writes to database/migrations by default and accepts a --path option. See Running migrations for how the commands are wired.

Creating tables ​

schema.create(name, callback) creates a table. The callback receives a Blueprint on which you declare columns, indexes and foreign keys.

ts
import { sqliteConnection, Schema } from '@plinthjs/database'

const db = sqliteConnection()
const schema = new Schema(db)

await schema.create('posts', (table) => {
  table.id()
  table.foreignId('user_id').constrained().cascadeOnDelete()
  table.string('title')
  table.text('body')
  table.boolean('published').default(false)
  table.timestamps()
})

await schema.hasTable('posts') // => true
await schema.hasColumn('posts', 'title') // => true
await schema.hasColumns('posts', ['title', 'body']) // => true

createIfNotExists() does the same but does nothing when the table already exists.

Table options ​

A few options apply to the whole table. engine(), charset() and collation() matter on MySQL and MariaDB and are ignored elsewhere. comment() writes a table comment on MySQL, MariaDB and Postgres. SQLite has no comment DDL, so it ignores the comment silently, the same way it ignores after(); SQL Server has none either and throws.

ts
await schema.create('logs', (table) => {
  table.engine('InnoDB')
  table.charset('utf8mb4')
  table.collation('utf8mb4_unicode_ci')
  table.id()
})

await schema.create('scratch', (table) => {
  table.temporary()
  table.id()
})

Column types ​

Each method on the blueprint adds a column and returns a ColumnDefinition you can chain modifiers on.

Keys ​

MethodColumn
id(name = 'id')auto-incrementing big integer primary key
increments(name), integerIncrements(name)auto-incrementing integer primary key
tinyIncrements, smallIncrements, mediumIncrements, bigIncrementsthe same, in other sizes
uuid(name), ulid(name = 'ulid')UUID and ULID columns
foreignId(name), foreignUuid(name), foreignUlid(name)key columns that can declare a foreign key

Numbers ​

MethodColumn
integer, bigInteger, tinyInteger, smallInteger, mediumIntegersigned integers
unsignedInteger, unsignedBigInteger, unsignedTinyInteger, unsignedSmallInteger, unsignedMediumIntegerunsigned integers
float(name, precision?), double(name)floating point
decimal(name, precision = 8, scale = 2), unsignedDecimal(...)exact decimals
boolean(name)true or false

Text and binary ​

MethodColumn
string(name, length = 255), char(name, length = 255)variable and fixed-length text
text, tinyText, mediumText, longTextlong text
binary(name, length?, fixed = false)binary data
json(name), jsonb(name)JSON documents
enum(name, values), set(name, values)one of, or several of, a list of strings
ipAddress(name = 'ip_address'), macAddress(name = 'mac_address')network addresses

Dates and times ​

MethodColumn
date(name), year(name)date, year
dateTime(name, precision?), dateTimeTz(name, precision?)date and time
timestamp(name, precision?), timestampTz(name, precision?)timestamps
time(name, precision?), timeTz(name, precision?)time of day

Conveniences ​

These add several columns at once.

ts
await schema.create('articles', (table) => {
  table.id()
  table.timestamps() // created_at and updated_at, both nullable
  table.softDeletes() // deleted_at, nullable
  table.rememberToken() // remember_token, nullable string of length 100
  table.morphs('taggable') // taggable_type, taggable_id, plus an index
})

nullableTimestamps(), timestampsTz(), datetimes(), softDeletesTz(), softDeletesDatetime() and the nullableMorphs(), uuidMorphs(), ulidMorphs() and numericMorphs() families are the variants. Each has a matching drop method (see Dropping columns).

Spatial, vector and custom columns ​

geometry(name, subtype?, srid?), geography(...), vector(name, dimensions?) and tsvector(name) cover specialised types on the engines that have them. For anything else, rawColumn(name, definition) writes the type yourself:

ts
table.rawColumn('area', 'point not null')

computed(name, expression) declares a computed column on SQL Server. On MySQL, MariaDB and Postgres use storedAs() or virtualAs() on a normal column type instead.

Column modifiers ​

Chain modifiers on the column definition to refine it.

ts
await schema.create('profiles', (table) => {
  table.id()
  table.string('nickname', 100).nullable()
  table.integer('age').unsigned().default(18)
  table.string('country').default('NP').comment('ISO country code')
  table.timestamp('seen_at').useCurrent()
  table.string('email').unique()
  table.string('slug').index()
})
ModifierEffect
nullable(value = true)allow NULL
default(value)default value; pass raw('...') for an expression
unsigned()unsigned numeric
autoIncrement()auto-increment
useCurrent(), useCurrentOnUpdate()default to, and refresh to, the current timestamp
unique(), index(), primary()single-column indexes (fullText(), spatialIndex() also exist)
comment(text)column comment
after(column), first()column position (MySQL and MariaDB)
charset(name), collation(name)column character set and collation (MySQL and MariaDB)
storedAs(expr), virtualAs(expr)generated column
invisible()hide from select * (MySQL and MariaDB)
change()modify an existing column instead of adding one

INFO

Modifiers that an engine has no equivalent for are accepted by the builder but have no effect on that engine. For example after() and column and table comment() are ignored on SQLite.

Indexes ​

Single-column indexes come from column modifiers. For multi-column indexes, or indexes added separately, call the blueprint directly. Each index takes a column name or an array, and an optional name. When you leave the name out, it is generated from the table and columns, such as users_name_age_index or t_a_b_unique.

ts
await schema.create('users', (table) => {
  table.id()
  table.string('name')
  table.integer('age')
  table.string('a')
  table.string('b')

  table.index(['name', 'age']) // users_name_age_index
  table.unique(['a', 'b']) // users_a_b_unique
  table.unique('name', 'users_name_custom') // an explicit name
})

Available index types:

MethodIndex
index(columns, name?, algorithm?)plain index
unique(columns, name?, algorithm?)unique index
primary(columns, name?)composite primary key
fullText(columns, name?, algorithm?)full-text index
spatialIndex(columns, name?)spatial index
rawIndex(expression, name)an index on a raw expression

Check what exists with hasIndex(). You can match by name, by column list, and narrow to 'primary' or 'unique':

ts
await schema.hasIndex('users', 'users_name_age_index') // => true
await schema.hasIndex('users', ['name', 'age']) // => true
await schema.hasIndex('users', ['a', 'b'], 'unique') // => true
await schema.getIndexListing('users') // => ['primary', 'users_name_age_index', 'users_a_b_unique', ...]

Foreign keys ​

The shortest form is foreignId() followed by constrained(). The referenced table is guessed by pluralising the column name without its _id suffix, and the referenced column defaults to id.

ts
await schema.create('comments', (table) => {
  table.id()
  table.foreignId('post_id').constrained() // references posts.id
  table.foreignId('author_id').constrained('users') // an explicit table
  table.foreignId('team_id').nullable().constrained('teams', 'uuid') // an explicit column
  table.string('body')
})

constrained() returns a foreign key builder with the referential actions:

ts
table.foreignId('user_id').constrained().cascadeOnDelete().restrictOnUpdate()
table.foreignId('user_id').constrained().nullOnDelete()

The available shorthands are cascadeOnDelete(), restrictOnDelete(), nullOnDelete(), noActionOnDelete() and the matching ...OnUpdate() methods. onDelete(action) and onUpdate(action) take one of 'cascade', 'restrict', 'set null' or 'no action'.

To define a key by hand, use foreign():

ts
await schema.create('post_tags', (table) => {
  table.unsignedBigInteger('post_id')
  table.unsignedBigInteger('tag_id')
  table.foreign('post_id').references('id').on('posts').onDelete('cascade')
  table.foreign('tag_id').references('id').on('tags').onDelete('cascade')
  table.primary(['post_id', 'tag_id'])
})

Read the keys back with getForeignKeys():

ts
await schema.getForeignKeys('post_tags')
// => [{ name: null, columns: ['post_id'], foreignTable: 'posts', foreignColumns: ['id'], onDelete: 'cascade', onUpdate: 'no action' }, ...]

Toggling constraint checks ​

Sometimes you must write rows in an order that would break a constraint. withoutForeignKeyConstraints() turns checking off for the duration of a callback and turns it back on afterwards, even if the callback throws. disableForeignKeyConstraints() and enableForeignKeyConstraints() do the two halves separately.

ts
await schema.withoutForeignKeyConstraints(async () => {
  await db.table('posts').delete()
  await db.table('users').delete()
})

Modifying tables ​

schema.table(name, callback) alters an existing table. Columns you declare are added; the commands below change what is already there.

ts
await schema.table('posts', (table) => {
  table.string('slug').nullable().after('title')
  table.index('slug')
})

Renaming ​

ts
await schema.table('posts', (table) => {
  table.renameColumn('slug', 'permalink')
})

await schema.rename('posts', 'articles') // rename a table

Changing a column ​

Declare the column with its new definition and call change(). State every attribute you want to keep, since the definition replaces the old one.

ts
await schema.table('users', (table) => {
  table.string('name', 100).nullable().change()
})
// MySQL: ALTER TABLE `users` MODIFY `name` VARCHAR(100) NULL

WARNING

SQLite has no ALTER COLUMN, so change() throws on SQLite with a message explaining that the table has to be rebuilt. Plan such migrations for the database you deploy to.

Dropping columns ​

ts
await schema.table('users', (table) => {
  table.dropColumn('phone')
  table.dropColumn(['legacy_a', 'legacy_b'])
})

await schema.dropColumns('users', 'nickname') // shorthand

There are matching helpers for the conveniences: dropTimestamps(), dropTimestampsTz(), dropSoftDeletes(), dropSoftDeletesTz(), dropRememberToken(), dropMorphs(name) and dropConstrainedForeignId(column).

Dropping indexes and keys ​

Pass either the index name or the column list the index was created from.

ts
await schema.table('users', (table) => {
  table.dropIndex('users_name_age_index')
  table.dropUnique(['a', 'b'])
  table.dropForeign(['user_id']) // users_user_id_foreign
  table.dropPrimary()
  table.renameIndex('old_name', 'new_name')
})

TIP

When you pass columns, Schema.table() looks up the index that covers those columns, so it still works after a renameColumn() left the index under its old generated name. A dry-run blueprint.toSql() cannot look anything up and shows the name derived from the columns.

Dropping tables ​

ts
await schema.drop('users')
await schema.dropIfExists('users')

dropAllTables() and dropAllViews() clear a whole database; they are what migrate:fresh uses.

Conditional changes ​

These helpers run a callback only when the table is in a given state, which keeps a migration safe to re-run.

ts
await schema.whenTableHasColumn('users', 'legacy', (table) => table.dropColumn('legacy'))
await schema.whenTableDoesntHaveColumn('users', 'slug', (table) => table.string('slug').nullable())
await schema.whenTableEmpty('settings', async () => {
  await db.table('settings').insert({ key: 'theme', value: 'light' })
})
await schema.whenTableNotEmpty('users', async () => {
  // backfill
})

Inspecting the schema ​

Schema carries the same read-back methods as SchemaInspector, so a migration can look before it leaps.

ts
await schema.getTables() // [{ name, schema, size, comment }]
await schema.getColumns('users') // [{ name, type, nullable, default, autoIncrement, comment }]
await schema.getColumnListing('users') // => ['id', 'name', ...]
await schema.getColumnType('users', 'name') // => 'VARCHAR'
await schema.getViews()
await schema.hasView('recent')

See Database: Getting Started for the shapes.

Previewing the SQL ​

Because every grammar is a plain class, you can see the SQL a blueprint produces for any dialect without a database. Blueprint.toSql(grammar, mode) returns the statements; mode is 'create' (the default) or 'table' for alterations.

ts
import { Blueprint, MySqlSchemaGrammar, PostgresSchemaGrammar } from '@plinthjs/database'

const table = new Blueprint('flights')
table.id()
table.string('name')
table.timestamps()

table.toSql(new MySqlSchemaGrammar())
// => ['CREATE TABLE `flights` (`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(255) NOT NULL, `created_at` TIMESTAMP NULL, `updated_at` TIMESTAMP NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci']

table.toSql(new PostgresSchemaGrammar())
// => ['CREATE TABLE "flights" ("id" BIGSERIAL PRIMARY KEY, "name" VARCHAR(255) NOT NULL, "created_at" TIMESTAMP, "updated_at" TIMESTAMP)']

SqliteSchemaGrammar, MariaDbSchemaGrammar and SqlServerSchemaGrammar are exported as well.

Running migrations ​

The Migrator runs migrations against a connection. It keeps a ledger in a migrations table (created on first use) holding each migration's name and the batch number it ran in. Every run() call is one batch.

ts
import { sqliteConnection, Migrator, loadMigrations } from '@plinthjs/database'

const db = sqliteConnection()
const migrator = new Migrator(db)

const migrations = await loadMigrations('database/migrations')
// => [{ name: '2024_01_01_000000_create_users_table', migration: <Migration> }, ...]

await migrator.run(migrations)
// => ['2024_01_01_000000_create_users_table', '2024_01_02_000000_add_email_to_users_table']

await migrator.run(migrations) // => [] (nothing pending)

loadMigrations(directory) imports every .ts and .js file in the directory, sorted by filename, and instantiates each default export. A missing directory gives an empty list. Because it uses a plain dynamic import(), loading .ts migrations needs a runtime that can run TypeScript, such as tsx, or Node with type stripping. A migration that does not default-export a Migration subclass throws.

Each migration runs inside its own transaction together with its ledger entry, so a failure leaves the database and the ledger consistent. On engines that cannot roll back schema changes (MySQL, for instance, commits DDL implicitly), a failed migration may be partly applied.

You can also build MigrationEntry values by hand, which is handy in tests:

ts
const entries = [{ name: 'create_users', migration: new CreateUsers() }]
await migrator.run(entries)

Sharing a database with another tool ​

The ledger table is called migrations by default. That is a very common name, and if the database already belongs to another application (a different framework, an older project, a database someone else created), a migrations table may already exist with a different shape. Plinth checks the table before using it, and if it has no name or batch column it stops with a clear message and changes nothing:

text
MigrationsTableError: The "migrations" table already exists in this database but has no "name"
column, so it was not created by Plinth. It most likely belongs to another application that shares
this database. Use a database of its own for this app (DB_DATABASE), or record Plinth migrations in
a different table (DB_MIGRATIONS_TABLE, or the `table` option of Migrator). No data has been changed.

You have two ways out. The cleaner one is a database of its own for the app. If you do have to share one, record Plinth's migrations in a table with a different name:

ts
const migrator = new Migrator(db, { table: 'plinth_migrations' })

The other tool's migrations table is never read or written. In a generated app, set DB_MIGRATIONS_TABLE=plinth_migrations in .env; the migrate, migrate:rollback, migrate:refresh and migrate:status commands all use it. For the packaged commands, pass migrationsTable to migrateCommands(connection, { migrationsTable: 'plinth_migrations' }).

Be careful with migrate:fresh on a shared database: it drops every table in the database, including the other tool's.

Reporting status ​

ts
await migrator.ran() // => names already applied, in order
await migrator.pending(migrations) // => entries not yet applied

await migrator.status(migrations)
// => [{ name: '2024_01_01_000000_create_users_table', batch: 1, ran: true }, ...]

status() follows the order of the list you give it. An entry that has not run has batch: null and ran: false.

Rolling back ​

rollback() undoes the most recent batch by calling each migration's down(), newest first, and removing its ledger entry. It returns the names rolled back.

ts
await migrator.rollback(migrations) // the last batch
await migrator.rollback(migrations, { step: 2 }) // the last two migrations, across batches
await migrator.rollback(migrations, { batch: 1 }) // every migration in batch 1

When step and batch are both given, step wins. Passing a bare number as the second argument is shorthand for { step }. A migration that is in the ledger but missing from the list you pass is skipped.

reset() rolls back every migration, newest first. refresh() resets and then runs everything again, or rolls back only the last step migrations when you set step. fresh() drops every table and runs all migrations from scratch, without calling any down().

ts
await migrator.reset(migrations)
await migrator.refresh(migrations) // reset, then run
await migrator.refresh(migrations, { step: 1 }) // redo only the last migration
await migrator.fresh(migrations) // drop everything, then run

WARNING

fresh() deletes every table in the database, not just the ones your migrations created.

Pretend mode ​

Pass pretend: true to any of these methods to capture the SQL instead of executing it. Nothing is changed, and the ledger is not touched or written to (the dry run contains the migration's own statements, not the ledger's bookkeeping). The methods return the names of the migrations that would have run. To see the SQL itself, listen on the connection first; events for pretended statements carry pretended: true.

ts
const statements: string[] = []
db.listen(({ sql }) => statements.push(sql))

const names = await migrator.run(migrations, { pretend: true })
// names => the migrations that would run
// statements => 'begin', 'CREATE TABLE "users" (...)', 'commit' (plus the real ledger reads that ran first)

pretend is accepted by run, rollback, reset, refresh and fresh.

INFO

A pretended fresh() shows the real table drops, but because nothing is actually dropped, the real ledger survives. The trailing run then only reports migrations that were still pending, not every migration.

The migrate commands ​

@plinthjs/database ships console commands for all of the above. Each is a @plinthjs/console command class. The migrate:* commands need a connection, and the kernel creates commands with a bare constructor, so use the migrateCommands() factory: it returns command classes that already have the connection bound, and you register them as they are.

ts
import { createKernel } from '@plinthjs/console'
import { migrateCommands, sqliteConnection } from '@plinthjs/database'

const db = sqliteConnection()

// migrate, migrate:rollback, migrate:reset, migrate:refresh, migrate:fresh, migrate:status, make:migration
const kernel = createKernel(migrateCommands(db, { migrationsPath: 'src/database/migrations' }))

connection can also be a function that returns the connection (or a promise of it), which is called the first time a command needs it, so the database is only opened when a command runs: migrateCommands(() => app.make(DB)). databaseCommands(connection, options) adds db:seed and make:seeder (see Seeding). Without a bound connection a command exits with an error that names these factories.

You can still bind one class by hand: new MigrateCommand().usingConnection(db), or .usingPath(directory) for the default directory.

CommandOptionsWhat it does
migrate--path=, --pretendrun pending migrations
migrate:rollback--step=, --batch=, --path=, --pretendundo the last batch, or a step or batch count
migrate:status--path=list each migration and whether it has run
migrate:reset--path=, --pretend, --forceroll back every migration
migrate:refresh--step=, --path=, --pretend, --forceroll back, then run again
migrate:fresh--path=, --pretend, --forcedrop all tables, then run all migrations
make:migrationname, --create=, --table=, --path=, --forcewrite a new migration file

--path is the migrations directory, which defaults to database/migrations. The destructive commands (reset, refresh, fresh) ask for confirmation, --force skips the question, and when NODE_ENV is production they refuse to run at all unless you pass --force. With --pretend, a command prints the SQL it would run.

bash
migrate:status
# +--------------------------------------------+----------------+
# | Migration                                  | Batch / Status |
# +--------------------------------------------+----------------+
# | 2024_01_01_000000_create_users_table       | [1] Ran        |
# | 2024_01_02_000000_add_email_to_users_table | Pending        |
# +--------------------------------------------+----------------+

You can also run one in-process, for example from a test, with kernel.call(name, argv):

ts
await kernel.call('migrate', ['--pretend'])
await kernel.call('migrate:fresh', ['--force'])

See Console for the kernel and how commands are built.

In a generated application ​

A scaffolded app does not register the packaged classes. It ships its own commands in src/commands, registered in src/routes/console.ts, which resolve the connection from the container and load migrations from src/database/migrations. Run them through the console entry at the project root:

bash
npx plinth migrate
npx plinth migrate:status
npx plinth migrate:rollback          # undoes the whole last batch
npx plinth migrate:rollback --step=3 # undoes the last three migrations
npx plinth migrate:refresh           # roll everything back, then migrate again
npx plinth migrate:refresh --seed    # ...and then run the database seeder
npx plinth make:migration create_posts_table --create=posts

The generated migrate:rollback behaves like the packaged command and Migrator.rollback(): with no option it undoes the whole last batch, and --step=N undoes the last N migrations. make:migration create_posts_table --create=posts writes the create stub, and make:migration add_slug_to_posts_table --table=posts (without --create) writes the alter stub. The generated app has no migrate:reset or migrate:fresh command; add the packaged ones, or call Migrator.reset() and Migrator.fresh() from your own command.

Testing migrations ​

Run them against an in-memory SQLite connection and assert on the schema:

ts
import { sqliteConnection, Migrator, Schema } from '@plinthjs/database'

const db = sqliteConnection()
await new Migrator(db).run(entries)

const schema = new Schema(db)
await schema.hasTable('users') // => true
await schema.hasColumn('users', 'email') // => true

await new Migrator(db).rollback(entries)
await schema.hasTable('users') // => false

Gotchas ​

  • Always write a real down(). rollback, reset and refresh call it, and a migration that is empty there leaves the schema behind.
  • Migration filenames are the identity of a migration. Renaming a file that has already run makes it look new, and it will run again.
  • A ledger entry whose migration file is no longer present is skipped by rollback and reset.
  • SQLite cannot change() a column. Adding, renaming and dropping columns works.

Released under the MIT License.