如何将默认值从基表复制到视图中?

时间:2019-07-16 15:47:11

标签: postgresql view

我有表格和视图:

CREATE TABLE base_table (id int, ts timestamptz NOT NULL DEFAULT now());
CREATE VIEW a_view AS SELECT * FROM base_table;

请告诉我一个查询,如何从base_table中选择所有默认值并将其应用于a_view

尽管The view will automatically show those default values for any row that was inserted,但如果视图有instead of insert触发器,则情况并非如此。在这种情况下,我会收到错误消息:

ERROR:  null value in column "ts" violates not-null constraint

因此,我希望在instead of insert触发器之前应用表默认值。

我可以alter table "a_view" alter ts set default now();,但是我想通过pg系统目录表对许多列和视图执行此操作

UPD

我的触发函数如下:

execute format('
  create or replace function %s_insert()
  returns trigger as $fn$
  begin
  IF( new.id is null ) THEN
    if( new.app_period is null ) THEN
      INSERT INTO "%s" ( %s )
      values ( %s )
      returning id, %s, app_period INTO new;
    ELSE
      INSERT INTO "%s" ( %s, app_period )
      values ( %s, new.app_period )
      returning id, %s, app_period INTO new;
    END IF;
  ELSE
    if( new.app_period is null ) THEN
      INSERT INTO "%s" ( id, %s )
      values ( new.id, %s )
      returning id, %s, app_period INTO new;
    ELSE
      INSERT INTO "%s" ( id, %s, app_period )
      values ( new.id, %s, new.app_period )
      returning id, %s, app_period INTO new;
    END IF;
  END IF;
  return NEW;
  end;
  $fn$ language plpgsql;

%s分别是table nametable's columns的地方

从一开始idapp_period都具有默认值,现在默认值具有更多字段,并且无法为每个默认值变体编写单独的IF分支。

0 个答案:

没有答案