| 177 | } |
| 178 | |
| 179 | transaction<T>(fn: (...args: any[]) => T, options?: TransactionOptions): (...args: any[]) => T { |
| 180 | return (...args: any[]) => { |
| 181 | // Nested call (a transaction()-wrapped helper invoked from inside another |
| 182 | // transaction): run the body directly inside the enclosing transaction. |
| 183 | // BEGIN would throw "cannot start a transaction within a transaction", |
| 184 | // so no existing caller ever relied on nested rollback granularity — |
| 185 | // flattening is behavior-preserving and free. |
| 186 | if (this._txDepth > 0) { |
| 187 | this._txDepth++; |
| 188 | try { |
| 189 | return fn(...args); |
| 190 | } finally { |
| 191 | this._txDepth--; |
| 192 | } |
| 193 | } |
| 194 | this._db.exec(options?.immediate ? 'BEGIN IMMEDIATE' : 'BEGIN'); |
| 195 | this._txDepth = 1; |
| 196 | try { |
| 197 | const result = fn(...args); |
| 198 | this._db.exec('COMMIT'); |
| 199 | this._txDepth = 0; |
| 200 | return result; |
| 201 | } catch (error) { |
| 202 | this._db.exec('ROLLBACK'); |
| 203 | this._txDepth = 0; |
| 204 | throw error; |
| 205 | } |
| 206 | }; |
| 207 | } |
| 208 | |
| 209 | close(): void { |
| 210 | // node:sqlite's DatabaseSync.close() throws if already closed; make it |