English
Writing migrations
This guide covers writing a migration:
- How migrations run
- Config wiring
- File naming
- Writing a migration
- Schema builder API
- Indexes
- Dialect support
- Complete example
- Migration tracking
Atlas tracks schema changes through migration files. Each migration is a TypeScript class that describes how to apply (up) and reverse (down) a set of database changes using a fluent schema builder API.
How migrations run
Booting the application does not migrate it. Migrations run when you run ream migration:run, which:
- Creates the
ream_migrationstracking table in the database if it does not already exist. - Reads all
.ts/.jsfiles in the migrations directory (migrations.path), sorted by name. - Skips any file whose name already appears in
ream_migrations. - Calls
up()on each pending migration and records its name inream_migrations, under a new batch number.
Rolling back is never automatic: ream migration:rollback calls down() on the latest batch.
A host that owns its database alone (a container that starts once, an embedded app on a file database) can ask AtlasProvider to run pending migrations at boot with migrations: { autoRun: true }. The option is off by default, and it is ignored in development (REAM_ENV, or else NODE_ENV, set to development, develop or dev). See When migrations run.
Config wiring
typescript
// config/database.ts
import app from '@c9up/ream/services/app'
export default {
client: 'sqlite' as const,
connection: {
filename: app.makePath('data', 'app.db'),
},
migrations: {
path: app.migrationsPath(),
},
}File naming
Name migration files with a zero-padded numeric prefix so they sort and run in the correct order:
database/migrations/
001_create_users.ts
002_create_posts.ts
003_create_comments.tsWriting a migration
Extend Migration from @c9up/atlas and implement up() and down(). The this.schema property gives you access to the full schema builder API.
typescript
import { Migration } from '@c9up/atlas'
export default class CreateUsers extends Migration {
up() {
this.schema.createTable('users', (t) => {
t.uuid('id').primary()
t.string('email', 255).notNullable().unique()
t.string('first_name', 100).notNullable()
t.string('last_name', 100).notNullable()
t.string('phone', 30).nullable()
t.string('password_hash', 255).notNullable()
t.timestamps()
})
}
down() {
this.schema.dropTable('users')
}
}A second migration that references the first:
typescript
import { Migration } from '@c9up/atlas'
export default class CreatePosts extends Migration {
up() {
this.schema.createTable('posts', (t) => {
t.uuid('id').primary()
t.uuid('user_id').notNullable().references('users', 'id')
t.string('title', 255).notNullable()
t.text('body').notNullable()
t.boolean('published').notNullable().defaultTo(false)
t.timestamps()
})
}
down() {
this.schema.dropTable('posts')
}
}Schema builder API
Table operations
| Method | Description |
|---|---|
schema.createTable(name, callback) | Create a new table. The callback receives a TableBuilder. |
schema.dropTable(name) | Drop the table (generates DROP TABLE IF EXISTS). |
schema.createIndex(table, columns, name?, unique?) | Create a standalone index. |
schema.dropIndex(name) | Drop an index. |
schema.raw(sql) | Append a raw SQL statement to the current migration. |
Column types
All column methods are called on the TableBuilder instance passed to the createTable callback. Every method returns this so modifiers can be chained.
| Method | SQL type (Postgres / SQLite) |
|---|---|
id() | Shortcut: uuid('id').primary().defaultTo(db.raw('gen_random_uuid()')) |
uuid(name) | UUID / TEXT |
string(name, length?) | VARCHAR(n) / TEXT — default length 255 |
text(name) | TEXT / TEXT |
integer(name) | INTEGER / INTEGER |
bigInteger(name) | BIGINT / INTEGER |
decimal(name, precision?, scale?) | DECIMAL(p, s) / REAL — defaults 10, 2 |
boolean(name) | BOOLEAN / INTEGER |
date(name) | DATE / TEXT |
timestamp(name) | TIMESTAMP / TEXT |
timestamps() | Shortcut: created_at + updated_at both NOT NULL DEFAULT CURRENT_TIMESTAMP |
json(name) | JSON / TEXT |
jsonb(name) | JSONB / TEXT |
binary(name) | BYTEA / BLOB |
Column modifiers
Modifiers apply to the column defined by the most recent column call.
| Modifier | Effect |
|---|---|
.primary() | Marks the column as PRIMARY KEY |
.notNullable() | Adds NOT NULL constraint |
.nullable() | Removes NOT NULL (columns are nullable by default) |
.unique() | Adds UNIQUE constraint |
.defaultTo(value) | Sets a column default — JS literals are quoted, SQL expressions use raw() |
.references(table, column?) | Adds a foreign key reference — column defaults to 'id' |
Column defaults
defaultTo() distinguishes literals from expressions: a JavaScript literal is quoted/escaped for you, and a SQL expression comes from this.now() (timestamps) or db.raw(...) (Database.raw / db.raw).
typescript
import db from '@c9up/atlas/services/db'
// Literals — quoted automatically
t.text('role').notNullable().defaultTo('member') // → DEFAULT 'member'
t.integer('count').notNullable().defaultTo(0) // → DEFAULT 0
t.boolean('active').notNullable().defaultTo(true) // → DEFAULT true
// SQL expressions — this.now() for timestamps, db.raw() for any other function
t.timestamp('created_at').notNullable().defaultTo(this.now()) // NOW() / CURRENT_TIMESTAMP
t.uuid('id').primary().defaultTo(db.raw('gen_random_uuid()'))Do not quote by hand
defaultTo() quotes a string itself, so a hand-quoted literal keeps its quotes: defaultTo("'member'") stores the characters 'member', quotes included. A SQL function passed as a string is a literal too: defaultTo('NOW()') stores the text NOW(). Pass literals bare and expressions through this.now() / db.raw(...); db.raw() returns a RawSql (the same raw type used in queries).
Indexes
Add indexes inside createTable:
typescript
this.schema.createTable('memberships', (t) => {
t.uuid('id').primary()
t.uuid('user_id').notNullable().references('users')
t.uuid('residence_id').notNullable().references('residences')
t.index('user_id') // single column
t.index(['user_id', 'residence_id']) // composite
t.uniqueIndex('email') // unique
t.index('status', 'idx_custom_name') // custom name
})Or as standalone operations:
typescript
this.schema.createIndex('orders', ['user_id', 'status'])
this.schema.dropIndex('idx_orders_status')Dialect support
The same migration code works across PostgreSQL, SQLite, MySQL, and MariaDB. The dialect is determined by config/database.ts:
typescript
export default {
client: 'mysql', // 'postgres' | 'sqlite' | 'mysql' | 'mariadb'
// ...
}See Atlas — Dialect System for details.
Complete example
typescript
import { Migration } from '@c9up/atlas'
export default class CreateMemberships extends Migration {
up() {
this.schema.createTable('memberships', (t) => {
t.uuid('id').primary()
t.uuid('user_id').notNullable().references('users', 'id')
t.uuid('residence_id').notNullable().references('residences', 'id')
t.string('role', 50).notNullable().defaultTo('member')
t.boolean('active').notNullable().defaultTo(true)
t.json('permissions').nullable()
t.timestamps()
})
}
down() {
this.schema.dropTable('memberships')
}
}Migration tracking
Atlas records which files have been applied in a ream_migrations table (renamed with migrations.tableName). It has four columns:
| Column | Content |
|---|---|
id | Auto-increment primary key |
name | The file name without extension (e.g. 001_create_users), unique |
batch | The run that applied it; migration:rollback undoes the latest batch |
executed_at | Timestamp, defaults to CURRENT_TIMESTAMP |
A migration is skipped on the next migration:run if its name already exists in this table. A second table, ream_migrations_lock, holds the lock that stops two runs from migrating the same database at once.
Next steps
- Atlas (ORM) — entities, repositories, and the query builder
- Configuration — wiring the database config
- Providers — how
AtlasProviderfits into the boot lifecycle