2013-01-25 161 views
3

我只是想知道是否有人知道如何在運行DROP ... CASCADE後自動創建視圖? 現在我試圖首先用經典的DROP VIEW myview語句刪除視圖,如果我不能刪除視圖,因爲其他對象仍然依賴它,然後檢出所有對象名稱postgres列表並保存它們創建,然後我運行拖放級聯。有時候就像十幾個物體一樣。但也許你有一些想法以更自動的方式處理這個問題?依賴關係跟蹤功能

也許任何人有一些功能?

回答

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, ' '); 
+0

謝謝,但它基本上是相同的通知,採用水滴的觀點與意見的依賴issue.Besides名後,我得到重複... – Borys

+0

這只是第一步。我希望你能做下一個;) – klin

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();