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,19 +19,25 @@
-- --- 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
CREATE ROLE teecup_app -- "syntax error at or near ':'". Erstattet med \if/\else slik at
LOGIN -- PASSWORD-linjen står som vanlig SQL utenfor $$ $$ (verifisert mot
PASSWORD :'teecup_app_password' -- scratch-database, se test_isolation.sql-kjøringen).
NOSUPERUSER SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'teecup_app') AS teecup_app_exists \gset
NOCREATEDB \if :teecup_app_exists
NOCREATEROLE \echo 'teecup_app finnes allerede, hopper over CREATE ROLE'
NOBYPASSRLS \else
INHERIT; CREATE ROLE teecup_app
END IF; LOGIN
END $$; PASSWORD :'teecup_app_password'
NOSUPERUSER
NOCREATEDB
NOCREATEROLE
NOBYPASSRLS
INHERIT;
\endif
-- --- 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;