// SQL snippet

Schema version table recipe

Hand-rolled deployments need one place that says 'this database is at schema version N'. A two-column table does the job and every script can read it.

Main statement
PostgreSQL
Também cobre
SQL Server MySQL

The task

Deploy scripts run against several environments, each needing to know which migrations it has already applied, without adopting a full migration framework.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
CREATE TABLE IF NOT EXISTS schema_version (
    version    integer PRIMARY KEY,
    name       text NOT NULL,
    applied_at timestamptz NOT NULL DEFAULT now(),
    checksum   text
);

INSERT INTO schema_version (version, name, checksum)
VALUES (12, 'add-orders-table', 'sha256:9f1c...')
ON CONFLICT (version) DO NOTHING;

Como funciona

One row per applied migration, keyed by version, gives you the current state with SELECT max(version) and the full history in the same table. ON CONFLICT DO NOTHING makes the insert re-runnable instead of failing on the primary key. The checksum column is optional; it lets a verification script notice a migration file that was edited after it was applied. MySQL's INSERT IGNORE does the same job but also turns other errors, such as a too-long value, into warnings.

Variations

MySQL

MySQL
CREATE TABLE IF NOT EXISTS schema_version (
    version    INT PRIMARY KEY,
    name       VARCHAR(200) NOT NULL,
    applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    checksum   VARCHAR(80) NULL  -- 'sha256:' + 64 hex digits
) ENGINE=InnoDB;

INSERT IGNORE INTO schema_version (version, name, checksum)
VALUES (12, 'add-orders-table', 'sha256:9f1c...');

SQL Server

SQL Server
IF OBJECT_ID('dbo.SchemaVersion', 'U') IS NULL
    CREATE TABLE dbo.SchemaVersion (
        Version INT PRIMARY KEY,
        Name NVARCHAR(200) NOT NULL,
        AppliedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),
        Checksum VARCHAR(80) NULL
    );

INSERT INTO dbo.SchemaVersion (Version, Name, Checksum)
SELECT 12, 'add-orders-table', 'sha256:9f1c...'
WHERE NOT EXISTS (
    SELECT 1 FROM dbo.SchemaVersion WHERE Version = 12);

Questions that come up

Why keep a checksum when the version already matches?

Because migration files get edited: someone fixes 'the same' migration in git after three environments already ran the old text. The version numbers still match everywhere, but the schemas do not. Comparing the stored checksum with a hash of the current file is how you notice.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.