PLPGSQL Procedures and Transactions #9524
-
I'm trying recreate an existing Firebase project on Supabase. I want client web apps to call PLPGSQL stored procedures exposed by pg_graphql or Postgrest to update the database. I'm used to Firebase Cloud Functions, which support transactions consisting of multiple read statements followed by multiple write statements. Having studied the Postgres docs and googled extensively, I cannot get clarity on how to do similar transactions using PLPGSQL stored procedures. Being a complete Postgres noob, I probably don't see the forest for the trees (at least that's my hope!). Could anyone tell me if the following code behaves as intended, or if not, how to get the intended behavior?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
PostgREST surrounds rpc functions with transaction logic but the function itself (if run in sql window is not). All operations must succeed or all are rolled back. From Postgres docs From PostgREST docs (POST is used for rpc call): "Trapping Errors" here might also be relevent: https://www.postgresql.org/docs/14/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING I've not read thru your function code, so hopefully this points you in the direction you need for more info. |
Beta Was this translation helpful? Give feedback.
PostgREST surrounds rpc functions with transaction logic but the function itself (if run in sql window is not). All operations must succeed or all are rolled back.
From Postgres docs
It is important not to confuse the use of BEGIN/END for grouping statements in PL/pgSQL with the similarly-named SQL commands for transaction control. PL/pgSQL's BEGIN/END are only for grouping; they do not start or end a transaction.
From PostgREST docs (POST is used for rpc call):
PostgREST executes POST requests in a read/write transaction except for functions marked as IMMUTABLE or STABLE. Those must not modify the database and are executed in a read-only transaction compatible for read-replicas.
"Trappi…