Skip to content

Instantly share code, notes, and snippets.

@scttnlsn
Created April 4, 2019 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scttnlsn/9b17d6f9834e737c296f1144371449b5 to your computer and use it in GitHub Desktop.
Save scttnlsn/9b17d6f9834e737c296f1144371449b5 to your computer and use it in GitHub Desktop.
Pure SQL migrations
--------------------------------------------------
--- SETUP
--------------------------------------------------
\set ON_ERROR_STOP true
CREATE TABLE IF NOT EXISTS migrations (
name CHAR VARYING PRIMARY KEY,
timestamp TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now()
);
CREATE OR REPLACE FUNCTION EXECUTE(TEXT) RETURNS VOID AS $$
BEGIN EXECUTE $1; END;
$$ LANGUAGE plpgsql STRICT;
CREATE OR REPLACE FUNCTION migration_exists(TEXT) RETURNS bool AS $$
SELECT EXISTS (SELECT FROM migrations WHERE name = $1);
$$ LANGUAGE SQL STRICT;
CREATE OR REPLACE FUNCTION migrate(TEXT, TEXT) RETURNS VOID AS $$
SELECT EXECUTE($2) WHERE NOT migration_exists($1);
INSERT INTO migrations (name) SELECT ($1) WHERE NOT migration_exists($1);
$$ LANGUAGE SQL STRICT;
--------------------------------------------------
--- MIGRATIONS
--------------------------------------------------
SELECT migrate('create_examples', $$
CREATE TABLE IF NOT EXISTS examples (
id SERIAL PRIMARY KEY,
other TEXT
);
$$);
SELECT migrate('add_foo_to_examples', $$
ALTER TABLE examples
ADD COLUMN foo TEXT NOT NULL;
$$);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment