sqlstack 3.5.0 → 3.6.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/cjs/adapters/index.d.ts +2 -0
  2. package/dist/cjs/adapters/index.d.ts.map +1 -1
  3. package/dist/cjs/adapters/index.js +3 -1
  4. package/dist/cjs/adapters/index.js.map +1 -1
  5. package/dist/cjs/adapters/sqlego.d.ts +41 -0
  6. package/dist/cjs/adapters/sqlego.d.ts.map +1 -0
  7. package/dist/cjs/adapters/sqlego.js +116 -0
  8. package/dist/cjs/adapters/sqlego.js.map +1 -0
  9. package/dist/cjs/adapters/sqlite.d.ts +2 -0
  10. package/dist/cjs/adapters/sqlite.d.ts.map +1 -1
  11. package/dist/cjs/adapters/sqlite.js +2 -0
  12. package/dist/cjs/adapters/sqlite.js.map +1 -1
  13. package/dist/cjs/codegen/generateManifest.d.ts +3 -1
  14. package/dist/cjs/codegen/generateManifest.d.ts.map +1 -1
  15. package/dist/cjs/codegen/generateManifest.js +195 -3
  16. package/dist/cjs/codegen/generateManifest.js.map +1 -1
  17. package/dist/cjs/core/fileResolution.d.ts +7 -0
  18. package/dist/cjs/core/fileResolution.d.ts.map +1 -1
  19. package/dist/cjs/core/fileResolution.js +53 -14
  20. package/dist/cjs/core/fileResolution.js.map +1 -1
  21. package/dist/cjs/core/metadata.d.ts +5 -0
  22. package/dist/cjs/core/metadata.d.ts.map +1 -1
  23. package/dist/cjs/core/metadata.js.map +1 -1
  24. package/dist/cjs/core/resources.d.ts +36 -0
  25. package/dist/cjs/core/resources.d.ts.map +1 -0
  26. package/dist/cjs/core/resources.js +98 -0
  27. package/dist/cjs/core/resources.js.map +1 -0
  28. package/dist/cjs/core/sourceScanResolver.d.ts +8 -14
  29. package/dist/cjs/core/sourceScanResolver.d.ts.map +1 -1
  30. package/dist/cjs/core/sourceScanResolver.js +8 -20
  31. package/dist/cjs/core/sourceScanResolver.js.map +1 -1
  32. package/dist/cjs/decorators/query.d.ts.map +1 -1
  33. package/dist/cjs/decorators/query.js +96 -35
  34. package/dist/cjs/decorators/query.js.map +1 -1
  35. package/dist/cjs/family.d.ts.map +1 -1
  36. package/dist/cjs/family.js +3 -1
  37. package/dist/cjs/family.js.map +1 -1
  38. package/dist/cjs/index.d.ts +2 -0
  39. package/dist/cjs/index.d.ts.map +1 -1
  40. package/dist/cjs/index.js +4 -1
  41. package/dist/cjs/index.js.map +1 -1
  42. package/dist/cjs/run.d.ts +44 -4
  43. package/dist/cjs/run.d.ts.map +1 -1
  44. package/dist/cjs/run.js +38 -7
  45. package/dist/cjs/run.js.map +1 -1
  46. package/dist/cjs/runtime.d.ts +6 -0
  47. package/dist/cjs/runtime.d.ts.map +1 -1
  48. package/dist/cjs/runtime.js +18 -0
  49. package/dist/cjs/runtime.js.map +1 -1
  50. package/dist/cjs/stack.d.ts +14 -0
  51. package/dist/cjs/stack.d.ts.map +1 -1
  52. package/dist/cjs/stack.js +20 -0
  53. package/dist/cjs/stack.js.map +1 -1
  54. package/dist/cjs/transactions.d.ts +52 -0
  55. package/dist/cjs/transactions.d.ts.map +1 -1
  56. package/dist/cjs/transactions.js +557 -3
  57. package/dist/cjs/transactions.js.map +1 -1
  58. package/dist/esm/adapters/index.js +1 -0
  59. package/dist/esm/adapters/index.js.map +1 -1
  60. package/dist/esm/adapters/sqlego.js +80 -0
  61. package/dist/esm/adapters/sqlego.js.map +1 -0
  62. package/dist/esm/adapters/sqlite.js +2 -2
  63. package/dist/esm/adapters/sqlite.js.map +1 -1
  64. package/dist/esm/codegen/generateManifest.js +195 -3
  65. package/dist/esm/codegen/generateManifest.js.map +1 -1
  66. package/dist/esm/core/fileResolution.js +52 -14
  67. package/dist/esm/core/fileResolution.js.map +1 -1
  68. package/dist/esm/core/metadata.js.map +1 -1
  69. package/dist/esm/core/resources.js +91 -0
  70. package/dist/esm/core/resources.js.map +1 -0
  71. package/dist/esm/core/sourceScanResolver.js +8 -19
  72. package/dist/esm/core/sourceScanResolver.js.map +1 -1
  73. package/dist/esm/decorators/query.js +101 -40
  74. package/dist/esm/decorators/query.js.map +1 -1
  75. package/dist/esm/family.js +3 -1
  76. package/dist/esm/family.js.map +1 -1
  77. package/dist/esm/index.js +1 -0
  78. package/dist/esm/index.js.map +1 -1
  79. package/dist/esm/run.js +38 -8
  80. package/dist/esm/run.js.map +1 -1
  81. package/dist/esm/runtime.js +17 -0
  82. package/dist/esm/runtime.js.map +1 -1
  83. package/dist/esm/stack.js +21 -1
  84. package/dist/esm/stack.js.map +1 -1
  85. package/dist/esm/transactions.js +554 -3
  86. package/dist/esm/transactions.js.map +1 -1
  87. package/package.json +1 -1
  88. package/readme.md +74 -133
@@ -86,6 +86,8 @@ class TxState {
86
86
  this.started = false;
87
87
  this.completed = false;
88
88
  this.rollbackOnly = false;
89
+ /** SQLite opening statement: name-based transactions keep plain BEGIN. */
90
+ this.sqliteBegin = 'BEGIN';
89
91
  this.entry = entry;
90
92
  this.db = entry.db;
91
93
  this.options = {
@@ -131,7 +133,7 @@ class TxState {
131
133
  return;
132
134
  }
133
135
  // sqlite: existing connection is already bound
134
- await this.db.query('BEGIN', []);
136
+ await this.db.query(this.sqliteBegin, []);
135
137
  this.started = true;
136
138
  }
137
139
  async query(sql, params) {
@@ -166,6 +168,9 @@ class TxState {
166
168
  finally {
167
169
  this.txDb = undefined;
168
170
  this.releaseFn = undefined;
171
+ const onRelease = this.onRelease;
172
+ this.onRelease = undefined;
173
+ onRelease?.();
169
174
  }
170
175
  }
171
176
  async finishOnSuccess() {
@@ -265,7 +270,533 @@ export async function withTransaction(fn, options) {
265
270
  };
266
271
  return isNewStore ? await als.run(store, run) : await run();
267
272
  }
268
- export const transaction = function (...args) {
273
+ // ---------------------------------------------------------------------------
274
+ // Scope-based @transaction (docs/transactions.md)
275
+ // ---------------------------------------------------------------------------
276
+ /**
277
+ * One @transaction method invocation. The root scope (no parent) owns every
278
+ * transaction opened in the flow and commits/rolls them back at its exit; a
279
+ * nested scope is a piece of its parent, delimited by savepoints.
280
+ */
281
+ class TxScope {
282
+ constructor(parent) {
283
+ this.closed = false;
284
+ this.markAll = false;
285
+ this.marked = new Set();
286
+ this.afterCommit = [];
287
+ this.afterSettled = [];
288
+ /** Nested scopes: the savepoint this scope holds on each open transaction. */
289
+ this.savepoints = [];
290
+ // Root-only bookkeeping.
291
+ /** Transactions opened in this flow, in open order (root commits them). */
292
+ this.opened = [];
293
+ this.opening = new Map();
294
+ /** Databases this root has opened (multi_database event), with their reported names. */
295
+ this.seen = [];
296
+ this.savepointSeq = 0;
297
+ /** Siblings share one savepoint stack; descendants queue on their own parent. */
298
+ this.childTail = Promise.resolve();
299
+ this.parent = parent;
300
+ this.root = parent ? parent.root : this;
301
+ this.depth = parent ? parent.depth + 1 : 1;
302
+ }
303
+ get hasMarks() {
304
+ return this.markAll || this.marked.size > 0;
305
+ }
306
+ isMarked(state) {
307
+ return this.markAll || this.marked.has(state);
308
+ }
309
+ reserveChild() {
310
+ const ready = this.childTail;
311
+ let release;
312
+ this.childTail = new Promise((resolve) => {
313
+ release = resolve;
314
+ });
315
+ return { ready, release };
316
+ }
317
+ async waitForChildren() {
318
+ let observed;
319
+ do {
320
+ observed = this.childTail;
321
+ await observed;
322
+ } while (observed !== this.childTail);
323
+ }
324
+ }
325
+ const eventListeners = new Set();
326
+ /**
327
+ * Observe transaction trace events. Today the only event is
328
+ * `sqlstack.transaction.multi_database`, emitted once per root scope the
329
+ * moment it opens its second database. Returns an unsubscribe function.
330
+ * Listener errors are ignored so observation never affects a transaction.
331
+ */
332
+ export function onTransactionEvent(listener) {
333
+ eventListeners.add(listener);
334
+ return () => {
335
+ eventListeners.delete(listener);
336
+ };
337
+ }
338
+ function emitTransactionEvent(event) {
339
+ for (const listener of [...eventListeners]) {
340
+ try {
341
+ listener(event);
342
+ }
343
+ catch {
344
+ // observation must never affect the transaction
345
+ }
346
+ }
347
+ }
348
+ /** Innermost scope of this flow that has not exited yet. */
349
+ function activeScope(store) {
350
+ let scope = store?.scope;
351
+ while (scope && scope.closed)
352
+ scope = scope.parent;
353
+ return scope;
354
+ }
355
+ function requireScope(api) {
356
+ const scope = activeScope(getStore());
357
+ if (!scope) {
358
+ throw new SqlStackError(`transaction.${api}() called outside a @transaction method.`);
359
+ }
360
+ return scope;
361
+ }
362
+ // SQLite serialisation: one connection carries one transaction at a time, so
363
+ // independent flows opening a scope transaction on the same connection wait
364
+ // for the previous holder to release instead of failing with "cannot start a
365
+ // transaction within a transaction". Keyed by the Database object (the
366
+ // connection), which is the entry's database.
367
+ const sqliteTails = new WeakMap();
368
+ async function acquireSqliteTurn(db) {
369
+ const previous = sqliteTails.get(db) ?? Promise.resolve();
370
+ let release;
371
+ const mine = new Promise((resolve) => {
372
+ release = resolve;
373
+ });
374
+ sqliteTails.set(db, previous.then(() => mine));
375
+ await previous;
376
+ let released = false;
377
+ return () => {
378
+ if (released)
379
+ return;
380
+ released = true;
381
+ release();
382
+ };
383
+ }
384
+ async function issueSavepoint(scope, state) {
385
+ const name = `sqlstack_sp_${scope.depth}_${++scope.root.savepointSeq}`;
386
+ await state.query(`SAVEPOINT ${name}`, []);
387
+ scope.savepoints.push({ state, name });
388
+ }
389
+ // A Database handle given to run(db, ...) that a @transaction scope opens a
390
+ // transaction on gets one synthetic entry per handle object, so the scope's
391
+ // TxState is keyed by the handle itself. Never registered anywhere; the name is
392
+ // a label only (excluded from name matching in transaction.rollback(name)).
393
+ const HANDLE_LABEL = 'handle';
394
+ const handleEntries = new WeakMap();
395
+ const syntheticEntries = new WeakSet();
396
+ function handleEntryFor(db) {
397
+ let entry = handleEntries.get(db);
398
+ if (!entry) {
399
+ entry = { name: HANDLE_LABEL, db: db, owned: false, stack: undefined };
400
+ handleEntries.set(db, entry);
401
+ syntheticEntries.add(entry);
402
+ }
403
+ return entry;
404
+ }
405
+ function isHandleEntry(entry) {
406
+ return syntheticEntries.has(entry);
407
+ }
408
+ /**
409
+ * Whether a transaction keyed by `other` is the transaction `entry` must join:
410
+ * the same entry, or — when either side was opened through a handle — the
411
+ * same database object (identity). Two registered entries that merely share
412
+ * a Database are left as they were.
413
+ */
414
+ function sameTransactionTarget(entry, other) {
415
+ if (entry === other)
416
+ return true;
417
+ return (isHandleEntry(entry) || isHandleEntry(other)) && entry.db === other.db;
418
+ }
419
+ function findOpenTransaction(store, entry) {
420
+ const direct = store.txByDb.get(entry);
421
+ if (direct)
422
+ return direct;
423
+ for (const [key, state] of store.txByDb) {
424
+ if (!state.completed && sameTransactionTarget(entry, key))
425
+ return state;
426
+ }
427
+ return undefined;
428
+ }
429
+ function findPendingOpen(root, entry) {
430
+ const direct = root.opening.get(entry);
431
+ if (direct)
432
+ return direct;
433
+ for (const [key, pending] of root.opening) {
434
+ if (sameTransactionTarget(entry, key))
435
+ return pending;
436
+ }
437
+ return undefined;
438
+ }
439
+ /** Name reported for `entry` in the multi_database event. */
440
+ function reportedName(store, entry) {
441
+ if (!isHandleEntry(entry))
442
+ return entry.name;
443
+ // A handle that is the database of a registered entry this flow knows uses that name.
444
+ for (const key of store.txByDb.keys()) {
445
+ if (!isHandleEntry(key) && key.db === entry.db)
446
+ return key.name;
447
+ }
448
+ return HANDLE_LABEL;
449
+ }
450
+ async function openScopedTransaction(store, scope, entry) {
451
+ const existing = findOpenTransaction(store, entry);
452
+ if (existing)
453
+ return existing;
454
+ const root = scope.root;
455
+ const pending = findPendingOpen(root, entry);
456
+ if (pending)
457
+ return await pending;
458
+ const open = (async () => {
459
+ const state = new TxState(entry, undefined);
460
+ state.sqliteBegin = 'BEGIN IMMEDIATE';
461
+ const dialect = entry.db.dialect ?? 'sqlite';
462
+ // A flow that already holds this connection must not wait on itself.
463
+ const holdsConnection = root.opened.some((s) => s.db === entry.db && !s.completed);
464
+ if (dialect === 'sqlite' && !holdsConnection) {
465
+ state.onRelease = await acquireSqliteTurn(entry.db);
466
+ }
467
+ try {
468
+ await state.ensureStarted();
469
+ }
470
+ catch (err) {
471
+ await state.release();
472
+ throw err;
473
+ }
474
+ store.txByDb.set(entry, state);
475
+ root.opened.push(state);
476
+ if (!root.seen.some((s) => sameTransactionTarget(entry, s.entry))) {
477
+ root.seen.push({ entry, name: reportedName(store, entry) });
478
+ if (root.seen.length === 2) {
479
+ emitTransactionEvent({
480
+ type: 'sqlstack.transaction.multi_database',
481
+ databases: root.seen.map((s) => s.name),
482
+ });
483
+ }
484
+ }
485
+ // First opened inside a nested scope: every enclosing nested scope gets
486
+ // its savepoint right after BEGIN, outermost first.
487
+ const chain = [];
488
+ for (let s = scope; s && s.parent; s = s.parent)
489
+ chain.unshift(s);
490
+ for (const s of chain)
491
+ await issueSavepoint(s, state);
492
+ return state;
493
+ })();
494
+ root.opening.set(entry, open);
495
+ try {
496
+ return await open;
497
+ }
498
+ finally {
499
+ root.opening.delete(entry);
500
+ }
501
+ }
502
+ /**
503
+ * @internal The transaction a query on `entry` runs in: the one already open
504
+ * in this flow (including one a handle of the same database opened), or —
505
+ * while a @transaction scope is active — one opened on that entry by the
506
+ * query itself (on first execution, not on resolution). Undefined means "run
507
+ * on the database directly".
508
+ */
509
+ export function getTransactionTarget(entry) {
510
+ const store = getStore();
511
+ const open = store ? findOpenTransaction(store, entry) : undefined;
512
+ if (open)
513
+ return open;
514
+ const scope = activeScope(store);
515
+ if (!store || !scope)
516
+ return undefined;
517
+ return {
518
+ async query(sql, params) {
519
+ if (scope.root.closed)
520
+ return await entry.db.query(sql, params);
521
+ const state = await openScopedTransaction(store, scope, entry);
522
+ return await state.query(sql, params);
523
+ },
524
+ };
525
+ }
526
+ /**
527
+ * @internal The transaction a query on a Database handle (run(db, ...)) runs
528
+ * in. A transaction already open in this flow on that exact object is joined
529
+ * (identity; registered or handle-opened). Inside a @transaction scope with
530
+ * none open, the query opens one on the handle on first execution, exactly as
531
+ * the name-resolved path does. Outside any scope the behaviour is unchanged:
532
+ * join by identity or run directly (undefined).
533
+ */
534
+ export function getTransactionTargetForHandle(db) {
535
+ const store = getStore();
536
+ if (!store)
537
+ return undefined;
538
+ for (const state of store.txByDb.values()) {
539
+ if (state.db === db)
540
+ return state;
541
+ }
542
+ const scope = activeScope(store);
543
+ if (!scope)
544
+ return undefined;
545
+ return {
546
+ async query(sql, params) {
547
+ if (scope.root.closed)
548
+ return (await db.query(sql, params));
549
+ const state = await openScopedTransaction(store, scope, handleEntryFor(db));
550
+ return await state.query(sql, params);
551
+ },
552
+ };
553
+ }
554
+ function dropFromStore(store, state) {
555
+ if (store.txByDb.get(state.entry) === state)
556
+ store.txByDb.delete(state.entry);
557
+ }
558
+ async function runHooks(hooks) {
559
+ let failed = false;
560
+ let error;
561
+ for (const hook of hooks) {
562
+ try {
563
+ // Outside every scope: a hook that is itself @transaction opens a fresh one.
564
+ await als.exit(() => hook());
565
+ }
566
+ catch (err) {
567
+ if (!failed) {
568
+ failed = true;
569
+ error = err;
570
+ }
571
+ }
572
+ }
573
+ return { failed, error };
574
+ }
575
+ /** Roll back and release every transaction the root owns. Returns the first failure. */
576
+ async function rollbackOwned(root, store) {
577
+ let failed = false;
578
+ let error;
579
+ for (const state of root.opened) {
580
+ try {
581
+ await state.rollbackIfStarted();
582
+ }
583
+ catch (err) {
584
+ if (!failed) {
585
+ failed = true;
586
+ error = err;
587
+ }
588
+ }
589
+ finally {
590
+ try {
591
+ await state.release();
592
+ }
593
+ catch (err) {
594
+ if (!failed) {
595
+ failed = true;
596
+ error = err;
597
+ }
598
+ }
599
+ dropFromStore(store, state);
600
+ }
601
+ }
602
+ root.opened.length = 0;
603
+ return { failed, error };
604
+ }
605
+ async function exitRootOnSuccess(root, store) {
606
+ // Name-based API compatibility: currentTransaction()?.rollbackOnly(err)
607
+ // rolls everything back and throws, exactly as it does for withTransaction.
608
+ const legacyMarked = root.opened.find((s) => s.rollbackOnly);
609
+ if (legacyMarked) {
610
+ const err = typeof legacyMarked.rollbackError !== 'undefined' ? legacyMarked.rollbackError : new RollbackTransactionError();
611
+ await rollbackOwned(root, store);
612
+ await runHooks(root.afterSettled);
613
+ throw err;
614
+ }
615
+ let failed = false;
616
+ let error;
617
+ for (const state of root.opened) {
618
+ try {
619
+ if (failed || root.isMarked(state))
620
+ await state.rollbackIfStarted();
621
+ else
622
+ await state.commitIfStarted();
623
+ }
624
+ catch (err) {
625
+ if (!failed) {
626
+ failed = true;
627
+ error = err;
628
+ }
629
+ }
630
+ finally {
631
+ try {
632
+ await state.release();
633
+ }
634
+ catch (err) {
635
+ if (!failed) {
636
+ failed = true;
637
+ error = err;
638
+ }
639
+ }
640
+ dropFromStore(store, state);
641
+ }
642
+ }
643
+ root.opened.length = 0;
644
+ const commitHooks = !failed && !root.hasMarks ? await runHooks(root.afterCommit) : { failed: false, error: undefined };
645
+ const settledHooks = await runHooks(root.afterSettled);
646
+ if (failed)
647
+ throw error;
648
+ if (commitHooks.failed)
649
+ throw commitHooks.error;
650
+ if (settledHooks.failed)
651
+ throw settledHooks.error;
652
+ }
653
+ async function exitRootOnError(root, store) {
654
+ await rollbackOwned(root, store);
655
+ await runHooks(root.afterSettled);
656
+ }
657
+ async function exitNestedOnSuccess(scope) {
658
+ const parent = scope.parent;
659
+ try {
660
+ for (const { state, name } of scope.savepoints) {
661
+ if (state.completed)
662
+ continue;
663
+ if (scope.isMarked(state))
664
+ await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
665
+ await state.query(`RELEASE SAVEPOINT ${name}`, []);
666
+ }
667
+ if (!scope.hasMarks)
668
+ parent.afterCommit.push(...scope.afterCommit);
669
+ }
670
+ finally {
671
+ parent.afterSettled.push(...scope.afterSettled);
672
+ }
673
+ }
674
+ async function exitNestedOnError(scope) {
675
+ for (const { state, name } of scope.savepoints) {
676
+ if (state.completed)
677
+ continue;
678
+ try {
679
+ await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
680
+ await state.query(`RELEASE SAVEPOINT ${name}`, []);
681
+ }
682
+ catch {
683
+ // the original error wins; the root rolls back everything if it propagates
684
+ }
685
+ }
686
+ scope.parent.afterSettled.push(...scope.afterSettled);
687
+ }
688
+ async function runInScope(fn) {
689
+ const outer = getStore();
690
+ const parent = activeScope(outer);
691
+ const scope = new TxScope(parent);
692
+ const store = { txByDb: outer?.txByDb ?? new Map(), scope };
693
+ // Reserve synchronously, before yielding: a parent must see even queued children.
694
+ const turn = parent?.reserveChild();
695
+ try {
696
+ if (turn)
697
+ await turn.ready;
698
+ return await als.run(store, async () => {
699
+ let out;
700
+ try {
701
+ if (parent) {
702
+ // Siblings enter one at a time, so releasing one cannot erase another's savepoint.
703
+ for (const state of scope.root.opened) {
704
+ if (!state.completed)
705
+ await issueSavepoint(scope, state);
706
+ }
707
+ }
708
+ out = await fn();
709
+ }
710
+ catch (err) {
711
+ // Promise.all may reject while another child is still writing. Keep this
712
+ // scope active until those children settle, then roll back their work too.
713
+ await scope.waitForChildren();
714
+ scope.closed = true;
715
+ if (parent) {
716
+ await exitNestedOnError(scope);
717
+ throw err;
718
+ }
719
+ await exitRootOnError(scope, store);
720
+ throw isRollbackTransactionError(err) ? unwrapRollbackCause(err) : err;
721
+ }
722
+ await scope.waitForChildren();
723
+ scope.closed = true;
724
+ if (parent)
725
+ await exitNestedOnSuccess(scope);
726
+ else
727
+ await exitRootOnSuccess(scope, store);
728
+ return out;
729
+ });
730
+ }
731
+ finally {
732
+ // Release only after savepoint cleanup and descendants, on success or failure.
733
+ turn?.release();
734
+ }
735
+ }
736
+ function matchOpenTransaction(scope, target) {
737
+ const open = scope.root.opened.filter((s) => !s.completed);
738
+ const state = typeof target === 'string'
739
+ ? open.find((s) => !isHandleEntry(s.entry) && s.entry.name === target)
740
+ : open.find((s) => s.db === target);
741
+ if (!state) {
742
+ throw new SqlStackError(typeof target === 'string'
743
+ ? `transaction.rollback("${target}"): no transaction is open on a database named "${target}" in this scope.`
744
+ : 'transaction.rollback(db): no transaction is open on that database handle in this scope.');
745
+ }
746
+ return state;
747
+ }
748
+ /**
749
+ * Mark the innermost @transaction scope for rollback. Synchronous and
750
+ * non-throwing for the method: SQL after it still runs inside the open
751
+ * transaction; at scope exit the scope rolls back instead of committing and
752
+ * the method's return value still reaches the caller. With a target (a
753
+ * registered database name or a Database handle), only that database's open
754
+ * transaction is marked.
755
+ */
756
+ function markRollback(target) {
757
+ const scope = requireScope('rollback');
758
+ if (typeof target === 'undefined') {
759
+ scope.markAll = true;
760
+ return;
761
+ }
762
+ scope.marked.add(matchOpenTransaction(scope, target));
763
+ }
764
+ /**
765
+ * Roll back everything the innermost scope has done so far, now. The root
766
+ * scope rolls back and releases its transactions (the next query opens fresh
767
+ * ones); a nested scope rolls back to its savepoints. Marks and the scope's
768
+ * pending afterCommit hooks are cleared; afterSettled hooks stay.
769
+ */
770
+ async function restartScope() {
771
+ const scope = requireScope('restart');
772
+ const store = getStore();
773
+ if (scope.parent) {
774
+ for (const { state, name } of scope.savepoints) {
775
+ if (state.completed)
776
+ continue;
777
+ await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
778
+ }
779
+ }
780
+ else {
781
+ const result = await rollbackOwned(scope, store);
782
+ if (result.failed)
783
+ throw result.error;
784
+ }
785
+ scope.markAll = false;
786
+ scope.marked.clear();
787
+ scope.afterCommit = [];
788
+ }
789
+ function registerAfterCommit(fn) {
790
+ if (typeof fn !== 'function')
791
+ throw new SqlStackError('transaction.afterCommit(fn) requires a function.');
792
+ requireScope('afterCommit').afterCommit.push(fn);
793
+ }
794
+ function registerAfterSettled(fn) {
795
+ if (typeof fn !== 'function')
796
+ throw new SqlStackError('transaction.afterSettled(fn) requires a function.');
797
+ requireScope('afterSettled').afterSettled.push(fn);
798
+ }
799
+ const transactionDecorator = function (...args) {
269
800
  // @transaction
270
801
  if (args.length === 3 && typeof args[2]?.value === 'function') {
271
802
  const [target, prop, desc] = args;
@@ -278,10 +809,30 @@ export const transaction = function (...args) {
278
809
  wrapMethod(target, prop, desc, options);
279
810
  };
280
811
  };
812
+ export const transaction = Object.assign(transactionDecorator, {
813
+ rollback: markRollback,
814
+ restart: restartScope,
815
+ afterCommit: registerAfterCommit,
816
+ afterSettled: registerAfterSettled,
817
+ });
818
+ /**
819
+ * A name (`{ db }`) or an eager open (`lazy: false`) keeps the name-based
820
+ * behaviour of withTransaction. Everything else is a scope: no entry is
821
+ * resolved; queries open transactions on first touch.
822
+ */
823
+ function isNameBased(options) {
824
+ return typeof options?.db !== 'undefined' || options?.lazy === false;
825
+ }
281
826
  function wrapMethod(_target, _prop, desc, options) {
282
827
  const original = desc.value;
828
+ if (isNameBased(options)) {
829
+ desc.value = async function (...callArgs) {
830
+ return await withTransaction(() => original.apply(this, callArgs), options);
831
+ };
832
+ return;
833
+ }
283
834
  desc.value = async function (...callArgs) {
284
- return await withTransaction(() => original.apply(this, callArgs), options);
835
+ return await runInScope(() => original.apply(this, callArgs));
285
836
  };
286
837
  }
287
838
  export function getActiveTransaction(entry) {