Question:

How to make PostgreSQL functions atomic?

Assume I have some PostgreSQL functions like the following:

CREATE FUNCTION insertSth() RETURNS void AS $$
BEGIN
INSERT INTO ...;
END; CREATE FUNCTION removeSthAfterSelect() RETURNS TABLE(...) AS $$
BEGIN
SELECT id INTO some_id ...;
RETURN QUERY SELECT * FROM ...;
DELETE FROM ... WHERE id = some_id;
END; CREATE FUNCTION justDeleteSth() RETURNS void AS $$
BEGIN
DELETE FROM ...;
END; CREATE FUNCTION justSelectSth() RETURNS TABLE(...) AS $$
BEGIN
RETURN SELECT * FROM ...;
END;

From my understanding PostgresSQL functions insertSthjustDeleteSth and justSelectSth are going to be executed atomically(?). So parallel executions of them won't mess anything up.

But for removeSthAfterSelect if there is a parallel execution it could be that SELECT id INTO some_id .. finds something, then concurrently another transaction calls justDeleteSth and deletes the row with id = someId, so when the transaction continues it won't delete anything here: DELETE FROM ... WHERE id = some_id; meaning it messes things up.

Is this the case? Is there a way to avoid this problem? E.g. by saying that removeSthAfterSelectshould be executed atomically?

--------------------------------------------------------------------------------------------------------------------------------------------
 
Answer:

A transaction has the property of atomic commit, i.e. the entire transaction is guaranteed to take effect, or none of it does.

That doesn't mean that transactions can't interact. In particular, in READ COMMITTED mode a transaction committing midway though another transaction can have visible effects. Even without that, concurrently anomalies are possible and normal. See the PostgreSQL chapter on concurrency control, particularly the transaction isolation section. Statements in functions are no more immune to concurrency issues than standalone statements.

Even within a single statement it's possible to have concurrency issues. Statements are not magically atomic. People often think that if they can pack everything into a single query using CTEs, subqueries, etc, it'll be magically immune to concurrency issues. That is not the case.

There's no function label to say "execute this atomically" because the concept you're looking for just doesn't exist in the DBMS. The closest you'll get is to LOCK TABLE ... IN ACCESS EXCLUSIVE all tables that the function uses, so that nothing else can touch them. That is usually rather excessive and unnecessary if you can reason effectively about concurrency and transaction isolation.

It's difficult to be more specific because you're using a very generalised example with all the details left out. For example, why does it matter if you attempt to delete the row twice?

A few concepts you should study:

  • Snapshots
  • READ COMMITTED vs SERIALIZABLE transaction isolation
  • Row and table level locks, both implicit (e.g. those taken by DML) and explicit (e.g. SELECT ... FOR UPDATE)
  • Transaction visibility
  • Predicate re-checks after a DML statement finishes waiting on a lock

As one example of concurrency in action, take a look at the upsert problem.


But for removeSthAfterSelect if there is a parallel execution it could be that SELECT id INTO some_id .. finds something, then concurrently another transaction calls justDeleteSth and deletes the row with id = someId, so when the transaction continues it won't delete anything here: DELETE FROM ... WHERE id = some_id; meaning it messes things up.

You're talking as if one transaction stops and the other runs, then the first continues. That's often not the case; things can run completely concurrently, with many statements happening truly simultaneously.

The main thing that limits that is row level locking. In this case, there's a race condition, as both DELETEs try to acquire the row update lock for the row. Whichever gets it will continue and delete the row. The other DELETE gets stuck on the row lock until the winning transaction commits or rolls back. If it rolls back, it's as if nothing happened and the waiting transaction continues as normal. If the winning transaction commits the delete, the waiting transaction sees the lock has been released, and (in READ COMMITTED mode) re-checks the WHERE clause predicate to make sure the row is still matched, discovers it doesn't exist anymore, and carries on without an error as it's not an error to delete zero rows.

In PL/PgSQL you can check the affected row count if you want to enforce that a statement affect exactly one row, and RAISE EXCEPTION if it didn't match the expected affected rows. There's also INTO STRICT for SELECT.

How to make PostgreSQL functions atomic?的更多相关文章

  1. WRITING POSTGRESQL TRIGGERS IN GO

    转自:https://www.opsdash.com/blog/postgresql-triggers-golang.html 可以学习如何使用golang 编写pg extension Trigge ...

  2. C-Language Functions

    转自:https://www.postgresql.org/docs/9.6/xfunc-c.html 可以作为学习基于c编写pg extension 的资料 36.9. C-Language Fun ...

  3. postgresql 创建函数

    One of the most powerful features of PostgreSQL is its support for user-defined functions written in ...

  4. postgresql spi开发笔记

    #include "postgres.h" #include "fmgr.h" #include <string.h> #ifdef PG_MODU ...

  5. PDO和PDOStatement类常用方法

    PDO — PDO 类 PDO::beginTransaction — 启动一个事务 PDO::commit — 提交一个事务 PDO::__construct — 创建一个表示数据库连接的 PDO ...

  6. 转---redshift database ---学习

    摘自他人 前沿 根据最近一段时间对redshift的研究,发现一些特性比较适合我们当前的业务. 1 比如它的快速恢复能力,因为这一点,我们可以尽量在redshit里面存放一定生命周期的数据,对过期的数 ...

  7. A Deep Dive into PL/v8

    Back in August, Compose.io announced the addition of JavaScript as an internal language for all new ...

  8. PostgreSQL 窗口函数 ( Window Functions ) 如何使用?

    一.为什么要有窗口函数 我们直接用例子来说明,这里有一张学生考试成绩表testScore: 现在有个需求,需要查询的时候多出一列subject_avg_score,为此科目所有人的平均成绩,好跟每个人 ...

  9. Linux -- GCC Built-in functions for atomic memory access

    下列内建函数旨在兼容Intel Itanium Processor-specific Application Binary Interface, section 7.4. 因此,这些函数区别于普通的G ...

随机推荐

  1. Redis五大数据类型以及操作

    目录: 一.redis的两种链接方式 二.redis的字符串操作(string) 三.redis的列表操作(list) 四.redis的散列表操作(类似于字典里面嵌套字典) 五.redis的集合操作( ...

  2. ctype

    original:http://www.runoob.com/cprogramming/c-standard-library-ctype-h.html 下面列出了头文件 ctype.h 中定义的函数: ...

  3. Jquery----属性的利用

    属性操作: 1.属性 属性(如果你的选择器选出了多个对象,那么默认只会返回出第一个属性). attr(属性名|属性值) - 一个参数是获取属性的值,两个参数是设置属性值 - 点击加载图片示例 remo ...

  4. python 全栈开发,Day102(支付宝支付)

    昨日内容回顾 1. django请求生命周期? - 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者po ...

  5. 步步为营-63-Asp.net-get与post

    1 get Get方式将数据发送到服务端,那么会将用户在表单中的数据放置到浏览器的地址栏中发送到服务器 格式:表单元素name属性的值=用户输入的值 请求地址:http://localhost:594 ...

  6. [Reprinted] 使用Spring Data Redis操作Redis(一) 很全面

    Original Address: http://blog.csdn.net/albertfly/article/details/51494080

  7. k短路([SDOI2010]魔法猪学院)

    题解: A*来做 首先对终点向外面跑一遍最短路 然后从起点开始dfs 按照估价函数建立小根堆 每次取出最小的那个继续更新 每次更新到终点cnt++直道cft=k为止 那估价函数怎么弄呢? 其实就是终点 ...

  8. python函数式编程——偏函数

    当函数的参数个数太多,需要简化时,使用functools.partial可以创建一个新的函数,这个新函数可以固定住原函数的部分参数,从而在调用时更简单. import functools def te ...

  9. Codeforces 498B Name That Tune 概率dp (看题解)

    Name That Tune 刚开始我用前缀积优化dp, 精度炸炸的. 我们可以用f[ i ][ j ] 来推出f[ i ][ j + 1 ], 记得加加减减仔细一些... #include<b ...

  10. tarjan 算法求强连通分量

    #include<bits/stdc++.h> #define ll long long using namespace std; const int P=1e6; ; ; const i ...