之前筆記中渡鴉之丘: 在 psql 指令界面下使用變數紀錄了 psql 指令裡面,如何使用 Meta-Variable 並指定一些值。到了 PGSQL 10 之後,psql 又擴增了 Meta-Variable 的能力,讓我們可以用 SQL 回傳結果當成 Meta-Variable 的值。
以下示範,是從 pg_settings 系統表查出 search_path 內容,然後把結果指定到 Meta-Variable。Meta-variable 的名稱,預設會使用回傳欄位名稱,這邊指定欄位名稱叫做 myvar,所以,Meta-variable 就叫做 myvar。
接著,就直接把結果,多增加一個 aaa 的 Schema,回頭指定到 search_path 裡面:
edb=# select setting as myvar from pg_settings where name='search_path' \gset
edb=# \echo :myvar
"$user", public
edb=# select :{?myvar};
bool
------
t
(1 row)
edb=# set search_path = :myvar , aaa;
SET
edb=# show search_path ;
search_path
----------------------
"$user", public, aaa
(1 row)
edb=#
這招是對 show 指令也有效,但。。。用起來就怪怪的不舒服,原因是,Meta-Variable 名稱就叫做 search_path。。
edb=# show search_path \gset
edb=# select :{?search_path};
bool
------
t
(1 row)
edb=# \echo :search_path
"$user", public
edb=#
所幸~\gset 有一個搞笑功能:增加前綴字串。 這邊,就重新作一次,直接用 show 指令儲存結果到 Meta-Variable 裡面,並且 Meta-Variable 名稱叫做 var_search_path
edb=# show search_path \gset var_
edb=# select :{?var_search_path};
bool
------
t
(1 row)
edb=# \echo :var_search_path
"$user", public
edb=# set search_path = :var_search_path , aaa;
SET
edb=# show search_path ;
search_path
----------------------
"$user", public, aaa
(1 row)
edb=#
如果 SQL 回傳的值不只一筆結果的話,就會無法存結果進 Meta-Variable
edb=# \d test
Table "public.test"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
id | integer | | |
edb=# select * from test ;
id
----
(0 rows)
edb=# insert into test values (1),(2);
INSERT 0 2
edb=# select * from test ;
id
----
1
2
(2 rows)
edb=# select * from test \gset
more than one row returned for \gset
edb=#
edb=# select id from test \gset
more than one row returned for \gset
edb=# select :{?id};
bool
------
f
(1 row)
edb=#
這個技巧另外的應用,則是增加 shared_preload_libraries 的內容
edb=# show shared_preload_libraries ;
shared_preload_libraries
--------------------------------------------------------------------------------------------------------------
"$libdir/dbms_pipe", "$libdir/edb_gen", "$libdir/dbms_aq", "$libdir/sql-profiler", "$libdir/edb_wait_states"
(1 row)
edb=# show shared_preload_libraries \gset orig_
edb=#
edb=# alter system set shared_preload_libraries = :orig_shared_preload_libraries , "$libdir/edb_filter_log";
ALTER SYSTEM
edb=#
..重啟之後..
edb=#
edb=# show shared_preload_libraries ;
shared_preload_libraries
----------------------------------------------------------------------------------------------------------------------------------------
"$libdir/dbms_pipe", "$libdir/edb_gen", "$libdir/dbms_aq", "$libdir/sql-profiler", "$libdir/edb_wait_states", "$libdir/edb_filter_log"
(1 row)
edb=#
值得注意的是,雖然 PGSQL 10 之後的 psql 指令才有這個功能,不過我們也是可以用「新版 psql」去連線到舊版資料庫的!然後,這樣的功能就可以套用到舊版資料庫(例如,Greenplum 5.x)了~
沒有留言:
張貼留言