Skip to content

Instantly share code, notes, and snippets.

@wttw
Created December 21, 2018 10:59
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 wttw/9635e468a1f30d20efbaab751cea8e0e to your computer and use it in GitHub Desktop.
Save wttw/9635e468a1f30d20efbaab751cea8e0e to your computer and use it in GitHub Desktop.
-- Schema version ---------------------------------------------------------
create table schema_version (
version integer not null
);
create unique index schema_version_one_row on schema_version((1));
create function schema_version_no_delete () returns trigger as $f$
begin
raise exception 'Cannot delete schema version';
end;
$f$ language plpgsql;
create trigger schema_version_no_delete before delete on schema_version for each row execute procedure schema_version_no_delete();
create function assert_schema_version(expected integer) returns boolean as $f$
declare
ver schema_version%ROWTYPE;
begin
begin
select * into strict ver from schema_version;
exception
when NO_DATA_FOUND then
raise exception 'Version not found in schema_version';
when TOO_MANY_ROWS then
raise exception 'schema_version malformed';
end;
if ver.version <> $1 then
raise exception 'This patch can only be applied to schema version % not %', $1, ver.version;
end if;
return true;
end;
$f$ language plpgsql;
insert into schema_version (version) values (1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment