| 108 | } |
| 109 | |
| 110 | transaction<T>(fn: (...args: any[]) => T): (...args: any[]) => T { |
| 111 | return (...args: any[]) => { |
| 112 | // Nested call (a transaction()-wrapped helper invoked from inside another |
| 113 | // transaction): run the body directly inside the enclosing transaction. |
| 114 | // BEGIN would throw "cannot start a transaction within a transaction", |
| 115 | // so no existing caller ever relied on nested rollback granularity — |
| 116 | // flattening is behavior-preserving and free. |
| 117 | if (this._txDepth > 0) { |
| 118 | this._txDepth++; |
| 119 | try { |
| 120 | return fn(...args); |
| 121 | } finally { |
| 122 | this._txDepth--; |
| 123 | } |
| 124 | } |
| 125 | this._db.exec('BEGIN'); |
| 126 | this._txDepth = 1; |
| 127 | try { |
| 128 | const result = fn(...args); |
| 129 | this._db.exec('COMMIT'); |
| 130 | this._txDepth = 0; |
| 131 | return result; |
| 132 | } catch (error) { |
| 133 | this._db.exec('ROLLBACK'); |
| 134 | this._txDepth = 0; |
| 135 | throw error; |
| 136 | } |
| 137 | }; |
| 138 | } |
| 139 | |
| 140 | close(): void { |
| 141 | // node:sqlite's DatabaseSync.close() throws if already closed; make it |