【问题标题】:nodejs pg transactions without nesting没有嵌套的nodejs pg事务
【发布时间】:2016-07-21 09:55:57
【问题描述】:

我想知道是否可以运行一系列 SQL 语句并将它们全部提交到一个事务中。

我正在研究的场景是一个数组有一系列值,我希望将这些值插入到表中,而不是单独插入,而是作为一个单元。

我正在查看以下项目,它为使用 pg 的节点中的事务提供框架。各个事务似乎相互嵌套,所以我不确定这将如何处理包含可变数量元素的数组。

https://github.com/brianc/node-postgres/wiki/Transactions

var pg = require('pg');
var rollback = function(client, done) {
  client.query('ROLLBACK', function(err) {
    //if there was a problem rolling back the query
    //something is seriously messed up.  Return the error
    //to the done function to close & remove this client from
    //the pool.  If you leave a client in the pool with an unaborted
    //transaction weird, hard to diagnose problems might happen.
    return done(err);
  });
};
pg.connect(function(err, client, done) {
  if(err) throw err;
  client.query('BEGIN', function(err) {
    if(err) return rollback(client, done);
    //as long as we do not call the `done` callback we can do 
    //whatever we want...the client is ours until we call `done`
    //on the flip side, if you do call `done` before either COMMIT or ROLLBACK
    //what you are doing is returning a client back to the pool while it 
    //is in the middle of a transaction.  
    //Returning a client while its in the middle of a transaction
    //will lead to weird & hard to diagnose errors.
    process.nextTick(function() {
      var text = 'INSERT INTO account(money) VALUES($1) WHERE id = $2';
      client.query(text, [100, 1], function(err) {
        if(err) return rollback(client, done);
        client.query(text, [-100, 2], function(err) {
          if(err) return rollback(client, done);
          client.query('COMMIT', done);
        });
      });
    });
  });
});

我的数组逻辑是:

banking.forEach(function(batch){
  client.query(text, [batch.amount, batch.id], function(err, result);
} 

【问题讨论】:

标签: node.js postgresql transactions


【解决方案1】:

pg-promise 为事务提供了非常灵活的支持。见Transactions。

它还支持部分嵌套事务,即保存点。

该库自动实现事务,这是现在应该使用的,因为如果您尝试像在示例中那样手动组织事务,可能会出错太多。

查看相关问题:Optional INSERT statement in a transaction

【讨论】:

  • 使用 node-progress 我会先建立一个连接池,然后使用 & 释放连接。 pgp 是否会自动执行此操作并且 php 自述文件会引用连接池?
  • @user1567212 pg-promise 自动管理连接,如其文档中所述。
【解决方案2】:

这是避免pg-promise 的简单 TypeScript 解决方案

import { PoolClient } from "pg"
import { pool } from "../database"

const tx = async (callback: (client: PoolClient) => void) => {
  const client = await pool.connect();

  try {
    await client.query('BEGIN')
    try {
      await callback(client)
      await client.query('COMMIT')
    } catch (e) {
      await client.query('ROLLBACK')
    }
  } finally {
    client.release()
  }
}

export { tx }

用法:

...

let result;

await tx(async client => {
  const { rows } = await client.query<{ cnt: string }>('SELECT COUNT(*) AS cnt FROM users WHERE username = $1', [username]);
  result = parseInt(rows[0].cnt) > 0;
});

return result;

【讨论】:

  • 请注意,这将与 pg-promise 所做的高级事务支持有很大不同,添加以下内容:1) 自动嵌套事务/保存点 2) 自动事务配置 3) 自动连接问题处理4) 自动性能测量5) 自动事务上下文传播(级别、协议扩展等)6) 自动监控+记录功能。所以,基本上,你剥离 pg-promise 强大的所有事务实现,并将其称为替代方案。让你知道。
  • 我在生产代码中使用了这个答案,发现它引入了一类微妙的错误。我写了一个改进的 npm 包:github.com/golergka/pg-tx
猜你喜欢
  • 2017-05-30
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多