sqlstack 3.7.1 → 3.7.2-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 (50) 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/codegen/cli.js +0 -0
  10. package/dist/cjs/core/errors.d.ts +13 -0
  11. package/dist/cjs/core/errors.d.ts.map +1 -1
  12. package/dist/cjs/core/errors.js +18 -1
  13. package/dist/cjs/core/errors.js.map +1 -1
  14. package/dist/cjs/family.d.ts +6 -0
  15. package/dist/cjs/family.d.ts.map +1 -1
  16. package/dist/cjs/family.js +126 -33
  17. package/dist/cjs/family.js.map +1 -1
  18. package/dist/cjs/familyBinding.d.ts +4 -0
  19. package/dist/cjs/familyBinding.d.ts.map +1 -1
  20. package/dist/cjs/familyBinding.js.map +1 -1
  21. package/dist/cjs/index.d.ts +1 -1
  22. package/dist/cjs/index.d.ts.map +1 -1
  23. package/dist/cjs/index.js.map +1 -1
  24. package/dist/cjs/registry.d.ts +26 -0
  25. package/dist/cjs/registry.d.ts.map +1 -1
  26. package/dist/cjs/registry.js.map +1 -1
  27. package/dist/cjs/stack.d.ts.map +1 -1
  28. package/dist/cjs/stack.js +29 -4
  29. package/dist/cjs/stack.js.map +1 -1
  30. package/dist/cjs/transactions.d.ts +66 -0
  31. package/dist/cjs/transactions.d.ts.map +1 -1
  32. package/dist/cjs/transactions.js +237 -40
  33. package/dist/cjs/transactions.js.map +1 -1
  34. package/dist/esm/adapters/execSqlite.js +33 -0
  35. package/dist/esm/adapters/execSqlite.js.map +1 -0
  36. package/dist/esm/adapters/index.js +1 -0
  37. package/dist/esm/adapters/index.js.map +1 -1
  38. package/dist/esm/core/errors.js +16 -0
  39. package/dist/esm/core/errors.js.map +1 -1
  40. package/dist/esm/family.js +127 -34
  41. package/dist/esm/family.js.map +1 -1
  42. package/dist/esm/familyBinding.js.map +1 -1
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/registry.js.map +1 -1
  45. package/dist/esm/stack.js +29 -4
  46. package/dist/esm/stack.js.map +1 -1
  47. package/dist/esm/transactions.js +237 -40
  48. package/dist/esm/transactions.js.map +1 -1
  49. package/package.json +22 -22
  50. package/readme.md +36 -3
@@ -137,9 +137,43 @@ class TxState {
137
137
  if (typeof this.db.transactionHandle === 'function') {
138
138
  this.txDb = this.db.transactionHandle();
139
139
  }
140
- await this.activeDb.query(this.sqliteBegin, []);
140
+ await this.control('begin');
141
141
  this.started = true;
142
142
  }
143
+ /**
144
+ * Send one transaction-control step on the active handle: through its
145
+ * `transactionHooks` when it has them, otherwise as SQL (unchanged path).
146
+ */
147
+ async control(op, name) {
148
+ const db = this.activeDb;
149
+ const hooks = db.transactionHooks;
150
+ if (!hooks) {
151
+ const sql = op === 'begin' ? this.sqliteBegin
152
+ : op === 'commit' ? 'COMMIT'
153
+ : op === 'rollback' ? 'ROLLBACK'
154
+ : op === 'savepoint' ? `SAVEPOINT ${name}`
155
+ : op === 'releaseSavepoint' ? `RELEASE SAVEPOINT ${name}`
156
+ : `ROLLBACK TO SAVEPOINT ${name}`;
157
+ await db.query(sql, []);
158
+ return;
159
+ }
160
+ if (op === 'begin')
161
+ return void (await hooks.begin({ immediate: this.sqliteBegin === 'BEGIN IMMEDIATE' }));
162
+ if (op === 'commit')
163
+ return void (await hooks.commit());
164
+ if (op === 'rollback')
165
+ return void (await hooks.rollback());
166
+ // Check the whole trio before opening a savepoint: a nested scope must not
167
+ // start if it could not later roll back (or release) its piece.
168
+ const required = op === 'savepoint' ? ['savepoint', 'releaseSavepoint', 'rollbackToSavepoint'] : [op];
169
+ const missing = required.filter((k) => typeof hooks[k] !== 'function');
170
+ if (missing.length > 0) {
171
+ throw new SqlStackError(`Nested @transaction scopes need savepoints, but this database's transactionHooks has no ${missing.map((k) => `${k}()`).join(', ')} hook. ` +
172
+ 'Supply savepoint, releaseSavepoint and rollbackToSavepoint, or avoid nesting @transaction methods on this database.');
173
+ }
174
+ const fn = hooks[op];
175
+ await fn.call(hooks, name);
176
+ }
143
177
  async query(sql, params) {
144
178
  await this.ensureStarted();
145
179
  return await this.activeDb.query(sql, params);
@@ -151,7 +185,7 @@ class TxState {
151
185
  this.completed = true;
152
186
  return;
153
187
  }
154
- await this.activeDb.query('COMMIT', []);
188
+ await this.control('commit');
155
189
  this.completed = true;
156
190
  }
157
191
  async rollbackIfStarted() {
@@ -161,7 +195,7 @@ class TxState {
161
195
  this.completed = true;
162
196
  return;
163
197
  }
164
- await this.activeDb.query('ROLLBACK', []);
198
+ await this.control('rollback');
165
199
  this.completed = true;
166
200
  }
167
201
  async release() {
@@ -291,9 +325,17 @@ class TxScope {
291
325
  this.afterSettled = [];
292
326
  /** Nested scopes: the savepoint this scope holds on each open transaction. */
293
327
  this.savepoints = [];
328
+ /**
329
+ * Queries (open + statement) owned by this scope or a descendant that have
330
+ * not settled. Every scope drains its own before it closes: a nested scope
331
+ * before its savepoint cleanup, the root before commit/rollback, so no
332
+ * query publishes or writes after its scope's exit has started.
333
+ */
334
+ this.inFlight = new Set();
294
335
  // Root-only bookkeeping.
295
336
  /** Transactions opened in this flow, in open order (root commits them). */
296
337
  this.opened = [];
338
+ /** Undefined: the root closed while the open was waiting, so it ran nothing. */
297
339
  this.opening = new Map();
298
340
  /** Databases this root has opened (multi_database event), with their reported names. */
299
341
  this.seen = [];
@@ -303,6 +345,12 @@ class TxScope {
303
345
  this.parent = parent;
304
346
  this.root = parent ? parent.root : this;
305
347
  this.depth = parent ? parent.depth + 1 : 1;
348
+ this.tornDown = new Promise((resolve) => {
349
+ this.resolveTornDown = resolve;
350
+ });
351
+ }
352
+ markTornDown() {
353
+ this.resolveTornDown();
306
354
  }
307
355
  get hasMarks() {
308
356
  return this.markAll || this.marked.size > 0;
@@ -326,6 +374,36 @@ class TxScope {
326
374
  } while (observed !== this.childTail);
327
375
  }
328
376
  }
377
+ /**
378
+ * The scope a query issued under `scope` belongs to now: `scope` itself, or
379
+ * its nearest ancestor that has not closed (a query can outlive the nested
380
+ * scope it was issued in). Undefined once the root has closed.
381
+ */
382
+ function owningScope(scope) {
383
+ let s = scope;
384
+ while (s && s.closed)
385
+ s = s.parent;
386
+ return s;
387
+ }
388
+ /**
389
+ * Run one scope query, registered in `inFlight` of `owner` and every ancestor
390
+ * until it settles. Callers pick `owner` with owningScope() and call this with
391
+ * no await in between, so registration and the closed check are one step.
392
+ */
393
+ function trackQuery(owner, work) {
394
+ const result = work();
395
+ const settled = result.then(() => undefined, () => undefined);
396
+ const scopes = [];
397
+ for (let s = owner; s; s = s.parent) {
398
+ s.inFlight.add(settled);
399
+ scopes.push(s);
400
+ }
401
+ void settled.then(() => {
402
+ for (const s of scopes)
403
+ s.inFlight.delete(settled);
404
+ });
405
+ return result;
406
+ }
329
407
  const eventListeners = new Set();
330
408
  /**
331
409
  * Observe transaction trace events. Today the only event is
@@ -387,7 +465,8 @@ async function acquireSqliteTurn(db) {
387
465
  }
388
466
  async function issueSavepoint(scope, state) {
389
467
  const name = `sqlstack_sp_${scope.depth}_${++scope.root.savepointSeq}`;
390
- await state.query(`SAVEPOINT ${name}`, []);
468
+ await state.ensureStarted();
469
+ await state.control('savepoint', name);
391
470
  scope.savepoints.push({ state, name });
392
471
  }
393
472
  // A Database handle given to run(db, ...) that a @transaction scope opens a
@@ -451,6 +530,10 @@ function reportedName(store, entry) {
451
530
  }
452
531
  return HANDLE_LABEL;
453
532
  }
533
+ /**
534
+ * Undefined when the root closed while this open was waiting: nothing was left
535
+ * open, and the caller runs the statement on the database directly.
536
+ */
454
537
  async function openScopedTransaction(store, scope, entry) {
455
538
  const existing = findOpenTransaction(store, entry);
456
539
  if (existing)
@@ -468,6 +551,12 @@ async function openScopedTransaction(store, scope, entry) {
468
551
  if (dialect === 'sqlite' && !holdsConnection) {
469
552
  state.onRelease = await acquireSqliteTurn(entry.db);
470
553
  }
554
+ // Backstop: the root drains in-flight queries before closing, so this
555
+ // should not happen; if it does, hand the turn straight back.
556
+ if (root.closed) {
557
+ await state.release();
558
+ return undefined;
559
+ }
471
560
  try {
472
561
  await state.ensureStarted();
473
562
  }
@@ -475,6 +564,54 @@ async function openScopedTransaction(store, scope, entry) {
475
564
  await state.release();
476
565
  throw err;
477
566
  }
567
+ // First opened inside a nested scope: every enclosing nested scope gets
568
+ // its savepoint right after BEGIN, outermost first. The transaction is
569
+ // published (txByDb / root.opened) only once they all exist: until then a
570
+ // concurrent query finds the pending open in root.opening and awaits it
571
+ // (receiving its rejection), so it can never run in — or after the
572
+ // teardown of — a transaction that lacks its savepoints.
573
+ const chain = [];
574
+ for (let s = scope; s && s.parent; s = s.parent)
575
+ chain.unshift(s);
576
+ try {
577
+ for (const s of chain)
578
+ await issueSavepoint(s, state);
579
+ }
580
+ catch (err) {
581
+ for (const s of chain) {
582
+ for (let j = s.savepoints.length - 1; j >= 0; j--)
583
+ if (s.savepoints[j].state === state)
584
+ s.savepoints.splice(j, 1);
585
+ }
586
+ try {
587
+ await state.rollbackIfStarted();
588
+ }
589
+ catch {
590
+ // the savepoint failure wins
591
+ }
592
+ finally {
593
+ await state.release();
594
+ }
595
+ throw err;
596
+ }
597
+ // Backstop: started, but the root has already committed/rolled back and
598
+ // nobody would ever finish it. Roll it back and release it now. No await
599
+ // between this check and the publish below.
600
+ if (root.closed) {
601
+ for (const s of chain) {
602
+ for (let j = s.savepoints.length - 1; j >= 0; j--)
603
+ if (s.savepoints[j].state === state)
604
+ s.savepoints.splice(j, 1);
605
+ }
606
+ try {
607
+ await state.rollbackIfStarted();
608
+ }
609
+ finally {
610
+ await state.release();
611
+ }
612
+ return undefined;
613
+ }
614
+ state.ownerRoot = root;
478
615
  store.txByDb.set(entry, state);
479
616
  root.opened.push(state);
480
617
  if (!root.seen.some((s) => sameTransactionTarget(entry, s.entry))) {
@@ -486,13 +623,6 @@ async function openScopedTransaction(store, scope, entry) {
486
623
  });
487
624
  }
488
625
  }
489
- // First opened inside a nested scope: every enclosing nested scope gets
490
- // its savepoint right after BEGIN, outermost first.
491
- const chain = [];
492
- for (let s = scope; s && s.parent; s = s.parent)
493
- chain.unshift(s);
494
- for (const s of chain)
495
- await issueSavepoint(s, state);
496
626
  return state;
497
627
  })();
498
628
  root.opening.set(entry, open);
@@ -509,24 +639,64 @@ async function openScopedTransaction(store, scope, entry) {
509
639
  * while a @transaction scope is active — one opened on that entry by the
510
640
  * query itself (on first execution, not on resolution). Undefined means "run
511
641
  * on the database directly".
642
+ *
643
+ * Inside a scope every query — on a transaction already open or one it opens —
644
+ * is tracked by its owning scope, so the scope's exit waits for it.
512
645
  */
513
646
  export function getTransactionTarget(entry) {
514
647
  const store = getStore();
515
- const open = store ? findOpenTransaction(store, entry) : undefined;
516
- if (open)
517
- return open;
518
- const scope = activeScope(store);
519
- if (!store || !scope)
648
+ if (!store)
520
649
  return undefined;
650
+ // The flow's innermost scope, closed or not: the wrapper decides at query time.
651
+ const scope = store.scope;
652
+ if (!scope)
653
+ return findOpenTransaction(store, entry);
521
654
  return {
522
655
  async query(sql, params) {
523
- if (scope.root.closed)
524
- return await entry.db.query(sql, params);
525
- const state = await openScopedTransaction(store, scope, entry);
526
- return await state.query(sql, params);
656
+ const owner = owningScope(scope);
657
+ if (!owner) {
658
+ return await queryAfterRootClosed(() => findOpenTransaction(store, entry), async () => await entry.db.query(sql, params), sql, params);
659
+ }
660
+ // Registered in the same synchronous step as the closed check.
661
+ return await trackQuery(owner, async () => {
662
+ const state = await openScopedTransaction(store, owner, entry);
663
+ if (!state)
664
+ return await entry.db.query(sql, params);
665
+ return await state.query(sql, params);
666
+ });
527
667
  },
528
668
  };
529
669
  }
670
+ function findStateForDatabase(store, db) {
671
+ for (const state of store.txByDb.values()) {
672
+ if (state.db === db)
673
+ return state;
674
+ }
675
+ return undefined;
676
+ }
677
+ /**
678
+ * A query whose scope chain has fully closed. It never joins a transaction a
679
+ * closed root still owns (its COMMIT/ROLLBACK and release may be in flight, and
680
+ * the query is not tracked by anything): it waits for that root's teardown and
681
+ * looks again — by then the transaction is gone from the flow. A transaction
682
+ * that genuinely encloses the query (an outer withTransaction) is joined.
683
+ */
684
+ async function queryAfterRootClosed(find, direct, sql, params) {
685
+ const waited = new Set();
686
+ for (;;) {
687
+ const open = find();
688
+ const closing = open?.ownerRoot;
689
+ if (closing && closing.closed) {
690
+ // Torn down already and still listed: never join it; run directly.
691
+ if (waited.has(closing))
692
+ return await direct();
693
+ waited.add(closing);
694
+ await closing.tornDown;
695
+ continue;
696
+ }
697
+ return open ? await open.query(sql, params) : await direct();
698
+ }
699
+ }
530
700
  /**
531
701
  * @internal The transaction a query on a Database handle (run(db, ...)) runs
532
702
  * in. A transaction already open in this flow on that exact object is joined
@@ -539,19 +709,25 @@ export function getTransactionTargetForHandle(db) {
539
709
  const store = getStore();
540
710
  if (!store)
541
711
  return undefined;
542
- for (const state of store.txByDb.values()) {
543
- if (state.db === db)
544
- return state;
545
- }
546
- const scope = activeScope(store);
712
+ // The flow's innermost scope, closed or not: the wrapper decides at query time.
713
+ const scope = store.scope;
547
714
  if (!scope)
548
- return undefined;
715
+ return findStateForDatabase(store, db);
549
716
  return {
550
717
  async query(sql, params) {
551
- if (scope.root.closed)
552
- return (await db.query(sql, params));
553
- const state = await openScopedTransaction(store, scope, handleEntryFor(db));
554
- return await state.query(sql, params);
718
+ const owner = owningScope(scope);
719
+ if (!owner) {
720
+ return await queryAfterRootClosed(() => findStateForDatabase(store, db), async () => (await db.query(sql, params)), sql, params);
721
+ }
722
+ // Registered in the same synchronous step as the closed check. An open
723
+ // transaction on this object (registered or handle-opened) is joined by
724
+ // openScopedTransaction's identity lookup.
725
+ return await trackQuery(owner, async () => {
726
+ const state = await openScopedTransaction(store, owner, handleEntryFor(db));
727
+ if (!state)
728
+ return (await db.query(sql, params));
729
+ return await state.query(sql, params);
730
+ });
555
731
  },
556
732
  };
557
733
  }
@@ -613,6 +789,7 @@ async function exitRootOnSuccess(root, store) {
613
789
  if (legacyMarked) {
614
790
  const err = typeof legacyMarked.rollbackError !== 'undefined' ? legacyMarked.rollbackError : new RollbackTransactionError();
615
791
  await rollbackOwned(root, store);
792
+ root.markTornDown();
616
793
  await runHooks(root.afterSettled);
617
794
  throw err;
618
795
  }
@@ -645,6 +822,7 @@ async function exitRootOnSuccess(root, store) {
645
822
  }
646
823
  }
647
824
  root.opened.length = 0;
825
+ root.markTornDown();
648
826
  const commitHooks = !failed && !root.hasMarks ? await runHooks(root.afterCommit) : { failed: false, error: undefined };
649
827
  const settledHooks = await runHooks(root.afterSettled);
650
828
  if (failed)
@@ -656,6 +834,7 @@ async function exitRootOnSuccess(root, store) {
656
834
  }
657
835
  async function exitRootOnError(root, store) {
658
836
  await rollbackOwned(root, store);
837
+ root.markTornDown();
659
838
  await runHooks(root.afterSettled);
660
839
  }
661
840
  async function exitNestedOnSuccess(scope) {
@@ -665,8 +844,8 @@ async function exitNestedOnSuccess(scope) {
665
844
  if (state.completed)
666
845
  continue;
667
846
  if (scope.isMarked(state))
668
- await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
669
- await state.query(`RELEASE SAVEPOINT ${name}`, []);
847
+ await state.control('rollbackToSavepoint', name);
848
+ await state.control('releaseSavepoint', name);
670
849
  }
671
850
  if (!scope.hasMarks)
672
851
  parent.afterCommit.push(...scope.afterCommit);
@@ -680,8 +859,8 @@ async function exitNestedOnError(scope) {
680
859
  if (state.completed)
681
860
  continue;
682
861
  try {
683
- await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
684
- await state.query(`RELEASE SAVEPOINT ${name}`, []);
862
+ await state.control('rollbackToSavepoint', name);
863
+ await state.control('releaseSavepoint', name);
685
864
  }
686
865
  catch {
687
866
  // the original error wins; the root rolls back everything if it propagates
@@ -689,6 +868,22 @@ async function exitNestedOnError(scope) {
689
868
  }
690
869
  scope.parent.afterSettled.push(...scope.afterSettled);
691
870
  }
871
+ /**
872
+ * Wait for child scopes and for every query this scope (or a descendant) still
873
+ * has in flight (opening or running), then close. The emptiness check and
874
+ * `closed = true` share one synchronous step, so no query can register in
875
+ * between: a nested scope's savepoint cleanup and the root's commit/rollback
876
+ * see every write made under them.
877
+ */
878
+ async function closeWhenIdle(scope) {
879
+ for (;;) {
880
+ await scope.waitForChildren();
881
+ if (scope.inFlight.size === 0)
882
+ break;
883
+ await Promise.all([...scope.inFlight]);
884
+ }
885
+ scope.closed = true;
886
+ }
692
887
  async function runInScope(fn) {
693
888
  const outer = getStore();
694
889
  const parent = activeScope(outer);
@@ -713,9 +908,9 @@ async function runInScope(fn) {
713
908
  }
714
909
  catch (err) {
715
910
  // Promise.all may reject while another child is still writing. Keep this
716
- // scope active until those children settle, then roll back their work too.
717
- await scope.waitForChildren();
718
- scope.closed = true;
911
+ // scope active until those children (and, on a root, queries still
912
+ // opening or running) settle, then roll back their work too.
913
+ await closeWhenIdle(scope);
719
914
  if (parent) {
720
915
  await exitNestedOnError(scope);
721
916
  throw err;
@@ -723,8 +918,7 @@ async function runInScope(fn) {
723
918
  await exitRootOnError(scope, store);
724
919
  throw isRollbackTransactionError(err) ? unwrapRollbackCause(err) : err;
725
920
  }
726
- await scope.waitForChildren();
727
- scope.closed = true;
921
+ await closeWhenIdle(scope);
728
922
  if (parent)
729
923
  await exitNestedOnSuccess(scope);
730
924
  else
@@ -733,6 +927,9 @@ async function runInScope(fn) {
733
927
  });
734
928
  }
735
929
  finally {
930
+ // Never leave a late query waiting on a root that exited abnormally.
931
+ if (!parent)
932
+ scope.markTornDown();
736
933
  // Release only after savepoint cleanup and descendants, on success or failure.
737
934
  turn?.release();
738
935
  }
@@ -778,7 +975,7 @@ async function restartScope() {
778
975
  for (const { state, name } of scope.savepoints) {
779
976
  if (state.completed)
780
977
  continue;
781
- await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);
978
+ await state.control('rollbackToSavepoint', name);
782
979
  }
783
980
  }
784
981
  else {