std.db

Applying ordered SQL-file migrations.

Importuse std.db

Functions

async fn run(pool: SqlPool, directory: string, on_apply: fn(string) -> void) -> Result<int, Error>async#

Applies every migration in directory that has not run yet, reporting each filename to on_apply as it starts. Answers how many were applied.

  • pool: Connection pool the migrations run through.
  • directory: Directory holding the *.sql migrations.
  • on_apply: Called with each filename as that migration starts.
use std.sql.SqlPool

async fn migrate(pool: SqlPool) -> Result<int, Error> {
  await std.db.run(pool, "internal/migrations", |name| println("applying " + name))
}
fn migration_files(directory: string) -> [string]#

migrationFiles: *.sql sorted by name.

  • directory: Directory to list *.sql from.
// Migration files are applied in lexical filename order.
let files = std.db.migration_files("internal/migrations")
println(files)
println(std.db.default_directory())
fn default_directory() -> string#

Resolves the migrations directory: MIGRATIONS_DIR when set, else the conventional locations beside a service — internal/migrations under the project or beside it. A service that keeps its SQL anywhere else passes the directory to run and never calls this.

fn split_statements(text: string) -> [string]#

Splits a migration file into statements. Semicolons inside string literals, quoted identifiers, dollar-quoted bodies, and comments do not end a statement.

  • text: The migration file to divide at top-level semicolons.
let sql = "CREATE TABLE notes (body text); INSERT INTO notes VALUES ('a;b');"
let statements = std.db.split_statements(sql)
println(statements.len()) // 2