Migrations

Versioned schema changes with rollback.

1 min readEdit this page

Migration file

// src/migrations/001_create_users.ts
import { Migration } from '@restjs/orm'
 
const migration: Migration = {
  async up(db) {
    await db.query(`
      CREATE TABLE users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) UNIQUE NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `)
  },
  async down(db) {
    await db.query('DROP TABLE IF EXISTS users')
  }
}
 
module.exports = migration

Run

import { MigrationRunner } from '@restjs/orm'
const runner = new MigrationRunner(db.getDriver())
 
await runner.up()
await runner.down()
await runner.status()

Note

Each migration runs in a transaction. Failures roll back automatically.