Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 425
菜合馍馍 Avatar asked Jan 29 '23 10:01

菜合馍馍


1 Answers

this is my code ,it's meet my needs

code:

CREATE OR REPLACE FUNCTION trg_create_table_func()
RETURNS event_trigger
LANGUAGE plpgsql
AS $$
DECLARE
    obj record;    
BEGIN
  FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE command_tag in ('SELECT INTO','CREATE TABLE','CREATE TABLE AS')
  LOOP
        if   obj.object_identity !~ 'public.temp_'  
        THEN
        raise EXCEPTION 'The table name must begin with temp_';
        end if;
        END LOOP;
END;
$$;

CREATE EVENT TRIGGER trg_create_table ON ddl_command_end
WHEN TAG IN ('SELECT INTO','CREATE TABLE','CREATE TABLE AS')
EXECUTE PROCEDURE trg_create_table_func();

out recods

[Err] ERROR: The table name must begin with temp_ CONTEXT: PL/pgSQL function trg_create_table_func() line 10 at RAISE

it's cool ~

like image 182
菜合馍馍 Avatar answered Mar 07 '23 15:03

菜合馍馍