Sources/App/Migrations
.
Migration
protocol and is implemented by filling out the up
and down
functions. up
is run when a migration is applied to a database. down
is run when a migration is rolled back.
up
and down
are passed a Schema
object representing the schema of the database to which this migration will be applied. The database schema is modified via functions on Schema
.
For example, this migration renames the user_todos
table to todos
. Notice the down
function does the reverse. You don’t have to fill out the down function of a migration, but it may be useful for rolling back the operation later.
Schema
has a variety of useful builder methods for doing various database migrations.
Schema.create(table: String, builder: (inout CreateTableBuilder) -> Void)
.
The CreateTableBuilder
comes packed with a variety of functions for adding columns of various types & modifiers to the new table.
.string()
or .int()
. These define a named column of the given type and return a column builder for adding modifiers to the column.
Supported builder functions for adding columns are
Table Builder Functions | Column Builder Functions |
---|---|
.uuid(_ column: String) | .default(expression: String) |
.int(_ column: String) | .default(val: String) |
.string(_ column: String) | .notNull() |
.increments(_ column: String) | .unique() |
.double(_ column: String) | .primary() |
.bool(_ column: String) | .references(_ column: String, on table: String) |
.date(_ column: String) | |
.json(_ column: String) |
.addIndex
. They can be on a single column or multiple columns and can be defined as unique or not.
users_email_key
.
alter(table: String, builder: (inout AlterTableBuilder) -> Void)
.
AlterTableBuilder
has the exact same interface as CreateTableBuilder
with a few extra functions for dropping columns, dropping indexes, and renaming columns.
Database.default
. You can should do this in your Application.boot
function.
migrate
argument to your app. This will cause the app to migrate Database.default
instead of serving.
--rollback
flag to instead rollback the latest batch of migrations.
--migrate
flag when running your server to automatically run outstanding migrations before serving.
migrations
table. You can delete this table to clear all records of migrations.