r/PostgreSQL • • 1d ago • Bravo 1

Projects The subtle trap with SQL functions when you drop or alter a column in a migration

I hit a Postgres behavior recently that surprised me, even after spending the last six months testing migration edge cases.

Say you have a simple helper function written the traditional way with a dollar-quoted body:

CREATE FUNCTION active_user_emails() RETURNS SETOF text
LANGUAGE sql AS $$ SELECT email FROM users WHERE active = true; $$;

Later on, somebody writes a migration that drops or renames users.email

If you run ALTER TABLE users DROP COLUMN email;, Postgres lets it through without a single warning. Even though check_function_bodies parsed the SQL when the function was created, Postgres stores a `$$` body as an opaque string literal and doesn't record pg_depend edges to the columns inside it. Your migration succeeds, CI is green, and the function only blows up in production the next time something calls it.

Now flip one line and write the exact same function using the SQL-standard body syntax (BEGIN ATOMIC, added in PG 14):

CREATE FUNCTION active_user_emails() RETURNS SETOF text
LANGUAGE sql
BEGIN ATOMIC
  SELECT email FROM users WHERE active = true;
END;

Because Postgres stores BEGIN ATOMIC as a parsed node tree in pg_proc.prosqlbody, it records hard dependency edges in pg_depend now that exact same ALTER TABLE users DROP COLUMN email; fails outright in the middle of your migration unless you pass CASCADE and if you do pass CASCADE, it silently drops the function along with the column.

And there is a third twist: if an earlier statement in your migration runs SET check_function_bodies = off; (which tools like pg_dump do all the time), a dollar-quoted LANGUAGE sql function won't even check whether the table exists at creation time, whereas BEGIN ATOMIC still parses and binds the objects immediately.

I've been building an open-source migration simulator (safe-migrate) that steps through migration files statement by statement against a snapshot of your catalog so it can catch things like this before deploy. Getting routine bodies, pg_depend edges, and check_function_bodies scoping (`SET`, `SET LOCAL`, `ROLLBACK TO SAVEPOINT`) to match real Postgres 14–18 took way more digging than I expected.

Have many of you switched your SQL functions over to `BEGIN ATOMIC` specifically so Postgres tracks the schema dependencies, or is almost everyone still on `$$` strings?

15 Upvotes

13 comments sorted by

4

u/SnowLoth 1d ago

With check_function_bodies = on you can execute fmgr_sql_validator() as a part of your CI:

SELECT p.oid::regprocedure AS function
     , fmgr_sql_validator(p.oid)
   FROM pg_proc      AS p
   JOIN pg_namespace AS n ON n.oid = p.pronamespace
   JOIN pg_language  AS l ON l.oid = p.prolang
   WHERE n.nspname = 'public'
     AND l.lanname = 'sql'
     AND p.prokind IN ('f', 'p')
   ORDER BY 1
;

2

u/dsecurity49 18h ago

Calling fmgr_sql_validator(p.oid) across pg_proc is a really clean post migration check if your CI spins up a live DB ,we do the $$ body check statically mainly to catch it offline before a DB is even running

3

u/elevarq 1d ago

This could (or even should) be implemented as a view.

2

u/dsecurity49 1d ago

Yeah without args a view makes more sense. I just left the parameters out to keep the example short (but we track view dependencies too).

2

u/SnowLoth 1d ago

Although I agree with the view, if this function is marked as STABLE,then the function body is going to be inlined and for EXPLAIN SELECT * FROM active_user_emails(); you see "Seq Scan on users". You can even index scan on the users.email using SELECT * FROM active_user_emails() AS u(e) WHERE e = 'a@b.c' or using respective ORDER BY clause.

3

u/Einar_Son_of_Bjorn 1d ago

I still see $$ strings everywhere, since BEGIN ATOMIC only works for LANGUAGE sql and skips PL/pgSQL. Moving a few simple helpers over saved me from two bad drops, though blocked alters do push people toward CASCADE. From what I've seen most teams just stay on $$ and run plpgsql_check in CI instead of rewriting old functions.

2

u/dsecurity49 18h ago

Yeah, BEGIN ATOMIC doesn't help once you're in plpgsql, and the reflex to slap CASCADE on a blocked drop is real. That's actually why we ended up parsing both $$ SQL and plpgsql bodies statically and flagging DROP...CASCADE with the exact dependent functions it'll take down.

2

u/AutoModerator 1d ago

AI Policy:

Linux is not one of those anti-AI projects, and if somebody has issues with that, they can do the open-source thing and fork it. Or just walk away., Linus Torvalds.

Mod decisions will be based on the quality of the content, not who or what generated it.

Sub Resources:

Youtube Channel

Free Postgres Webinars and Workshops

Discord: People, Postgres, Data

Join us, we have cookies and nice people.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.