Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Sometimes I just want to write my own database

4 views
Skip to first unread message

Mike Austin

unread,
Apr 21, 2025, 3:54:30 PMApr 21
to PiLuD
I just want to increment a value in one table and use it in another, in one transaction.

This almost works in Postgres, but I get "WITH clause containing a data-modifying statement must be at the top level". :(

CREATE OR REPLACE FUNCTION set_public_items_team_seq_id()
  RETURNS TRIGGER LANGUAGE PLPGSQL AS $$
BEGIN
  NEW.team_key_seq_id := (
    WITH updated_teams AS (
      UPDATE teams
        SET next_seq_id = next_seq_id + 1
        WHERE id = NEW.team_id
        RETURNING next_seq_id
    )
    SELECT next_seq_id from updated_teams
  );

  RETURN NEW;
END;
$$;

Mike Austin

unread,
Apr 21, 2025, 6:35:44 PMApr 21
to PiLuD
The fix is to use UPDATE + INTO instead of WITH + UPDATE. The former is considered a "top level" statement.

CREATE OR REPLACE FUNCTION set_public_items_team_seq_id()

RETURNS TRIGGER LANGUAGE PLPGSQL  AS $$

DECLARE

  result integer;

BEGIN

  UPDATE teams

    SET next_seq_id = next_seq_id + 1

    WHERE id = NEW.team_id

    RETURNING next_seq_id

    INTO result;


  NEW.team_key_seq_id := result;


  RETURN NEW;

END;

$$;


Reply all
Reply to author
Forward
0 new messages