PostgreSQL Oracle兼容性之 - plpgsql 自治事务(autonomous_transaction)补丁

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
云原生数据库 PolarDB 分布式版,标准版 2核8GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

PostgreSQL Oracle兼容性之 - plpgsql 自治事务(autonomous_transaction)补丁

作者

digoal

日期

2016-11-04

标签

PostgreSQL , autonomous_transaction , 自治事务 , Oracle兼容性 , plpgsql


背景

PostgreSQL的plpgsql服务端编程语言与Oracle数据库的pl/sql编程语言非常类似,但是对于自治事务一直没有语法层面的支持。

以往如果要支持自治事务,可以使用exception或者使用dblink来实现。

写法有点复杂,如果你想要语法层面的支持,可以试试社区放出的这个补丁,补丁还没有合并到主分支,不建议生产使用。

用法

以9.6为例,介绍一下这个补丁的用法。

安装补丁

$ wget https://www.postgresql.org/message-id/attachment/45863/autonomous.patch

$ cd postgresql-9.6.1

$ patch -p1 < ../autonomous.patch 

$ make && make install

重启数据库

$ pg_ctl restart -m fast

语法讲解

查看这两个回归测试的文件,可以了解它的用法

1. src/pl/plpgsql/src/expected/plpgsql_autonomous.out

CREATE TABLE test1 (a int);
CREATE FUNCTION autonomous_test() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  FOR i IN 0..9 LOOP
    START TRANSACTION;
    EXECUTE 'INSERT INTO test1 VALUES (' || i::text || ')';
    IF i % 2 = 0 THEN
        COMMIT;
    ELSE
        ROLLBACK;
    END IF;
  END LOOP;

  RETURN 42;
END;
$$;
SELECT autonomous_test();
 autonomous_test 
-----------------
              42
(1 row)

SELECT * FROM test1;
 a 
---
 0
 2
 4
 6
 8
(5 rows)

TRUNCATE test1;
CREATE FUNCTION autonomous_test2() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  FOR i IN 0..9 LOOP
    START TRANSACTION;
    INSERT INTO test1 VALUES (i);
    IF i % 2 = 0 THEN
        COMMIT;
    ELSE
        ROLLBACK;
    END IF;
  END LOOP;

  RETURN 42;
END;
$$;
SELECT autonomous_test2();
 autonomous_test2 
------------------
               42
(1 row)

SELECT * FROM test1;
 a
---





(5 rows)

2. src/pl/plpython/expected/plpython_autonomous.out

CREATE TABLE test1 (a int, b text);
CREATE FUNCTION autonomous_test() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
    for i in range(0, 10):
        a.execute("BEGIN")
        a.execute("INSERT INTO test1 (a) VALUES (%d)" % i)
        if i % 2 == 0:
            a.execute("COMMIT")
        else:
            a.execute("ROLLBACK")

return 42
$$;
SELECT autonomous_test();
 autonomous_test 
-----------------
              42
(1 row)

SELECT * FROM test1;
 a | b 
---+---
 0 | 
 2 | 
 4 | 
 6 | 
 8 | 
(5 rows)

CREATE FUNCTION autonomous_test2() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
        a.execute("BEGIN")
        a.execute("INSERT INTO test1 (a) VALUES (11)")
        rv = a.execute("SELECT * FROM test1")
        plpy.info(rv)
        a.execute("ROLLBACK")

return 42
$$;
SELECT autonomous_test2();
INFO:  <PLyResult status=5 nrows=6 rows=[{'a': 0, 'b': None}, {'a': 2, 'b': None}, {'a': 4, 'b': None}, {'a': 6, 'b': None}, {'a': 8, 'b': None}, {'a': 11, 'b': None}]>
 autonomous_test2 
------------------
               42
(1 row)

SELECT * FROM test1;
 a | b 
---+---
 0 | 
 2 | 
 4 | 
 6 | 
 8 | 
(5 rows)

CREATE FUNCTION autonomous_test3() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
    a.execute("DO $_$ BEGIN RAISE NOTICE 'notice'; END $_$")
    a.execute("DO $_$ BEGIN RAISE EXCEPTION 'error'; END $_$")

return 42
$$;
SELECT autonomous_test3();
NOTICE:  notice
ERROR:  error
CONTEXT:  PL/pgSQL function inline_code_block line 1 at RAISE
PL/Python function "autonomous_test3"
CREATE FUNCTION autonomous_test4() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
    a.execute("SET client_encoding TO SJIS")

return 42
$$;
SELECT autonomous_test4();
ERROR:  cannot set client encoding in autonomous session
CONTEXT:  PL/Python function "autonomous_test4"
TRUNCATE test1;
CREATE FUNCTION autonomous_test5() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
    plan = a.prepare("INSERT INTO test1 (a, b) VALUES ($1, $2)", ["int4", "text"])
    a.execute_prepared(plan, [1, "one"])
    a.execute_prepared(plan, [2, "two"])

return 42
$$;
SELECT autonomous_test5();
 autonomous_test5 
------------------
               42
(1 row)

SELECT * FROM test1;
 a |  b  
---+-----
 1 | one
 2 | two
(2 rows)

TRUNCATE test1;
CREATE FUNCTION autonomous_test6() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
    plan = a.prepare("INSERT INTO test1 (a) VALUES (i)", {"i": "int4"})
    a.execute_prepared(plan, [1])
    a.execute_prepared(plan, [2])

return 42
$$;
SELECT autonomous_test6();
 autonomous_test6 
------------------
               42
(1 row)

SELECT * FROM test1;
 a | b 
---+---
 1 | 
 2 | 
(2 rows)

TRUNCATE test1;
CREATE FUNCTION autonomous_test7() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
        a.execute("BEGIN")
        plan = a.prepare("INSERT INTO test1 (a) VALUES ($1)", ["int4"])
        a.execute_prepared(plan, [11])
        plan = a.prepare("SELECT * FROM test1")
        rv = a.execute_prepared(plan, [])
        plpy.info(rv)
        a.execute("ROLLBACK")

return 42
$$;
SELECT autonomous_test7();
INFO:  <PLyResult status=5 nrows=1 rows=[{'a': 11, 'b': None}]>
 autonomous_test7 
------------------
               42
(1 row)

SELECT * FROM test1;
 a | b 
---+---
(0 rows)

CREATE FUNCTION autonomous_test8() RETURNS integer
LANGUAGE plpythonu
AS $$
with plpy.autonomous() as a:
        a.execute("BEGIN")

return 42
$$;
SELECT autonomous_test8();
ERROR:  autonomous session ended with transaction block open
CONTEXT:  PL/Python function "autonomous_test8"
DROP TABLE test1;

测试

测试plpgsql的自治事务用法

-- 创建测试表
CREATE TABLE test1 (a int);

创建测试函数
CREATE FUNCTION autonomous_test() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
  -- 定义使用自治事务
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  FOR i IN 0..9 LOOP
    -- 启动自治事务
    START TRANSACTION;
    -- 目前仅支持动态SQL
    EXECUTE 'INSERT INTO test1 VALUES (' || i::text || ')';
    IF i % 2 = 0 THEN
        -- 整除2的提交
    COMMIT;
    ELSE
        -- 不能整除2的回归
    ROLLBACK;
    END IF;
  END LOOP;

  RETURN 42;
END;
$$;

-- 调用测试函数
SELECT autonomous_test();
 autonomous_test 
-----------------
              42
(1 row)

-- 查看结果
SELECT * FROM test1;
 a 
---
 0
 2
 4
 6
 8
(5 rows)

TRUNCATE test1;


CREATE FUNCTION autonomous_test2() RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  FOR i IN 0..9 LOOP
    START TRANSACTION;
    -- 不支持spi prepared statement
    -- 与当前自治事务的设计有关
    INSERT INTO test1 VALUES (i);
    IF i % 2 = 0 THEN
        COMMIT;
    ELSE
        ROLLBACK;
    END IF;
  END LOOP;

  RETURN 42;
END;
$$;

SELECT autonomous_test2();
 autonomous_test2 
------------------
               42
(1 row)

SELECT * FROM test1;
 a
---





(5 rows)

目前这个PATCH还在fix,请注意跟踪,也许后面的用法就变了。

When running in-process (SPI), we install parser hooks that allow the
parser to check back into PL/pgSQL about whether x, y are variables and
what they mean.  When we run in an autonomous session, we don't have
that available.  So my idea was to extend the protocol Parse message to
allow sending a symbol table instead of parameter types.  So instead of
saying, there are two parameters and here are their types, I would send
a list of symbols and types, and the server would respond to the Parse
message with some kind of information about which symbols it found.  I
think that would work, but I got lost in the weeds and didn't get very
far.  But you can see some of that in the code.  If anyone has other
ideas, I'd be very interested.

参考

http://blog.dalibo.com/2016/09/08/Pragma_Autonoumous_transactions.html

http://blog.dalibo.com/2016/08/19/Autonoumous_transactions_support_in_PostgreSQL.html

https://www.postgresql.org/message-id/659a2fce-b6ee-06de-05c0-c8ed6a01979e@2ndquadrant.com

https://www.postgresql.org/message-id/flat/659a2fce-b6ee-06de-05c0-c8ed6a01979e%402ndquadrant.com#659a2fce-b6ee-06de-05c0-c8ed6a01979e@2ndquadrant.com

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
相关文章
|
2月前
|
Oracle 关系型数据库
oracle rac 手工安装补丁,不适用auto
oracle rac 手工安装补丁,不适用auto
25 3
|
7月前
|
Oracle 关系型数据库
oracle基础|什么是事务控制|事务的ACID原则|什么是不可重复读、幻影读、脏读
oracle基础|什么是事务控制|事务的ACID原则|什么是不可重复读、幻影读、脏读
|
9月前
|
关系型数据库 PostgreSQL
PostgreSQL事务提交日志与CLOG操作初步认识
PostgreSQL事务提交日志与CLOG操作初步认识
147 0
|
10月前
|
Oracle 关系型数据库 数据库
PostgreSQL技术大讲堂 - 第20讲:事务概述与隔离级别
PostgreSQL从小白到专家,技术大讲堂 - 第20讲:事务概述与隔离级别
187 2
|
安全 Oracle Java
|
11月前
|
SQL Oracle 关系型数据库
Oracle 19c 补丁升级引发的单表恢复失败谜案
问题表现 某客户在恢复 Oracle 数据库的单表时,提示类似下面的信息
|
11月前
|
SQL Oracle 关系型数据库
|
11月前
|
SQL 存储 Oracle
Oracle事务和锁机制
Oracle事务和锁机制
85 0
|
SQL Oracle 网络协议
【.NET 6】使用EF Core 访问Oracle+Mysql+PostgreSQL并进行简单增改操作与性能比较
唠嗑一下。都在说去O或者开源,但是对于数据库选型来说,很多人却存在着误区。例如,去O,狭义上讲,是去Oracle数据库。但是从广义上来说,是去Oracle公司产品或者具有漂亮国垄断地位和需要商业授权的数据库产品。
320 0
【.NET 6】使用EF Core 访问Oracle+Mysql+PostgreSQL并进行简单增改操作与性能比较
|
SQL 存储 Oracle
Oracle的视图,索引,约束,事务,数据库范式
🍅程序员小王的博客:程序员小王的博客 🍅 欢迎点赞 👍 收藏 ⭐留言 📝 🍅 如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕 🍅java自学的学习路线:java自学的学习路线
79 0
Oracle的视图,索引,约束,事务,数据库范式

相关产品

  • 云原生数据库 PolarDB
  • 推荐镜像

    更多