sqlstack 3.7.1 → 3.7.2-dev.0

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 (49) hide show
  1. package/dist/cjs/adapters/execSqlite.d.ts +34 -0
  2. package/dist/cjs/adapters/execSqlite.d.ts.map +1 -0
  3. package/dist/cjs/adapters/execSqlite.js +36 -0
  4. package/dist/cjs/adapters/execSqlite.js.map +1 -0
  5. package/dist/cjs/adapters/index.d.ts +2 -0
  6. package/dist/cjs/adapters/index.d.ts.map +1 -1
  7. package/dist/cjs/adapters/index.js +3 -1
  8. package/dist/cjs/adapters/index.js.map +1 -1
  9. package/dist/cjs/core/errors.d.ts +13 -0
  10. package/dist/cjs/core/errors.d.ts.map +1 -1
  11. package/dist/cjs/core/errors.js +18 -1
  12. package/dist/cjs/core/errors.js.map +1 -1
  13. package/dist/cjs/family.d.ts +6 -0
  14. package/dist/cjs/family.d.ts.map +1 -1
  15. package/dist/cjs/family.js +126 -33
  16. package/dist/cjs/family.js.map +1 -1
  17. package/dist/cjs/familyBinding.d.ts +4 -0
  18. package/dist/cjs/familyBinding.d.ts.map +1 -1
  19. package/dist/cjs/familyBinding.js.map +1 -1
  20. package/dist/cjs/index.d.ts +1 -1
  21. package/dist/cjs/index.d.ts.map +1 -1
  22. package/dist/cjs/index.js.map +1 -1
  23. package/dist/cjs/registry.d.ts +26 -0
  24. package/dist/cjs/registry.d.ts.map +1 -1
  25. package/dist/cjs/registry.js.map +1 -1
  26. package/dist/cjs/stack.d.ts.map +1 -1
  27. package/dist/cjs/stack.js +29 -4
  28. package/dist/cjs/stack.js.map +1 -1
  29. package/dist/cjs/transactions.d.ts +66 -0
  30. package/dist/cjs/transactions.d.ts.map +1 -1
  31. package/dist/cjs/transactions.js +237 -40
  32. package/dist/cjs/transactions.js.map +1 -1
  33. package/dist/esm/adapters/execSqlite.js +33 -0
  34. package/dist/esm/adapters/execSqlite.js.map +1 -0
  35. package/dist/esm/adapters/index.js +1 -0
  36. package/dist/esm/adapters/index.js.map +1 -1
  37. package/dist/esm/core/errors.js +16 -0
  38. package/dist/esm/core/errors.js.map +1 -1
  39. package/dist/esm/family.js +127 -34
  40. package/dist/esm/family.js.map +1 -1
  41. package/dist/esm/familyBinding.js.map +1 -1
  42. package/dist/esm/index.js.map +1 -1
  43. package/dist/esm/registry.js.map +1 -1
  44. package/dist/esm/stack.js +29 -4
  45. package/dist/esm/stack.js.map +1 -1
  46. package/dist/esm/transactions.js +237 -40
  47. package/dist/esm/transactions.js.map +1 -1
  48. package/package.json +1 -1
  49. package/readme.md +33 -0
@@ -150,9 +150,43 @@ class TxState {
150
150
  if (typeof this.db.transactionHandle === 'function') {
151
151
  this.txDb = this.db.transactionHandle();
152
152
  }
153
- await this.activeDb.query(this.sqliteBegin, []);
153
+ await this.control('begin');
154
154
  this.started = true;
155
155
  }
156
+ /**
157
+ * Send one transaction-control step on the active handle: through its
158
+ * `transactionHooks` when it has them, otherwise as SQL (unchanged path).
159
+ */
160
+ async control(op, name) {
161
+ const db = this.activeDb;
162
+ const hooks = db.transactionHooks;
163
+ if (!hooks) {
164
+ const sql = op === 'begin' ? this.sqliteBegin
165
+ : op === 'commit' ? 'COMMIT'
166
+ : op === 'rollback' ? 'ROLLBACK'
167
+ : op === 'savepoint' ? `SAVEPOINT ${name}`
168
+ : op === 'releaseSavepoint' ? `RELEASE SAVEPOINT ${name}`
169
+ : `ROLLBACK TO SAVEPOINT ${name}`;
170
+ await db.query(sql, []);
171
+ return;
172
+ }
173
+ if (op === 'begin')
174
+ return void (await hooks.begin({ immediate: this.sqliteBegin === 'BEGIN IMMEDIATE' }));
175
+ if (op === 'commit')
176
+ return void (await hooks.commit());
177
+ if (op === 'rollback')
178
+ return void (await hooks.rollback());
179
+ // Check the whole trio before opening a savepoint: a nested scope must not
180
+ // start if it could not later roll back (or release) its piece.
181
+ const required = op === 'savepoint' ? ['savepoint', 'releaseSavepoint', 'rollbackToSavepoint'] : [op];
182
+ const missing = required.filter((k) => typeof hooks[k] !== 'function');
183
+ if (missing.length > 0) {
184
+ throw new errors_1.SqlStackError(`Nested @transaction scopes need savepoints, but this database's transactionHooks has no ${missing.map((k) => `${k}()`).join(', ')} hook. ` +
185
+ 'Supply savepoint, releaseSavepoint and rollbackToSavepoint, or avoid nesting @transaction methods on this database.');
186
+ }
187
+ const fn = hooks[op];
188
+ await fn.call(hooks, name);
189
+ }
156
190
  async query(sql, params) {
157
191
  await this.ensureStarted();
158
192
  return await this.activeDb.query(sql, params);
@@ -164,7 +198,7 @@ class TxState {
164
198
  this.completed = true;
165
199
  return;
166
200
  }
167
- await this.activeDb.query('COMMIT', []);
201
+ await this.control('commit');
168
202
  this.completed = true;
169
203
  }
170
204
  async rollbackIfStarted() {
@@ -174,7 +208,7 @@ class TxState {
174
208
  this.completed = true;
175
209
  return;
176
210
  }
177
- await this.activeDb.query('ROLLBACK', []);
211
+ await this.control('rollback');
178
212
  this.completed = true;
179
213
  }
180
214
  async release() {
@@ -304,9 +338,17 @@ class TxScope {
304
338
  this.afterSettled = [];
305
339
  /** Nested scopes: the savepoint this scope holds on each open transaction. */
306
340
  this.savepoints = [];
341
+ /**
342
+ * Queries (open + statement) owned by this scope or a descendant that have
343
+ * not settled. Every scope drains its own before it closes: a nested scope
344
+ * before its savepoint cleanup, the root before commit/rollback, so no
345
+ * query publishes or writes after its scope's exit has started.
346
+ */
347
+ this.inFlight = new Set();
307
348
  // Root-only bookkeeping.
308
349
  /** Transactions opened in this flow, in open order (root commits them). */
309
350
  this.opened = [];
351
+ /** Undefined: the root closed while the open was waiting, so it ran nothing. */
310
352
  this.opening = new Map();
311
353
  /** Databases this root has opened (multi_database event), with their reported names. */
312
354
  this.seen = [];
@@ -316,6 +358,12 @@ class TxScope {
316
358
  this.parent = parent;
317
359
  this.root = parent ? parent.root : this;
318
360
  this.depth = parent ? parent.depth + 1 : 1;
361
+ this.tornDown = new Promise((resolve) => {
362
+ this.resolveTornDown = resolve;
363
+ });
364
+ }
365
+ markTornDown() {
366
+ this.resolveTornDown();
319
367
  }
320
368
  get hasMarks() {
321
369
  return this.markAll || this.marked.size > 0;
@@ -339,6 +387,36 @@ class TxScope {
339
387
  } while (observed !== this.childTail);
340
388
  }
341
389
  }
390
+ /**
391
+ * The scope a query issued under `scope` belongs to now: `scope` itself, or
392
+ * its nearest ancestor that has not closed (a query can outlive the nested
393
+ * scope it was issued in). Undefined once the root has closed.
394
+ */
395
+ function owningScope(scope) {
396
+ let s = scope;
397
+ while (s && s.closed)
398
+ s = s.parent;
399
+ return s;
400
+ }
401
+ /**
402
+ * Run one scope query, registered in `inFlight` of `owner` and every ancestor
403
+ * until it settles. Callers pick `owner` with owningScope() and call this with
404
+ * no await in between, so registration and the closed check are one step.
405
+ */
406
+ function trackQuery(owner, work) {
407
+ const result = work();
408
+ const settled = result.then(() => undefined, () => undefined);
409
+ const scopes = [];
410
+ for (let s = owner; s; s = s.parent) {
411
+ s.inFlight.add(settled);
412
+ scopes.push(s);
413
+ }
414
+ void settled.then(() => {
415
+ for (const s of scopes)
416
+ s.inFlight.delete(settled);
417
+ });
418
+ return result;
419
+ }
342
420
  const eventListeners = new Set();
343
421
  /**
344
422
  * Observe transaction trace events. Today the only event is
@@ -400,7 +478,8 @@ async function acquireSqliteTurn(db) {
400
478
  }
401
479
  async function issueSavepoint(scope, state) {
402
480
  const name = `sqlstack_sp_${scope.depth}_${++scope.root.savepointSeq}`;
403
- await state.query(`SAVEPOINT ${name}`, []);
481
+ await state.ensureStarted();
482
+ await state.control('savepoint', name);
404
483
  scope.savepoints.push({ state, name });
405
484
  }
406
485
  // A Database handle given to run(db, ...) that a @transaction scope opens a
@@ -464,6 +543,10 @@ function reportedName(store, entry) {
464
543
  }
465
544
  return HANDLE_LABEL;
466
545
  }
546
+ /**
547
+ * Undefined when the root closed while this open was waiting: nothing was left
548
+ * open, and the caller runs the statement on the database directly.
549
+ */
467
550
  async function openScopedTransaction(store, scope, entry) {
468
551
  const existing = findOpenTransaction(store, entry);
469
552
  if (existing)
@@ -481,6 +564,12 @@ async function openScopedTransaction(store, scope, entry) {
481
564
  if (dialect === 'sqlite' && !holdsConnection) {
482
565
  state.onRelease = await acquireSqliteTurn(entry.db);
483
566
  }
567
+ // Backstop: the root drains in-flight queries before closing, so this
568
+ // should not happen; if it does, hand the turn straight back.
569
+ if (root.closed) {
570
+ await state.release();
571
+ return undefined;
572
+ }
484
573
  try {
485
574
  await state.ensureStarted();
486
575
  }
@@ -488,6 +577,54 @@ async function openScopedTransaction(store, scope, entry) {
488
577
  await state.release();
489
578
  throw err;
490
579
  }
580
+ // First opened inside a nested scope: every enclosing nested scope gets
581
+ // its savepoint right after BEGIN, outermost first. The transaction is
582
+ // published (txByDb / root.opened) only once they all exist: until then a
583
+ // concurrent query finds the pending open in root.opening and awaits it
584
+ // (receiving its rejection), so it can never run in — or after the
585
+ // teardown of — a transaction that lacks its savepoints.
586
+ const chain = [];
587
+ for (let s = scope; s && s.parent; s = s.parent)
588
+ chain.unshift(s);
589
+ try {
590
+ for (const s of chain)
591
+ await issueSavepoint(s, state);
592
+ }
593
+ catch (err) {
594
+ for (const s of chain) {
595
+ for (let j = s.savepoints.length - 1; j >= 0; j--)
596
+ if (s.savepoints[j].state === state)
597
+ s.savepoints.splice(j, 1);
598
+ }
599
+ try {
600
+ await state.rollbackIfStarted();
601
+ }
602
+ catch {
603
+ // the savepoint failure wins
604
+ }
605
+ finally {
606
+ await state.release();
607
+ }
608
+ throw err;
609
+ }
610
+ // Backstop: started, but the root has already committed/rolled back and
611
+ // nobody would ever finish it. Roll it back and release it now. No await
612
+ // between this check and the publish below.
613
+ if (root.closed) {
614
+ for (const s of chain) {
615
+ for (let j = s.savepoints.length - 1; j >= 0; j--)
616
+ if (s.savepoints[j].state === state)
617
+ s.savepoints.splice(j, 1);
618
+ }
619
+ try {
620
+ await state.rollbackIfStarted();
621
+ }
622
+ finally {
623
+ await state.release();
624
+ }
625
+ return undefined;
626
+ }
627
+ state.ownerRoot = root;
491
628
  store.txByDb.set(entry, state);
492
629
  root.opened.push(state);
493
630
  if (!root.seen.some((s) => sameTransactionTarget(entry, s.entry))) {
@@ -499,13 +636,6 @@ async function openScopedTransaction(store, scope, entry) {
499
636
  });
500
637
  }
501
638
  }
502
- // First opened inside a nested scope: every enclosing nested scope gets
503
- // its savepoint right after BEGIN, outermost first.
504
- const chain = [];
505
- for (let s = scope; s && s.parent; s = s.parent)
506
- chain.unshift(s);
507
- for (const s of chain)
508
- await issueSavepoint(s, state);
509
639
  return state;
510
640
  })();
511
641
  root.opening.set(entry, open);
@@ -522,24 +652,64 @@ async function openScopedTransaction(store, scope, entry) {
522
652
  * while a @transaction scope is active — one opened on that entry by the
523
653
  * query itself (on first execution, not on resolution). Undefined means "run
524
654
  * on the database directly".
655
+ *
656
+ * Inside a scope every query — on a transaction already open or one it opens —
657
+ * is tracked by its owning scope, so the scope's exit waits for it.
525
658
  */
526
659
  function getTransactionTarget(entry) {
527
660
  const store = getStore();
528
- const open = store ? findOpenTransaction(store, entry) : undefined;
529
- if (open)
530
- return open;
531
- const scope = activeScope(store);
532
- if (!store || !scope)
661
+ if (!store)
533
662
  return undefined;
663
+ // The flow's innermost scope, closed or not: the wrapper decides at query time.
664
+ const scope = store.scope;
665
+ if (!scope)
666
+ return findOpenTransaction(store, entry);
534
667
  return {
535
668
  async query(sql, params) {
536
- if (scope.root.closed)
537
- return await entry.db.query(sql, params);
538
- const state = await openScopedTransaction(store, scope, entry);
539
- return await state.query(sql, params);
669
+ const owner = owningScope(scope);
670
+ if (!owner) {
671
+ return await queryAfterRootClosed(() => findOpenTransaction(store, entry), async () => await entry.db.query(sql, params), sql, params);
672
+ }
673
+ // Registered in the same synchronous step as the closed check.
674
+ return await trackQuery(owner, async () => {
675
+ const state = await openScopedTransaction(store, owner, entry);
676
+ if (!state)
677
+ return await entry.db.query(sql, params);
678
+ return await state.query(sql, params);
679
+ });
540
680
  },
541
681
  };
542
682
  }
683
+ function findStateForDatabase(store, db) {
684
+ for (const state of store.txByDb.values()) {
685
+ if (state.db === db)
686
+ return state;
687
+ }
688
+ return undefined;
689
+ }
690
+ /**
691
+ * A query whose scope chain has fully closed. It never joins a transaction a
692
+ * closed root still owns (its COMMIT/ROLLBACK and release may be in flight, and
693
+ * the query is not tracked by anything): it waits for that root's teardown and
694
+ * looks again — by then the transaction is gone from the flow. A transaction
695
+ * that genuinely encloses the query (an outer withTransaction) is joined.
696
+ */
697
+ async function queryAfterRootClosed(find, direct, sql, params) {
698
+ const waited = new Set();
699
+ for (;;) {
700
+ const open = find();
701
+ const closing = open?.ownerRoot;
702
+ if (closing && closing.closed) {
703
+ // Torn down already and still listed: never join it; run directly.
704
+ if (waited.has(closing))
705
+ return await direct();
706
+ waited.add(closing);
707
+ await closing.tornDown;
708
+ continue;
709
+ }
710
+ return open ? await open.query(sql, params) : await direct();
711
+ }
712
+ }
543
713
  /**
544
714
  * @internal The transaction a query on a Database handle (run(db, ...)) runs
545
715
  * in. A transaction already open in this flow on that exact object is joined
@@ -552,19 +722,25 @@ function getTransactionTargetForHandle(db) {
552
722
  const store = getStore();
553
723
  if (!store)
554
724
  return undefined;
555
- for (const state of store.txByDb.values()) {
556
- if (state.db === db)
557
- return state;
558
- }
559
- const scope = activeScope(store);
725
+ // The flow's innermost scope, closed or not: the wrapper decides at query time.
726
+ const scope = store.scope;
560
727
  if (!scope)
561
- return undefined;
728
+ return findStateForDatabase(store, db);
562
729
  return {
563
730
  async query(sql, params) {
564
- if (scope.root.closed)
565
- return (await db.query(sql, params));
566
- const state = await openScopedTransaction(store, scope, handleEntryFor(db));
567
- return await state.query(sql, params);
731
+ const owner = owningScope(scope);
732
+ if (!owner) {
733
+ return await queryAfterRootClosed(() => findStateForDatabase(store, db), async () => (await db.query(sql, params)), sql, params);
734
+ }
735
+ // Registered in the same synchronous step as the closed check. An open
736
+ // transaction on this object (registered or handle-opened) is joined by
737
+ // openScopedTransaction's identity lookup.
738
+ return await trackQuery(owner, async () => {
739
+ const state = await openScopedTransaction(store, owner, handleEntryFor(db));
740
+ if (!state)
741
+ return (await db.query(sql, params));
742
+ return await state.query(sql, params);
743
+ });
568
744
  },
569
745
  };
570
746
  }
@@ -626,6 +802,7 @@ async function exitRootOnSuccess(root, store) {
626
802
  if (legacyMarked) {
627
803
  const err = typeof legacyMarked.rollbackError !== 'undefined' ? legacyMarked.rollbackError : new errors_1.RollbackTransactionError();
628
804
  await rollbackOwned(root, store);
805
+ root.markTornDown();
629
806
  await runHooks(root.afterSettled);
630
807
  throw err;
631
808
  }
@@ -658,6 +835,7 @@ async function exitRootOnSuccess(root, store) {
658
835
  }
659
836
  }
660
837
  root.opened.length = 0;
838
+ root.markTornDown();
661
839
  const commitHooks = !failed && !root.hasMarks ? await runHooks(root.afterCommit) : { failed: false, error: undefined };
662
840
  const settledHooks = await runHooks(root.afterSettled);
663
841
  if (failed)
@@ -669,6 +847,7 @@ async function exitRootOnSuccess(root, store) {
669
847
  }
670
848
  async function exitRootOnError(root, store) {
671
849
  await rollbackOwned(root, store);
850
+ root.markTornDown();
672
851
  await runHooks(root.afterSettled);
673
852
  }
674
853
  async function exitNestedOnSuccess(scope) {
@@ -678,8 +857,8 @@ async function exitNestedOnSuccess(scope) {
678
857
  if (state.completed)
679
858
  continue;
680
859
  if (scope.isMarked(state))
681
- await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
682
- await state.query(`RELEASE SAVEPOINT ${name}`, []);
860
+ await state.control('rollbackToSavepoint', name);
861
+ await state.control('releaseSavepoint', name);
683
862
  }
684
863
  if (!scope.hasMarks)
685
864
  parent.afterCommit.push(...scope.afterCommit);
@@ -693,8 +872,8 @@ async function exitNestedOnError(scope) {
693
872
  if (state.completed)
694
873
  continue;
695
874
  try {
696
- await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
697
- await state.query(`RELEASE SAVEPOINT ${name}`, []);
875
+ await state.control('rollbackToSavepoint', name);
876
+ await state.control('releaseSavepoint', name);
698
877
  }
699
878
  catch {
700
879
  // the original error wins; the root rolls back everything if it propagates
@@ -702,6 +881,22 @@ async function exitNestedOnError(scope) {
702
881
  }
703
882
  scope.parent.afterSettled.push(...scope.afterSettled);
704
883
  }
884
+ /**
885
+ * Wait for child scopes and for every query this scope (or a descendant) still
886
+ * has in flight (opening or running), then close. The emptiness check and
887
+ * `closed = true` share one synchronous step, so no query can register in
888
+ * between: a nested scope's savepoint cleanup and the root's commit/rollback
889
+ * see every write made under them.
890
+ */
891
+ async function closeWhenIdle(scope) {
892
+ for (;;) {
893
+ await scope.waitForChildren();
894
+ if (scope.inFlight.size === 0)
895
+ break;
896
+ await Promise.all([...scope.inFlight]);
897
+ }
898
+ scope.closed = true;
899
+ }
705
900
  async function runInScope(fn) {
706
901
  const outer = getStore();
707
902
  const parent = activeScope(outer);
@@ -726,9 +921,9 @@ async function runInScope(fn) {
726
921
  }
727
922
  catch (err) {
728
923
  // Promise.all may reject while another child is still writing. Keep this
729
- // scope active until those children settle, then roll back their work too.
730
- await scope.waitForChildren();
731
- scope.closed = true;
924
+ // scope active until those children (and, on a root, queries still
925
+ // opening or running) settle, then roll back their work too.
926
+ await closeWhenIdle(scope);
732
927
  if (parent) {
733
928
  await exitNestedOnError(scope);
734
929
  throw err;
@@ -736,8 +931,7 @@ async function runInScope(fn) {
736
931
  await exitRootOnError(scope, store);
737
932
  throw isRollbackTransactionError(err) ? unwrapRollbackCause(err) : err;
738
933
  }
739
- await scope.waitForChildren();
740
- scope.closed = true;
934
+ await closeWhenIdle(scope);
741
935
  if (parent)
742
936
  await exitNestedOnSuccess(scope);
743
937
  else
@@ -746,6 +940,9 @@ async function runInScope(fn) {
746
940
  });
747
941
  }
748
942
  finally {
943
+ // Never leave a late query waiting on a root that exited abnormally.
944
+ if (!parent)
945
+ scope.markTornDown();
749
946
  // Release only after savepoint cleanup and descendants, on success or failure.
750
947
  turn?.release();
751
948
  }
@@ -791,7 +988,7 @@ async function restartScope() {
791
988
  for (const { state, name } of scope.savepoints) {
792
989
  if (state.completed)
793
990
  continue;
794
- await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
991
+ await state.control('rollbackToSavepoint', name);
795
992
  }
796
993
  }
797
994
  else {