Created
January 21, 2024 13:15
-
-
Save hetzge/5d9d5040811defedd2ac32dab8b46246 to your computer and use it in GitHub Desktop.
Postgresql Migration
This file contains hidden or 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
| CREATE OR REPLACE PROCEDURE migrate(key_input TEXT) LANGUAGE plpgsql AS | |
| $$ | |
| BEGIN | |
| -- create table to persist migration status | |
| CREATE TABLE IF NOT EXISTS migrations ( | |
| "key" TEXT NOT NULL, | |
| created TIMESTAMP NOT NULL DEFAULT NOW() | |
| ); | |
| -- check if already migrated | |
| IF NOT EXISTS (SELECT * FROM migrations WHERE migrations."key" = key_input) THEN | |
| -- execute the migration body | |
| EXECUTE 'CALL ' || key_input || '();'; | |
| -- mark as migrated | |
| INSERT INTO migrations (key) VALUES (key_input); | |
| END IF; | |
| END; | |
| $$; | |
| CREATE OR REPLACE PROCEDURE my_migration() LANGUAGE plpgsql AS | |
| $$ | |
| BEGIN | |
| -- TODO migration code | |
| END; | |
| $$; | |
| DO $$ | |
| begin | |
| CALL migrate('my_migration'); | |
| END $$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment