Skip to content

Commit

Permalink
Merge pull request #779 from vitaly-t/savepoints
Browse files Browse the repository at this point in the history
improvement on #774
  • Loading branch information
vitaly-t authored Feb 28, 2021
2 parents 193fecb + fe6b2c6 commit 667cb6e
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,13 @@ Postgres uses `BEGIN` with `COMMIT / ROLLBACK` for top-level transactions, and `
with `RELEASE / ROLLBACK TO name` for inner save-points.

This library automatically executes all such transaction and savepoint commands, with unique
savepoint names, based on the transaction level.
savepoint names, based on the transaction level, plus index within the current level, in the
form of `sp_x_y`.

In the name, `x` is the transaction level, starting with `1` (because `0` is the top-level
transaction that does not use savepoints). And `y` represents sub-transaction order/index
within the current level, starting with `1`. So the first savepoint on the top level will
be named `sp_1_1`.

### Configurable Transactions

Expand Down
13 changes: 13 additions & 0 deletions lib/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class ConnectionContext {
this.parentCtx = null; // parent context
this.taskCtx = null; // task context
this.start = null; // Date/Time when connected
this.txCount = 0;
}

connect(db) {
Expand All @@ -65,9 +66,21 @@ class ConnectionContext {

clone() {
const obj = new ConnectionContext(this);
obj.parent = this;
obj.parentCtx = this.taskCtx;
return obj;
}

get nextTxCount() {
let txCurrent = this, txTop = this;
while(txCurrent.parent) {
txCurrent = txCurrent.parent;
if(txCurrent.taskCtx && txCurrent.taskCtx.isTX) {
txTop = txCurrent;
}
}
return txTop.txCount ++;
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/task.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ const execute = (ctx, obj, isTX, config) => {

if (isTX) {
// executing a transaction;
spName = `level_` + ctx.txLevel;
spName = `sp_${ctx.txLevel}_${ctx.nextTxCount}`;
return begin()
.then(() => callback(ctx, obj, ctx.cb, config)
.then(data => {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pg-promise",
"version": "10.9.2",
"version": "10.9.3",
"description": "PostgreSQL interface for Node.js",
"main": "lib/index.js",
"typings": "typescript/pg-promise.d.ts",
Expand Down

0 comments on commit 667cb6e

Please sign in to comment.