@mistriwork/engine 1.0.0-rc.10 → 1.0.0-rc.12

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 (93) hide show
  1. package/dist/adapters/adapter.d.ts +33 -0
  2. package/dist/adapters/postgres.d.ts +21 -16
  3. package/dist/adapters/postgres.js +199 -223
  4. package/dist/adapters/postgresCatalog.d.ts +12 -1
  5. package/dist/adapters/postgresCatalog.js +57 -23
  6. package/dist/adapters/postgresCatalogDigest.js +40 -34
  7. package/dist/adapters/postgresCatalogRows.d.ts +2 -0
  8. package/dist/adapters/postgresWriteAhead.d.ts +47 -0
  9. package/dist/adapters/postgresWriteAhead.js +209 -0
  10. package/dist/adapters/scoped/keyRows.js +9 -3
  11. package/dist/adapters/scoped/keyTypes.d.ts +34 -0
  12. package/dist/adapters/scoped/keyTypes.js +66 -0
  13. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +40 -1
  14. package/dist/adapters/scoped/postgresScopeCatalog.js +417 -13
  15. package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
  16. package/dist/adapters/scoped/postgresTriggers.js +1545 -0
  17. package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
  18. package/dist/adapters/scoped/scopeTriggers.js +131 -0
  19. package/dist/adapters/scoped/scopedReads.d.ts +3 -1
  20. package/dist/adapters/scoped/scopedReads.js +28 -8
  21. package/dist/adapters/scoped/scopedTransaction.d.ts +95 -6
  22. package/dist/adapters/scoped/scopedTransaction.js +308 -34
  23. package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +17 -1
  24. package/dist/adapters/scoped/sqliteScopeCatalog.js +197 -18
  25. package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
  26. package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
  27. package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
  28. package/dist/adapters/scoped/sqliteTriggers.js +822 -0
  29. package/dist/adapters/scoped/storedText.d.ts +45 -0
  30. package/dist/adapters/scoped/storedText.js +61 -0
  31. package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
  32. package/dist/adapters/scoped/triggerEffects.js +189 -0
  33. package/dist/adapters/scoped/triggerProof.d.ts +124 -0
  34. package/dist/adapters/scoped/triggerProof.js +366 -0
  35. package/dist/adapters/snapshotRead.d.ts +8 -0
  36. package/dist/adapters/snapshotRead.js +37 -0
  37. package/dist/adapters/sqlite.d.ts +13 -2
  38. package/dist/adapters/sqlite.js +139 -16
  39. package/dist/adapters/sqliteDecimals.d.ts +2 -2
  40. package/dist/adapters/sqliteDecimals.js +2 -8
  41. package/dist/adapters/storeHost.d.ts +4 -1
  42. package/dist/adapters/writeCapture.d.ts +7 -0
  43. package/dist/server/cli/args.d.ts +6 -0
  44. package/dist/server/cli/args.js +6 -0
  45. package/dist/server/columnGrants.d.ts +3 -0
  46. package/dist/server/columnGrants.js +12 -1
  47. package/dist/server/config/profile.d.ts +123 -0
  48. package/dist/server/config/profile.js +236 -0
  49. package/dist/server/connections.d.ts +5 -0
  50. package/dist/server/connections.js +11 -1
  51. package/dist/server/hiddenColumns.js +6 -0
  52. package/dist/server/http/refusalReport.js +16 -4
  53. package/dist/server/http/router.d.ts +11 -22
  54. package/dist/server/http/router.js +0 -15
  55. package/dist/server/migrate/cli.d.ts +50 -3
  56. package/dist/server/migrate/cli.js +199 -14
  57. package/dist/server/migrate/runner.js +5 -1
  58. package/dist/server/shapeonly.js +5 -0
  59. package/dist/shared/addressParams.d.ts +2 -0
  60. package/dist/shared/addressParams.js +2 -0
  61. package/dist/shared/aggregate.d.ts +49 -0
  62. package/dist/shared/aggregate.js +107 -0
  63. package/dist/shared/breakdown.js +19 -6
  64. package/dist/shared/decimals.d.ts +37 -0
  65. package/dist/shared/decimals.js +148 -0
  66. package/dist/shared/displayDefaults.js +15 -1
  67. package/dist/shared/filter.d.ts +39 -1
  68. package/dist/shared/filter.js +96 -15
  69. package/dist/shared/listPresentations.d.ts +2 -0
  70. package/dist/shared/listQuestion.d.ts +3 -1
  71. package/dist/shared/money.d.ts +9 -0
  72. package/dist/shared/money.js +17 -0
  73. package/dist/shared/moneyEntry.d.ts +6 -3
  74. package/dist/shared/moneyEntry.js +14 -7
  75. package/dist/shared/pageModel.d.ts +1 -1
  76. package/dist/shared/recordview.d.ts +1 -1
  77. package/dist/shared/refusal.d.ts +16 -0
  78. package/dist/shared/refusal.js +40 -0
  79. package/dist/shared/rowScope.js +12 -4
  80. package/dist/shared/schema.d.ts +6 -0
  81. package/dist/shared/schematext.d.ts +22 -6
  82. package/dist/shared/schematext.js +18 -2
  83. package/dist/shared/scopeCatalog.js +4 -0
  84. package/dist/shared/servedApp.d.ts +15 -4
  85. package/dist/shared/view.js +4 -4
  86. package/dist/shared/viewLabels.d.ts +1 -0
  87. package/dist/shared/viewLabels.js +8 -2
  88. package/dist/shared/viewPaths.d.ts +3 -0
  89. package/dist/shared/viewPaths.js +8 -0
  90. package/package.json +5 -2
  91. package/schema/model.d.ts +1 -1
  92. package/dist/shared/order.d.ts +0 -59
  93. package/dist/shared/order.js +0 -133
@@ -9,10 +9,12 @@
9
9
  */
10
10
  import { isProxy } from 'node:util/types';
11
11
  import { POSTGRES_STYLE, buildWhere, clampLimit, boundStatement, dedupe, looksWrappable, refuseStacked, trimStatement, clampOffset, Refusal, WriteConflict, TransactionOperations, queueRecordLock, recordLockFilter, TransactionOutcomeUnknown, refuseAnalyze, countStatement, countEachStatement, countEachRows, countsTogether, orderClause, } from './adapter.js';
12
+ import { compileAggregate } from '../shared/aggregate.js';
12
13
  import { coerceForColumn } from '../shared/schema.js';
13
14
  import { buildUpdateGuard } from './scoped/updateGuard.js';
14
- import { createScopedTransaction, wholeWithin } from './scoped/scopedTransaction.js';
15
- import { readPostgresScopeCatalog } from './scoped/postgresScopeCatalog.js';
15
+ import { createScopedTransaction, foreignKeyRefusal, isForeignKeyViolation, referencesStatement, wholeWithin, } from './scoped/scopedTransaction.js';
16
+ import { attestPostgresTriggers, effectCatalogFacts, hierarchyRecheck, joinedHierarchy, readPostgresScopeCatalog, } from './scoped/postgresScopeCatalog.js';
17
+ import { postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, readPostgresTableCode, } from './scoped/postgresTriggers.js';
16
18
  import { captureScopeCatalog, mapScopeCatalog } from '../shared/scopeCatalog.js';
17
19
  import { createPinnedPostgresReadOwner } from './postgresReadCatalog.js';
18
20
  import { isRuntimeRelation, qualified, redact, valueSafe, withBytes, toJsonSafe } from './postgresValues.js';
@@ -21,9 +23,11 @@ import { lendStoreHost, } from './storeHost.js';
21
23
  import { compileView, compileViewCount } from '../shared/view.js';
22
24
  import { compileBreakdown, compileBreakdownCount } from '../shared/breakdown.js';
23
25
  import { PgConnectionManager, sharedPgConnections } from './postgresPool.js';
24
- import { aheadReport, behindWrite, generationOf, holdAhead, redoWithoutAhead, sendAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
26
+ import { aheadReport, beforeCommit, behindWrite, generationOf, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
27
+ import { snapshotRead, withoutSnapshotRead } from './snapshotRead.js';
25
28
  import { withoutWriteAhead, writeAhead } from './writeAhead.js';
26
29
  import { KeyRows } from './scoped/keyRows.js';
30
+ import { PLAIN_SCOPE, catalogId, heldLocks, heldRows, lockKey, plainStatement, plainTable, reportWriteAhead, rowLockKey, rowLockStatement, scopedStatement, sendPlainAhead, sendWriteAhead, } from './postgresWriteAhead.js';
27
31
  import { postgresRowEstimate } from './postgresCatalogRows.js';
28
32
  import { describePostgresCatalog, postgresScopeStyle, SYSTEM_SCHEMAS, postgresColumnsOf, assertPostgresTable, } from './postgresCatalog.js';
29
33
  import { postgresCatalogDigestOf, postgresCatalogDigestStatement } from './postgresCatalogDigest.js';
@@ -427,6 +431,59 @@ export class PostgresAdapter {
427
431
  async privileges() {
428
432
  return primaryReads(async () => postgresPrivileges(await this.conn(), this.schemas, SYSTEM_SCHEMAS));
429
433
  }
434
+ /**
435
+ * Each table's triggers, read as a scoped write reads them on its writer. On
436
+ * a writer, inside a transaction rolled back: the proof has PostgreSQL parse
437
+ * each condition into a temporary view (postgresTriggers.ts), which a
438
+ * read-only transaction may not make. Without a writer nothing with a
439
+ * condition is proven, and such a trigger is then said to block.
440
+ */
441
+ async triggers() {
442
+ const schema = await this.introspect();
443
+ const tables = schema.tables.filter((table) => !table.isView);
444
+ // Triggers, and the code a write runs that is not one (a CHECK, a default, a domain calling a function of the database's).
445
+ const read = async (db, analyzer) => {
446
+ const triggers = await postgresTriggersByTable((await db.query(postgresTriggerStatement(false))).rows, analyzer);
447
+ const code = await readPostgresTableCode(db, tables);
448
+ return (key) => [...(triggers.get(key)?.triggers ?? []), ...(code.get(key) ?? [])];
449
+ };
450
+ const byTable = await this.connections
451
+ .withWriteClient(async (write) => {
452
+ await write.query('BEGIN');
453
+ try {
454
+ return await read(write, postgresTriggerAnalyzer(write));
455
+ }
456
+ finally {
457
+ await write.query('ROLLBACK');
458
+ }
459
+ })
460
+ .catch(() => primaryReads(async () => read(await this.conn(), undefined)));
461
+ const found = new Map();
462
+ for (const table of tables) {
463
+ const triggers = byTable(`${table.schema}.${table.name}`);
464
+ if (triggers.length)
465
+ found.set(table.id, triggers);
466
+ }
467
+ return found;
468
+ }
469
+ /**
470
+ * What a write reads of `tables` to judge a trigger's effects (postgresScopeCatalog.ts effectCatalogFacts): their
471
+ * keys, which are in a partition or inheritance hierarchy, and which a scoped write cannot target. On a writer where there is one,
472
+ * inside a transaction rolled back, so the privileges read are the writer's, as `triggers` reads.
473
+ */
474
+ async triggerKeys(tables) {
475
+ return this.connections
476
+ .withWriteClient(async (write) => {
477
+ await write.query('BEGIN');
478
+ try {
479
+ return await effectCatalogFacts(write, tables);
480
+ }
481
+ finally {
482
+ await write.query('ROLLBACK');
483
+ }
484
+ })
485
+ .catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables)));
486
+ }
430
487
  /** The catalog as one handle sees it, read by postgresCatalog.ts: the
431
488
  * reader on connect, or the leased writer inside a scoped transaction,
432
489
  * where the same description is the evidence the deployed permissions are
@@ -513,12 +570,13 @@ export class PostgresAdapter {
513
570
  * plainly, and the transaction describes what it needs as before.
514
571
  */
515
572
  async openWrite(write, options, began) {
573
+ const begin = beginOf(write) + (options.session ?? '');
516
574
  // Begun again on the same handle (a scope's retry), what the last transaction read is not this one's.
517
575
  noteCatalogVersion(write, this.database, undefined);
518
576
  if (this.epochStore === false) {
519
577
  if (options.digest)
520
578
  return this.openWithDigest(write, options, began);
521
- const opening = write.query('BEGIN');
579
+ const opening = write.query(begin);
522
580
  options.sent?.();
523
581
  await opening;
524
582
  began();
@@ -529,7 +587,7 @@ export class PostgresAdapter {
529
587
  const statement = schemaEpochStatement();
530
588
  let answered;
531
589
  try {
532
- const opening = write.query(`BEGIN;${options.lock?.length ? ` LOCK TABLE ${options.lock.join(', ')} IN ROW EXCLUSIVE MODE;` : ''}${options.pin ? ` ${options.pin};` : ''} ${statement}`);
590
+ const opening = write.query(`${begin};${options.lock?.length ? ` LOCK TABLE ${options.lock.join(', ')} IN ROW EXCLUSIVE MODE;` : ''}${options.pin ? ` ${options.pin};` : ''} ${statement}`);
533
591
  // Behind it, in the same flight: what the transaction opens with (sendWriteAhead).
534
592
  options.sent?.();
535
593
  answered = await opening;
@@ -546,7 +604,7 @@ export class PostgresAdapter {
546
604
  }
547
605
  if (this.epochStore === false && options.digest)
548
606
  return this.openWithDigest(write, options, began);
549
- await write.query('BEGIN');
607
+ await write.query(begin);
550
608
  began();
551
609
  return {};
552
610
  }
@@ -577,9 +635,10 @@ export class PostgresAdapter {
577
635
  * never less exact; a message that fails begins again the long way.
578
636
  */
579
637
  async openWithDigest(write, options, began) {
638
+ const begin = beginOf(write) + (options.session ?? '');
580
639
  let answered;
581
640
  try {
582
- const opening = write.query(`BEGIN;${options.lock?.length ? ` LOCK TABLE ${options.lock.join(', ')} IN ROW EXCLUSIVE MODE;` : ''}${options.pin ? ` ${options.pin};` : ''} ${SCOPED_CATALOG_DIGEST}`);
641
+ const opening = write.query(`${begin};${options.lock?.length ? ` LOCK TABLE ${options.lock.join(', ')} IN ROW EXCLUSIVE MODE;` : ''}${options.pin ? ` ${options.pin};` : ''} ${SCOPED_CATALOG_DIGEST}`);
583
642
  options.sent?.();
584
643
  answered = await opening;
585
644
  }
@@ -590,7 +649,7 @@ export class PostgresAdapter {
590
649
  catch {
591
650
  /* The BEGIN below says whether this client can go on. */
592
651
  }
593
- await write.query('BEGIN');
652
+ await write.query(begin);
594
653
  began();
595
654
  return {};
596
655
  }
@@ -767,6 +826,9 @@ export class PostgresAdapter {
767
826
  async count(table, filter, limit) {
768
827
  return this.countOn(table, filter, await this.conn(), limit, true);
769
828
  }
829
+ async aggregate(request) {
830
+ return this.aggregateOn(request, await this.conn());
831
+ }
770
832
  async countEach(items, limit) {
771
833
  const relations = await Promise.all(items.map(async (item) => {
772
834
  const { schema, name } = await this.readTable(item.table);
@@ -783,6 +845,15 @@ export class PostgresAdapter {
783
845
  const result = await db.query(text, where.params);
784
846
  return Number(result.rows[0]?.n ?? 0);
785
847
  }
848
+ /* A command's aggregate on its own transaction's client (shared/aggregate.ts): one statement over the table as
849
+ `countOn` names it, its numeric and bigint answers the exact text the driver reads them as. */
850
+ async aggregateOn(request, db) {
851
+ const { schema: namespace, name } = await this.assertTable(request.table, db);
852
+ const catalog = await this.schema();
853
+ const compiled = compileAggregate(catalog, { ...request, table: `${namespace}.${name}` }, POSTGRES_STYLE);
854
+ const result = await db.query(compiled.text, compiled.params);
855
+ return { rows: result.rows.map(toJsonSafe) };
856
+ }
786
857
  async columnsOf(schema, name, db) {
787
858
  return postgresColumnsOf(schema, name, db, this.epochOf(db), this.catalogCache, () => this.conn());
788
859
  }
@@ -839,7 +910,7 @@ export class PostgresAdapter {
839
910
  /* Coerced against the declared type, because everything typed into a
840
911
  text box arrives as a string — and Postgres, unlike SQLite, rejects
841
912
  "17901" for a numeric column rather than quietly taking it. */
842
- applied[column] = coerceForColumn(declared.type || '', raw);
913
+ applied[column] = coerceForColumn(declared.written || declared.type || '', raw);
843
914
  if (applied[column] === null && declared.notnull) {
844
915
  throw new Refusal(`"${column}" is NOT NULL and cannot be emptied.`);
845
916
  }
@@ -912,7 +983,7 @@ export class PostgresAdapter {
912
983
  const declared = meta.find((c) => c.name === column);
913
984
  if (!declared)
914
985
  throw new Refusal(`${id} has no column called "${column}".`);
915
- applied[column] = coerceForColumn(declared.type || '', raw);
986
+ applied[column] = coerceForColumn(declared.written || declared.type || '', raw);
916
987
  if (applied[column] === null && declared.notnull) {
917
988
  throw new Refusal(`"${column}" is NOT NULL and cannot be null. Leave it out to use its default, if it has one.`);
918
989
  }
@@ -998,7 +1069,7 @@ export class PostgresAdapter {
998
1069
  },
999
1070
  });
1000
1071
  if (!history)
1001
- return { ...base, finish: async () => { }, committed: () => { } };
1072
+ return { ...base, finish: async () => { }, committed: () => { }, triggered: async () => { } };
1002
1073
  return {
1003
1074
  insert: (r) => history.insert(r, base.insert),
1004
1075
  update: (r) => history.update(r, base.update),
@@ -1006,6 +1077,7 @@ export class PostgresAdapter {
1006
1077
  tell: (r) => history.tell(r),
1007
1078
  finish: () => finishWriteCapture(history),
1008
1079
  committed: () => committedWriteCapture(history),
1080
+ triggered: async (change) => history.triggered?.(change),
1009
1081
  };
1010
1082
  }
1011
1083
  async removeNow(request, write, read) {
@@ -1063,11 +1135,14 @@ export class PostgresAdapter {
1063
1135
  record's earlier writes. */
1064
1136
  async transact(lane, run) {
1065
1137
  const hint = writeAhead();
1138
+ const snapshot = snapshotRead();
1066
1139
  const schema = hint ? await this.schema().catch(() => undefined) : undefined;
1067
1140
  return this.watched(this.writes.run(lane, () => this.connections.withWriteClient(async (leased) => {
1068
1141
  // Its own handle, as a journal's: what it was told leaves behind its BEGIN, and writes nothing reads with its COMMIT.
1069
1142
  // A writer that pipelines sends reads asked together in one flight (TransactionOperations.read).
1070
1143
  const write = transactionHandle(leased, this), operations = new TransactionOperations(sendsAhead(write));
1144
+ if (snapshot)
1145
+ snapshotHandles.add(write);
1071
1146
  let began = false;
1072
1147
  let commitAttempted = false;
1073
1148
  let committed = false;
@@ -1081,15 +1156,16 @@ export class PostgresAdapter {
1081
1156
  update: (r) => this.updateNow(r, write, write),
1082
1157
  }, reads);
1083
1158
  // The transaction's own work runs without the hint: a transaction it opens is not this one.
1084
- const out = await withoutWriteAhead(() => run({
1159
+ const out = await withoutWriteAhead(() => withoutSnapshotRead(() => run({
1085
1160
  lockRecord: (r) => queueRecordLock(operations, r, (request) => this.lockRecordNow(request, write)),
1086
1161
  query: (r) => operations.read(() => reads(r)),
1087
1162
  count: (table, filter) => operations.read(() => this.countOn(table, filter, write)),
1163
+ aggregate: (r) => operations.read(() => this.aggregateOn(r, write)),
1088
1164
  insert: (r) => operations.run(() => writes.insert(r)),
1089
1165
  remove: (r) => operations.run(() => writes.remove(r)),
1090
1166
  update: (r) => operations.run(() => writes.update(r)),
1091
1167
  ...(writes.tell ? { tell: (r) => operations.run(() => writes.tell(r)) } : {}),
1092
- }));
1168
+ })));
1093
1169
  await operations.finish();
1094
1170
  await writes.finish();
1095
1171
  commitAttempted = true;
@@ -1140,7 +1216,7 @@ export class PostgresAdapter {
1140
1216
  async openPlain(write, schema, journal, hint, began) {
1141
1217
  const keyRows = new KeyRows(() => generationOf(write));
1142
1218
  let aheads = [];
1143
- await this.openWrite(write, schema && hint ? { sent: () => void (aheads = this.sendPlainAhead(write, schema, keyRows, journal, hint)) } : {}, began);
1219
+ await this.openWrite(write, schema && hint ? { sent: () => void (aheads = sendPlainAhead(this, write, schema, keyRows, journal, hint)) } : {}, began);
1144
1220
  if (aheads.length && (await aheadsFailed(aheads))) {
1145
1221
  redoWithoutAhead(write);
1146
1222
  keyRows.forget();
@@ -1180,60 +1256,6 @@ export class PostgresAdapter {
1180
1256
  return kept(named);
1181
1257
  };
1182
1258
  }
1183
- /** The statements openPlain sends behind the BEGIN; each exactly what the transaction sends in its turn (lockRecordNow, queryOn). */
1184
- sendPlainAhead(write, schema, keyRows, journal, hint) {
1185
- if (!sendsAhead(write))
1186
- return [];
1187
- const opening = [];
1188
- try {
1189
- if (hint.receipt !== undefined && journal?.ahead)
1190
- opening.push(...journal.ahead(hint.receipt));
1191
- }
1192
- catch {
1193
- /* Asked in its turn. */
1194
- }
1195
- const answers = sendAhead(write, opening);
1196
- for (const target of hint.targets) {
1197
- const table = schema.tables.find((candidate) => candidate.id === catalogId(target.table));
1198
- if (!table || table.isView || isRuntimeRelation(table.id))
1199
- continue;
1200
- const pk = table.columns.filter((column) => column.primaryKey).map((column) => column.name);
1201
- const key = target.key;
1202
- if (!pk.length ||
1203
- Object.keys(key).length !== pk.length ||
1204
- !pk.every((column) => Object.hasOwn(key, column) && (typeof key[column] === 'string' || typeof key[column] === 'number')))
1205
- continue;
1206
- const filter = { groups: [pk.map((column) => ({ column, op: '=', value: key[column] }))] };
1207
- if (!hint.readOnly && (hint.locks || (hint.writes && capturesWrites(this, table.id)))) {
1208
- /* lockRecordNow's statement, where the transaction will send it (the save's own lock, the history capture's). Held rather than answered once: the row stays locked until the transaction ends,
1209
- so each later lock of it in this transaction (the command's, the history capture's) is answered by it, even
1210
- after a write to another record has moved the statement generation. */
1211
- const [text, values] = rowLockStatement(table, key);
1212
- const lock = holdAhead(write, { text, values });
1213
- if (lock) {
1214
- answers.push(lock.answer);
1215
- const locks = heldLocks.get(write) ?? new Map();
1216
- heldLocks.set(write, locks);
1217
- const rows = heldRows.get(write) ?? new Set();
1218
- heldRows.set(write, rows);
1219
- void lock.answer.then((result) => {
1220
- if (result.rows.length <= 1)
1221
- locks.set(lockKey(text, values), lock.take);
1222
- // Only a row that is there is held: one that is not could be inserted by another transaction meanwhile.
1223
- if (result.rows.length === 1)
1224
- rows.add(lockKey(text, values));
1225
- }, () => { });
1226
- }
1227
- }
1228
- const read = plainStatement({ table: table.id, filter, limit: 2, offset: 0 });
1229
- const row = read && holdAhead(write, { text: read.text, values: read.params });
1230
- if (row) {
1231
- answers.push(row.answer);
1232
- keyRows.keep(PLAIN_SCOPE, table, filter, row.answer.then((result) => result.rows), row.take);
1233
- }
1234
- }
1235
- return answers;
1236
- }
1237
1259
  /**
1238
1260
  * Same-source records and a durable journal in one transaction, the
1239
1261
  * journal lent by the App framework (storeHost.ts TransactionJournal): the
@@ -1264,18 +1286,21 @@ export class PostgresAdapter {
1264
1286
  const verify = options.ordinaryVerify;
1265
1287
  return this.ordinaryJournalTransaction(journal, run, verify && (async () => void (await verify())));
1266
1288
  }
1267
- return this.scopedTransact(options.scope, journal, run, options.verify, options.bound);
1289
+ return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers);
1268
1290
  }
1269
1291
  async ordinaryJournalTransaction(journal, run, verify) {
1270
1292
  /* The command host supplies target and receipt lanes through inWriteLanes.
1271
1293
  Extra records discovered inside the handler still rely on row locks and
1272
1294
  compare-and-set, as they do across processes. */
1273
1295
  const hint = writeAhead();
1296
+ const snapshot = snapshotRead();
1274
1297
  const schema = hint ? await this.schema().catch(() => undefined) : undefined;
1275
1298
  return this.watched(this.writes.run([], () => this.connections.withWriteClient(async (leased) => {
1276
1299
  // Its own handle, as a scoped transaction's: writes nothing reads leave with its COMMIT (beforeCommit).
1277
1300
  // A writer that pipelines sends reads asked together in one flight (TransactionOperations.read).
1278
1301
  const write = transactionHandle(leased, this), operations = new TransactionOperations(sendsAhead(write));
1302
+ if (snapshot)
1303
+ snapshotHandles.add(write);
1279
1304
  let began = false;
1280
1305
  let commitAttempted = false;
1281
1306
  let committed = false;
@@ -1295,13 +1320,14 @@ export class PostgresAdapter {
1295
1320
  lockRecord: (r) => queueRecordLock(operations, r, (request) => this.lockRecordNow(request, write)),
1296
1321
  query: (r) => operations.read(() => reads(r)),
1297
1322
  count: (table, filter) => operations.read(() => this.countOn(table, filter, write)),
1323
+ aggregate: (r) => operations.read(() => this.aggregateOn(r, write)),
1298
1324
  insert: (r) => operations.run(() => writes.insert(r)),
1299
1325
  remove: (r) => operations.run(() => writes.remove(r)),
1300
1326
  update: (r) => operations.run(() => writes.update(r)),
1301
1327
  ...(writes.tell ? { tell: (r) => operations.run(() => writes.tell(r)) } : {}),
1302
1328
  };
1303
1329
  // The transaction's own work runs without the hint: a transaction it opens is not this one.
1304
- const out = await withoutWriteAhead(() => run(Object.freeze(records), journal.open(write, operations)));
1330
+ const out = await withoutWriteAhead(() => withoutSnapshotRead(() => run(Object.freeze(records), journal.open(write, operations))));
1305
1331
  await operations.finish();
1306
1332
  await writes.finish();
1307
1333
  if (verify) {
@@ -1365,9 +1391,9 @@ export class PostgresAdapter {
1365
1391
  * rollback that was not acknowledged, is unknown, and the client is
1366
1392
  * discarded rather than reused. Everything else did not commit.
1367
1393
  */
1368
- async scopeTransaction(input, run) {
1394
+ async scopeTransaction(input, run, triggers) {
1369
1395
  const scope = captureRowScope(input);
1370
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog));
1396
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers);
1371
1397
  }
1372
1398
  /**
1373
1399
  * Private source-owner boundary, deliberately absent from Adapter: the
@@ -1435,18 +1461,28 @@ export class PostgresAdapter {
1435
1461
  /* Scoped records and, for a command, the durable journal and fresh catalog
1436
1462
  evidence in one transaction. The journal is attested before the catalog
1437
1463
  is read, so an unmigrated layout refuses before any lock is taken. */
1438
- async scopedTransact(scope, journal, run, verify, bound) {
1464
+ async scopedTransact(scope, journal, run, verify, bound, triggers) {
1465
+ /* The proof is loaded where a transaction accepts triggers, not at startup; and awaited in the transaction's turn,
1466
+ not before it is queued: a write asked after this one would otherwise take its turn while the module loads. */
1467
+ const loading = triggers && !journal?.fixedRecords ? import('./scoped/triggerProof.js') : undefined;
1468
+ loading?.catch(() => { }); // Rejected or not, it is awaited in its turn below.
1439
1469
  // This transaction's own handle: what its verifier learns is kept on it, never on the pooled client.
1440
1470
  /* No lane: every target is taken FOR UPDATE and every parent FOR SHARE
1441
1471
  before it is checked (below), which is what orders two of these
1442
1472
  across connections, in this process as across pods. */
1443
1473
  const hint = writeAhead();
1474
+ const snapshot = snapshotRead();
1444
1475
  return this.writes.run([], () => this.connections.withWriteClient(async (leased) => {
1476
+ const proving = await loading;
1445
1477
  // A writer that pipelines sends reads asked together in one flight (TransactionOperations.read).
1446
1478
  const write = transactionHandle(leased, this), operations = new TransactionOperations(sendsAhead(write));
1479
+ if (snapshot)
1480
+ snapshotHandles.add(write);
1447
1481
  let began = false;
1448
1482
  let commitAttempted = false;
1449
1483
  let committed = false;
1484
+ // The proof of the validation-only triggers this transaction's writes fired, read again (attestPostgresTriggers).
1485
+ let attest;
1450
1486
  try {
1451
1487
  /* The scope catalog is kept per set of scoped tables under the epoch;
1452
1488
  the tables it pinned last time are pinned in the message that reads
@@ -1464,10 +1500,10 @@ export class PostgresAdapter {
1464
1500
  // The rows whose locks were sent ahead, held from the moment their answers came back (sendWriteAhead).
1465
1501
  const lockedAhead = new Set();
1466
1502
  let aheads = [];
1467
- const opening = { lock: pinned, pin, digest: true };
1503
+ const opening = { lock: pinned, pin, digest: true, session: SCOPED_SESSION };
1468
1504
  let opened = await this.openWrite(write, {
1469
1505
  ...opening,
1470
- sent: () => void (aheads = this.sendWriteAhead(write, scope, peeked, keyRows, journal, verify, hint, lockedAhead)),
1506
+ sent: () => void (aheads = sendWriteAhead(this, write, scope, peeked, keyRows, journal, verify, hint, lockedAhead)),
1471
1507
  }, () => {
1472
1508
  began = true;
1473
1509
  });
@@ -1537,7 +1573,7 @@ export class PostgresAdapter {
1537
1573
  checkedScopes.set(given, (checked = snapshotRowScope(catalog.schema, given)));
1538
1574
  return checked;
1539
1575
  };
1540
- const scopedReads = (guard, given = scope, within = checkedScope(given)) => keyRows.over(createScopedReads(catalog.schema, within, POSTGRES_STYLE, executor(guard)), given, catalog.schema, (request) => scopedStatement(catalog.schema, within, request), (row, request) => formatted(guard, request.binary)(row), guard, guard ? undefined : { held: holds, reads: createScopedReads(catalog.schema, within, POSTGRES_STYLE, executor(true)) });
1576
+ const scopedReads = (guard, given = scope, within = checkedScope(given)) => keyRows.over(createScopedReads(catalog.schema, within, POSTGRES_STYLE, executor(guard), guard), given, catalog.schema, (request) => scopedStatement(catalog.schema, within, request), (row, request) => formatted(guard, request.binary)(row), guard, guard ? undefined : { held: holds, reads: createScopedReads(catalog.schema, within, POSTGRES_STYLE, executor(true)) });
1541
1577
  const lock = (mode) => async (table, filter) => {
1542
1578
  // A parent the role cannot update cannot be held; its FK's own KEY
1543
1579
  // SHARE still stops deletion, and the visibility check is one read.
@@ -1550,7 +1586,8 @@ export class PostgresAdapter {
1550
1586
  const had = held.get(at);
1551
1587
  if (had === 'UPDATE' || had === mode)
1552
1588
  return;
1553
- const where = buildWhere(filter, POSTGRES_STYLE);
1589
+ // A parent is held by the key its reference names as the foreign key compares it (Condition.equality).
1590
+ const where = buildWhere(filter, POSTGRES_STYLE, 1, undefined, undefined, undefined, undefined, mode === 'SHARE');
1554
1591
  const text = `SELECT 1 FROM ${qualified(table)}${where.text} FOR ${mode}`;
1555
1592
  /* Sent ahead behind the BEGIN and granted, its answer since dropped by a write of the transaction's own:
1556
1593
  the row is held all the same, to the transaction's end. While that answer still waits, asking takes it. */
@@ -1566,6 +1603,11 @@ export class PostgresAdapter {
1566
1603
  remove: (r) => this.removeNow(r, write, write),
1567
1604
  update: (r) => this.updateNow(r, write, write),
1568
1605
  });
1606
+ // The tables whose validation-only triggers a write of this transaction fired: their proof is read again before COMMIT.
1607
+ const relied = new Set();
1608
+ // The tables this transaction's writes targeted: whether one joined a hierarchy is read again with the COMMIT.
1609
+ const written = new Set();
1610
+ attest = () => attestPostgresTriggers(write, catalog, relied);
1569
1611
  let records = createScopedTransaction(catalog, {
1570
1612
  query: (r) => this.queryOn(r, write),
1571
1613
  count: (table, filter) => this.countOn(table, filter, write),
@@ -1580,29 +1622,87 @@ export class PostgresAdapter {
1580
1622
  return behindWrite(write, (text) => text.startsWith(update), ride);
1581
1623
  },
1582
1624
  together: sendsAhead(write),
1583
- }, bound && { reads: scopedReads(true, bound), whole: wholeWithin(scope, bound) },
1625
+ relied: (table) => void relied.add(table.id),
1626
+ written: (table) => void written.add(table.id),
1627
+ }, bound && {
1628
+ reads: scopedReads(true, bound),
1629
+ whole: wholeWithin(scope, bound),
1630
+ references: async (fk, key) => {
1631
+ const statement = referencesStatement(catalog, fk, key, POSTGRES_STYLE);
1632
+ return Number((await write.query(statement.text, statement.params)).rows[0]?.n ?? 0);
1633
+ },
1634
+ },
1584
1635
  // A public intake writes exactly its fixed rows; only a principal's own transaction counts its new parents in.
1585
- journal?.fixedRecords ? undefined : { scope, reads: (within, guard) => scopedReads(guard, within) });
1636
+ journal?.fixedRecords ? undefined : { scope, reads: (within, guard) => scopedReads(guard, within) },
1637
+ // Triggers the App names, on a principal's own transaction: their effects proven per write (triggerProof.ts).
1638
+ triggers && proving
1639
+ ? {
1640
+ prove: proving.createTriggerProof,
1641
+ acceptance: {
1642
+ ...triggers,
1643
+ // Kept and announced as the transaction's own writes are (writeCapture.ts).
1644
+ changed: async (change) => {
1645
+ await writes.triggered(change);
1646
+ await triggers.changed?.(change);
1647
+ },
1648
+ },
1649
+ scope,
1650
+ }
1651
+ : undefined);
1586
1652
  if (journal?.fixedRecords)
1587
1653
  records = journal.fixedRecords(records);
1588
1654
  const invoke = scopedCommandInvoker(operations, true, journal !== undefined, isRuntimeRelation);
1589
1655
  // The transaction's own work runs without the hint: a transaction it opens is not this one.
1590
- const out = await withoutWriteAhead(() => run(Object.freeze({
1656
+ const out = await withoutWriteAhead(() => withoutSnapshotRead(() => run(Object.freeze({
1591
1657
  // The scoped policy facade deliberately has no generic lock capability.
1592
1658
  query: (r) => invoke(r, (r) => records.query(r), true),
1593
1659
  count: (table, filter) => invoke({ table, filter }, (r) => records.count(r.table, r.filter), true),
1660
+ ...(records.aggregate ? { aggregate: (r) => invoke(r, (r) => records.aggregate(r), true) } : {}),
1594
1661
  insert: (r) => invoke(r, (r) => records.insert(r)),
1595
1662
  remove: (r) => invoke(r, (r) => records.remove(r)),
1596
1663
  update: (r) => invoke(r, (r) => records.update(r)),
1597
1664
  // Beneath the row scope: the flows' command tells only of its own target, which it read through the scope.
1598
1665
  ...(writes.tell ? { tell: (r) => invoke(r, (r) => writes.tell(r)) } : {}),
1599
- }), journal?.open(write, operations), evidence));
1666
+ }), journal?.open(write, operations), evidence)));
1600
1667
  await operations.finish();
1601
1668
  await writes.finish();
1602
1669
  if (verify)
1603
1670
  await verify(write, catalog, described);
1671
+ await attestPostgresTriggers(write, catalog, relied);
1672
+ /* A target's triggers may write any table the scope can write (triggerEffects.ts): where one ran, each of
1673
+ those is read again too. */
1674
+ const reached = [...written].some((id) => catalog.triggered?.has(id))
1675
+ ? [...written, ...catalog.writable, ...(catalog.triggered?.keys() ?? [])]
1676
+ : written;
1677
+ /* And what they reference, for a parent that gained an inheritance child (ScopeCatalog.inheritanceParents):
1678
+ one that was a parent when the catalog was read was judged by the parent checks, which refused a
1679
+ reference to it. A table that became one is refused whether or not a reference to it was checked. */
1680
+ const wrote = new Set(reached);
1681
+ const recheck = hierarchyRecheck(reached, catalog.schema.foreignKeys
1682
+ .filter((fk) => wrote.has(fk.from.table) && !catalog.inheritanceParents?.has(fk.to.table))
1683
+ .map((fk) => fk.to.table));
1684
+ if (recheck && !beforeCommit(write, [recheck]))
1685
+ await write.query(recheck.text, recheck.values).catch((error) => {
1686
+ throw joinedHierarchy(error) ?? error;
1687
+ });
1604
1688
  commitAttempted = true;
1605
- await write.query('COMMIT');
1689
+ try {
1690
+ await write.query('COMMIT');
1691
+ }
1692
+ catch (error) {
1693
+ // The recheck sent with the COMMIT found a hierarchy: the server answered the COMMIT as a ROLLBACK.
1694
+ const joined = error instanceof RolledBackAtCommit ? joinedHierarchy(error.cause) : undefined;
1695
+ if (joined) {
1696
+ commitAttempted = false;
1697
+ throw joined;
1698
+ }
1699
+ /* A deferred foreign key the COMMIT found broken: the server answered, so nothing committed, and the
1700
+ refusal is a hidden parent's (foreignKeyRefusal). */
1701
+ if (!isForeignKeyViolation(error))
1702
+ throw error;
1703
+ commitAttempted = false;
1704
+ throw foreignKeyRefusal(error);
1705
+ }
1606
1706
  committed = true;
1607
1707
  writes.committed();
1608
1708
  return out;
@@ -1623,7 +1723,13 @@ export class PostgresAdapter {
1623
1723
  COMMIT as a ROLLBACK: nothing committed, and that write's failure is
1624
1724
  what is said. */
1625
1725
  const refused = err instanceof RolledBackAtCommit;
1626
- const failure = refused ? err.cause : err;
1726
+ let failure = refused ? err.cause : err;
1727
+ /* A write that fired a trigger proven validation-only failed, and what the trigger raised is in its error,
1728
+ said to the caller. A trigger's function can be replaced without a lock on its table: replaced since the
1729
+ proof, it raised whatever its replacement read. So the proof is read again, once the transaction is
1730
+ rolled back, before that error is said; changed, the write is refused instead. */
1731
+ if (rolledBack && attest && !(failure instanceof Refusal))
1732
+ failure = await attest().then(() => failure, (refusal) => refusal);
1627
1733
  // withWriteClient destroys the client on any failure, so a connection
1628
1734
  // in an uncertain state is never handed to the next write.
1629
1735
  const unknown = !refused && (commitAttempted || (began && !rolledBack));
@@ -1639,68 +1745,6 @@ export class PostgresAdapter {
1639
1745
  }
1640
1746
  }));
1641
1747
  }
1642
- /**
1643
- * The statements a scoped transaction opens with, sent behind its BEGIN
1644
- * (openWrite's `sent`), from what it was told (writeAhead.ts) and the scope
1645
- * catalog read last time: the verifier's own (its fence), the journal's
1646
- * receipt lookup, and for each target its row lock, its row read in full
1647
- * through the scope (kept to answer its reads by key, keyRows.ts), and,
1648
- * where the write is captured for history, the capture's own lock and read
1649
- * (historyWrites). Each is exactly the statement the transaction sends in
1650
- * its turn, built by the same rules; one it never sends is left, counted,
1651
- * and changes nothing. None where the client does not pipeline.
1652
- */
1653
- sendWriteAhead(write, scope, peeked, keyRows, journal, verify, hint, locked) {
1654
- if (!sendsAhead(write) || (!hint && !verify?.ahead))
1655
- return [];
1656
- const opening = [];
1657
- try {
1658
- opening.push(...(verify?.ahead?.() ?? []));
1659
- if (hint?.receipt !== undefined && journal?.ahead)
1660
- opening.push(...journal.ahead(hint.receipt));
1661
- }
1662
- catch {
1663
- /* Asked in its turn. */
1664
- }
1665
- const answers = sendAhead(write, opening);
1666
- for (const target of (peeked && hint?.targets) || []) {
1667
- const table = peeked.schema.tables.find((candidate) => candidate.id === catalogId(target.table));
1668
- if (!table || !peeked.lockable.has(table.id))
1669
- continue;
1670
- const pk = table.columns.filter((column) => column.primaryKey).map((column) => column.name);
1671
- const key = target.key;
1672
- if (!pk.length ||
1673
- Object.keys(key).length !== pk.length ||
1674
- !pk.every((column) => Object.hasOwn(key, column) && (typeof key[column] === 'string' || typeof key[column] === 'number')))
1675
- continue;
1676
- // The scoped transaction's own key filter and lock (scopedTransaction.ts keyFilter, `lock` above).
1677
- const filter = { groups: [pk.map((column) => ({ column, op: '=', value: key[column] }))] };
1678
- const where = buildWhere(filter, POSTGRES_STYLE);
1679
- if (!hint.readOnly) {
1680
- answers.push(...sendAhead(write, [{ text: `SELECT 1 FROM ${qualified(table)}${where.text} FOR UPDATE`, values: where.params }]));
1681
- locked.add(rowLockKey(table, filter));
1682
- }
1683
- const read = scopedStatement(peeked.schema, scope, { table: table.id, filter, limit: 2, offset: 0 });
1684
- const row = read && holdAhead(write, { text: read.text, values: read.params });
1685
- if (row) {
1686
- answers.push(row.answer);
1687
- keyRows.keep(scope, table, filter, row.answer.then((result) => result.rows), row.take);
1688
- }
1689
- if (hint.writes && !hint.readOnly && capturesWrites(this, table.id)) {
1690
- // historyWrites' read: lockRecordNow, then queryOn of the whole row by the key as given.
1691
- const given = buildWhere({ groups: [Object.entries(key).map(([column, value]) => ({ column, op: '=', value }))] }, POSTGRES_STYLE);
1692
- const n = given.params.length;
1693
- answers.push(...sendAhead(write, [
1694
- {
1695
- text: `SELECT ${pk.map(POSTGRES_STYLE.quote).join(', ')} FROM ${qualified(table)}${where.text} FOR UPDATE`,
1696
- values: where.params,
1697
- },
1698
- { text: `SELECT * FROM ${qualified(table)}${given.text} LIMIT $${n + 1} OFFSET $${n + 2}`, values: [...given.params, 2, 0] },
1699
- ]));
1700
- }
1701
- }
1702
- return answers;
1703
- }
1704
1748
  /**
1705
1749
  * Internal runtime-owner composition, deliberately absent from Adapter: the
1706
1750
  * PostgreSQL counterpart of `SqliteAdapter.runtimeMaintenanceTransaction`,
@@ -1810,81 +1854,13 @@ function verifierPin(verify) {
1810
1854
  const pin = verify?.pin;
1811
1855
  return typeof pin === 'string' && /^LOCK TABLE [^;$]+ IN [A-Z ]+ MODE(; LOCK TABLE [^;$]+ IN [A-Z ]+ MODE)*$/.test(pin) ? pin : undefined;
1812
1856
  }
1813
- /* The row scope an unscoped transaction's kept rows are filed under (keyRows.ts): none, the same object every time. */
1814
- const PLAIN_SCOPE = Object.freeze({});
1815
- /* The record locks a transaction took behind its BEGIN (openPlain), by statement, each with what marks it taken.
1816
- Only those: a lock taken later could be let go by a ROLLBACK TO SAVEPOINT, one taken at the opening cannot. */
1817
- const heldLocks = new WeakMap();
1818
- /* Of those, the ones that found their row: it is the transaction's, unmoving, until it ends (openPlain's `widen`). */
1819
- const heldRows = new WeakMap();
1820
- const lockKey = (text, values) => JSON.stringify([text, values]);
1821
- /* lockRecordNow's statement for a row named by its whole primary key, and its values. */
1822
- function rowLockStatement(table, key) {
1823
- const pk = table.columns.filter((column) => column.primaryKey).map((column) => column.name);
1824
- const where = buildWhere({ groups: [pk.map((column) => ({ column, op: '=', value: key[column] }))] }, POSTGRES_STYLE);
1825
- return [`SELECT ${pk.map(POSTGRES_STYLE.quote).join(', ')} FROM ${qualified(table)}${where.text} FOR UPDATE`, where.params];
1826
- }
1827
- /* A table's schema and name from the name a request gives it, as assertPostgresTable reads it. */
1828
- function plainTable(table) {
1829
- const dot = table.indexOf('.');
1830
- return dot === -1 ? { schema: 'public', name: table } : { schema: table.slice(0, dot), name: table.slice(dot + 1) };
1831
- }
1832
- /* A table's catalog id from the name a request gives it: a bare name is in the public schema, as assertPostgresTable reads it. */
1833
- const catalogId = (table) => (table.includes('.') ? table : `public.${table}`);
1834
- /* The statement queryOn sends for an unordered read, without sending it: the table as its id names it
1835
- (assertPostgresTable), the read bounded as every read is. */
1836
- function plainStatement(request) {
1837
- if (request.orderBy?.length)
1838
- return undefined;
1839
- const at = plainTable(request.table);
1840
- const where = buildWhere(request.filter, POSTGRES_STYLE);
1841
- const cols = request.columns?.length ? request.columns.map((column) => POSTGRES_STYLE.quote(column)).join(', ') : '*';
1842
- const n = where.params.length;
1843
- return {
1844
- text: `SELECT ${cols} FROM ${qualified(at)}${where.text} LIMIT $${n + 1} OFFSET $${n + 2}`,
1845
- params: [...where.params, clampLimit(request.limit), clampOffset(request.offset)],
1846
- };
1847
- }
1848
- /* A statement a scoped read would send, without sending it: createScopedReads
1849
- compiles before it executes, so the executor is reached synchronously and
1850
- says what it was handed. */
1851
- /** A row lock as a scoped transaction keeps it: its table and the filter that names the row. */
1852
- const rowLockKey = (table, filter) => `${table.id}\u0000${JSON.stringify(filter)}`;
1853
- function scopedStatement(schema, within, request) {
1854
- let said;
1855
- void createScopedReads(schema, within, POSTGRES_STYLE, async (sql) => {
1856
- said = sql;
1857
- return { columns: [], rows: [], ms: 0, sql };
1858
- })
1859
- .query(request)
1860
- .catch(() => { });
1861
- return said;
1862
- }
1863
- /* Statements sent ahead that a committed transaction never asked: a hint
1864
- that no longer says what the transaction does. Warned once per statement
1865
- outside production; a refused transaction stops early, and leaves some by
1866
- design. With MISTRI_AHEAD_REPORT set, every transaction's account is a line
1867
- on stderr (e2e/write-storm.spec.ts reads it). */
1868
- const warnedAhead = new Set();
1869
- function reportWriteAhead(report, committed) {
1870
- if (!report || (!report.sent && !report.missed))
1871
- return;
1872
- const said = (key) => {
1873
- try {
1874
- return String(JSON.parse(key)[0]).slice(0, 160);
1875
- }
1876
- catch {
1877
- return key.slice(0, 160);
1878
- }
1879
- };
1880
- if (process.env.MISTRI_AHEAD_REPORT)
1881
- process.stderr.write(`mistri-ahead ${JSON.stringify({ at: Date.now(), committed, sent: report.sent, taken: report.taken, answered: report.answered, missed: report.missed, left: report.left.map(said), redone: report.redone, asked: report.asked })}\n`);
1882
- if (!committed || process.env.NODE_ENV === 'production')
1883
- return;
1884
- for (const statement of report.left.map(said)) {
1885
- if (warnedAhead.has(statement))
1886
- continue;
1887
- warnedAhead.add(statement);
1888
- process.emitWarning(`A statement sent ahead was never asked by the transaction it was sent for: ${statement}`, 'MistriWriteAhead');
1889
- }
1890
- }
1857
+ /* Handles whose transaction reads one snapshot (snapshotRead.ts): REPEATABLE READ from its BEGIN, so every statement
1858
+ reads as of its first. Kept on the handle, as its epoch is, so a retry of the opening begins the same way. */
1859
+ const snapshotHandles = new WeakSet();
1860
+ const beginOf = (write) => (snapshotHandles.has(write) ? 'BEGIN ISOLATION LEVEL REPEATABLE READ' : 'BEGIN');
1861
+ /* What a scoped transaction's BEGIN also says, in its one message: the text a date is read as, whatever the role or
1862
+ database set. A check binds a key's stored text and the database reads it back (storedText.ts, keyTypes.ts); under
1863
+ `DateStyle = 'SQL, YMD'` a date said as 01/02/2026 reads back as another day. Only the output style is set: the
1864
+ field order, which decides how a person's own 01/02/2026 is read, stays the database's. The float and interval
1865
+ text, which no key is (keyTypes.ts), is pinned as well, so a value a trigger's proof compares reads as stored. */
1866
+ const SCOPED_SESSION = '; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3';