PostgreSQL trigger to generate codes for multiple tables dynamically

后端 未结 2 578
青春惊慌失措
青春惊慌失措 2021-01-03 11:18

I\'d like to generate codes for many tables in the database, and stopped to refactor my solution when I was ready to write my third implementation of \"get code for table X\

相关标签:
2条回答
  • 2021-01-03 11:52

    I'd be quite enthusiastic to be shown wrong (I occasionally need this myself too), but best I'm aware, referring column names using variables is one of those cases where you actually need to use PL/C triggers rather than PL/PgSQL triggers. You'll find examples of such triggers in contrib/spi and on PGXN.

    Alternatively, name your columns consistently so as to be able to reference them directly, e.g. NEW.tenant_code.

    Personally, I generally end up writing a function that creates the trigger:

    create function create_tg_stuff(_table regclass, _args[] text[])
      returns void as $$
    begin
      -- explore pg_catalog a bit
      execute $x$
      create function $x$ || quote_ident(_table || '_tg_stuff') || $x$()
        returns trigger as $t$
      begin
        -- more stuff
        return new;
      end;
      $t$ language plpgsql;
      $x$;
    end;
    $$ language plpgsql;
    
    0 讨论(0)
  • 2021-01-03 12:09

    NEW is type RECORD, so you can't assign to that AFAIK.

    To set the value of a column, assign to NEW.column, for example:

    NEW.tenant_code := (SELECT some_calculation);
    

    Maybe your design is too complicated; PL/SQL is a very limited language - try to make your code as simple as possible

    0 讨论(0)
提交回复
热议问题