Skip to content

Instantly share code, notes, and snippets.

@hetzge
Created January 21, 2024 13:15
Show Gist options
  • Select an option

  • Save hetzge/5d9d5040811defedd2ac32dab8b46246 to your computer and use it in GitHub Desktop.

Select an option

Save hetzge/5d9d5040811defedd2ac32dab8b46246 to your computer and use it in GitHub Desktop.
Postgresql Migration
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