如何在 SailsJs 中使用 PostgreSQL 事务?

How can I use PostgreSQL transactions in SailsJs?

我的问题是我有一个复杂的查询链,如果其中某个交易失败,它会回滚。 我读过有关 Sails 中的事务的信息,默认情况下,Sails 不支持事务,因为每个事务都会与 Postgres 建立新连接,因此,一个查询有一个新连接。 那么,我如何使用 Sails 进行交易?

水线目前不支持交易。你可以在这里加入讨论 https://github.com/balderdashy/waterline/issues/755.

交易在路线图上,但预计不会在不久的将来发生:https://github.com/balderdashy/waterline/blob/master/ROADMAP.md#pending-proposals

作为解决方法,您可以尝试 https://github.com/Shyp/pg-transactions,但是您将失去水线的灵活性,因为您的代码将不再与数据库无关。

同时勾选 Sails.js best practice in using transactions with promises (Postgres) and Sails.js + Postgres: issue with transactions

最简单的方法是通过 pg-promise 支持的自动交易:

db.tx(t=> {
    // - returning a value or a resolved promise will result in COMMIT
    // - returning a resolved promise or throwing an error will result in ROLLBACK
})
    .then(data=> {
        // COMMIT has been executed
        // data  = data returned from the callback
    })
    .catch(error=> {
        // ROLLBACK has been executed
        // error = rejection reason or error thrown
    });

但是您需要直接执行查询,而不是通过 Waterline,正如@zabware 所说:

you will loose the flexibility of waterline because your code will not be database agnostic any more.

另请参阅:Transactions