Skip to main content

Migrations

Migrations allow you to version and evolve your database schema safely.

Creating a Migration

Create a migration file in your migrations directory:

import { Migration } from 'hysteria-orm';

export default class extends Migration {
async up() {
this.schema.createTable('users', (table) => {
table.bigSerial('id').primary();
table.string('name');
table.string('email').unique();
table.integer('age');
table.boolean('is_active');
table.timestamp('created_at');
table.timestamp('updated_at');
});
}

async down() {
this.schema.dropTable('users');
}
}

Running Migrations

In order to run typescript migrations, you need have typescript package installed. It's advised to install typescript as a dev dependency and to use typescript migrations only in development. Run migrations using the CLI or programmatically:

npx hysteria run:migrations
yarn hysteria run:migrations

Rolling Back

npx hysteria rollback:migrations
yarn hysteria rollback:migrations

Schema Builder API

  • createTable, alterTable, dropTable, renameTable, truncateTable
  • Column types: string, integer, bigSerial, boolean, date, jsonb, enum, etc.
  • Constraints: primary, unique, references, notNullable, default, etc.

API Reference

createTable

Create a new table with columns and constraints.

schema.createTable('users', (table) => {
table.bigSerial('id').primary();
table.string('email').unique();
});
  • table (string): Table name
  • cb (function): Callback to define columns
  • options.ifNotExists (boolean, optional): Only create if not exists

alterTable

Alter an existing table (add/drop/modify columns).

schema.alterTable('users', (table) => {
table.addColumn('age', 'integer', {
notNullable: true,
// other options
});
});
  • table (string): Table name
  • cb (function): Callback to define alterations

dropTable

Drop a table.

schema.dropTable('users');
  • table (string): Table name
  • ifExists (boolean, optional): Only drop if exists

renameTable

Rename a table.

schema.renameTable('old_users', 'users');
  • oldtable (string): Current table name
  • newtable (string): New table name

truncateTable

Remove all rows from a table.

schema.truncateTable('users');
  • table (string): Table name

unique

Add a unique constraint to columns.

schema.unique('users', ['email']);
  • table (string): Table name
  • columns (string[]): Column names
  • constraintName (string, optional): Custom constraint name

Best Practices

  • Use one migration per schema change.
  • Always provide a down method.
  • Test migrations in CI.

Next: Programmatic Migrations