PostgreSQL DBA(68) - 使用DBLink实现自治事务

由于PostgreSQL没有提供类似Oracle的自治事务控制功能,本节介绍了如何使用dblink实现简单的自治事务控制.

样例
安装dblink插件,验证dblink可连接至本地PG


[local]:5432 pg12@testdb=# create extension dblink;
ERROR:  extension "dblink" already exists
Time: 1.128 ms
[local]:5432 pg12@testdb=# select t1.* from dblink('host=/tmp port=5432 dbname=testdb user=pg12','select * from t1') as t1(id int,c1 int,c2 int) limit 1;
 id | c1 | c2 
----+----+----
  4 |  4 |  4
(1 row)
Time: 1413.943 ms (00:01.414)

创建数据表和存储过程


[local]:5432 pg12@testdb=# drop table if exists log;
DROP TABLE
Time: 38.531 ms
[local]:5432 pg12@testdb=# CREATE TABLE log(
pg12@testdb(#   msg text not null,
pg12@testdb(#   sender_ts timestamptz not null,
pg12@testdb(#   local_ts timestamptz default now()
pg12@testdb(# );
CREATE TABLE
Time: 8.686 ms
[local]:5432 pg12@testdb=# CREATE OR REPLACE FUNCTION log_dblink(msg text)
pg12@testdb-#  RETURNS void
pg12@testdb-#  LANGUAGE sql
pg12@testdb-# AS $function$
pg12@testdb$#    select dblink('host=/tmp port=5432 user=pg12 dbname=testdb',
pg12@testdb$#     format('insert into log select %L, %L', msg, clock_timestamp()::text))
pg12@testdb$# $function$;
CREATE FUNCTION
Time: 3.657 ms

测试验证,启动事务,调用函数,然后rollback


[local]:5432 pg12@testdb=# begin;
BEGIN
Time: 1.293 ms
[local]:5432 pg12@testdb=#* select log_dblink('log message');
 log_dblink 
------------
(1 row)
Time: 16.394 ms
[local]:5432 pg12@testdb=#* rollback;
ROLLBACK
Time: 0.845 ms

通过dblink执行的SQL主事务隔离,已commit


[local]:5432 pg12@testdb=# select * from log;
     msg     |           sender_ts           |           local_ts            
-------------+-------------------------------+-------------------------------
 log message | 2019-08-05 14:23:30.459183+08 | 2019-08-05 14:23:30.468047+08
(1 row)
Time: 0.695 ms

参考资料
PostgreSQL DBA(58) - DBLink
Implementing Autonomous Transactions in Postgres

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/6906/viewspace-2652695/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/6906/viewspace-2652695/

你可能感兴趣的:(PostgreSQL DBA(68) - 使用DBLink实现自治事务)