Sourced.EventStore.Postgres.Migrations (sourced_postgres v0.3.0)

Copy Markdown View Source

Migrations creating and upgrading the tables, triggers and functions the event store reads and writes.

The schema is versioned. Each version is one step, and up/1 runs every step between the version the database is at and the one asked for, so a fresh install and an upgrade delegate to the same function and an upgrade runs only what the install is missing.

Generate a migration in the host application and delegate to this module:

defmodule MyApp.Repo.Migrations.AddSourced do
  use Ecto.Migration

  def up, do: Sourced.EventStore.Postgres.Migrations.up()
  def down, do: Sourced.EventStore.Postgres.Migrations.down()
end

up/1 migrates to the latest version by default and down/1 reverts everything. When a release adds a version, upgrade an existing install with a second migration pinned to it:

defmodule MyApp.Repo.Migrations.UpgradeSourcedToV2 do
  use Ecto.Migration

  def up, do: Sourced.EventStore.Postgres.Migrations.up(version: 2)
  def down, do: Sourced.EventStore.Postgres.Migrations.down(version: 2)
end

down(version: 2) reverts version 2 and anything above it, leaving the database at version 1, so the pair above is one clean step in either direction. Pinning up matters too: a migration that always went to the latest would do different things depending on which release ran it.

Versions

  • 1 — sourced_events and sourced_event_tags, their indexes and triggers, and the read watermark functions. What every 0.1.x and 0.2.x release created.
  • 2 — sourced_checkpoints, for Sourced.EventStore.Postgres.Subscriber.

The version is recorded as a comment on sourced_events. A database migrated by a release before versioning has the tables and no comment, and is read as version 1.

Summary

Functions

Reverts :version and every version above it, leaving the database at the one below. Defaults to version 1, which reverts everything. A no-op when the database is already below :version.

The version the database behind repo is migrated to, 0 before the first migration has run.

Migrates the database up to :version, the latest by default, running each version it is missing in order. A no-op when it is already there.

Types

opts()

@type opts() :: [{:version, pos_integer()}]

Functions

down(opts \\ [])

@spec down(opts()) :: :ok

Reverts :version and every version above it, leaving the database at the one below. Defaults to version 1, which reverts everything. A no-op when the database is already below :version.

migrated_version(repo)

@spec migrated_version(repo :: module()) :: non_neg_integer()

The version the database behind repo is migrated to, 0 before the first migration has run.

up(opts \\ [])

@spec up(opts()) :: :ok

Migrates the database up to :version, the latest by default, running each version it is missing in order. A no-op when it is already there.