我只是想知道在运行DROP ... CASCADE
之后是否有人知道如何自动化视图创建?
现在我尝试使用经典DROP VIEW myview
语句删除视图,如果我不能删除视图,因为其他对象仍然依赖于它,然后检出postgres列出的所有对象名称并保存它们的创建然后我运行与级联下降。有时它就像十几个物体。但也许你有一些想法以更自动化的方式处理这个问题?
也许有人有一些功能?
答案 0 :(得分:2)
下一步......(继续我之前的回答)。
功能 save_views(对象名称文字)根据表 saved_views 中的对象名称(视图或表格)存储视图。
功能 restore_views()从表 saved_views 恢复视图。
create or replace function save_views_oid(objectid oid)
returns void language plpgsql as $$
declare
r record;
begin
for r in
select distinct c.oid, c.relname, n.nspname
from pg_depend d
join pg_rewrite w on w.oid = d.objid
join pg_class c on c.oid = w.ev_class
join pg_namespace n on n.oid = c.relnamespace
where d.refclassid = 'pg_class'::regclass
and d.classid = 'pg_rewrite'::regclass
and d.refobjid = objectid
and c.oid <> objectid
loop
insert into saved_views values (
'CREATE VIEW ' || r.nspname || '.' || r.relname ||
' AS ' || pg_get_viewdef(r.oid, 'f'));
perform save_views_oid(r.oid);
end loop;
end; $$;
create or replace function save_views(objectname text)
returns void language plpgsql as $$
begin
create table if not exists saved_views(viewbody text);
truncate saved_views;
perform save_views_oid(objectname::regclass);
end; $$;
create or replace function restore_views()
returns void language plpgsql as $$
declare
viewtext text;
begin
for viewtext in
select viewbody from saved_views
loop
execute viewtext;
end loop;
drop table saved_views;
end; $$;
测试:
select save_views('my_view'); -- may be save_views('my_schema.my_view');
select * from saved_views;
使用:
select save_views('my_view');
drop view my_view cascade;
create view my_view as ...
select restore_views();
答案 1 :(得分:0)
表pg_depend包含所有必要的信息,但解释它们并不容易。这里有草图递归函数来检索文本格式的pg_class对象的依赖关系。您可以根据需要调整功能(并向我们显示结果:)。
create or replace function dependency
(class_id regclass, obj_id regclass, obj_subid integer, dep_type "char")
returns setof text language plpgsql as $$
declare
r record;
begin
return query
select pg_describe_object(class_id, obj_id, obj_subid)
|| ' ('|| dep_type|| ')';
for r in
select classid, objid, objsubid, deptype
from pg_depend
where class_id = refclassid
and obj_id = refobjid
and (obj_subid = refobjsubid or obj_subid = 0)
loop
return query select dependency(r.classid, r.objid, r.objsubid, r.deptype);
end loop;
end; $$;
use:
select dependency('pg_class'::regclass, 'my_view'::regclass, 0, ' ');
select dependency('pg_class'::regclass, 'my_table'::regclass, 0, ' ');