简体   繁体   中英

Insert trigger in postgresql, dynamic statement

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM