pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

"REFERENCING OLD TABLE" clause for triggers is not replicated

Open whoward opened this issue 1 year ago • 1 comments

Hey folks, First off - I love the project, I'm very excited to hopefully use it on our application at some point. Unfortunately with our application structure currently we can't successfully dump the schema using pgschema. I'll probably be filing a number of bugs which illustrate dump failures we've noticed.

First off is the REFERENCING OLD TABLE clause in trigger definitions. Here is an example of it's usage:

CREATE TABLE public.orders (
  id SERIAL PRIMARY KEY,
  customer_name TEXT NOT NULL,
  order_date TIMESTAMP NOT NULL DEFAULT NOW(),
  total_amount NUMERIC(10, 2)
);

CREATE TABLE public.archived_orders (
  id INTEGER,
  customer_name TEXT,
  order_date TIMESTAMP,
  total_amount NUMERIC(10, 2),
  archived_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE OR REPLACE FUNCTION public.archive_old_records()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
  -- Insert all deleted rows from the transition table into archive
  INSERT INTO public.archived_orders (id, customer_name, order_date, total_amount)
  SELECT id, customer_name, order_date, total_amount
  FROM old_orders;

  RETURN NULL; -- Result is ignored for AFTER triggers
END;
$$;

-- Create the statement-level trigger with transition table
CREATE TRIGGER
  archive_deleted_orders_tr
  AFTER DELETE
  ON public.orders
  REFERENCING OLD TABLE AS old_orders
  FOR EACH STATEMENT EXECUTE FUNCTION public.archive_old_records();

For this example usage pgschema dumps the triggers as:

CREATE OR REPLACE TRIGGER archive_deleted_orders_tr
    AFTER DELETE ON orders
    FOR EACH STATEMENT
    EXECUTE FUNCTION archive_old_records();

This won't work obviously as the function references old_table in the code.

Tested this on PostgreSQL 17

whoward avatar Oct 09 '25 20:10 whoward

thanks for the quick turnaround! fix is working great!

whoward avatar Oct 10 '25 18:10 whoward