UNPKG

pg-tx

Version:

Transaction wrapper for node-postgres

67 lines 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cancelTransaction = exports.commitTransaction = exports.beginTransaction = void 0; const client_1 = require("./client"); async function getTxId(client) { const { rows: [{ txid }] } = await client.query(`SELECT txid_current() AS "txid"`); return txid; } /** * How have we implemented transaction - with database transaction or with a * savepoint */ var TransactionMode; (function (TransactionMode) { TransactionMode[TransactionMode["Transaction"] = 0] = "Transaction"; TransactionMode[TransactionMode["Savepoint"] = 1] = "Savepoint"; })(TransactionMode || (TransactionMode = {})); async function beginTransaction({ client, clientMode }) { switch (clientMode) { case client_1.ClientMode.Connected: /** * If it's a client that we connected, we can be sure we can use it for a * transaction */ { await client.query(`BEGIN`); return TransactionMode.Transaction; } case client_1.ClientMode.Provided: /** * If it's a client that has been provided to us, we have to check if we * actually start a new transaction, and revert to savepoints */ { const preBeginTxId = await getTxId(client); await client.query(`BEGIN`); const postBeginTxId = await getTxId(client); const transactionMode = preBeginTxId !== postBeginTxId ? TransactionMode.Transaction : TransactionMode.Savepoint; if (transactionMode === TransactionMode.Savepoint) { await client.query(`SAVEPOINT pg_tx`); } return transactionMode; } } } exports.beginTransaction = beginTransaction; function commitTransaction({ client, transactionMode }) { switch (transactionMode) { case TransactionMode.Transaction: return client.query(`COMMIT`); case TransactionMode.Savepoint: return client.query(`RELEASE SAVEPOINT pg_tx`); } } exports.commitTransaction = commitTransaction; async function cancelTransaction({ client, transactionMode }) { switch (transactionMode) { case TransactionMode.Transaction: return client.query(`ROLLBACK`); case TransactionMode.Savepoint: await client.query(`ROLLBACK TO SAVEPOINT pg_tx`); await client.query(`RELEASE SAVEPOINT pg_tx`); break; } } exports.cancelTransaction = cancelTransaction; //# sourceMappingURL=transaction.js.map