KScript docs
EN

Databases: KScript.Data

Migrations

Introduction to migrations

$db->create_table() is enough for a script. A project whose tables already hold rows changes them with migrations instead. Each migration is a file in database/migrations (paths.migrations in kscript.json) that says, step by step, how the tables change.

You don't usually write migrations yourself. Change your models, then let kscript db diff write the migration that takes the tables from where the migrations leave them to what the models want:

CommandWhat it does
kscript db diffWrite a migration from the changes to your models.
kscript db diff add_bioThe same, named add_bio.
kscript db diff --pretendPrint the migration instead of writing it.
kscript db migrateRun the migrations that haven't run.

A migration it writes looks like this:

<!-- Written by kscript db diff from the models. -->
<KScript.Migration>
  <CreateTable name="users">
    <Field name="id" type="int" key="yes" auto="yes" />
    <Field name="name" type="string" max="80" />
    <Field name="email" type="email" />
    <Field name="role" type="enum" values="member, admin" default="'member'" />
    <Index columns="email" unique="yes" />
  </CreateTable>
  <AddField table="posts" name="views" type="int" default="0" />
</KScript.Migration>
// Written by kscript db diff from the models.
import KScript.Data

Migration {
  CreateTable(name: 'users') {
    Field(name: 'id', type: int, key, auto)
    Field(name: 'name', type: string, max: 80)
    Field(name: 'email', type: email)
    Field(name: 'role', type: enum, values: [member, admin], default: 'member')
    Index(columns: [email], unique)
  }
  AddField(table: 'posts', name: 'views', type: int, default: 0)
}

When a table or column has gone and another has appeared, diff asks whether it was renamed, so a rename keeps its rows instead of dropping them. Where it can't ask, such as in CI or with its input piped in, it assumes no, drops and adds, and warns about each one. You should always read a migration before you run it.

To write a migration by hand, kscript make migration add_bio_to_users gives you an empty one to fill in.

Migration steps

Migration steps call a table's columns fields, as models do.

CreateTable(name:) { ... } makes a table, with a Field for each column and an Index for each index. A key made of two columns, such as a pivot table's, is Key(columns: [a, b]). DropTable(name:) drops a table and its rows, and RenameTable(from:, to:) renames one. Foreign keys that point to a renamed table follow it.

AddField(table:, name:, type:, ...) adds a field. A required field needs a default: when the table has rows. DropField(table:, name:) drops a field and its indexes, and RenameField(table:, from:, to:) renames one, keeping its values. ChangeField(table:, name:, type:, ...) changes a field to match what you describe: its type, whether it's optional, its default or what it references. The rows are kept.

AddIndex(table:, columns:) adds an index, with unique for a unique one, and DropIndex(...) drops it.

A field's type: is one of string, int, number, bool, date, email, handle, uuid, password, json or enum (with values:), each stored the way a model's field of that type is. max: gives a string a length, optional lets it be empty, and default: is what the database fills in. The key and auto flags make a numbered key, and references: (with references_column: and on_delete:) makes a foreign key, like a model's relation field.

For anything the other steps can't do, Sql(up:, down:) runs SQL as it is.

Moving data in a migration

When a change to the tables needs the rows moved too, put the code that moves them in a Run { ... } block. It runs at its place among the steps, so it sees the tables and fields made above it, and the steps below it wait until it's done:

<KScript.Migration>
  <AddField table="posts" name="user_id" type="int" references="users" optional="yes" />
  <Run>
    <for each="post" in="@db('posts')->get()">
      <do>@db('posts')->where(id: $post.id)->update(user_id: $post.owner->replace('user:', '')->to_int())</do>
    </for>
  </Run>
  <DropField table="posts" name="owner" />
  <Down>
    <AddField table="posts" name="owner" type="string" optional="yes" />
    <Run>
      <for each="post" in="@db('posts')->get()">
        <do>@db('posts')->where(id: $post.id)->update(owner: "user:{ $post.user_id }")</do>
      </for>
    </Run>
    <DropField table="posts" name="user_id" />
  </Down>
</KScript.Migration>
import KScript.Data

Migration {
  AddField(table: 'posts', name: 'user_id', type: int, references: 'users', optional)
  Run {
    for post in @db('posts')->get() {
      @db('posts')->where(id: $post.id)->update(user_id: $post.owner->replace('user:', '')->to_int())
    }
  }
  DropField(table: 'posts', name: 'owner')
  Down {
    AddField(table: 'posts', name: 'owner', type: string, optional)
    Run {
      for post in @db('posts')->get() {
        @db('posts')->where(id: $post.id)->update(owner: "user:{ $post.user_id }")
      }
    }
    DropField(table: 'posts', name: 'user_id')
  }
}

A Run block may use anything a script can, such as @read_json() to read rows from files or a model's ->create(). Its queries run in the migration's transaction, so when it fails the migration's other steps are undone with it.

Migration { } and Down { } hold only steps, and CreateTable { } holds only its Field, Index and Key lines. Any other code there, such as @db('posts')->update(...) or a variable, is an error that points you to Run, and the editor suggests only the steps that fit where you're typing. That's because kscript reads a migration's steps before any of them run, and for db status and db diff too, so code beside them would run at the wrong time.

Rollback can't know what a Run block did, so a migration with one needs a Down { ... } block to be undone.

Every step is checked against the tables the earlier migrations make before anything runs. Dropping a table that isn't there, adding a column twice, or pointing at a column that isn't a key tells you which migration and what's wrong, with the closest name when it looks like a typo.

Running and rolling back

CommandWhat it does
kscript db migrateRun what hasn't run, as one batch.
kscript db migrate --pretendPrint the SQL instead of running it.
kscript db rollbackUndo the last batch.
kscript db rollback --steps 2Undo the last two migrations.
kscript db statusShow what has run, and what the models want that no migration makes.
kscript db freshDrop every table and run every migration again.
kscript db fresh --pretendName the tables it would drop and print the SQL, changing nothing.

On SQLite and Postgres, each migration runs in a transaction, so one that fails changes nothing. MySQL and MariaDB commit each change to a table as it's made, so a migration that fails there stops where it failed. The error says how many of its steps ran, and the migration isn't marked as run.

Rolling back undoes each step the other way round. A created table is dropped, an added column is dropped, and a dropped table or column comes back as it was, empty. A Sql step needs its down: for that, and a Run block needs a Down block. When you'd rather say the steps yourself, add a Down { ... } block, and rollback runs that block instead. The migrations that have run are recorded in the kscript_migrations table, with the batch each ran in.

In the production environment (kscript db --env production, or KSCRIPT_ENV=production), migrate, rollback and seed ask before they start, and fresh won't run without --force.

diff and status see the models on the default connection, in the models folder and inside components. Models on another connection, and changes made by a Sql step, are left out, so after a Sql step that changes a table, diff may suggest changing it back.

Seeders

A seeder is a script in database/seeders (paths.seeders) that fills the database with records for development and tests:

<import package="KScript.Data" />
<import path="../../models/user.kscript" />

<do>User->create(name: 'Ada', email: 'ada@example.com')</do>
import KScript.Data
import "../../models/user.kscript"

User->create(name: 'Ada', email: 'ada@example.com')

kscript db seed runs every seeder in name order, and kscript db seed users runs one. kscript db migrate --seed and kscript db fresh --seed run them after migrating. kscript make seeder users writes a new one.