Created
January 13, 2020 21:31
-
-
Save docteurklein/c958def27c16e5e2f0a9b2a219e33e93 to your computer and use it in GitHub Desktop.
postgres-only transactional migration script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
begin; | |
create table if not exists migration (id bigint primary key, at timestamptz not null default clock_timestamp()); | |
drop function if exists migrate; | |
create function migrate() returns bigint language plpgsql as $$ | |
declare current_migration bigint; | |
begin | |
select coalesce((select id from migration order by id desc limit 1), 0) into current_migration; | |
raise notice 'current_migration "%"', current_migration; | |
case when current_migration < 1 then | |
create table test (id int); | |
insert into migration (id) values (1); | |
else null; | |
end case; | |
case when current_migration < 2 then | |
alter table test add col1 text; | |
insert into migration (id) values (2); | |
else null; | |
end case; | |
case when current_migration < 3 then | |
alter table test add col2 text; | |
insert into migration (id) values (3); | |
else null; | |
end case; | |
case when current_migration < 4 then | |
alter table test add col3 text; | |
insert into migration (id) values (4); | |
else null; | |
end case; | |
case when current_migration < 5 then | |
alter table test add col4 text; | |
insert into migration (id) values (5); | |
else null; | |
end case; | |
select coalesce((select id from migration order by id desc limit 1), 0) into current_migration; | |
return current_migration; | |
end; | |
$$; | |
select migrate() as current_migration; | |
commit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment