Search code examples
postgresqlevent-triggers

how to create event trigger for create table or select into


i want create event trigger for create table or select into, eg: when create table xxxx must table name bigen with 'temp'

my code

    CREATE OR REPLACE FUNCTION create_table_func()
    RETURNS event_trigger
    AS
    $$
    DECLARE
          V_TABLE name := TG_TABLE_NAME;

BEGIN

    if V_TABLE !~ '^temp'

    then

      RAISE EXCEPTION 'must bigen with temp';

    end if;

END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

CREATE EVENT TRIGGER create_table_1 ON ddl_command_start

WHEN TAG IN ('SELECT INTO')

EXECUTE PROCEDURE create_table_func();

but when execute select * into test11 from test_bak

[Err] ERROR: column "tg_table_name" does not exist


Solution

  • The special variable TG_TABLE_NAME is only supported in normal triggers, not in event triggers (there is not always an associated table!).

    The documentation has a list of functions that can return context information in an event trigger.

    You could use pg_event_trigger_ddl_commands() to get the information you need, but that only works in ddl_command_end event triggers. That should work for you; I don't see a reason why the trigger should not run at the end of the statement.