【问题标题】:How to get the name of the altered table in a Postgres event trigger?如何在 Postgres 事件触发器中获取更改表的名称?
【发布时间】:2014-05-04 08:54:48
【问题描述】:

postgres 数据库中,有表base1,它是视图view1 的基表。

如果 base1 中的列被创建、删除或重命名,我想使用 ddl 触发器重新创建视图 view1

create event trigger base1_views
   on ddl_command_end
   when tag in( 'ALTER TABLE' )
   execute procedure base1_views_fn();

create function base1_views_fn() returns void as $$
declare
  buf varchar;
begin
  -- is table being altered = 'base'?
  -- add, drop or renaming a column?
  buf = 'drop view view1';
  execute buf;
  buf = 'create view view1 as select * from base1 where ...';
  execute buf;
end;
$$ language 'plpgsql';

在函数base1_views_fn()中,我们如何获取表名以及是否正在更改列?

【问题讨论】:

    标签: postgresql ddl triggers


    【解决方案1】:

    触发器中 plpgsql 可用的变量在这里定义:

    http://www.postgresql.org/docs/9.3/static/plpgsql-trigger.html#PLPGSQL-EVENT-TRIGGER-EXAMPLE

    我无法从文本中看出有多少“事件”变量。当然有两个:

    TG_EVENT
    Data type text; a string representing the event the trigger is fired for.
    
    TG_TAG
    Data type text; variable that contains the command tag for which the trigger is fired.
    

    您可以在您的函数中打印这些以查看它们是否包含您要查找的表格信息。该文档显示了许多其他用于常规事件的变量。我不知道这些是否有帮助,但是,也许 TG_TABLE_NAME 已设置?

    【讨论】:

    • 标签是 ALTER TABLE。 tg_table_name 不存在。如果可以看到原始查询会暴露所有内容,但也看不到。
    • 事件触发器是相当新的。 TG_EVENT 有什么有用的吗?我在 postgres 中到处使用视图/函数。我将它们放在一个单独的架构中,然后每次有一个基本架构更改时,我都会删除包含所有函数/视图/等级联的架构。我进行基表更改,然后重新创建所有函数/视图/等。您可以在事务中执行此操作,这可以(稍微)隔离活跃用户可能看到的打嗝。您可以对单个表执行相同的操作。
    • 在此处查看 cmets:stackoverflow.com/questions/23488228/how-to-get-sql-text-from-postgres-event-trigger
    【解决方案2】:

    这里解决了同样的问题:How to get SQL text from Postgres event trigger

    最重要的是,到目前为止,请等到在未来版本中向 EVENT TRIGGER 添加更多功能

    【讨论】:

      猜你喜欢
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2019-06-24
      • 2013-05-01
      • 1970-01-01
      相关资源
      最近更新 更多