Fix migration 002: psql does not interpolate :'var' inside DO $$ blocks

CREATE ROLE ... PASSWORD :'teecup_app_password' silently failed with
"syntax error at or near ':'" because the whole DO $$ ... $$ body is a
dollar-quoted string and psql skips variable substitution inside it.
Replaced the idempotency check with \gset + \if/\else so the PASSWORD
line is plain top-level SQL, where interpolation does work. Verified
against a scratch database (see test_isolation.sql run).
This commit is contained in:
Erol Haagenrud 2026-07-16 08:24:48 +02:00
parent 4f90fb05dc
commit 576ae64fa3

View file

@ -19,9 +19,16 @@
-- --- Rolle (cluster-nivå: opprett bare hvis den ikke finnes) ---------- -- --- Rolle (cluster-nivå: opprett bare hvis den ikke finnes) ----------
-- Eksplisitt NOSUPERUSER / NOBYPASSRLS — dette er hele poenget. -- Eksplisitt NOSUPERUSER / NOBYPASSRLS — dette er hele poenget.
DO $$ -- MERK: dette var opprinnelig en DO $$ ... $$-blokk med
BEGIN -- "PASSWORD :'teecup_app_password'" inni. psql interpolerer ikke :'var'
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'teecup_app') THEN -- inne i dollar-quoted strenger, så det feilet alltid med
-- "syntax error at or near ':'". Erstattet med \if/\else slik at
-- PASSWORD-linjen står som vanlig SQL utenfor $$ $$ (verifisert mot
-- scratch-database, se test_isolation.sql-kjøringen).
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'teecup_app') AS teecup_app_exists \gset
\if :teecup_app_exists
\echo 'teecup_app finnes allerede, hopper over CREATE ROLE'
\else
CREATE ROLE teecup_app CREATE ROLE teecup_app
LOGIN LOGIN
PASSWORD :'teecup_app_password' PASSWORD :'teecup_app_password'
@ -30,8 +37,7 @@ BEGIN
NOCREATEROLE NOCREATEROLE
NOBYPASSRLS NOBYPASSRLS
INHERIT; INHERIT;
END IF; \endif
END $$;
-- --- Grants (kjøres mens du er koblet til teecup_db) ------------------ -- --- Grants (kjøres mens du er koblet til teecup_db) ------------------
GRANT CONNECT ON DATABASE teecup_db TO teecup_app; GRANT CONNECT ON DATABASE teecup_db TO teecup_app;