0

I am trying to add an insert trigger to a table in order to implement partitioning. The following code works:

CREATE OR REPLACE FUNCTION item_lines_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO item_lines_partitions.p11_1 VALUES (NEW.*);
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

My problem - is that when I try to make it dynamic (so that I can redirect to a table based on the values that I get), I just can't insert the record (NEW.*) into a dynamic statement. Here is what I Tried to do:

CREATE OR REPLACE FUNCTION item_lines_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    EXECUTE format('INSERT INTO item_lines_partitions.p%s_%s VALUES ',NEW.tenant_id,NEW.store_id) || quote_literal(NEW.*);
    RETURN NULL;
END;

I get a syntax error as following with the dynamic statement: PG::SyntaxError: ERROR: syntax error at or near "'(49563,,1,11,100125,100125,1,,...

I also tried using EXECUTE <expression ... $1> USING NEW.* but it did not work as well.

Any ideas on how to insert NEW.* expression into a dynamic statement?

Thanks!

1

1 Answer 1

1

Try this:

EXECUTE
   format(
      'INSERT INTO item_lines_partitions.%I SELECT ($1::text::item_lines_partitions.%I).*',
      'p' || NEW.tenant_id || '_' || NEW.store_id,
      'p' || NEW.tenant_id || '_' || NEW.store_id
   )
   USING NEW;

Here, NEW is used as a parameter to the statement and type cast to the appropriate table type.

The way you construct the table string was not safe, so I changed that.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It did not work. I got the following error: PG::CannotCoerce: ERROR: cannot cast type item_lines to item_lines_partitions.p11_1 where item_lines is the parent table name (I do partitioning with table inheritance)
Now I get the following: ActiveRecord::StatementInvalid (PG::DatatypeMismatch: ERROR: column "id" is of type integer but expression is of type item_lines_partitions.p11_1) I Assume this is because I have many column types in that table. Thank you very much for your help. I can provide the table schema if that helps, but in general I have datatypes of text, integer, float, date, and time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.