Skip to content

Migrations ​

Migrations are version control for your database schema. Each migration is a small TypeScript file that creates or changes tables, and Holo runs them in order so every developer and every server ends up with the same schema.

bash
npx holo make:migration create_posts_table
ts
import { defineMigration } from '@holo-js/db'

export default defineMigration({
  async up({ schema }) {
    await schema.createTable('posts', (table) => {
      table.id()
      table.foreignId('user_id').constrained().cascadeOnDelete()
      table.string('title')
      table.string('slug').unique()
      table.enum('status', ['draft', 'published']).default('draft')
      table.text('body')
      table.timestamp('published_at').nullable()
      table.timestamps()
    })
  },
  async down({ schema }) {
    await schema.dropTable('posts')
  },
})
bash
npx holo migrate

Migrations and model types ​

After each migrate, migrate:rollback, migrate:fresh, and holo build, and when holo dev, holo seed, or holo media:regenerate starts, Holo reads your default connection's database and regenerates the schema file at .holo-js/generated/schema.generated.ts from it. Holo never replays a migration to work out your schema, and it leaves its own tables, such as _holo_migrations, out of the file. Holo writes this file for you; don't edit it.

Your models read their column types from that file. You never repeat column definitions in the model:

ts
import { defineModel } from '@holo-js/db'

export default defineModel('posts', {
  fillable: ['title', 'slug', 'body', 'status', 'user_id'],
})

With the migration above, post.status is typed as 'draft' | 'published', post.published_at as Date | null, and Post.where('...') autocompletes every column name. Columns with a default (or auto-incrementing keys like id) are optional when you create a record. A model's casts set the type of columns the database can't describe, such as JSON in a SQLite text column.

Generating migrations ​

bash
npx holo make:migration create_posts_table

This writes a timestamped file to server/db/migrations, for example 2026_04_26_120000_create_posts_table.ts. The file name is the migration's identity, and migrations run in file-name order.

Holo picks a starting template from the name:

Name patternTemplate
create_posts or create_posts_tableschema.createTable('posts', ...) with id() and timestamps()
add_..._to_posts, remove_..._from_posts, rename_..._on_posts, alter_postsschema.table('posts', ...)
drop_posts or drop_posts_tableschema.dropTable('posts'), with a down that recreates posts with id() and timestamps() for you to fill in
anything elsean empty up and down

Pass a flag to choose the template yourself:

bash
npx holo make:migration create_post_archive --create posts_archive
npx holo make:migration add_reading_time --table posts
FlagEffect
--create <table>Create-table template for <table>
--table <table>Alter-table template for <table>

You can't use --create and --table together.

TIP

npx holo make:model Post --migration creates the model and its create-table migration in one step. See Defining Models.

Migration structure ​

A migration exports defineMigration() with an up function and, usually, a down function that reverses it:

ts
import { defineMigration } from '@holo-js/db'

export default defineMigration({
  async up({ schema }) {
    await schema.table('posts', (table) => {
      table.integer('views').default(0)
    })
  },
  async down({ schema }) {
    await schema.table('posts', (table) => {
      table.dropColumn('views')
    })
  },
})

Both functions receive:

  • schema — the schema builder for tables, columns, indexes, and foreign keys.
  • db — the database connection, for moving or seeding data inside the migration.

Each migration runs inside its own transaction, and Holo records it as run in the same transaction. If up throws, the migration stays pending, so you can fix it and run migrate again. What happens to the changes it already made depends on the database:

  • On PostgreSQL and SQLite, schema changes are transactional, so every change the migration made rolls back.
  • On MySQL, each schema statement such as CREATE TABLE or ALTER TABLE commits at once, as in Laravel. The statements that ran before the failure stay in the database, and running the migration again can fail on them, for example with Duplicate column name. Undo those changes by hand before you run migrate again, or keep each MySQL migration to one schema change.

Changing data in a migration ​

Use db.table() to read or write rows as part of a schema change. It runs in the same transaction as the migration:

ts
import { defineMigration } from '@holo-js/db'

export default defineMigration({
  async up({ schema, db }) {
    await schema.createTable('categories', (table) => {
      table.id()
      table.string('name')
      table.string('slug').unique()
    })

    await db.table('categories').insert({ name: 'General', slug: 'general' })
  },
  async down({ schema }) {
    await schema.dropTable('categories')
  },
})

Running migrations ​

Run every pending migration:

bash
npx holo migrate

Holo records each migration in a _holo_migrations table. All migrations from one migrate run share a batch number, which is what rollback uses.

For PostgreSQL and MySQL, if the database itself doesn't exist yet, migrate creates it before running.

Run only the next few migrations:

bash
npx holo migrate --step 1

Holo never runs migrations when your app starts. Run migrate yourself, in your deploy script or CI.

Isolating migration runs ​

When several replicas run migrate at the same time, add --isolated:

bash
npx holo migrate --isolated

The first run takes an atomic lock named migrations from your application's default cache store and applies the pending migrations. A run that starts while the lock is held skips the migrations, prints a message, and exits successfully, so a deploy step on every replica still passes. The lock is released when the run ends. If a runner stops without releasing it, the lock expires after an hour.

As in Laravel, every server must use the same default cache store, and that store must be shared by all of them. Without a config/cache.ts, the default store is the file store in storage/framework/cache/data, which only coordinates processes that share that folder, so replicas on different servers all run the migrations. Set a redis or database default store when you run more than one server. A memory store only covers the current process. See Which processes a lock covers. When it can't take the lock, migrate --isolated fails before it runs any migration, and the error names the cause:

CauseThe error says
@holo-js/cache isn't installed@holo-js/cache isn't installed.
The default store can't be resolved, such as a missing driver package, driver plugin, or database connectionThe store and its driver can't be resolved, followed by the reason.
A database store whose cache table migration hasn't runThe store's cache tables haven't been migrated. Run npx holo migrate.
A database store with no cache table migrationThe store has no cache tables and no migration creates them. Run npx holo cache:table, then npx holo migrate.
The default store doesn't support locksThe store and its driver can't provide a lock, followed by the reason.
Taking the lock fails, such as when the store's database or Redis server can't be reachedThe store and its driver couldn't take the lock, followed by the error.

The errors for a store that can't be resolved or can't give a lock also tell you to use a default cache store that every server shares, such as database or redis.

A database cache store keeps its locks in a table, so create the cache tables before the first isolated run:

bash
npx holo cache:table
npx holo migrate

A plain migrate doesn't use the cache.

Rolling back ​

Undo the latest batch:

bash
npx holo migrate:rollback
FlagEffect
--step <n>Roll back only the last n migrations of the batch
--batch <n>Roll back batch n instead of the latest one
--forceSkip the production confirmation

Migrations roll back newest first. A migration without down is still marked as not run, but nothing in the database changes.

When APP_ENV is production, migrate:rollback asks you to confirm first.

Starting fresh ​

Drop every table and run all migrations from scratch:

bash
npx holo migrate:fresh

Add --seed to run your seeders afterwards. The seeding flags --only, --quietly, and --force work here too:

bash
npx holo migrate:fresh --seed --only database

When APP_ENV is production, migrate:fresh asks you to confirm first.

WARNING

migrate:fresh drops every table on the connection, including tables Holo didn't create. Never run it against a production database.

Migration API ​

defineMigration() ​

Wraps a migration object and returns it unchanged, so TypeScript checks its shape. Set name only when you need to override the file-name identity; if you do, it must follow the YYYY_MM_DD_HHMMSS_description format.

ts
import { defineMigration } from '@holo-js/db'

export default defineMigration({
  async up({ schema }) {
    await schema.table('posts', (table) => {
      table.string('slug').nullable()
    })
  },
})

MigrationContext ​

The object passed to up() and down(). It has two properties:

  • db: the DatabaseContext for the connection the migration runs on. Use db.table() to read or write rows.
  • schema: the SchemaService described in the next sections.

Schema operations ​

These methods live on schema (the SchemaService) and run immediately inside the migration's transaction.

createTable() ​

Creates a table. Pass a callback that declares its columns, indexes, and foreign keys.

ts
await schema.createTable('tags', (table) => {
  table.id()
  table.string('name').unique()
  table.timestamps()
})

If the table already exists, createTable() leaves it as it is and creates only the declared indexes it lacks, so running the same createTable() again succeeds. A declared index whose name the table already uses for other columns, or with other uniqueness, throws SchemaError.

table() ​

Changes an existing table. The callback receives a builder for adding, changing, renaming, and dropping columns, indexes, and foreign keys.

ts
await schema.table('users', (table) => {
  table.string('nickname').nullable()
  table.index(['nickname'])
})

dropTable() ​

Drops a table.

ts
await schema.dropTable('articles')

renameTable() ​

Renames a table from one name to another. Indexes, unique constraints and foreign keys keep their names, as in Laravel, so drop them by their existing names after a rename. On PostgreSQL, Holo also renames each enum column's <table>_<column>_check constraint to the new table name. SQLite can't rename a constraint, so on SQLite the check constraints keep their names; nothing in Holo drops them by name.

ts
await schema.renameTable('posts', 'articles')

hasTable() ​

Returns true when the table exists on the connection. A schema-qualified name, such as tenant.orders on PostgreSQL or other_database.orders on MySQL, is looked up in that schema, as in Laravel. Views don't count as tables.

ts
if (!(await schema.hasTable('settings'))) {
  await schema.createTable('settings', (table) => {
    table.id()
    table.string('key').unique()
    table.json('value')
  })
}

To check for a column, call getColumns() and search the result.

getTables() ​

Returns the names of every table on the connection, as a string[].

ts
const tables = await schema.getTables()

On PostgreSQL, getTables(), getColumns(), getIndexes() and getForeignKeys() read the schema that unqualified statements use: the connection's schema, which is public by default, or the first existing schema of a search_path that wins over it. Pass a schema-qualified name such as reports.daily_totals to read a table in another schema.

getColumns() ​

Returns the columns of a table. Each entry has name, type (the database's native type), logicalType, notNull, defaultValue, and primaryKey.

ts
const columns = await schema.getColumns('posts')
const hasSlug = columns.some(column => column.name === 'slug')

getIndexes() ​

Returns the indexes of a table. Each entry has name, unique, and columns.

ts
const indexes = await schema.getIndexes('comments')

getForeignKeys() ​

Returns the foreign keys of a table. Each entry has table, from, to, onUpdate, and onDelete.

ts
const foreignKeys = await schema.getForeignKeys('posts')

enableForeignKeyConstraints() ​

Turns foreign key checks on for the connection.

ts
await schema.enableForeignKeyConstraints()

disableForeignKeyConstraints() ​

Turns foreign key checks off for the connection. Call enableForeignKeyConstraints() afterward, or use withoutForeignKeyConstraints().

WARNING

On a connection pool, PostgreSQL and MySQL run each statement on whichever pooled connection is free. These two methods change only the connection that runs them, so the other connections keep their checks. Use withoutForeignKeyConstraints() on a pool.

ts
await schema.disableForeignKeyConstraints()

withoutForeignKeyConstraints() ​

Runs a callback with foreign key checks turned off, then turns them back on, even when the callback throws. Every query in the callback runs on one connection. A query outside that transaction that runs while it is open fails with TransactionError. Await the transaction before running other queries, or run the query inside the transaction.

ts
await schema.withoutForeignKeyConstraints(async () => {
  await schema.dropTable('users')
  await schema.dropTable('teams')
})

getDialectName() ​

Returns the name of the active database dialect, such as 'sqlite', 'postgres', or 'mysql'.

ts
if (schema.getDialectName() === 'sqlite') {
  return
}

Available column types ​

Use these methods inside createTable() callbacks. Inside table() callbacks, the same types add a new column to an existing table. Column names are required unless noted. For UUID, ULID, and Snowflake primary keys, replace id() with a key column and .primaryKey(), for example table.uuid('id').primaryKey(). Holo can generate these IDs for you when you add the matching trait to the model. See Defining Models.

Each method creates these database column types:

MethodSQLitePostgreSQLMySQL
id(), autoIncrementId()INTEGER with AUTOINCREMENTBIGINT GENERATED BY DEFAULT AS IDENTITYBIGINT AUTO_INCREMENT
integer()INTEGERINTEGERINT
bigInteger(), foreignId()INTEGERBIGINTBIGINT
real()REALDOUBLE PRECISIONDOUBLE
decimal()NUMERICNUMERICDECIMAL(10, 2)
string()varchar(255)VARCHAR(255)VARCHAR(255)
text()TEXTTEXTTEXT
enum()TEXT with a CHECK constraintTEXT with a CHECK constraintENUM(...)
boolean()tinyint(1)BOOLEANTINYINT(1)
date()dateDATEDATE
datetime()datetimeTIMESTAMPDATETIME
timestamp()datetimeTIMESTAMPTIMESTAMP
json()textJSONBJSON
blob()BLOBBYTEABLOB
vector()Not supportedVECTOR(n)Not supported
uuid(), foreignUuid()TEXTUUIDCHAR(36)
ulid(), foreignUlid()TEXTVARCHAR(26)CHAR(26)
snowflake(), foreignSnowflake()TEXTVARCHAR(32)VARCHAR(32)

The SQLite types follow Laravel, so schema.getColumns() reports them and SQLite keeps each value's storage class: strings that look like numbers stay strings, and JSON text is stored unchanged. Tables that an earlier Holo version created on SQLite keep the types they were created with, such as TEXT for strings, dates, and JSON and INTEGER for booleans. Their models see those columns as strings and integers until you add casts.

id() ​

Adds an auto-incrementing primary key. It defaults to the name id; pass a name to use another column.

ts
await schema.createTable('posts', (table) => {
  table.id()
})

autoIncrementId() ​

Same as id(). Use it when you want the intent to be explicit.

ts
table.autoIncrementId('post_id')

integer() ​

Adds an integer column.

ts
table.integer('views').default(0)

bigInteger() ​

Adds a big integer column.

ts
table.bigInteger('view_count').default(0)

real() ​

Adds a floating-point column.

ts
table.real('rating').nullable()

decimal() ​

Adds an exact decimal column. It becomes DECIMAL(10, 2) on MySQL and NUMERIC on PostgreSQL and SQLite. The TypeScript type is string.

Models and typed DB.table() queries read the value as a string on every database. MySQL returns two decimal places, and PostgreSQL returns the digits you stored. SQLite stores decimals as floating-point numbers and drops trailing zeros, so on SQLite Holo reads the value back with at least two decimal places, the scale of MySQL's DECIMAL(10, 2): '12.30' reads back as '12.30' and 12 as '12.00', and a value with more places keeps them. A SQLite decimal keeps about 15 significant digits, so a larger value reads back rounded. Raw queries return what the database driver returns, and aggregates such as sum() return a number. On SQLite, a realtime query that reads, groups or orders by a decimal column runs again when its table changes, instead of patching its result.

ts
table.decimal('total')

string() ​

Adds a short text column. It becomes VARCHAR(255) on PostgreSQL and MySQL and varchar(255) on SQLite.

ts
table.string('title')

text() ​

Adds a long text column with no length limit.

ts
table.text('body')

enum() ​

Adds a string column that accepts one of a fixed list of values. The TypeScript type is the union of those values. The database rejects any other value, including values written with raw SQL or by other apps. A nullable enum also accepts NULL.

ts
table.enum('status', ['draft', 'published']).default('draft')
DatabaseColumn typeHow the list is enforced
MySQLENUM('draft', 'published')Native enum type
PostgreSQLTEXTCHECK constraint named <table>_<column>_check, such as posts_status_check
SQLiteTEXTCHECK constraint named <table>_<column>_check

The table part of the name leaves out the schema, so public.posts also gives posts_status_check. A name longer than 63 characters is cut short and ends with a hash, such as <start of name>_1a2b3c4d_check.

To add or remove a value, redeclare the column with the full new list and call change() in a new migration:

ts
await schema.table('posts', (table) => {
  table.enum('status', ['draft', 'published', 'archived']).default('draft').change()
})

On PostgreSQL, change() drops <table>_<column>_check and adds it again with the new list. Changing an enum column to another type, such as string(), drops the constraint, and renaming the table or the column renames it. Holo finds these constraints by reading the database, so this also works for tables created by raw SQL. change() on a column that isn't an enum leaves check constraints alone. On SQLite, change() rebuilds the table with the new constraint. The migration fails, and changes nothing, if existing rows hold a value that isn't in the new list; update those rows first.

boolean() ​

Adds a true or false column. It becomes BOOLEAN on PostgreSQL and TINYINT(1) on MySQL and SQLite. The TypeScript type is boolean.

Models and typed DB.table() queries read the value as true or false on every database. MySQL and SQLite store booleans as 1 and 0, so Holo converts them when it reads a boolean column. Name-only DB.table('name') queries use the same conversion when the table is in the generated schema. Raw queries and tables absent from the generated schema keep the driver's values. sum(), avg(), min() and max() count true as 1 and false as 0.

A boolean column should hold only 1 and 0 (or true and false), which is all Holo writes. Realtime subscriptions read changed rows the same way and keep patching their results. A subscription runs again instead when it reads a table absent from the generated schema, an aggregate over a boolean column, or a read of another value that raw SQL or another program stored.

ts
table.boolean('is_gift').default(false)

date() ​

Adds a date column without a time part.

ts
table.date('published_on').nullable()

On PostgreSQL, a date column reads back as a Date at midnight in app.timezone on the stored day, so the day doesn't change when you save the value again. timestamp columns use app.timezone for their wall-clock time too.

datetime() ​

Adds a date and time column that is not tied to a time zone.

ts
table.datetime('starts_at')

timestamp() ​

Adds a timestamp column. Use it for values such as published_at.

ts
table.timestamp('published_at').nullable()

json() ​

Adds a JSON column. It becomes JSONB on PostgreSQL, JSON on MySQL, and text on SQLite. On PostgreSQL and MySQL, reads return the parsed value. On SQLite the database only knows the column as text, so add a 'json' cast to the model to read and type it as JSON.

ts
table.json('shipping_address').nullable()

blob() ​

Adds a binary column. Reads return a Uint8Array.

ts
table.blob('thumbnail').nullable()

vector() ​

Adds an embedding column with a fixed number of dimensions. It needs the pgvector extension and works only on PostgreSQL. SQLite and MySQL throw a CapabilityError.

ts
await schema.createTable('documents', (table) => {
  table.id()
  table.text('content')
  table.vector('embedding', { dimensions: 1536 })
})

uuid() ​

Adds a UUID column. It becomes UUID on PostgreSQL and CHAR(36) on MySQL.

ts
table.uuid('id').primaryKey()

ulid() ​

Adds a ULID column. It becomes VARCHAR(26) on PostgreSQL and CHAR(26) on MySQL.

ts
table.ulid('public_id').unique()

snowflake() ​

Adds a Snowflake ID column stored as a string.

ts
table.snowflake('external_id').unique()

foreignId() ​

Adds a big-integer column meant to reference another table's id. Chain constrained() to create the foreign key.

ts
table.foreignId('user_id').constrained()

foreignUuid() ​

Adds a UUID column for a foreign key to a UUID primary key.

ts
table.foreignUuid('account_uuid').constrained('accounts', 'uuid')

foreignUlid() ​

Adds a ULID column for a foreign key to a ULID primary key.

ts
table.foreignUlid('ticket_ulid').constrained('tickets', 'ulid')

foreignSnowflake() ​

Adds a Snowflake column for a foreign key to a Snowflake primary key.

ts
table.foreignSnowflake('device_snowflake').constrained('devices', 'snowflake')

Column modifiers ​

Chain these after a column type, for example table.string('email').unique().

notNull() ​

Disallows NULL. Columns are already NOT NULL by default, so you need this mainly to make a change explicit or to reverse nullable().

ts
table.text('bio').notNull()

nullable() ​

Allows NULL. In TypeScript, the value type becomes T | null.

ts
table.timestamp('last_seen_at').nullable()

default() ​

Sets a default value. It accepts a string, number, boolean, null, Date, or a plain object or array, which is stored as JSON.

ts
table.string('role').default('member')
table.json('preferences').default({ theme: 'light' })

On a json() column, a string is JSON text and is written as is, as with Laravel's default(json_encode(...)). Any other value is written as JSON. A string that isn't JSON text raises a SchemaError before any SQL runs, so pass JSON.stringify('hello') for the JSON string "hello". default(null) defaults to SQL NULL.

ts
table.json('tags').default('["new"]')
table.json('label').default(JSON.stringify('hello'))
table.json('retries').default(3)

To default to an SQL expression the database evaluates for each row, pass DB.raw(), as with Laravel's default(DB::raw(...)):

ts
import { DB } from '@holo-js/db'

table.uuid('public_id').default(DB.raw('gen_random_uuid()'))

The expression is raw SQL for your database, so never build it from user input. DB.raw() here takes no bindings; passing any raises a SchemaError. MySQL and SQLite wrap the expression in parentheses, as in DEFAULT (uuid()). On SQLite, adding such a column inside schema.table() rebuilds the table, so existing rows get a value from the expression. MySQL refuses to add a column whose default calls a function such as uuid() to an existing table; add the column nullable, fill it, then make it the default with change(). The Generated schema writes an expression default the database reports, from Holo or from raw SQL, as .default(DB.raw('…')), so it never looks like a string default.

defaultNow() ​

Sets the default to the current time. Use it for timestamp columns that record when a row was created or changed.

ts
table.timestamp('joined_at').defaultNow()

storedAs() ​

Makes a computed column that the database fills in from an SQL expression and stores with the row, written as GENERATED ALWAYS AS (expression) STORED. The expression is raw SQL for your database, so never build it from user input. SQLite, PostgreSQL and MySQL support it.

ts
table.integer('total').storedAs('price * quantity')

A model never writes a computed column. Its Generated schema keeps the column as storedAs() or virtualAs(), so insert and update types leave it out, and writing it through a model, including with increment() or decrement(), throws Column "total" is generated and cannot be written directly. The same holds for computed columns that tables created by raw SQL declare.

As in Laravel, a computed column is nullable on SQLite and MySQL unless you chain notNull(), in either order. On PostgreSQL it is NOT NULL unless you chain nullable(), like any other column. The Generated schema follows the column the database made, so a model types a nullable computed column with null.

ts
table.integer('total').storedAs('price * quantity').notNull()

You can add a storedAs() column with table() to a table that already has rows, and the database computes it for each of them. SQLite can't add a stored column with ALTER TABLE, so Holo rebuilds the table as change() does, keeping its rows, indexes, constraints and triggers.

virtualAs() ​

Makes a computed column that the database works out from an SQL expression when you read the row, written as GENERATED ALWAYS AS (expression) VIRTUAL. SQLite and MySQL support it. PostgreSQL supports it from version 18; on older servers createTable() and table() throw SchemaError and create nothing, so use storedAs() there. They also throw when the server doesn't report its version.

ts
table.string('full_name').virtualAs("first_name || ' ' || last_name")

primaryKey() ​

Makes the column the table's primary key. For a key on several columns, use primary(columns).

ts
table.uuid('id').primaryKey()

unique() ​

Adds a unique constraint on this column, named {table}_{column}_unique. On SQLite, Holo creates a unique index with that name. Holo shortens names longer than 63 bytes with a hash. dropUnique(['column']) finds the constraint whatever its name. Inside createTable(), you can also pass a list of columns and a name to create a composite unique index. See unique(columns).

ts
table.string('email').unique()

If another table already has an index with that name, the migration fails and creates nothing. Drop the constraint with dropUnique().

index() ​

Adds an index on this column. Pass a name to use your own index name; otherwise Holo builds one from the table and column.

ts
table.integer('post_id').index()
table.string('status').index('posts_status_lookup')

references() ​

Sets the column the foreign key points to. The default is id. Use it with on() when the parent key has another name.

ts
table.foreignId('author_id').references('id').on('users')

on() ​

Sets the table the foreign key points to.

ts
table.foreignId('author_id').references('id').on('users')

constrained() ​

Adds a foreign key. With no arguments, Holo infers the table from the column name, so user_id points to users, and uses the id column. Pass a table and column to override both.

ts
table.foreignId('user_id').constrained()
table.foreignId('owner_ref').constrained('accounts', 'account_number')

onDelete() ​

Sets the action when the referenced row is deleted. Use 'cascade', 'restrict', 'set null', or 'no action'. Any other value throws a SchemaError. The shortcuts below do the same thing.

ts
table.foreignId('user_id').constrained().onDelete('cascade')

onUpdate() ​

Sets the action when the referenced key changes. Accepts the same values as onDelete().

ts
table.foreignId('user_id').constrained().onUpdate('cascade')

cascadeOnDelete() ​

Deletes child rows when the parent row is deleted. Same as onDelete('cascade').

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

restrictOnDelete() ​

Blocks deleting a parent row while child rows point to it. Same as onDelete('restrict').

ts
table.foreignId('user_id').constrained().restrictOnDelete()

nullOnDelete() ​

Sets the foreign key to NULL when the parent row is deleted. The column must be nullable. Same as onDelete('set null').

ts
table.foreignId('category_id').nullable().constrained().nullOnDelete()

noActionOnDelete() ​

Rejects the delete without a special action. Same as onDelete('no action').

ts
table.foreignId('user_id').constrained().noActionOnDelete()

cascadeOnUpdate() ​

Updates child rows when the parent key changes. Same as onUpdate('cascade').

ts
table.foreignId('user_id').constrained().cascadeOnUpdate()

restrictOnUpdate() ​

Blocks changing a parent key while child rows point to it. Same as onUpdate('restrict').

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

nullOnUpdate() ​

Sets the foreign key to NULL when the parent key changes. The column must be nullable. Same as onUpdate('set null').

ts
table.foreignId('category_id').nullable().constrained().nullOnUpdate()

noActionOnUpdate() ​

Rejects the update without a special action. Same as onUpdate('no action').

ts
table.foreignId('user_id').constrained().noActionOnUpdate()

change() ​

Changes an existing column instead of adding one. Call it inside table() after redeclaring the column. As in Laravel, the new definition replaces the old one with exactly the modifiers you give: a column that was nullable() or had a default() loses them unless you state them again. Redeclaring an enum() column replaces its list of allowed values.

ts
await schema.table('users', (table) => {
  table.text('bio').nullable().change()
})

The column keeps its primary key, unique constraint and foreign key; change those with their own operations.

On SQLite, Holo rebuilds the table from the database: it reads the table's definition, replaces only the changed column, copies the rows, and restores the table's indexes and triggers. Every other column keeps its stored type, constraints and collation, including columns your migrations never declared, so tables created by raw SQL can be changed too.

On SQLite, the changed column gets the new type, nullability and default, and keeps the rest of its stored definition: its COLLATE clause, its CHECK constraints other than an enum's list of values, and its generated expression, written as GENERATED ALWAYS AS (...) or the shorter AS (...). Holo has no collation modifier, so you can't change a collation with change(). SQLite doesn't allow a default on a generated column, so change() throws SchemaError when you give a generated column a default(). Redeclare the column with storedAs() or virtualAs() to replace its expression, or to turn an ordinary column into a computed one; SQLite works the values out again for every row.

On PostgreSQL, change() throws SchemaError when the column is redeclared with storedAs() or virtualAs(), as in Laravel, because PostgreSQL can't change a generated column's expression. The table() call throws before it runs any of its operations. Drop the column and add it again instead.

On MySQL, change() runs MODIFY COLUMN with the new definition, so the column gets the table's default collation in place of a collation it had. Redeclare a computed column with storedAs() or virtualAs(). Without them, a stored computed column becomes an ordinary column, and MySQL refuses to change a virtual one. MySQL can turn an ordinary column into a computed one with storedAs(), but not with virtualAs().

As in Laravel, the rebuild runs with foreign key checks off, so rows in other tables that reference the rebuilt table are kept, even with ON DELETE CASCADE, and RESTRICT keys don't block it. Holo then checks every foreign key and puts the checks back as they were. If a foreign key would be left pointing at a missing row, change() throws SchemaError and the table is left unchanged. Inside a migration the checks are already off for the whole migration. Inside your own transaction SQLite can't turn them off, so change() throws SchemaError when another table references the rebuilt table; run it outside the transaction or in a migration.

Shortcut columns ​

timestamps() ​

Adds created_at and updated_at, both defaulting to the current time. Available in createTable() and table(), with the same column definitions in both.

ts
await schema.createTable('posts', (table) => {
  table.id()
  table.timestamps()
})

softDeletes() ​

Adds a nullable deleted_at timestamp, or the column name you pass. Available in createTable() and table().

ts
await schema.table('posts', (table) => {
  table.softDeletes()
})

dropTimestamps() ​

Drops created_at and updated_at. Available inside table(). Use it to undo timestamps().

ts
await schema.table('posts', (table) => {
  table.dropTimestamps()
})

dropSoftDeletes() ​

Drops deleted_at, or the column name you pass. Available inside table(). Use it to undo softDeletes().

ts
await schema.table('posts', (table) => {
  table.dropSoftDeletes()
})

morphs() ​

Adds a {name}_type string column and a {name}_id big-integer column, with an index on both. Morph columns back polymorphic relationships.

ts
await schema.createTable('comments', (table) => {
  table.id()
  table.morphs('commentable')
  table.text('body')
  table.timestamps()
})

nullableMorphs() ​

Same as morphs(), with both columns nullable.

ts
table.nullableMorphs('owner')

uuidMorphs() ​

Adds the morph columns with a UUID {name}_id column.

ts
table.uuidMorphs('attachable')

nullableUuidMorphs() ​

Same as uuidMorphs(), with both columns nullable.

ts
table.nullableUuidMorphs('attachable')

ulidMorphs() ​

Adds the morph columns with a ULID {name}_id column.

ts
table.ulidMorphs('ticketable')

nullableUlidMorphs() ​

Same as ulidMorphs(), with both columns nullable.

ts
table.nullableUlidMorphs('ticketable')

snowflakeMorphs() ​

Adds the morph columns with a Snowflake {name}_id column.

ts
table.snowflakeMorphs('reactable')

nullableSnowflakeMorphs() ​

Same as snowflakeMorphs(), with both columns nullable.

ts
table.nullableSnowflakeMorphs('reactable')

Every morph helper accepts an index name as its second argument, for example table.morphs('commentable', 'comments_commentable_lookup').

dropMorphs() ​

Drops the index on the {name}_type and {name}_id columns, or the index name you pass, then both columns. Available inside table(). Use it to undo any of the morph shortcuts above. Holo finds the index by its columns, as dropIndex() does, so it works whatever the index is called. When no index or more than one index covers those columns, dropMorphs() raises an error.

ts
await schema.table('comments', (table) => {
  table.dropMorphs('commentable')
})

Primary keys ​

Mark one column as the key with id() or the primaryKey() modifier, or several columns with the table methods below.

primary(columns) ​

Makes one or more columns the table's primary key. Use it for a pivot table whose rows are unique by a pair of columns. Inside createTable(), declare the columns first.

ts
await schema.createTable('post_tag', (table) => {
  table.foreignId('post_id').constrained('posts')
  table.foreignId('tag_id').constrained('tags')
  table.primary(['post_id', 'tag_id'])
})

Inside table(), primary() adds a key to an existing table that has none. Adding it fails, and changes nothing, when existing rows repeat a key.

The optional second argument names the key on PostgreSQL. Without it, PostgreSQL names the key {table}_pkey. MySQL always names it PRIMARY, and SQLite doesn't name it. On SQLite, primary() inside table() rebuilds the table, the same way change() does.

Models don't support composite primary keys, as in Laravel. Query the table with DB.table() or use it as a belongsToMany pivot. See Primary keys.

dropPrimary() ​

Drops the table's primary key and keeps its rows. Available inside table().

ts
await schema.table('post_tag', (table) => {
  table.dropPrimary()
})

On PostgreSQL, Holo reads the key's name from the database, so dropPrimary() works after renameTable(), when the key keeps its old {table}_pkey name. If you pass a name, it must be the key's name, or dropPrimary() throws SchemaError and changes nothing. MySQL drops the key with DROP PRIMARY KEY, and SQLite rebuilds the table, the same way change() does. MySQL refuses to drop the key of an auto-increment column such as id(). A table without a primary key throws SchemaError.

On MySQL, a foreign key needs an index on its columns, and it uses the primary key when the key starts with those columns. MySQL then refuses to drop the primary key, with Cannot drop index 'PRIMARY': needed in a foreign key constraint, as in Laravel. Drop the foreign key with dropForeign() first.

Indexes ​

Index one column with the index() or unique() modifier, or several columns with the table methods below.

index(columns) ​

Creates an index on one or more columns. Pass a name as the second argument, or let Holo build one.

ts
await schema.createTable('comments', (table) => {
  table.id()
  table.integer('post_id')
  table.string('status')
  table.index(['post_id', 'status'])
})

unique(columns) ​

Creates a unique index on one or more columns. Pass a name as the second argument.

ts
table.unique(['post_id', 'created_at'], 'comments_post_created_unique')

When you don't pass a name, Holo builds one from the table and columns: comments_post_id_index, comments_post_id_status_index, or ..._unique for unique indexes.

On PostgreSQL and SQLite, index names are shared by every table in a schema. If another table already has an index with the name, creating the index fails, as in Laravel, instead of skipping it. This happens after renameTable(), because the renamed table's indexes keep their names: pass a different name to the new table's index. Inside createTable(), the failure rolls back and creates no table. On MySQL, index names belong to their table, so this can't happen.

Upgrading from 0.5.x

Before 0.6.0, on SQLite and PostgreSQL, Holo skipped an index whose name another table already used, so the new table had no such index. Creating it now raises an error, as in Laravel. If a migration that hasn't run yet creates a table under a name you renamed away, give its indexes names of their own.

dropIndex() ​

Drops an index by name, or by its columns. Available inside table(). A name that doesn't exist raises an error and changes nothing.

ts
await schema.table('comments', (table) => {
  table.dropIndex('comments_post_id_status_index')
})

When you pass an array of columns, Holo reads the table from the database and drops the index on exactly those columns, in that order, whatever its name. The first call drops comments_post_id_status_index, and the second drops the index of morphs('commentable'):

ts
await schema.table('comments', (table) => {
  table.dropIndex(['post_id', 'status'])
  table.dropIndex(['commentable_type', 'commentable_id'])
})

When no index covers those columns, Holo raises an error. When more than one does, the error lists their names, and you drop the one you mean by name. Holo never picks one for you.

Laravel builds the conventional name from the columns and drops that name. Holo reads the actual index instead, because the database is the source of truth for the schema. So the same migration works on a database that an earlier release created, on a fresh one, and after renameTable(), where index names keep the old table name. A name you pass is dropped exactly as given. On PostgreSQL, Holo looks for the index in the table's schema, so a schema-qualified table such as tenant.comments works.

A unique() column is backed by a unique constraint on PostgreSQL, and dropIndex() can't drop it. Use dropUnique().

Upgrading from 0.5.x

Before 0.6.0, dropIndex() on SQLite and PostgreSQL did nothing when the name was wrong. A wrong name now raises an error, as in Laravel. If a migration that hasn't run yet drops an index by a guessed name, check the name with getIndexes() first.

dropUnique() ​

Drops a unique constraint or unique index by name, or by its columns. Available inside table(). A name that doesn't exist raises an error.

ts
await schema.table('users', (table) => {
  table.dropUnique('users_email_unique')
})

When you pass an array of columns, Holo reads the table from the database and drops the unique constraint or unique index on exactly those columns, whatever its name, as dropIndex() does. On a table created by this release, this call drops users_team_id_slug_unique:

ts
await schema.table('users', (table) => {
  table.dropUnique(['team_id', 'slug'])
})

When no unique covers those columns, Holo raises an error. When more than one does, the error lists their names, and you drop the one you mean by name.

On MySQL, a foreign key uses a unique index that starts with its columns as its own index. MySQL then refuses to drop that unique, with Cannot drop index '...': needed in a foreign key constraint, as in Laravel. Drop the foreign key with dropForeign() first. To keep the foreign key, add an index on its columns in an earlier table() call, so the foreign key uses that index instead.

Holo versions before 0.6.0 created unique() columns with an inline UNIQUE, so the database chose the name: {table}_{column}_key on PostgreSQL, {column} on MySQL, and sqlite_autoindex_{table}_{n} on SQLite. A fresh database, such as the one migrate:fresh or CI creates, names the same unique {table}_{column}_unique. Drop it by its columns, so the migration works on both:

ts
await schema.table('tenants', (table) => {
  table.dropUnique(['owner_email'])
})

SQLite can't drop its own sqlite_autoindex_* index, so Holo rebuilds the table without the unique, as it does for change().

renameIndex() ​

Renames an index. Available inside table(). On PostgreSQL, Holo looks for the index in the table's schema. SQLite can't rename an index, so Holo reads the index's columns and uniqueness from the database, then drops it and creates it under the new name in one transaction, as Laravel does. SQLite partial and expression indexes can't be recreated that way, so Holo refuses to rename them; drop the index and create it again with raw SQL.

ts
await schema.table('comments', (table) => {
  table.renameIndex('comments_post_id_index', 'comments_post_lookup')
})

Index names must be 63 bytes or shorter. Holo rejects longer names so your migrations stay portable to PostgreSQL. If a generated name is too long, pass a shorter one.

Foreign keys ​

foreignId() adds a big-integer column, and constrained() points it at another table. Use the matching type helper when the parent key isn't an integer:

ts
await schema.createTable('posts', (table) => {
  table.id()
  table.foreignId('user_id').constrained()
  table.foreignId('category_id').nullable().constrained().nullOnDelete()
  table.foreignUuid('account_uuid').constrained('accounts', 'uuid')
})

foreign(column) ​

Adds a foreign key to an existing column. Chain references(), on(), or constrained() and an action shortcut. Pass a constraint name as the second argument to use it instead of the default name.

ts
await schema.createTable('post_tags', (table) => {
  table.bigInteger('post_id')
  table.bigInteger('tag_id')
  table.foreign('post_id').references('id').on('posts').cascadeOnDelete()
  table.foreign('tag_id', 'post_tags_tag_fk').references('id').on('tags').cascadeOnDelete()
})

Holo names foreign keys {table}_{column}_foreign by default. The post_tags example names its foreign keys post_tags_post_id_foreign and post_tags_tag_fk.

The column must have the same type as the key it references. id() is a big integer, so reference it from a bigInteger() or foreignId() column. MySQL refuses a foreign key from an integer() column to an id() column.

Inside table(), foreign() and foreignId().constrained() add the key to an existing table. SQLite can't add a foreign key to an existing table, so Holo rebuilds the table with the new key, as Laravel does. The rebuild keeps every other column, index, trigger and foreign key, and the rows of tables that reference it, as for change(). Existing rows that break the new key make it fail and leave the table unchanged.

dropForeign() ​

Drops a foreign key by its constraint name, or by its columns. Available inside table(). On SQLite, Holo rebuilds the table without the key, as for change().

ts
await schema.table('posts', (table) => {
  table.dropForeign('posts_user_id_foreign')
})

When you pass an array of columns, Holo reads the table from the database and drops the key on exactly those columns, whatever its name, as dropIndex() does. On a table created by this release, this call drops posts_user_id_foreign:

ts
await schema.table('posts', (table) => {
  table.dropForeign(['user_id'])
})

Dropping a foreign key that doesn't exist fails. When more than one key covers those columns, the error lists their names, and you drop the one you mean by name.

Holo versions before 0.6.0 created foreign keys declared inside createTable() or added through a new column without a constraint name, so PostgreSQL named them {table}_{column}_fkey and SQLite left them unnamed. A fresh database names the same key {table}_{column}_foreign. Drop it by its columns, so the migration works on both.

dropConstrainedForeignId() ​

Drops the foreign key on the column, whatever its name, then the column. Available inside table(). Holo finds the key as dropForeign([column]) does. Use it to undo foreignId().constrained(). MySQL refuses dropColumn() on a column that a foreign key uses.

ts
await schema.table('posts', (table) => {
  table.dropConstrainedForeignId('user_id')
})

Column changes and renames ​

dropColumn() ​

Drops a column, or every column in a list. Available inside table(). On PostgreSQL, dropping a column also drops its indexes and constraints. SQLite and MySQL refuse to drop some columns and raise their own error, which leaves the table unchanged:

  • SQLite refuses a column that an index, a unique constraint, the primary key or a foreign key uses. Drop the index or unique first, or use dropConstrainedForeignId() for a foreign key.
  • MySQL refuses a column that a foreign key uses.
ts
await schema.table('users', (table) => {
  table.dropColumn('legacy_flags')
  table.dropColumn(['legacy_notes', 'legacy_score'])
})

renameColumn() ​

Renames a column. Available inside table(). Indexes, unique constraints and foreign keys on the column keep their names, and the database updates them to the new column name. On SQLite, an enum column's <table>_<column>_check constraint keeps its old name and keeps enforcing the allowed values.

ts
await schema.table('users', (table) => {
  table.renameColumn('nickname', 'display_name')
})

SQLite table rebuilds

On SQLite, schema.table() can add, change, rename and drop columns, add, drop and rename indexes, and add and drop primary and foreign keys. Changing a column, adding or dropping a primary or foreign key, and dropping a unique that SQLite created inline rebuild the table, as described under change().

Command reference ​

CommandFlags
npx holo make:migration <name>--create <table>, --table <table>
npx holo migrate--step <n>, --isolated
npx holo migrate:rollback--step <n>, --batch <n>, --force
npx holo migrate:fresh--seed, --only <names>, --quietly, --force

Next steps ​

Released under the MIT License.