uql-orm 0.114.4 → 0.115.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 (84) hide show
  1. package/dist/cockroachdb/cockroachDialect.d.ts +2 -0
  2. package/dist/cockroachdb/cockroachDialect.js +5 -0
  3. package/dist/d1/d1Querier.d.ts +2 -4
  4. package/dist/d1/d1Querier.js +0 -4
  5. package/dist/d1/d1SqliteDialect.js +1 -1
  6. package/dist/dialect/abstractDialect.d.ts +17 -8
  7. package/dist/dialect/abstractDialect.js +30 -16
  8. package/dist/dialect/abstractSqlDialect.d.ts +11 -2
  9. package/dist/dialect/abstractSqlDialect.js +17 -2
  10. package/dist/dialect/mysqlLikeSqlDialect.js +2 -0
  11. package/dist/dialect/operators.d.ts +2 -2
  12. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -1
  13. package/dist/dialect/pgLikeSqlDialect.js +20 -0
  14. package/dist/entity/columnOptionsBuilder.d.ts +2 -1
  15. package/dist/entity/columnOptionsBuilder.js +3 -0
  16. package/dist/entity/metadata/definedFixture/author.d.ts +1 -1
  17. package/dist/entity/metadata/definedFixture/book.d.ts +2 -2
  18. package/dist/entity/metadata/definedFixture/folder.d.ts +1 -1
  19. package/dist/entity/metadata/definition.js +69 -30
  20. package/dist/http/api.d.ts +1 -1
  21. package/dist/http/wireQuery.js +1 -1
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.js +2 -0
  24. package/dist/migrate/ddl/tableDdl.d.ts +5 -0
  25. package/dist/migrate/ddl/tableDdl.js +9 -0
  26. package/dist/migrate/drift/driftDetector.js +2 -1
  27. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +3 -1
  28. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
  29. package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -1
  30. package/dist/migrate/introspection/postgresIntrospector.js +14 -1
  31. package/dist/migrate/introspection/tableSchemaAST.js +1 -0
  32. package/dist/migrate/policySql.d.ts +12 -0
  33. package/dist/migrate/policySql.js +74 -0
  34. package/dist/migrate/schemaChange.js +1 -0
  35. package/dist/migrate/schemaGenerator.d.ts +2 -0
  36. package/dist/migrate/schemaGenerator.js +37 -11
  37. package/dist/mongodb/mongoDialect.js +3 -1
  38. package/dist/mongodb/mongodbQuerier.d.ts +0 -2
  39. package/dist/mongodb/mongodbQuerier.js +0 -4
  40. package/dist/mssql/mssqlDialect.js +2 -0
  41. package/dist/neon/neonQuerier.d.ts +1 -2
  42. package/dist/nestjs/uqlContextInterceptor.d.ts +1 -1
  43. package/dist/nestjs/uqlContextInterceptor.js +1 -1
  44. package/dist/nestjs/uqlModule.d.ts +2 -2
  45. package/dist/nestjs/uqlModule.js +1 -1
  46. package/dist/querier/abstractQuerier.d.ts +31 -4
  47. package/dist/querier/abstractQuerier.js +120 -52
  48. package/dist/querier/abstractQuerierPool.js +2 -0
  49. package/dist/querier/abstractSqlQuerier.d.ts +16 -6
  50. package/dist/querier/abstractSqlQuerier.js +66 -6
  51. package/dist/querier/queryError.js +1 -0
  52. package/dist/schema/schemaAST.js +1 -0
  53. package/dist/schema/schemaASTBuilder.d.ts +3 -1
  54. package/dist/schema/schemaASTBuilder.js +1 -0
  55. package/dist/schema/schemaASTDiffer.js +4 -2
  56. package/dist/schema/types.d.ts +12 -4
  57. package/dist/sqlite/bindValues.d.ts +1 -1
  58. package/dist/sqlite/hranaQuerier.d.ts +2 -2
  59. package/dist/sqlite/sqliteDialect.js +2 -0
  60. package/dist/turso/tursoSessionQuerier.d.ts +2 -2
  61. package/dist/type/column.d.ts +10 -0
  62. package/dist/type/definedEntity.d.ts +9 -4
  63. package/dist/type/dialect.d.ts +13 -0
  64. package/dist/type/entity.d.ts +10 -0
  65. package/dist/type/index.d.ts +1 -0
  66. package/dist/type/index.js +1 -0
  67. package/dist/type/migration.d.ts +5 -1
  68. package/dist/type/policy.d.ts +91 -0
  69. package/dist/type/policy.js +1 -0
  70. package/dist/type/querier.d.ts +14 -0
  71. package/dist/type/querierPool.d.ts +2 -2
  72. package/dist/type/query.d.ts +18 -31
  73. package/dist/type/query.js +2 -0
  74. package/dist/util/contextRefs.d.ts +6 -0
  75. package/dist/util/contextRefs.js +5 -0
  76. package/dist/util/dialect.util.d.ts +10 -11
  77. package/dist/util/dialect.util.js +70 -56
  78. package/dist/util/fieldOption.util.js +1 -0
  79. package/dist/util/policy.util.d.ts +100 -0
  80. package/dist/util/policy.util.js +239 -0
  81. package/dist/util/uqlError.d.ts +2 -5
  82. package/dist/util/uqlError.js +2 -5
  83. package/package.json +1 -1
  84. package/skills/uql-orm/SKILL.md +23 -13
@@ -1,9 +1,9 @@
1
1
  import { getMeta, idOf, namesEvery, namesKey, relationOf } from '../entity/index.js';
2
2
  import { SAVEPOINT_PREFIX } from '../dialect/aliases.js';
3
3
  import { namesRows } from '../dialect/operators.js';
4
- import { parseQueryLock } from '../type/index.js';
5
- import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, getKeys, deletionOf, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keyJoins, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, pointAt, queryLoggerFor, parseRelationAtKey, rowKey, runHooks, securityConditions, someKey, targetJoins, foundRowAssigned, whereAnd, whereIds, whereKeysIn, whereWith, withDeleted, cascadingRelations, isClass, defaultReadKeys, holdsForeignKey, noop, } from '../util/index.js';
6
- import { UqlOptimisticLockError, UqlUsageError } from '../util/uqlError.js';
4
+ import { parseQueryLock, PAST_POLICIES } from '../type/index.js';
5
+ import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, getKeys, deletionOf, hasKeys, getRelationRequestSummary, guardWrite, pinWrite, idOnlyQuery, keyJoins, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, pointAt, queryLoggerFor, parseRelationAtKey, rowKey, runHooks, someKey, targetJoins, foundRowAssigned, whereAnd, whereIds, whereKeysIn, whereWith, withDeleted, cascadingRelations, isClass, defaultReadKeys, holdsForeignKey, noop, } from '../util/index.js';
6
+ import { UqlOptimisticLockError, UqlSecurityError, UqlUsageError } from '../util/uqlError.js';
7
7
  import { keysetRead } from './keyset.js';
8
8
  import { enrichError } from './queryError.js';
9
9
  import { awaitTurn, claim, currentTransaction, depthOf, free, inTransaction, newScope, slotOf, } from './transaction.js';
@@ -86,15 +86,6 @@ function upsertBranch(q) {
86
86
  const keys = getKeys(q.$conflict);
87
87
  return (row) => (namesEvery(row, keys) ? 'upsert' : 'insert');
88
88
  }
89
- /**
90
- * Whether an upsert has to read before it writes: `ON CONFLICT` updates a guarded row whatever tenant it belongs
91
- * to, writes no relation, and cannot tell a found row it skipped for a stale version.
92
- */
93
- function upsertsByReading(meta, q, rows) {
94
- return (meta.version !== undefined ||
95
- securityConditions(meta, ['read', 'insert', 'update']).length > 0 ||
96
- writesRelations(meta, q.$update ? [...rows, q.$update] : rows));
97
- }
98
89
  /**
99
90
  * Writes the key an upsert reported onto `row`, over the one it named: a found row keeps its own. Only the key, since
100
91
  * an `onInsert` value was never written to a row the upsert updated. Answers `id`.
@@ -177,9 +168,11 @@ async function runCallbacks(callbacks) {
177
168
  }
178
169
  /**
179
170
  * What an upsert or a restore reads and updates rows with: soft-deleted ones too, since a key holds across both, held
180
- * to the `security` filters an update is.
171
+ * to the policies an update is.
181
172
  */
182
173
  const UPDATING_DELETED = { ...withDeleted(), access: 'update' };
174
+ /** A read of rows as they are stored, past filters and policies: what checks a write the policies settled. */
175
+ const UNPOLICED = { filters: false, [PAST_POLICIES]: true };
183
176
  const STREAM_HOLDS_QUERIER = 'a stream is reading on this querier: run the statement after its loop, or on another querier';
184
177
  /** Base class for all database queriers. */
185
178
  export class AbstractQuerier {
@@ -425,10 +418,71 @@ export class AbstractQuerier {
425
418
  const meta = getMeta(entity);
426
419
  await this.writeHeldReferences(entity, rows);
427
420
  fillOnFields(meta, rows, 'onInsert');
428
- guardWrite(meta, rows, 'insert');
429
- const inserted = await insert(rows);
430
- await this.insertChildren(entity, rows);
431
- return inserted;
421
+ const held = this.guarded(entity, rows, 'insert');
422
+ return held(async () => {
423
+ const inserted = await insert(rows);
424
+ await this.insertChildren(entity, rows);
425
+ return inserted;
426
+ }, () => rows.map((row) => idOf(meta, row)));
427
+ }
428
+ /**
429
+ * {@link guardWrite} under a pool holding writes to the policies, answering how the write of `rows` runs: alone, or
430
+ * with the rows it wrote read back against the check they could not settle, in a transaction undoing it where one
431
+ * does not hold. Where the database holds the policies the rows still get their pinned fields and an early refusal,
432
+ * and nothing is read back. A checked write is refused where this querier holds no transaction to undo it in.
433
+ */
434
+ guarded(entity, rows, write) {
435
+ const check = this.guardRows(getMeta(entity), rows, write);
436
+ const held = (run, written) => {
437
+ if (!check) {
438
+ return run();
439
+ }
440
+ if (!this.undoesSteps()) {
441
+ throw new UqlUsageError(`'${entity.name}' policies check written rows by reading them back, which needs a transaction ${this.dialect.engineName} holds none of here`);
442
+ }
443
+ return this.atomically(async () => {
444
+ const result = await run();
445
+ await this.holdToCheck(entity, written(result), check);
446
+ return result;
447
+ });
448
+ };
449
+ return Object.assign(held, { reads: !!check });
450
+ }
451
+ /**
452
+ * {@link guardWrite} where this pool reads written rows back, answering the check to read them against; else
453
+ * {@link pinUpserted}'s pinning alone, where it guards writes at all.
454
+ */
455
+ guardRows(meta, rows, write) {
456
+ const { guards, checks } = this.dialect.policies;
457
+ if (checks) {
458
+ return guardWrite(meta, rows, write);
459
+ }
460
+ if (guards) {
461
+ pinWrite(meta, rows, write);
462
+ }
463
+ return undefined;
464
+ }
465
+ /** {@link pinWrite} where this pool guards writes: an upsert's branches check what they write, or its database does. */
466
+ pinUpserted(meta, rows) {
467
+ if (this.dialect.policies.guards) {
468
+ pinWrite(meta, rows, 'insert');
469
+ }
470
+ }
471
+ /** Whether {@link atomically} undoes every step of a write that fails partway: a transaction holds them. */
472
+ undoesSteps() {
473
+ return this.dialect.features.transactions || this.scopeHere() !== undefined;
474
+ }
475
+ /** Refuses, undoing the write, where any row `ids` names does not hold `check` once written. */
476
+ async holdToCheck(entity, ids, check) {
477
+ const meta = getMeta(entity);
478
+ const known = ids.filter((id) => id !== undefined);
479
+ if (known.length < ids.length) {
480
+ throw new UqlUsageError(`'${entity.name}' wrote a row whose key it cannot read back to check against its policies`);
481
+ }
482
+ const holding = await this.writeBatches(known, meta.ids.length, (batch) => this.internalCount(entity, { $where: whereAnd(whereIds(meta, batch), [check]) }, UNPOLICED));
483
+ if (holding < known.length) {
484
+ throw new UqlSecurityError(`a row written to '${entity.name}' does not hold its policies under this context`);
485
+ }
432
486
  }
433
487
  async updateOneById(entity, id, payload, opts) {
434
488
  assertIdValue(entity, id);
@@ -452,7 +506,7 @@ export class AbstractQuerier {
452
506
  return this.updateMatching(entity, q, payload, rest);
453
507
  }
454
508
  const reportingWrites = this.reportingWrites(meta, 'update');
455
- const reporting = (row) => reportingWrites && this.updatesByFilter(entity, q, row) ? reportingWrites : undefined;
509
+ const reporting = (row) => reportingWrites && this.updatesByFilter(entity, q, row, rest) ? reportingWrites : undefined;
456
510
  // Decided again on the row the hooks hand over, which may now write a relation one statement cannot.
457
511
  const write = () => this.hooked(entity, 'Update', [payload], async ([row]) => {
458
512
  const writes = reporting(row);
@@ -474,10 +528,10 @@ export class AbstractQuerier {
474
528
  async updateReturning(writes, entity, q, row, opts, keys) {
475
529
  const meta = getMeta(entity);
476
530
  const read = [...keys, ...meta.ids];
477
- await this.prepareUpdate(entity, row);
478
- const rows = writesColumns(meta, row)
479
- ? await writes.update(entity, q, row, opts, read)
480
- : await this.internalFindMany(entity, { ...q, $select: keySet(read) }, opts);
531
+ const held = await this.prepareUpdate(entity, row);
532
+ const rows = await held(() => writesColumns(meta, row)
533
+ ? writes.update(entity, q, row, opts, read)
534
+ : this.internalFindMany(entity, { ...q, $select: keySet(read) }, opts), (written) => written.map((it) => idOf(meta, it)));
481
535
  return this.returned(entity, rows, keys);
482
536
  }
483
537
  /**
@@ -497,30 +551,32 @@ export class AbstractQuerier {
497
551
  */
498
552
  async updateRows(entity, q, row, opts, lockKey, settled) {
499
553
  const meta = getMeta(entity);
500
- await this.prepareUpdate(entity, row);
554
+ const held = await this.prepareUpdate(entity, row);
501
555
  const relKeys = ownedRelations(meta).filter((key) => Object.hasOwn(row, key));
502
- const settles = !!relKeys.length || this.settlesWrite(entity, q);
556
+ const settles = !!relKeys.length || this.settlesWrite(entity, q, opts);
503
557
  if (lockKey) {
504
558
  assertLockableUpdate(meta, q, settles);
505
559
  const lock = lockVersion(meta, lockKey, q, row);
506
560
  row[lockKey] = lock.next;
507
- const changes = await this.updateColumns(entity, lock.q, row, opts, 0);
561
+ const changes = await held(() => this.updateColumns(entity, lock.q, row, opts, 0), (changed) => (changed ? [idOf(meta, { ...q.$where })] : []));
508
562
  return changes || this.throwStaleVersion(entity, lockKey, q, lock.expected, opts);
509
563
  }
510
- if (!settles && !settled) {
564
+ if (!settles && !settled && !held.reads) {
511
565
  return this.updateColumns(entity, q, row, opts, 0);
512
566
  }
513
- return this.atomically(async () => {
567
+ const write = async () => {
514
568
  const ids = settled ?? (await this.settleIds(entity, q, opts));
515
569
  if (!ids.length) {
516
- return 0;
570
+ return { ids, changes: 0 };
517
571
  }
518
572
  const changes = await this.writeBatches(ids, meta.ids.length, (batch) => this.updateColumns(entity, { $where: whereIds(meta, batch) }, row, opts, batch.length));
519
573
  for (const relKey of relKeys) {
520
574
  await this.replaceChildren(entity, relKey, ids, row[relKey]);
521
575
  }
522
- return changes;
523
- });
576
+ return { ids, changes };
577
+ };
578
+ const { changes } = await held(() => this.atomically(write), ({ ids }) => ids);
579
+ return changes;
524
580
  }
525
581
  /**
526
582
  * Why an update matched no row. The filter named the row by its id, so reading by that id alone
@@ -540,12 +596,15 @@ export class AbstractQuerier {
540
596
  : `'${entityName(meta)}' moved on: the payload carries '${key}' ${String(expected)}, the row is at ${String(actual)}`;
541
597
  throw new UqlOptimisticLockError(message, expected, actual);
542
598
  }
543
- /** What every update does to its row before its statement: writes the to-ones it holds, fills and guards it. */
599
+ /**
600
+ * What every update does to its row before its statement: writes the to-ones it holds, fills and guards it.
601
+ * Answers how its write runs, as {@link guarded} does.
602
+ */
544
603
  async prepareUpdate(entity, row) {
545
604
  const meta = getMeta(entity);
546
605
  await this.writeHeldReferences(entity, [row]);
547
606
  fillOnFields(meta, [row], 'onUpdate');
548
- guardWrite(meta, [row], 'update');
607
+ return this.guarded(entity, [row], 'update');
549
608
  }
550
609
  /** The UPDATE, skipped where the payload writes no column, reporting `unwritten` instead. */
551
610
  async updateColumns(entity, q, row, opts, unwritten) {
@@ -555,9 +614,9 @@ export class AbstractQuerier {
555
614
  * Whether a write has to name the rows `q` matches by their ids: no engine pages or orders an update or
556
615
  * delete, and one without {@link DialectFeatures.correlatedWrites} cannot read a relation in its filter.
557
616
  */
558
- settlesWrite(entity, q) {
617
+ settlesWrite(entity, q, opts) {
559
618
  const { dialect } = this;
560
- return isPagedQuery(q) || (!dialect.features.correlatedWrites && dialect.constrainsRelations(entity, q.$where));
619
+ return (isPagedQuery(q) || (!dialect.features.correlatedWrites && dialect.constrainsRelations(entity, q.$where, opts)));
561
620
  }
562
621
  /**
563
622
  * `write` over `rows` in lists of as many as one statement names by `keyCount` keys, summing what each changed,
@@ -572,7 +631,7 @@ export class AbstractQuerier {
572
631
  }
573
632
  /** Runs a write of several statements as one: in a transaction of its own, or the one already open. */
574
633
  atomically(write) {
575
- return this.scopeHere() ? write() : this.transaction(write);
634
+ return this.scopeHere() || !this.dialect.features.transactions ? write() : this.transaction(write);
576
635
  }
577
636
  /** The ids `q` matches, in its own order and page, held as {@link readForWrite} holds them. */
578
637
  async settleIds(entity, q, opts) {
@@ -626,22 +685,31 @@ export class AbstractQuerier {
626
685
  if (!keys || !reportingWrites) {
627
686
  return this.writtenOrReadBack(entity, () => this.hooked(entity, 'Upsert', payload, (rows) => this.writeEach(rows, branch, {
628
687
  insert: (inserts) => this.insertedIds(entity, inserts),
629
- upsert: (upserts) => this.upsertIds(entity, q, upserts),
688
+ upsert: (upserts) => this.upsertIds(entity, q, upserts, this.upsertsByReading(meta, q, upserts)),
630
689
  })), opts);
631
690
  }
632
691
  return this.atomically(() => this.hooked(entity, 'Upsert', payload, (rows) => this.writeEach(rows, branch, {
633
692
  insert: (inserts) => this.insertReturning(reportingWrites, entity, inserts, keys),
634
- upsert: async (upserts) => upsertsByReading(meta, q, upserts)
635
- ? this.readBack(entity, await this.upsertIds(entity, q, upserts), keys)
693
+ upsert: async (upserts) => this.upsertsByReading(meta, q, upserts)
694
+ ? this.readBack(entity, await this.upsertIds(entity, q, upserts, true), keys)
636
695
  : this.upsertReturning(reportingWrites, entity, q, upserts, keys),
637
696
  })));
638
697
  }
639
- /** Upserts `rows`, each naming every conflict key, reading first where {@link upsertsByReading} says so: the id each got. */
640
- async upsertIds(entity, q, rows) {
698
+ /**
699
+ * Whether an upsert has to read before it writes: `ON CONFLICT` updates a row the querier holds to policies whatever
700
+ * tenant it belongs to, writes no relation, and cannot tell a found row it skipped for a stale version. A database
701
+ * holding the policies itself holds the conflicting row to them in the one statement.
702
+ */
703
+ upsertsByReading(meta, q, rows) {
704
+ return (meta.version !== undefined ||
705
+ (this.dialect.policies.scopes && !!meta.policies?.length) ||
706
+ writesRelations(meta, q.$update ? [...rows, q.$update] : rows));
707
+ }
708
+ /** Upserts `rows`, each naming every conflict key, reading first where `reads`: the id each got. */
709
+ async upsertIds(entity, q, rows, reads) {
641
710
  const meta = getMeta(entity);
642
- const ids = upsertsByReading(meta, q, rows)
643
- ? await this.readThenUpsert(entity, q, rows)
644
- : await this.reportedOrKeptIds(entity, q, rows);
711
+ this.pinUpserted(meta, rows);
712
+ const ids = reads ? await this.readThenUpsert(entity, q, rows) : await this.reportedOrKeptIds(entity, q, rows);
645
713
  return rows.map((row, index) => adoptId(meta, row, ids[index] ?? this.unmatched(entity, q, row)));
646
714
  }
647
715
  /**
@@ -678,6 +746,7 @@ export class AbstractQuerier {
678
746
  async upsertReturning(writes, entity, q, rows, keys) {
679
747
  const meta = getMeta(entity);
680
748
  const read = [...new Set([...keys, ...meta.ids, ...getKeys(q.$conflict)])];
749
+ this.pinUpserted(meta, rows);
681
750
  const written = await this.withKept(entity, q, rows, await writes.upsert(entity, q, rows, read), read, (row) => row);
682
751
  const stands = rows.map((row, index) => {
683
752
  const stand = written[index] ?? this.unmatched(entity, q, row);
@@ -725,12 +794,11 @@ export class AbstractQuerier {
725
794
  /**
726
795
  * An upsert as a read, then writes: the rows the conflict names are read through the filters, those found update
727
796
  * by id as `updateOne` does, a versioned one at its version, and the rest insert, so either branch writes its
728
- * relations and a guarded row stays its tenant's. Inside a transaction a found row is held until the write, and
729
- * a row inserted concurrently fails on its key. See architecture/security-filter-writes.md.
797
+ * relations and a policied row stays its tenant's. Inside a transaction a found row is held until the write, and
798
+ * a row inserted concurrently fails on its key. See architecture/row-level-security.md.
730
799
  */
731
800
  async readThenUpsert(entity, q, rows) {
732
801
  const meta = getMeta(entity);
733
- guardWrite(meta, rows, 'insert');
734
802
  return this.atomically(async () => {
735
803
  const found = await this.rowsByConflict(entity, q.$conflict, rows, meta.ids);
736
804
  const ids = found.map((row) => row && idOf(meta, row));
@@ -781,7 +849,7 @@ export class AbstractQuerier {
781
849
  // A soft delete stamps the rows, which a `RETURNING` would report stamped rather than as they were.
782
850
  const reportingWrites = this.reportingWrites(meta, 'delete');
783
851
  const deletion = deletionOf(meta, rest);
784
- if (reportingWrites && !deletion.stamp && this.deletesByFilter(entity, q)) {
852
+ if (reportingWrites && !deletion.stamp && this.deletesByFilter(entity, q, rest)) {
785
853
  return this.returned(entity, await reportingWrites.delete(entity, q, rest, read), keys);
786
854
  }
787
855
  // A delete hook receives whole rows; without one, only the keys `returning` names and the ids are read.
@@ -795,14 +863,14 @@ export class AbstractQuerier {
795
863
  });
796
864
  }
797
865
  /** Whether an update is its one statement over `q`: no version to lock, relation to write or page to settle first. */
798
- updatesByFilter(entity, q, payload) {
866
+ updatesByFilter(entity, q, payload, opts) {
799
867
  const meta = getMeta(entity);
800
- return !meta.version && !writesRelations(meta, [payload]) && !this.settlesWrite(entity, q);
868
+ return !meta.version && !writesRelations(meta, [payload]) && !this.settlesWrite(entity, q, opts);
801
869
  }
802
870
  /** Whether a delete is its one statement over `q`: no hook, cascade or page needs its rows read first. */
803
- deletesByFilter(entity, q) {
871
+ deletesByFilter(entity, q, opts) {
804
872
  const meta = getMeta(entity);
805
- return !this.watchesDelete(entity) && !cascadingRelations(meta, 'delete').length && !this.settlesWrite(entity, q);
873
+ return (!this.watchesDelete(entity) && !cascadingRelations(meta, 'delete').length && !this.settlesWrite(entity, q, opts));
806
874
  }
807
875
  /** Whether a delete hook listens on the entity, so a delete reads each row whole to hand it over. */
808
876
  watchesDelete(entity) {
@@ -811,7 +879,7 @@ export class AbstractQuerier {
811
879
  /** Deletes the rows `q` matches, or the ones `read` holds, reading them first where a hook, cascade or page needs them. */
812
880
  async deleteRows(entity, q, opts, read) {
813
881
  const meta = getMeta(entity);
814
- if (!read && this.deletesByFilter(entity, q)) {
882
+ if (!read && this.deletesByFilter(entity, q, opts)) {
815
883
  return this.internalDeleteMany(entity, q, opts);
816
884
  }
817
885
  const cascades = cascadingRelations(meta, 'delete').length > 0;
@@ -61,6 +61,8 @@ export class AbstractQuerierPool {
61
61
  constructor(dialect, extra) {
62
62
  this.dialect = dialect;
63
63
  this.extra = extra;
64
+ // Reading `policies` refuses a mode the engine cannot hold: read now, the pool is refused when built.
65
+ void dialect.policies;
64
66
  }
65
67
  /** The querier of the transaction this flow runs in, where this pool handed it out. */
66
68
  ambientQuerier() {
@@ -1,12 +1,7 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, EntityMeta, ExtraOptions, WrittenId, Query, QueryAggregate, QueryUpsert, QueryPage, StatementOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, Type, TransactionOptions, UpdatePayload, ReportedWrite } from '../type/index.js';
2
+ import type { EntityData, EntityMeta, ExtraOptions, WrittenId, Query, QueryAggregate, QueryUpsert, QueryPage, StatementOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, Type, TransactionOptions, UpdatePayload, BoundStatement, ReportedWrite } from '../type/index.js';
3
3
  import type { SqlExecution } from '../util/sql.util.js';
4
4
  import { AbstractQuerier, type ReportingWrites } from './abstractQuerier.js';
5
- /** A statement as it is sent: its SQL and the values it binds. */
6
- export type BoundStatement = {
7
- readonly sql: string;
8
- readonly values: unknown[];
9
- };
10
5
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
11
6
  #private;
12
7
  readonly dialect: AbstractSqlDialect;
@@ -42,6 +37,20 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
42
37
  * where `atomic` (a split write) asks for one, opened before the queue is taken, which its `BEGIN` waits on.
43
38
  */
44
39
  protected runStatements(statements: readonly BoundStatement[], atomic?: boolean): Promise<readonly SqlExecution[]>;
40
+ /**
41
+ * The statement binding the ambient context into the open transaction ahead of its next statement: none where it is
42
+ * bound already, or there is nothing to bind. `ask` runs the question of the connected role.
43
+ */
44
+ private pendingBinding;
45
+ /** Whether a statement here runs under a context the database's policies read, which binds in a transaction. */
46
+ private bindsContext;
47
+ /**
48
+ * Refuses a statement under a context where the connected role reads past the database's policies, which would show
49
+ * one tenant another's rows. A statement under none, a migration's, runs as the owner it connects as.
50
+ */
51
+ private assertHeldToPolicies;
52
+ /** {@link runStatements} once the context is bound. */
53
+ private runBound;
45
54
  /** Runs `statements` one after another on the connection, each timed. */
46
55
  private inTurn;
47
56
  /** Runs `task` on the connection, connected, after everything queued before it. */
@@ -150,6 +159,7 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
150
159
  * victim's on SQL Server, left nothing open to roll back.
151
160
  */
152
161
  protected endTransaction(commit: boolean): Promise<void>;
162
+ /** A rollback to a savepoint undoes the context bound inside it, so the next statement binds it again. */
153
163
  protected savepoint(command: SavepointCommand, name: string): Promise<void>;
154
164
  /**
155
165
  * How this driver opens, commits and rolls back: the dialect's statements, unless its transactions
@@ -1,8 +1,10 @@
1
+ import { getContext } from '../context/context.js';
1
2
  import { AGGREGATE_VALUE_ALIAS, KEY_DEFAULT_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
2
3
  import { getMeta } from '../entity/index.js';
3
4
  import { generatesKey, idOf, namesKey, soleId } from '../entity/metadata/definition.js';
4
5
  import { QuerySql } from '../type/querySql.js';
5
- import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, getKeys, rowKey } from '../util/index.js';
6
+ import { buildUpdateResult, cachedIn, chunk, clone, getInsertFieldKeys, insertShapeOf, getKeys, rowKey, } from '../util/index.js';
7
+ import { contextEntries, nextBinding, NOTHING_BOUND, unsettled } from '../util/policy.util.js';
6
8
  import { sql, statementOf } from '../util/sql.js';
7
9
  import { UqlUsageError } from '../util/uqlError.js';
8
10
  import { AbstractQuerier } from './abstractQuerier.js';
@@ -63,9 +65,12 @@ function inPayloadOrder(meta, rows, reported) {
63
65
  const [idKey] = meta.ids;
64
66
  return generatesKey(meta) ? reported.toSorted((a, b) => byGeneratedKey(a[idKey], b[idKey])) : reported;
65
67
  }
68
+ /** Each dialect whose connected role was found held to its policies, answered once per pool. */
69
+ const heldToPolicies = new WeakMap();
66
70
  export class AbstractSqlQuerier extends AbstractQuerier {
67
71
  dialect;
68
72
  hasOpenTransaction = false;
73
+ #bound = NOTHING_BOUND;
69
74
  /** Cached `auto_increment_increment` stride; see {@link loadInsertIdIncrement}. */
70
75
  #insertIdIncrement;
71
76
  constructor(dialect, extra) {
@@ -109,7 +114,52 @@ export class AbstractSqlQuerier extends AbstractQuerier {
109
114
  * the driver has {@link executeBatch}, a failure tagged with the statement it names; else in turn, in a transaction
110
115
  * where `atomic` (a split write) asks for one, opened before the queue is taken, which its `BEGIN` waits on.
111
116
  */
112
- runStatements(statements, atomic = false) {
117
+ async runStatements(statements, atomic = false) {
118
+ if (!this.dialect.policies.database) {
119
+ return this.runBound(statements, atomic);
120
+ }
121
+ if (!this.scopeHere()) {
122
+ return this.bindsContext()
123
+ ? this.atomically(() => this.runStatements(statements, atomic))
124
+ : this.runBound(statements, atomic);
125
+ }
126
+ const binding = await this.pendingBinding((sql) => this.onConnection(() => this.execute(sql)));
127
+ const results = await this.runBound(binding ? [binding, ...statements] : statements, atomic);
128
+ return binding ? results.slice(1) : results;
129
+ }
130
+ /**
131
+ * The statement binding the ambient context into the open transaction ahead of its next statement: none where it is
132
+ * bound already, or there is nothing to bind. `ask` runs the question of the connected role.
133
+ */
134
+ async pendingBinding(ask) {
135
+ const { entries, bound } = nextBinding(this.#bound, getContext());
136
+ if (entries.length && this.bindsContext()) {
137
+ await this.assertHeldToPolicies(ask);
138
+ }
139
+ this.#bound = bound;
140
+ return this.dialect.contextBinding(entries);
141
+ }
142
+ /** Whether a statement here runs under a context the database's policies read, which binds in a transaction. */
143
+ bindsContext() {
144
+ return this.dialect.policies.database && contextEntries(getContext()).length > 0;
145
+ }
146
+ /**
147
+ * Refuses a statement under a context where the connected role reads past the database's policies, which would show
148
+ * one tenant another's rows. A statement under none, a migration's, runs as the owner it connects as.
149
+ */
150
+ assertHeldToPolicies(ask) {
151
+ const { dialect } = this;
152
+ return cachedIn(heldToPolicies, dialect, () => ask(dialect.rowSecurityBypassQuery()).then(({ rows }) => {
153
+ if (rows[0]?.['bypasses'] !== false) {
154
+ throw new UqlUsageError(`a pool with policies: 'native' runs a context's statements as a role ${dialect.engineName} lets past row-level security: connect as one that does not, or leave policies unset`);
155
+ }
156
+ })).catch((error) => {
157
+ heldToPolicies.delete(dialect);
158
+ throw error;
159
+ });
160
+ }
161
+ /** {@link runStatements} once the context is bound. */
162
+ runBound(statements, atomic) {
113
163
  const executeBatch = statements.length > 1 ? this.executeBatch?.bind(this) : undefined;
114
164
  if (!executeBatch) {
115
165
  const inTurn = () => this.inTurn(statements);
@@ -234,15 +284,20 @@ export class AbstractSqlQuerier extends AbstractQuerier {
234
284
  */
235
285
  async *internalFindManyStream(entity, q, opts) {
236
286
  const tuning = this.vectorTuning(entity, q);
237
- if (this.tunedInTransaction(tuning) && !this.scopeHere()) {
238
- throw new UqlUsageError(`a streamed $candidates needs an open transaction on ${this.dialect.engineName}; run the stream inside pool.transaction(...)`);
287
+ const binds = this.bindsContext();
288
+ if (!this.scopeHere() && (binds || this.tunedInTransaction(tuning))) {
289
+ throw new UqlUsageError(`a stream ${binds ? 'binding its context for the policies' : 'of $candidates'} needs an open transaction on ${this.dialect.engineName}; run it inside pool.transaction(...)`);
239
290
  }
240
291
  const ctx = this.dialect.createContext();
241
292
  const read = rowReader(this.dialect.find(ctx, entity, q, opts));
242
293
  this.assertBindBudget(ctx.values);
243
294
  await this.lazyConnect();
244
- for (const { sql } of tuning) {
245
- await this.timed(sql, undefined, () => this.execute(sql));
295
+ // The stream holds the querier for its loop, so its leading statements run on the connection directly.
296
+ const binding = this.scopeHere() && this.dialect.policies.database
297
+ ? await this.pendingBinding((sql) => this.execute(sql))
298
+ : undefined;
299
+ for (const { sql, values } of binding ? [binding, ...tuning] : tuning) {
300
+ await this.timed(sql, values, () => this.execute(sql, values));
246
301
  }
247
302
  for await (const row of this.timedStream(ctx.sql, ctx.values, this.internalStream(ctx.sql, ctx.values))) {
248
303
  yield read(row);
@@ -456,6 +511,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
456
511
  await this.lazyConnect();
457
512
  await this.internalBegin(opts);
458
513
  this.hasOpenTransaction = true;
514
+ this.#bound = NOTHING_BOUND;
459
515
  }
460
516
  /**
461
517
  * A `COMMIT` that fails can leave the transaction open (SQLite answers `SQLITE_BUSY` and keeps it), so the
@@ -475,11 +531,15 @@ export class AbstractSqlQuerier extends AbstractQuerier {
475
531
  this.hasOpenTransaction = false;
476
532
  }
477
533
  }
534
+ /** A rollback to a savepoint undoes the context bound inside it, so the next statement binds it again. */
478
535
  async savepoint(command, name) {
479
536
  const sql = this.dialect.savepointStatement(command, name);
480
537
  if (sql) {
481
538
  await this.runTransactionCommand(sql);
482
539
  }
540
+ if (command === 'rollback') {
541
+ this.#bound = unsettled(this.#bound);
542
+ }
483
543
  }
484
544
  /**
485
545
  * How this driver opens, commits and rolls back: the dialect's statements, unless its transactions
@@ -5,6 +5,7 @@ const SQLSTATE_KINDS = new Map([
5
5
  ['23503', 'foreignKeyViolation'],
6
6
  ['23502', 'notNullViolation'],
7
7
  ['23514', 'checkViolation'],
8
+ ['42501', 'security'],
8
9
  ['40P01', 'retryable'],
9
10
  ['40001', 'retryable'],
10
11
  ['55P03', 'retryable'],
@@ -10,6 +10,7 @@ export function createTableNode(name, schema, indexFacets = new Set()) {
10
10
  indexes: [],
11
11
  checks: [],
12
12
  triggers: [],
13
+ policies: [],
13
14
  externalForeignKeys: [],
14
15
  incomingRelations: [],
15
16
  outgoingRelations: [],
@@ -1,6 +1,6 @@
1
1
  import type { EntityMeta, EntityWhereMeta, FieldOptions, AbstractType } from '../type/index.js';
2
2
  import { SchemaAST } from './schemaAST.js';
3
- import { type ForeignKeyAction, type TriggerSchema } from './types.js';
3
+ import { type ForeignKeyAction, type PolicySchema, type TriggerSchema } from './types.js';
4
4
  /** What a build needs from its dialect, which `SqlSchemaGenerator.buildAST` supplies. */
5
5
  export interface BuildSchemaASTOptions {
6
6
  /** A table's own name, unqualified. */
@@ -20,6 +20,8 @@ export interface BuildSchemaASTOptions {
20
20
  vectorIndexRequiresNotNull: boolean;
21
21
  /** The triggers an entity's table carries, as its dialect renders them. */
22
22
  renderTriggers: (meta: EntityMeta<object>) => TriggerSchema[];
23
+ /** The row-level policies the database holds an entity's table to, none where the querier holds them. */
24
+ renderPolicies: (meta: EntityMeta<object>) => PolicySchema[];
23
25
  }
24
26
  /**
25
27
  * Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
@@ -60,6 +60,7 @@ function addTableFromEntity(ctx, meta) {
60
60
  }
61
61
  table.primaryKey = keyOfColumns(columns.values());
62
62
  table.triggers.push(...ctx.renderTriggers(meta));
63
+ table.policies.push(...ctx.renderPolicies(meta));
63
64
  ctx.ast.addTable(table);
64
65
  return table;
65
66
  }
@@ -26,6 +26,7 @@ export function diffSchemas(source, target, options = {}) {
26
26
  indexes: matched.flatMap(([sourceTable, targetTable]) => diffTableIndexes(sourceTable, targetTable)),
27
27
  checks: altered.flatMap((tableDiff) => tableDiff.checks),
28
28
  triggers: altered.flatMap((tableDiff) => tableDiff.triggers),
29
+ policies: altered.flatMap((tableDiff) => tableDiff.policies),
29
30
  primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
30
31
  // Relationships span tables, so they are compared over the whole schema rather than per table.
31
32
  relationships: diffRelationshipNodes(source.relationships, target.relationships),
@@ -40,9 +41,10 @@ export function diffTable(source, target, options = {}) {
40
41
  const columns = diffTableColumns(source, target, opts);
41
42
  const checks = diffOwned(source.name, source.checks, target.checks);
42
43
  const triggers = diffOwned(source.name, source.triggers, target.triggers);
44
+ const policies = diffOwned(source.name, source.policies, target.policies);
43
45
  const primaryKey = diffPrimaryKey(source, target);
44
- return columns.length || checks.length || triggers.length || primaryKey
45
- ? { columns, checks, triggers, primaryKey }
46
+ return columns.length || checks.length || triggers.length || policies.length || primaryKey
47
+ ? { columns, checks, triggers, policies, primaryKey }
46
48
  : undefined;
47
49
  }
48
50
  /**
@@ -52,13 +52,17 @@ export interface CheckSchema {
52
52
  readonly expression: string;
53
53
  }
54
54
  /**
55
- * A trigger, compared by name alone as a check is: its name ends in a hash of its SQL. The statements create
56
- * it; read back, they are the engine's own, which is what a rollback restores.
55
+ * An object uql installs on a table, compared by name alone as a check is: its name ends in a hash of its SQL. The
56
+ * statements create it; read back, they are the engine's own, which is what a rollback restores.
57
57
  */
58
- export interface TriggerSchema {
58
+ export interface OwnedSchema {
59
59
  readonly name: string;
60
60
  readonly statements: readonly string[];
61
61
  }
62
+ /** A trigger uql installs. */
63
+ export type TriggerSchema = OwnedSchema;
64
+ /** A row-level policy the database holds a table to. */
65
+ export type PolicySchema = OwnedSchema;
62
66
  /**
63
67
  * Default action for foreign key ON DELETE and ON UPDATE clauses.
64
68
  */
@@ -133,6 +137,8 @@ export interface TableNode {
133
137
  readonly checks: CheckSchema[];
134
138
  /** The triggers uql installs on this table. */
135
139
  readonly triggers: TriggerSchema[];
140
+ /** The row-level policies uql installs on this table. */
141
+ readonly policies: PolicySchema[];
136
142
  /** Optional table comment */
137
143
  readonly comment?: string;
138
144
  /** The statements the engine keeps for the table, where it keeps them; none on a table built from entities. */
@@ -223,9 +229,10 @@ export type TableChange<T> = Change<T> & {
223
229
  /** The differences within a table that exists on both sides. */
224
230
  export interface TableDiff {
225
231
  readonly columns: ColumnDiff[];
226
- /** A check or trigger only one side has. Never both: a changed one is a new name, one dropped and one added. */
232
+ /** A check, trigger or policy only one side has. Never both: a changed one is a new name, one dropped and one added. */
227
233
  readonly checks: TableChange<CheckSchema>[];
228
234
  readonly triggers: TableChange<TriggerSchema>[];
235
+ readonly policies: TableChange<PolicySchema>[];
229
236
  /** Set only when the two primary keys have different columns. */
230
237
  readonly primaryKey?: PrimaryKeyDiff;
231
238
  }
@@ -237,6 +244,7 @@ export interface SchemaDiffResult {
237
244
  readonly indexes: IndexDiff[];
238
245
  readonly checks: TableChange<CheckSchema>[];
239
246
  readonly triggers: TableChange<TriggerSchema>[];
247
+ readonly policies: TableChange<PolicySchema>[];
240
248
  readonly primaryKeys: PrimaryKeyDiff[];
241
249
  readonly relationships: RelationshipDiff[];
242
250
  }
@@ -1,4 +1,4 @@
1
- import type { BoundStatement } from '../querier/index.js';
1
+ import type { BoundStatement } from '../type/index.js';
2
2
  /** What every SQLite driver binds. No `boolean`, which the drivers refuse and the dialect writes as an integer. */
3
3
  export type SqliteBindValue = null | string | number | bigint | Uint8Array;
4
4
  /** The compiler hands values over untyped, which the dialect has already normalized to what SQLite binds. */
@@ -1,5 +1,5 @@
1
- import { AbstractSqlQuerier, type BoundStatement } from '../querier/index.js';
2
- import type { ExtraOptions, RawRow, TransactionOptions } from '../type/index.js';
1
+ import { AbstractSqlQuerier } from '../querier/index.js';
2
+ import type { BoundStatement, ExtraOptions, RawRow, TransactionOptions } from '../type/index.js';
3
3
  import type { SqlExecution } from '../util/sql.util.js';
4
4
  import { type SqliteBindValue } from './bindValues.js';
5
5
  import type { SqliteDialect } from './sqliteDialect.js';
@@ -49,6 +49,8 @@ export const SQLITE_FEATURES = {
49
49
  deferrable: false,
50
50
  },
51
51
  namedLocks: 'journal',
52
+ rowSecurity: false,
53
+ transactions: true,
52
54
  };
53
55
  export class SqliteDialect extends AbstractSqlDialect {
54
56
  features = SQLITE_FEATURES;