PostgreSQL

ストアドファンクションのソースをファイル出力

pg_get_functiondef()

ソースを出力するSQL
select pg_get_functiondef((select max(t.oid) from pg_proc t ,pg_namespace n 
where t.pronamespace = n.oid
and n.nspname = 'sooni' 
and t.proname = 'destination'))
;
psqlを使いファンクションのソースを取得しファイル出力する例

psqlを使いファイル出力する際に肝となるのが以下オプションです。
-t オプション:列名と結果の行数フッタなどの表示を無効にします
-A オプション:位置揃えなしの出力モードに切り替えます

-- まずは接続
D:\temp\work>psql -h vm022 -d myposdb -U sooni -t -A
psql (13.5, server 13.6)
Type "help" for help.

-- \o オプションにて出力ファイル名を指定する
-- 以下はsooniスキーマのdestinationファンクションのソースを取得する例です。
-- max(oid)としているのはオーバーロードされている可能性を考慮したものです。適宜変更して使ってください。
-- ※Windows環境ではShift-JISになります。
myposdb=# \o create_sooni_destination.sql
myposdb=# select pg_get_functiondef((select max(t.oid) from pg_proc t ,pg_namespace n
myposdb(# where t.pronamespace = n.oid
myposdb(# and n.nspname = 'sooni'
myposdb(# and t.proname = 'destination'));
myposdb=# \q


-- 出力されたファイルの確認
D:\temp\work>type create_sooni_destination.sql
CREATE OR REPLACE FUNCTION sooni.destination()
 RETURNS TABLE(item_no integer, item_name text, item_value text)
 LANGUAGE plpgsql
AS $function$
begin
raise info '接続先を確認するサンプルファンクション';
return query

select 1 as item_no,'current_database' as item_name,cast(current_database() as text) as item_value
union select 2 as item_no,'version' as item_name,substring(version() from 'PostgreSQL [0-9|.]*') as item_value
union select 3 as item_no,'inet_server_addr' as item_name,cast(inet_server_addr() as text) as item_value
union select 4 as item_no,'inet_server_port' as item_name,cast(inet_server_port() as text) as item_value
union select 5 as item_no,'current_user' as item_name,cast(current_user as text) as item_value

union select 6 as item_no,'current_schema' as item_name,cast(current_schema() as text) as item_value
union select 7 as item_no,'inet_client_addr' as item_name,cast(inet_client_addr() as text) as item_value
order by item_no
;

END;
$function$


D:\temp\work>
-- 参考までにですが、以下のようにpsql起動オプションで出力ファイルを指定する事も可能です。
-- (複数のファンクションを出力したい場合この方法では毎回接続/切断となるのでイマイチですよね)
D:\temp\work>psql -h vm022 -d myposdb -U sooni -t -A -o create_sooni_destination.sql
psql (13.5, server 13.6)
Type "help" for help.

myposdb=# select pg_get_functiondef((select max(t.oid) from pg_proc t ,pg_namespace n
myposdb(# where t.pronamespace = n.oid
myposdb(# and n.nspname = 'sooni'
myposdb(# and t.proname = 'destination'))
myposdb-# ;
myposdb=# \q

D:\temp\work>
スポンサーリンク
タイトルとURLをコピーしました