Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Created October 19, 2017 14:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pesterhazy/9f7c0a7a9edd002759779c1732e0ac43 to your computer and use it in GitHub Desktop.
Save pesterhazy/9f7c0a7a9edd002759779c1732e0ac43 to your computer and use it in GitHub Desktop.
Minimalist migration framework for PostgreSQL
create table if not exists migrations (
key text CONSTRAINT pkey PRIMARY KEY
);
create or replace function idempotent(migration_name text,code text) returns void as $$
begin
if exists (select key from migrations where key=migration_name) then
raise notice 'Migration already applied: %', migration_name;
else
raise notice 'Running migration: %', migration_name;
execute code;
insert into migrations (key) VALUES (migration_name);
end if;
end;
$$ language plpgsql strict;
/* USAGE: V0001__orders.sql
do $do$ begin perform idempotent('V0001__orders', $$
CREATE TABLE orders
(
id bigint NOT NULL,
user_id bigint,
address_id bigint,
product_id bigint)
$$); end $do$;
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment