Search code examples
javascriptnode.jspostgresqlexpressplpgsql

Does postgres-nodejs support pl/pgsql block code?


I am trying to declare a custom UUID variable to be used on multiple queries during a transaction.

I have tried using a javascript variable but that defeated the purpose of trying to declare the variable on the server? The below code executes fine in psql...

BEGIN;
DO $$
DECLARE
gen_ulid UUID;

BEGIN
gen_ulid = generate_ulid();
INSERTION queries ...
...
END $$;
COMMIT;

...but the following returns error: '...Failed to insert error: syntax error at or near "DECLARE"'

try {
      await pool.query("BEGIN")
      await pool.query("DO $$ DECLARE gen_ulid UUID")
      await pool.query("BEGIN gen_ulid = generate_ulid()")
      await pool.query("INSERT ... ")
      ...
      await pool.query("END$$")
      await pool.query("COMMIT")
   }

Solution

  • A single DO-statement is a single query. And you have to send this as a single query to your database, not in multiple queries.

    For a single DO-statement you don't need a transaction, a single statement is already some sort of transaction by itself. So you don't need the BEGIN and COMMIT statements, but it doesn't hurt either.

    try {
          await pool.query("BEGIN")
          await pool.query("DO $$
          DECLARE
          gen_ulid UUID;
    
          BEGIN
          gen_ulid = generate_ulid();
          INSERTION queries ...
          ...
          END $$;")
          await pool.query("COMMIT")
       }