erlang_migrate (erlang_migrate v0.3.1)

View Source

erlang_migrate — database migration library modeled after golang-migrate/v4.

Quick Start

  Config = #{
      conn  => Conn,           % epgsql connection pid
      dir   => "priv/migrations",
      table => <<"schema_migrations">>,  % optional
      lock_id => 7369284       % optional, auto-derived from table name
  },
  ok = erlang_migrate:up(Config).

File naming

Migrations live in dir as pairs: {version}_{title}.up.sql {version}_{title}.down.sql (optional — skipping makes down/2 fail)

version must be a positive integer, e.g. 1, 100, 20240101120000.

GracefulStop

Send erlang_migrate_abort to the migration process to abort between migrations: MigPid ! erlang_migrate_abort

dry_run mode

Set dry_run => true in Config to log what would be applied without touching the database. dry_run also bypasses strict-mode bookkeeping.

strict mode (out-of-order detection)

Set strict => true to record every applied migration in a Table_history table (one row per version). up/1,2 then fails with {error, {out_of_order, Versions}} if a file's version is at or below current but was never applied — e.g. a timestamp-versioned migration merged late from another branch, which would otherwise be silently skipped forever. Recovery: re-timestamp the late file to a fresh version, or run force/2 to rebuild the history after applying it manually. Requires a driver exporting applied_versions/2 (pg/mysql/sqlite all do).

Summary

Functions

create(Dir, Title)

-spec create(Dir :: file:filename(), Title :: iodata()) ->
                {ok, file:filename(), file:filename()} | {error, term()}.

down(Config)

-spec down(Config :: map()) -> ok | {error, term()}.

down(Config, Steps)

-spec down(Config :: map(), Steps :: pos_integer() | all) -> ok | {error, term()}.

drop(Config)

-spec drop(Config :: map()) -> ok | {error, term()}.

force(Config, Version)

-spec force(Config :: map(), Version :: integer() | undefined) -> ok | {error, term()}.

goto(Config, Version)

-spec goto(Config :: map(), Version :: integer()) -> ok | {error, term()}.

up(Config)

-spec up(Config :: map()) -> ok | {error, term()}.

up(Config, Steps)

-spec up(Config :: map(), Steps :: pos_integer() | all) -> ok | {error, term()}.

version(Config)

-spec version(Config :: map()) -> {ok, integer() | undefined, boolean()} | {error, term()}.