uql-orm 0.115.5 → 0.116.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cockroachdb/cockroachDialect.d.ts +2 -0
- package/dist/cockroachdb/cockroachDialect.js +4 -0
- package/dist/dialect/abstractSqlDialect.d.ts +6 -3
- package/dist/dialect/abstractSqlDialect.js +10 -5
- package/dist/dialect/pgLikeSqlDialect.d.ts +6 -2
- package/dist/dialect/pgLikeSqlDialect.js +11 -3
- package/dist/entity/metadata/definition.js +72 -4
- package/dist/migrate/policySql.d.ts +7 -1
- package/dist/migrate/policySql.js +50 -14
- package/dist/migrate/schemaGenerator.js +5 -4
- package/dist/migrate/triggerSql.d.ts +12 -1
- package/dist/migrate/triggerSql.js +40 -15
- package/dist/querier/abstractQuerier.d.ts +24 -11
- package/dist/querier/abstractQuerier.js +116 -42
- package/dist/type/dialect.d.ts +1 -0
- package/dist/type/entity.d.ts +12 -7
- package/dist/type/policy.d.ts +8 -5
- package/dist/type/query.d.ts +2 -2
- package/dist/type/queryWhere.d.ts +14 -1
- package/dist/util/dialect.util.d.ts +7 -9
- package/dist/util/dialect.util.js +17 -27
- package/dist/util/policy.util.d.ts +54 -13
- package/dist/util/policy.util.js +168 -25
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +14 -10
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { getMeta, idOf, namesEvery, namesKey, relationOf } from '../entity/index.js';
|
|
2
|
+
import { getContext } from '../context/context.js';
|
|
2
3
|
import { SAVEPOINT_PREFIX } from '../dialect/aliases.js';
|
|
3
4
|
import { namesRows } from '../dialect/operators.js';
|
|
4
5
|
import { parseQueryLock, PAST_POLICIES } from '../type/index.js';
|
|
5
|
-
import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, getKeys, deletionOf, hasKeys, getRelationRequestSummary, guardWrite,
|
|
6
|
+
import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, getKeys, accessOf, deletionOf, hasKeys, getRelationRequestSummary, guardWrite, 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';
|
|
7
|
+
import { movesRefused, oldReads, onWritten, pairsRows, policyTransitions, } from '../util/policy.util.js';
|
|
6
8
|
import { UqlOptimisticLockError, UqlSecurityError, UqlUsageError } from '../util/uqlError.js';
|
|
7
9
|
import { keysetRead } from './keyset.js';
|
|
8
10
|
import { enrichError } from './queryError.js';
|
|
@@ -426,62 +428,121 @@ export class AbstractQuerier {
|
|
|
426
428
|
}, () => rows.map((row) => idOf(meta, row)));
|
|
427
429
|
}
|
|
428
430
|
/**
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
* and
|
|
431
|
+
* How a statement doing `write` to `rows` runs where this pool reads rows to hold it to the check {@link guardWrite}
|
|
432
|
+
* answers and, for an update, to the transitions: alone where neither applies; else in a transaction reading each
|
|
433
|
+
* found row before the write, refusing one no transition lets go unwritten, then each written row after it against
|
|
434
|
+
* the check and what its transitions leave. A write read around is refused where no transaction undoes it.
|
|
433
435
|
*/
|
|
434
436
|
guarded(entity, rows, write) {
|
|
435
|
-
const
|
|
436
|
-
const
|
|
437
|
-
|
|
437
|
+
const meta = getMeta(entity);
|
|
438
|
+
const check = this.guardRows(meta, rows, write);
|
|
439
|
+
const checked = this.dialect.policies.checks ? check : undefined;
|
|
440
|
+
const transitions = pairsRows(write) ? this.heldTransitions(meta) : [];
|
|
441
|
+
const reads = !!checked || transitions.length > 0;
|
|
442
|
+
const held = (run, written, found) => {
|
|
443
|
+
if (!reads) {
|
|
438
444
|
return run();
|
|
439
445
|
}
|
|
440
446
|
if (!this.undoesSteps()) {
|
|
441
447
|
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
448
|
}
|
|
443
449
|
return this.atomically(async () => {
|
|
450
|
+
const owed = await this.transitionsOwed(entity, found ?? [], transitions);
|
|
444
451
|
const result = await run();
|
|
445
|
-
await this.
|
|
452
|
+
await this.holdWritten(entity, written(result), checked, owed);
|
|
446
453
|
return result;
|
|
447
454
|
});
|
|
448
455
|
};
|
|
449
|
-
return Object.assign(held, { reads
|
|
456
|
+
return Object.assign(held, { reads });
|
|
457
|
+
}
|
|
458
|
+
/** The transitions this pool holds an update of `meta` to under the context: none where the database holds them. */
|
|
459
|
+
heldTransitions(meta) {
|
|
460
|
+
return this.dialect.policies.checks && meta.policies?.length ? policyTransitions(meta, getContext()) : [];
|
|
450
461
|
}
|
|
451
462
|
/**
|
|
452
|
-
*
|
|
453
|
-
*
|
|
463
|
+
* What each row `found` names owes `transitions` once written, by its {@link rowKey}: each reads the row as found
|
|
464
|
+
* first, and one that lets it go nowhere refuses the write before it runs. Rows holding alike owe alike.
|
|
454
465
|
*/
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
466
|
+
async transitionsOwed(entity, found, transitions) {
|
|
467
|
+
const meta = getMeta(entity);
|
|
468
|
+
const refused = () => new UqlSecurityError(movesRefused(entity.name));
|
|
469
|
+
const live = transitions.filter((transition) => transition !== false);
|
|
470
|
+
if (live.length < transitions.length) {
|
|
471
|
+
throw refused();
|
|
459
472
|
}
|
|
460
|
-
|
|
461
|
-
|
|
473
|
+
const owed = new Map(found.map((id) => [rowKey(whereIds(meta, id), meta.ids), { signature: '', left: [] }]));
|
|
474
|
+
for (const transition of live) {
|
|
475
|
+
const holding = await Promise.all(oldReads(transition).map((read) => this.idsHolding(entity, found, read)));
|
|
476
|
+
const folded = new Map();
|
|
477
|
+
for (const [key, row] of owed) {
|
|
478
|
+
const signature = holding.map((ids) => (ids.has(key) ? '1' : '0')).join('');
|
|
479
|
+
let left = folded.get(signature);
|
|
480
|
+
if (left === undefined) {
|
|
481
|
+
left = onWritten(transition, (at) => signature[at] === '1');
|
|
482
|
+
folded.set(signature, left);
|
|
483
|
+
}
|
|
484
|
+
if (left === false) {
|
|
485
|
+
throw refused();
|
|
486
|
+
}
|
|
487
|
+
row.signature += `${signature}.`;
|
|
488
|
+
if (left !== true) {
|
|
489
|
+
row.left.push(left);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
462
492
|
}
|
|
463
|
-
return
|
|
493
|
+
return owed;
|
|
464
494
|
}
|
|
465
|
-
/** {@link
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
495
|
+
/** The {@link rowKey}s of the rows among `ids` holding `where` as they are stored. */
|
|
496
|
+
async idsHolding(entity, ids, where) {
|
|
497
|
+
const meta = getMeta(entity);
|
|
498
|
+
const holding = new Set();
|
|
499
|
+
const named = ids.map((id) => whereIds(meta, id));
|
|
500
|
+
for (const q of this.keyedReads(meta.ids, named, meta.ids)) {
|
|
501
|
+
const rows = await this.internalFindMany(entity, { ...q, $where: whereAnd(q.$where, [where]) }, UNPOLICED);
|
|
502
|
+
rows.forEach((row) => holding.add(rowKey(row, meta.ids)));
|
|
469
503
|
}
|
|
504
|
+
return holding;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* {@link guardWrite} where this pool guards writes: it pins and refuses `rows`, answering the check left to read
|
|
508
|
+
* them back against.
|
|
509
|
+
*/
|
|
510
|
+
guardRows(meta, rows, write) {
|
|
511
|
+
return this.dialect.policies.guards ? guardWrite(meta, rows, write) : undefined;
|
|
470
512
|
}
|
|
471
513
|
/** Whether {@link atomically} undoes every step of a write that fails partway: a transaction holds them. */
|
|
472
514
|
undoesSteps() {
|
|
473
515
|
return this.dialect.features.transactions || this.scopeHere() !== undefined;
|
|
474
516
|
}
|
|
475
|
-
/**
|
|
476
|
-
|
|
517
|
+
/**
|
|
518
|
+
* Refuses, undoing the write, where any row `ids` names does not hold `check` and what `owed` holds it to once
|
|
519
|
+
* written: one count per distinct predicate.
|
|
520
|
+
*/
|
|
521
|
+
async holdWritten(entity, ids, check, owed) {
|
|
477
522
|
const meta = getMeta(entity);
|
|
478
523
|
const known = ids.filter((id) => id !== undefined);
|
|
479
524
|
if (known.length < ids.length) {
|
|
480
525
|
throw new UqlUsageError(`'${entity.name}' wrote a row whose key it cannot read back to check against its policies`);
|
|
481
526
|
}
|
|
482
|
-
const
|
|
483
|
-
|
|
484
|
-
|
|
527
|
+
const groups = new Map();
|
|
528
|
+
for (const id of known) {
|
|
529
|
+
const row = owed.get(rowKey(whereIds(meta, id), meta.ids));
|
|
530
|
+
const signature = row?.signature ?? '';
|
|
531
|
+
let group = groups.get(signature);
|
|
532
|
+
if (!group) {
|
|
533
|
+
group = { where: [...(check ? [check] : []), ...(row?.left ?? [])], ids: [] };
|
|
534
|
+
groups.set(signature, group);
|
|
535
|
+
}
|
|
536
|
+
group.ids.push(id);
|
|
537
|
+
}
|
|
538
|
+
for (const group of groups.values()) {
|
|
539
|
+
if (!group.where.length) {
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
const holding = await this.writeBatches(group.ids, meta.ids.length, (batch) => this.internalCount(entity, { $where: whereAnd(whereIds(meta, batch), group.where) }, UNPOLICED));
|
|
543
|
+
if (holding < group.ids.length) {
|
|
544
|
+
throw new UqlSecurityError(`a row written to '${entity.name}' does not hold its policies under this context`);
|
|
545
|
+
}
|
|
485
546
|
}
|
|
486
547
|
}
|
|
487
548
|
async updateOneById(entity, id, payload, opts) {
|
|
@@ -558,25 +619,28 @@ export class AbstractQuerier {
|
|
|
558
619
|
assertLockableUpdate(meta, q, settles);
|
|
559
620
|
const lock = lockVersion(meta, lockKey, q, row);
|
|
560
621
|
row[lockKey] = lock.next;
|
|
561
|
-
const
|
|
622
|
+
const id = idOf(meta, { ...q.$where });
|
|
623
|
+
const changed = (count) => (count ? [id] : []);
|
|
624
|
+
const changes = await held(() => this.updateColumns(entity, lock.q, row, opts, 0), changed, [id]);
|
|
562
625
|
return changes || this.throwStaleVersion(entity, lockKey, q, lock.expected, opts);
|
|
563
626
|
}
|
|
564
627
|
if (!settles && !settled && !held.reads) {
|
|
565
628
|
return this.updateColumns(entity, q, row, opts, 0);
|
|
566
629
|
}
|
|
567
|
-
const write = async () => {
|
|
568
|
-
const ids = settled ?? (await this.settleIds(entity, q, opts));
|
|
630
|
+
const write = async (ids) => {
|
|
569
631
|
if (!ids.length) {
|
|
570
|
-
return
|
|
632
|
+
return 0;
|
|
571
633
|
}
|
|
572
634
|
const changes = await this.writeBatches(ids, meta.ids.length, (batch) => this.updateColumns(entity, { $where: whereIds(meta, batch) }, row, opts, batch.length));
|
|
573
635
|
for (const relKey of relKeys) {
|
|
574
636
|
await this.replaceChildren(entity, relKey, ids, row[relKey]);
|
|
575
637
|
}
|
|
576
|
-
return
|
|
638
|
+
return changes;
|
|
577
639
|
};
|
|
578
|
-
|
|
579
|
-
|
|
640
|
+
return this.atomically(async () => {
|
|
641
|
+
const ids = settled ?? (await this.settleIds(entity, q, opts));
|
|
642
|
+
return held(() => write(ids), () => ids, ids);
|
|
643
|
+
});
|
|
580
644
|
}
|
|
581
645
|
/**
|
|
582
646
|
* Why an update matched no row. The filter named the row by its id, so reading by that id alone
|
|
@@ -708,7 +772,7 @@ export class AbstractQuerier {
|
|
|
708
772
|
/** Upserts `rows`, each naming every conflict key, reading first where `reads`: the id each got. */
|
|
709
773
|
async upsertIds(entity, q, rows, reads) {
|
|
710
774
|
const meta = getMeta(entity);
|
|
711
|
-
this.
|
|
775
|
+
this.guardRows(meta, rows, 'insert');
|
|
712
776
|
const ids = reads ? await this.readThenUpsert(entity, q, rows) : await this.reportedOrKeptIds(entity, q, rows);
|
|
713
777
|
return rows.map((row, index) => adoptId(meta, row, ids[index] ?? this.unmatched(entity, q, row)));
|
|
714
778
|
}
|
|
@@ -746,7 +810,7 @@ export class AbstractQuerier {
|
|
|
746
810
|
async upsertReturning(writes, entity, q, rows, keys) {
|
|
747
811
|
const meta = getMeta(entity);
|
|
748
812
|
const read = [...new Set([...keys, ...meta.ids, ...getKeys(q.$conflict)])];
|
|
749
|
-
this.
|
|
813
|
+
this.guardRows(meta, rows, 'insert');
|
|
750
814
|
const written = await this.withKept(entity, q, rows, await writes.upsert(entity, q, rows, read), read, (row) => row);
|
|
751
815
|
const stands = rows.map((row, index) => {
|
|
752
816
|
const stand = written[index] ?? this.unmatched(entity, q, row);
|
|
@@ -862,10 +926,16 @@ export class AbstractQuerier {
|
|
|
862
926
|
return reported;
|
|
863
927
|
});
|
|
864
928
|
}
|
|
865
|
-
/**
|
|
929
|
+
/**
|
|
930
|
+
* Whether an update is its one statement over `q`: no version to lock, relation to write, page to settle first, or
|
|
931
|
+
* transition to read its rows as found for.
|
|
932
|
+
*/
|
|
866
933
|
updatesByFilter(entity, q, payload, opts) {
|
|
867
934
|
const meta = getMeta(entity);
|
|
868
|
-
return !meta.version &&
|
|
935
|
+
return (!meta.version &&
|
|
936
|
+
!writesRelations(meta, [payload]) &&
|
|
937
|
+
!this.settlesWrite(entity, q, opts) &&
|
|
938
|
+
!this.heldTransitions(meta).length);
|
|
869
939
|
}
|
|
870
940
|
/** Whether a delete is its one statement over `q`: no hook, cascade or page needs its rows read first. */
|
|
871
941
|
deletesByFilter(entity, q, opts) {
|
|
@@ -879,12 +949,15 @@ export class AbstractQuerier {
|
|
|
879
949
|
/** Deletes the rows `q` matches, or the ones `read` holds, reading them first where a hook, cascade or page needs them. */
|
|
880
950
|
async deleteRows(entity, q, opts, read) {
|
|
881
951
|
const meta = getMeta(entity);
|
|
882
|
-
|
|
952
|
+
const deleting = opts ?? {};
|
|
953
|
+
// A soft delete is an update, held as one: its written row checked, and its transitions. Its stamp is filled as it
|
|
954
|
+
// writes, so the row the guard sees sets no field.
|
|
955
|
+
const held = this.guarded(entity, [{}], accessOf(meta, deleting));
|
|
956
|
+
if (!read && !held.reads && this.deletesByFilter(entity, q, opts)) {
|
|
883
957
|
return this.internalDeleteMany(entity, q, opts);
|
|
884
958
|
}
|
|
885
959
|
const cascades = cascadingRelations(meta, 'delete').length > 0;
|
|
886
960
|
const watched = this.watchesDelete(entity);
|
|
887
|
-
const deleting = opts ?? {};
|
|
888
961
|
return this.atomically(async () => {
|
|
889
962
|
// A hook receives the rows themselves; the ids read off them name the same rows a second read might not.
|
|
890
963
|
const doomed = read ?? (await this.readForWrite(entity, watched ? q : idOnlyQuery(meta, q), deletionOf(meta, deleting).opts));
|
|
@@ -893,13 +966,14 @@ export class AbstractQuerier {
|
|
|
893
966
|
}
|
|
894
967
|
const ids = doomed.map((row) => idOf(meta, row));
|
|
895
968
|
await this.emitHook(entity, 'beforeDelete', doomed);
|
|
896
|
-
const
|
|
969
|
+
const write = () => this.writeBatches(ids, meta.ids.length, async (batch) => {
|
|
897
970
|
// Children first: they hold the foreign key, which a schema without `ON DELETE CASCADE` enforces.
|
|
898
971
|
if (cascades) {
|
|
899
972
|
await this.deleteChildren(entity, batch, deleting);
|
|
900
973
|
}
|
|
901
974
|
return this.internalDeleteMany(entity, { $where: whereIds(meta, batch) }, opts);
|
|
902
975
|
});
|
|
976
|
+
const changes = await held(write, () => ids, ids);
|
|
903
977
|
await this.emitHook(entity, 'afterDelete', doomed);
|
|
904
978
|
return changes;
|
|
905
979
|
});
|
package/dist/type/dialect.d.ts
CHANGED
package/dist/type/entity.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { PolicyMeta, PolicySection } from './policy.js';
|
|
|
4
4
|
import type { Querier } from './querier.js';
|
|
5
5
|
import type { EntityAccess, FilterOptions, RelationQuery, Wire } from './query.js';
|
|
6
6
|
import type { ColumnRef, JsonPathRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
|
|
7
|
-
import type { QueryWhere } from './queryWhere.js';
|
|
7
|
+
import type { QueryWhere, QueryWhereFields, RowSide, RowsWhere } from './queryWhere.js';
|
|
8
8
|
import type { StandardSchemaV1 } from './standardSchema.js';
|
|
9
9
|
import type { AtLeastOne, ExactlyOne, IsBranded, IsEqual, Merge, IsJson, JsonBrand, IsMany, Json, JsonScalar, Scalar, Type, AbstractType, Unpacked, Writable } from './utility.js';
|
|
10
10
|
import type { VectorDistance, VectorIndexOptions, VectorIndexType } from './vector.js';
|
|
@@ -817,9 +817,9 @@ type TriggerUpdateEvent = TriggerEventOn<'Update'>;
|
|
|
817
817
|
* The rows an event has, as `where` keys them: the incoming one on an insert, the outgoing one on a
|
|
818
818
|
* delete, both on an update.
|
|
819
819
|
*/
|
|
820
|
-
type TriggerRow<Ev extends TriggerEvent> = Ev extends TriggerEventOn<'Insert'> ? '$new' : Ev extends TriggerEventOn<'Delete'> ? '$old' :
|
|
820
|
+
type TriggerRow<Ev extends TriggerEvent> = Ev extends TriggerEventOn<'Insert'> ? '$new' : Ev extends TriggerEventOn<'Delete'> ? '$old' : RowSide;
|
|
821
821
|
/** One row's refs, rendering `NEW."col"` or `OLD."col"`, or `never` where the event has no such row. */
|
|
822
|
-
type TriggerRowRefs<E, Ev extends TriggerEvent, R extends
|
|
822
|
+
type TriggerRowRefs<E, Ev extends TriggerEvent, R extends RowSide> = R extends TriggerRow<Ev> ? RefMap<E> : never;
|
|
823
823
|
/**
|
|
824
824
|
* What a trigger runs, over its rows: the incoming row first and the outgoing one second, on every event.
|
|
825
825
|
* The one an event lacks is `never`, so reading it does not compile, and a body reading only the outgoing
|
|
@@ -827,12 +827,17 @@ type TriggerRowRefs<E, Ev extends TriggerEvent, R extends '$new' | '$old'> = R e
|
|
|
827
827
|
*/
|
|
828
828
|
type TriggerBody<E, Ev extends TriggerEvent> = (newRow: TriggerRowRefs<E, Ev, '$new'>, oldRow: TriggerRowRefs<E, Ev, '$old'>) => QuerySql;
|
|
829
829
|
/**
|
|
830
|
-
* A condition as data: a predicate on each row it names, of the rows the event has, all of which hold.
|
|
831
|
-
*
|
|
830
|
+
* A condition as data: a predicate on each row it names, of the rows the event has, all of which hold. The row is
|
|
831
|
+
* `$`-marked, as the operators inside it are, so it never reads as a field of the entity. An update's pairs its rows
|
|
832
|
+
* in groups, and holds a condition beside neither on both, as a policy's does.
|
|
832
833
|
*/
|
|
833
|
-
type TriggerPredicate<E, Ev extends TriggerEvent> = {
|
|
834
|
+
type TriggerPredicate<E, Ev extends TriggerEvent> = Ev extends TriggerUpdateEvent ? TriggerWhere<E> : {
|
|
834
835
|
readonly [R in TriggerRow<Ev>]?: EntityPredicate<E>;
|
|
835
836
|
};
|
|
837
|
+
/** An update trigger's predicate over its two rows, on the table's own fields. */
|
|
838
|
+
type TriggerWhere<E> = RowsWhere<QueryWhereFields<E, QuerySql, FieldKey<E>>, EntityPredicate<E>>;
|
|
839
|
+
/** A trigger's predicate, whatever its event. */
|
|
840
|
+
export type TriggerMetaWhere<E> = TriggerPredicate<E, TriggerEvent>;
|
|
836
841
|
/**
|
|
837
842
|
* The body, the engine's own SQL: one for every engine it reads alike, or a map naming one per engine
|
|
838
843
|
* where they differ, as SQL Server's set-based `inserted`/`deleted` does. A missing entry for the engine
|
|
@@ -890,7 +895,7 @@ export type TriggerOptions<E = unknown> = {
|
|
|
890
895
|
*/
|
|
891
896
|
export type EntityTriggerMeta<E = object> = Merge<TriggerOptions<E>, {
|
|
892
897
|
readonly of?: readonly string[];
|
|
893
|
-
readonly where?:
|
|
898
|
+
readonly where?: TriggerMetaWhere<E> | TriggerMetaBody<E>;
|
|
894
899
|
readonly run: TriggerMetaBody<E> | Readonly<Partial<Record<SqlDialectName, TriggerMetaBody<E>>>>;
|
|
895
900
|
}>;
|
|
896
901
|
/**
|
package/dist/type/policy.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { EntityAccess, UqlContext } from './query.js';
|
|
2
2
|
import type { QuerySql, SQL_VALUE_TYPE } from './querySql.js';
|
|
3
|
-
import type { QueryWhere } from './queryWhere.js';
|
|
3
|
+
import type { QueryWhere, QueryWhereFields, QueryWhereRootOperator, RowsWhere } from './queryWhere.js';
|
|
4
4
|
/**
|
|
5
5
|
* A context key read where a policy's predicate takes a value, as data: `{ $context: 'tenantId' }`. Read off
|
|
6
6
|
* {@link $context}, which types it by {@link UqlContext}, so a key holding a string never meets a number column.
|
|
@@ -39,8 +39,13 @@ export type ContextRefs = string extends ContextKey ? {
|
|
|
39
39
|
export type TenantKey<V> = string extends ContextKey ? [contextKey?: ContextRef<V>] : [ContextRef<ContextValue<'tenantId'>>] extends [ContextRef<V>] ? 'tenantId' extends ContextKey ? [contextKey?: ContextRef<V>] : [contextKey: ContextRef<V>] : [contextKey: ContextRef<V>];
|
|
40
40
|
/** What a policy's predicate interpolates where a query takes SQL: SQL itself, or a context key. */
|
|
41
41
|
export type PolicySql = QuerySql | ContextKeyRef;
|
|
42
|
-
/** A
|
|
43
|
-
export type
|
|
42
|
+
/** A `$where` over the entity, its relations included, whose values may read the context: a filter's, a row's. */
|
|
43
|
+
export type ContextWhere<E> = QueryWhere<E, PolicySql>;
|
|
44
|
+
/**
|
|
45
|
+
* A policy's predicate: a {@link ContextWhere} holding every row a statement touches, and `$old` the row as found or
|
|
46
|
+
* `$new` the row as written alone, grouped as any condition is: `{ $or: [{ $old: { status: 'draft' } }, ...] }`.
|
|
47
|
+
*/
|
|
48
|
+
export type PolicyWhere<E> = RowsWhere<QueryWhereFields<E, PolicySql> & Pick<QueryWhereRootOperator<E, PolicySql>, '$text' | '$exists' | '$nexists'>, ContextWhere<E>, PolicySql>;
|
|
44
49
|
/**
|
|
45
50
|
* How a policy joins the others holding a statement: rows any `allow` reaches, and of them only those every `must`
|
|
46
51
|
* holds, Postgres's permissive and restrictive policies. An entity with policies and no `allow` for a statement
|
|
@@ -60,8 +65,6 @@ export type PolicyWhen = string extends ContextKey ? {
|
|
|
60
65
|
export type PolicyOptions<E> = {
|
|
61
66
|
/** The statements it holds, every one where unset. An update and a delete are held to the `read` ones too. */
|
|
62
67
|
readonly ops?: readonly EntityAccess[];
|
|
63
|
-
/** What a written row must hold, the predicate itself where unset: Postgres's `WITH CHECK`. */
|
|
64
|
-
readonly check?: PolicyWhere<E>;
|
|
65
68
|
readonly when?: PolicyWhen;
|
|
66
69
|
/** Names it in the database; derived from its effect and position where unset. */
|
|
67
70
|
readonly name?: string;
|
package/dist/type/query.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { FieldKey, FieldKeyOf, JsonFieldPaths, MethodKey, RelationKey, RelationTarget, ToManyRelationKey, UpdateWrite, WrittenId } from './entity.js';
|
|
2
|
-
import type {
|
|
2
|
+
import type { ContextWhere } from './policy.js';
|
|
3
3
|
import type { QueryLock } from './queryLock.js';
|
|
4
4
|
import type { QuerySql } from './querySql.js';
|
|
5
5
|
import type { QueryWhere } from './queryWhere.js';
|
|
@@ -110,7 +110,7 @@ export interface UqlContext {
|
|
|
110
110
|
* the filter skipped where the context lacks a key it reads; or a function of the ambient {@link UqlContext}, skipped
|
|
111
111
|
* where it answers `undefined`.
|
|
112
112
|
*/
|
|
113
|
-
export type FilterWhere<E> =
|
|
113
|
+
export type FilterWhere<E> = ContextWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);
|
|
114
114
|
/** What a field takes: reading it (select, filter, sort, distinct, aggregate) and writing it. */
|
|
115
115
|
export type FieldAccess = 'read' | 'insert' | 'update';
|
|
116
116
|
/** What a statement does to an entity's rows: a field's access, and deleting rows, which no field has a part in. */
|
|
@@ -27,7 +27,20 @@ export type QueryTextSearchOptions<E> = {
|
|
|
27
27
|
* entity's keys so each stays linked for rename. An object and nothing else, so a wrong value is
|
|
28
28
|
* reported on its key: ids go through `{ id: 1 }` or the by-id methods.
|
|
29
29
|
*/
|
|
30
|
-
export type QueryWhere<E, Sql = QuerySql, K extends keyof E = FieldKey<E> | RelationKey<E>> = QueryWhereRootOperator<E, Sql> &
|
|
30
|
+
export type QueryWhere<E, Sql = QuerySql, K extends keyof E = FieldKey<E> | RelationKey<E>> = QueryWhereRootOperator<E, Sql> & QueryWhereFields<E, Sql, K>;
|
|
31
|
+
/** The rows a write's predicate reads, as a trigger names them: `$old`, the row as found, and `$new`, as written. */
|
|
32
|
+
export type RowSide = '$old' | '$new';
|
|
33
|
+
/**
|
|
34
|
+
* A predicate over a write's rows, grouped as any condition is: its `Fields` hold every row, `$old` the row as found
|
|
35
|
+
* and `$new` the row as written alone, each a `Row`. A trigger's on an update, and a policy's.
|
|
36
|
+
*/
|
|
37
|
+
export type RowsWhere<Fields, Row, Sql = never> = Fields & {
|
|
38
|
+
readonly [Op in QueryGroupOp]?: readonly (RowsWhere<Fields, Row, Sql> | Sql)[];
|
|
39
|
+
} & {
|
|
40
|
+
readonly [S in RowSide]?: Row;
|
|
41
|
+
};
|
|
42
|
+
/** {@link QueryWhere}'s conditions on fields, JSON paths and relations, without its root operators. */
|
|
43
|
+
export type QueryWhereFields<E, Sql = QuerySql, K extends keyof E = FieldKey<E> | RelationKey<E>> = {
|
|
31
44
|
[P in K]?: P extends FieldKey<E> ? QueryWhereFieldValue<E[P], Sql> : QueryWhereRelation<RelationTarget<E[P]>, Sql>;
|
|
32
45
|
} & ([JsonFieldPaths<E>] extends [never] ? unknown : {
|
|
33
46
|
[P in JsonFieldPaths<E>]?: QueryWhereFieldValue<JsonFieldPathValue<E, P>, Sql>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IndexType } from '../schema/types.js';
|
|
2
|
-
import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type StatementOptions, type UpdatePayload, type VectorDistance } from '../type/index.js';
|
|
2
|
+
import { type AggregateCall, type CascadeType, type EntityAccess, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type StatementOptions, type UpdatePayload, type VectorDistance } from '../type/index.js';
|
|
3
3
|
import { type CallbackKey } from './field.util.js';
|
|
4
4
|
/** The keys of `payload` a write persists as columns. */
|
|
5
5
|
export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
|
|
@@ -30,6 +30,8 @@ type Deletion<O> = {
|
|
|
30
30
|
* an entity with no soft-delete field, removes them, soft-deleted ones included.
|
|
31
31
|
*/
|
|
32
32
|
export declare function deletionOf<E, O extends QueryOptions>(meta: EntityMeta<E>, opts: O): Deletion<O>;
|
|
33
|
+
/** What a statement under `opts` does to `meta`'s rows: a delete stamping them is an update, as the database runs it. */
|
|
34
|
+
export declare function accessOf<E>(meta: EntityMeta<E>, opts: StatementOptions | undefined): EntityAccess;
|
|
33
35
|
/**
|
|
34
36
|
* What the row an upsert of `row` finds takes: a copy of `q.$update`, none for `{}`, which leaves it as `DO NOTHING`
|
|
35
37
|
* does, and by default the payload less its key and what it matched on.
|
|
@@ -132,16 +134,12 @@ export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof
|
|
|
132
134
|
*/
|
|
133
135
|
export declare function applyFilters<E>(meta: EntityMeta<E>, whereMap: QueryWhere<E>, opts?: StatementOptions): QueryWhere<E>;
|
|
134
136
|
/**
|
|
135
|
-
* Holds rows
|
|
137
|
+
* Holds rows a statement doing `write` writes to the entity's policies under the ambient context, before the write: a
|
|
136
138
|
* field the check pins to one value is filled into an inserted row leaving it out, and refused where a row sets
|
|
137
|
-
* another.
|
|
139
|
+
* another. Answers what the rows themselves cannot settle, which the querier reads back inside the write's
|
|
140
|
+
* transaction. See architecture/row-level-security.md.
|
|
138
141
|
*/
|
|
139
|
-
export declare function
|
|
140
|
-
/**
|
|
141
|
-
* {@link pinWrite}, answering what the rows themselves cannot settle as the check the written rows must hold once
|
|
142
|
-
* written, which the querier reads back inside the write's transaction.
|
|
143
|
-
*/
|
|
144
|
-
export declare function guardWrite<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, rows: readonly R[], write: 'insert' | 'update'): QueryWhere<E> | undefined;
|
|
142
|
+
export declare function guardWrite<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, rows: readonly R[], write: EntityAccess): QueryWhere<E> | undefined;
|
|
145
143
|
/**
|
|
146
144
|
* Parsed entry from a `$group` map - either a raw group key or an aggregate function call.
|
|
147
145
|
*/
|
|
@@ -4,7 +4,7 @@ import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
|
|
|
4
4
|
import { defaultReadKeys, fieldKeys, isDatabaseWritten, isWrittenOn, jsonKey, jsonPathKeys, } from './field.util.js';
|
|
5
5
|
import { withDeleted } from './filters.util.js';
|
|
6
6
|
import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isPlainObject, isRecord, someKey, } from './object.util.js';
|
|
7
|
-
import { asWhere, conjuncts,
|
|
7
|
+
import { asWhere, conjuncts, policyWhere, withContextValues } from './policy.util.js';
|
|
8
8
|
import { assertNoUndefined, whereAnd } from './query.util.js';
|
|
9
9
|
import { UqlSecurityError, UqlUsageError } from './uqlError.js';
|
|
10
10
|
/** The keys of `payload` a write persists as columns. */
|
|
@@ -77,6 +77,11 @@ export function deletionOf(meta, opts) {
|
|
|
77
77
|
}
|
|
78
78
|
return { stamp: { key, field, value: () => softDeleteValue(field) }, opts };
|
|
79
79
|
}
|
|
80
|
+
/** What a statement under `opts` does to `meta`'s rows: a delete stamping them is an update, as the database runs it. */
|
|
81
|
+
export function accessOf(meta, opts) {
|
|
82
|
+
const access = opts?.access ?? 'read';
|
|
83
|
+
return access === 'delete' && deletionOf(meta, opts ?? {}).stamp ? 'update' : access;
|
|
84
|
+
}
|
|
80
85
|
/**
|
|
81
86
|
* What the row an upsert of `row` finds takes: a copy of `q.$update`, none for `{}`, which leaves it as `DO NOTHING`
|
|
82
87
|
* does, and by default the payload less its key and what it matched on.
|
|
@@ -423,7 +428,7 @@ export function applyFilters(meta, whereMap, opts) {
|
|
|
423
428
|
}
|
|
424
429
|
}
|
|
425
430
|
const merged = result;
|
|
426
|
-
const scope = opts?.[PAST_POLICIES] ? undefined :
|
|
431
|
+
const scope = opts?.[PAST_POLICIES] ? undefined : policyWhere(meta, accessOf(meta, opts), '$old', getContext());
|
|
427
432
|
return scope === undefined || scope === true ? merged : whereAnd(merged, conjuncts(asWhere(meta, scope)));
|
|
428
433
|
}
|
|
429
434
|
/** A filter's condition under the ambient context, `undefined` where it reads what the context lacks, which skips it. */
|
|
@@ -432,34 +437,14 @@ function filterCondition(filter) {
|
|
|
432
437
|
return typeof filter.where === 'function' ? filter.where(context) : withContextValues(filter.where, context);
|
|
433
438
|
}
|
|
434
439
|
/**
|
|
435
|
-
* Holds rows
|
|
440
|
+
* Holds rows a statement doing `write` writes to the entity's policies under the ambient context, before the write: a
|
|
436
441
|
* field the check pins to one value is filled into an inserted row leaving it out, and refused where a row sets
|
|
437
|
-
* another.
|
|
438
|
-
|
|
439
|
-
export function pinWrite(meta, rows, write) {
|
|
440
|
-
pinRows(meta, rows, write, getContext());
|
|
441
|
-
}
|
|
442
|
-
/**
|
|
443
|
-
* {@link pinWrite}, answering what the rows themselves cannot settle as the check the written rows must hold once
|
|
444
|
-
* written, which the querier reads back inside the write's transaction.
|
|
442
|
+
* another. Answers what the rows themselves cannot settle, which the querier reads back inside the write's
|
|
443
|
+
* transaction. See architecture/row-level-security.md.
|
|
445
444
|
*/
|
|
446
445
|
export function guardWrite(meta, rows, write) {
|
|
447
446
|
const context = getContext();
|
|
448
|
-
const
|
|
449
|
-
if (!pins) {
|
|
450
|
-
return undefined;
|
|
451
|
-
}
|
|
452
|
-
const { check, pinned, rest } = pins;
|
|
453
|
-
const scope = write === 'update' ? policyScope(meta, 'update', context) : undefined;
|
|
454
|
-
const held = typeof scope === 'object' ? pinnedFields(meta, scope).pinned : [];
|
|
455
|
-
const settles = ([key, value]) => write === 'insert' ||
|
|
456
|
-
rows.every((row) => row[key] !== undefined) ||
|
|
457
|
-
held.some(([at, holds]) => at === key && holds === value);
|
|
458
|
-
return !rest && pinned.every(settles) ? undefined : check;
|
|
459
|
-
}
|
|
460
|
-
/** The check `rows` are written under, the fields it pins filled and refused: none where it lets every row be. */
|
|
461
|
-
function pinRows(meta, rows, write, context) {
|
|
462
|
-
const check = policyCheck(meta, write, context);
|
|
447
|
+
const check = policyWhere(meta, write, '$new', context);
|
|
463
448
|
if (check === undefined || check === true) {
|
|
464
449
|
return undefined;
|
|
465
450
|
}
|
|
@@ -479,7 +464,12 @@ function pinRows(meta, rows, write, context) {
|
|
|
479
464
|
}
|
|
480
465
|
}
|
|
481
466
|
}
|
|
482
|
-
|
|
467
|
+
const scope = policyWhere(meta, write, '$old', context);
|
|
468
|
+
const held = typeof scope === 'object' ? pinnedFields(meta, scope).pinned : [];
|
|
469
|
+
const settles = ([key, value]) => write === 'insert' ||
|
|
470
|
+
rows.every((row) => row[key] !== undefined) ||
|
|
471
|
+
held.some(([at, holds]) => at === key && holds === value);
|
|
472
|
+
return !rest && pinned.every(settles) ? undefined : check;
|
|
483
473
|
}
|
|
484
474
|
/**
|
|
485
475
|
* The fields `where` pins to one value, each a top-level equality it ANDs, and whether anything else is left of it:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AbstractType, type ContextKeyRef, type EntityAccess, type EntityMeta, type FieldKey, type FieldMeta, type Policy, type PolicyMeta, type PolicyMode, type
|
|
1
|
+
import { type AbstractType, type ContextKeyRef, type ContextWhere, type EntityAccess, type EntityMeta, type FieldKey, type FieldMeta, type Policy, type PolicyMeta, type PolicyMode, type RowSide, type PolicyWhere, type QueryWhere, type UqlContext } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* What the querier does to hold statements to the policies, under each {@link PolicyMode}: whether it ANDs their
|
|
4
4
|
* scope in (`scopes`), fills and refuses pinned fields (`guards`), reads written rows back against a check (`checks`),
|
|
@@ -26,7 +26,7 @@ export declare function contextKeys(value: unknown): Set<string>;
|
|
|
26
26
|
* `where` with each context key it reads replaced by the value `context` holds, `undefined` where it holds none for
|
|
27
27
|
* one: a filter reading what the context lacks is skipped, where a policy reaching no row is not.
|
|
28
28
|
*/
|
|
29
|
-
export declare function withContextValues<E>(where:
|
|
29
|
+
export declare function withContextValues<E>(where: ContextWhere<E>, context: UqlContext | undefined): QueryWhere<E> | undefined;
|
|
30
30
|
/** A predicate once its context is read: a `$where`, or what it reduced to, every row or none. */
|
|
31
31
|
export type BoundWhere<E> = QueryWhere<E> | boolean;
|
|
32
32
|
/** `bound` as a `$where` of `meta`: `{}` for every row, {@link noRows} for none. */
|
|
@@ -86,19 +86,60 @@ export declare function tenantPolicy<E>(key: FieldKey<E>, contextKey: string): P
|
|
|
86
86
|
*/
|
|
87
87
|
export declare function policiesOf<E>(policies: readonly PolicyMeta<E>[]): readonly PolicyMeta<E>[];
|
|
88
88
|
/**
|
|
89
|
-
* The
|
|
90
|
-
* and a delete
|
|
89
|
+
* The policies each side a statement reads is held to: `$old`, the row as found, and `$new`, the row as written. An
|
|
90
|
+
* update and a delete find their rows as a read does, as Postgres holds them.
|
|
91
91
|
*/
|
|
92
|
-
export declare
|
|
93
|
-
/**
|
|
94
|
-
export declare function
|
|
92
|
+
export declare const POLICY_SIDES: Readonly<Record<EntityAccess, Partial<Record<RowSide, readonly EntityAccess[]>>>>;
|
|
93
|
+
/** Whether a statement doing `access` has both rows, the only one a predicate may pair them for: an update. */
|
|
94
|
+
export declare function pairsRows(access: EntityAccess): boolean;
|
|
95
|
+
/** The refusal of a row an update moves where no transition of `entity`'s lets it, in the querier and the database. */
|
|
96
|
+
export declare function movesRefused(entity: string): string;
|
|
97
|
+
/** Whether `key` names a row of a policy's predicate. */
|
|
98
|
+
export declare function isRowSide(key: string): key is RowSide;
|
|
99
|
+
/** The groups of `where` pairing both rows: the transitions an update is held to. */
|
|
100
|
+
export declare function transitionsOf<E>(where: PolicyWhere<E>): PolicyWhere<E>[];
|
|
101
|
+
/** The sides `where` reads at its root or in a group, where a policy may read them. */
|
|
102
|
+
export declare function sidesOf(where: unknown): Set<RowSide>;
|
|
95
103
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
* policies. What the querier ANDs in, so it answers why a read under a context reaches no row.
|
|
104
|
+
* `where` as one side reads it: its conditions on every row and those on `side`, those on the other side left out, as
|
|
105
|
+
* is a group pairing both rows, which {@link policyTransitions} holds.
|
|
99
106
|
*/
|
|
100
|
-
export declare function
|
|
101
|
-
|
|
102
|
-
|
|
107
|
+
export declare function project<E>(where: PolicyWhere<E>, side: RowSide): ContextWhere<E>;
|
|
108
|
+
/**
|
|
109
|
+
* What `side` of a row a statement doing `access` touches must be under `context`: the rows it reaches as found, and
|
|
110
|
+
* what it writes. `undefined` for an entity with no policies, or a side the statement has none of.
|
|
111
|
+
*/
|
|
112
|
+
export declare function policyWhere<E>(meta: EntityMeta<E>, access: EntityAccess, side: RowSide, context: UqlContext | undefined): BoundWhere<E> | undefined;
|
|
113
|
+
/**
|
|
114
|
+
* The transitions an update is held to under `context`: each group pairing both rows of a `must` holding updates, its
|
|
115
|
+
* context read, `$old` the row as found and `$new` as written. None that holds whatever the rows.
|
|
116
|
+
*/
|
|
117
|
+
export declare function policyTransitions<E>(meta: EntityMeta<E>, context: UqlContext | undefined): (QueryWhere<E> | false)[];
|
|
118
|
+
/**
|
|
119
|
+
* `policy`'s transitions, each with its context read by `read`, those holding whatever the rows left out. Only a `must`
|
|
120
|
+
* holding updates states one, which registering a policy enforces.
|
|
121
|
+
*/
|
|
122
|
+
export declare function boundTransitions<E>(meta: EntityMeta<E>, policy: PolicyMeta<E>, read: ContextRead): (QueryWhere<E> | false)[];
|
|
123
|
+
/**
|
|
124
|
+
* `transition` with each read of the row as found answered by `held`, whether the row holds it, met in the order
|
|
125
|
+
* {@link oldReads} lists them: what is left holds the row as written. A condition beside no side holds both rows.
|
|
126
|
+
*/
|
|
127
|
+
export declare function onWritten<E>(transition: PolicyWhere<E> | QueryWhere<E>, held: (at: number) => boolean): BoundWhere<E>;
|
|
128
|
+
/**
|
|
129
|
+
* What `transition` reads of the row as found, in the order {@link onWritten} meets them. A condition under a
|
|
130
|
+
* negation is read negated, so a null the condition cannot decide lets nothing go, as the database's `IS NOT TRUE`.
|
|
131
|
+
*/
|
|
132
|
+
export declare function oldReads<E>(transition: PolicyWhere<E> | QueryWhere<E>): QueryWhere<E>[];
|
|
133
|
+
/** What `explainPolicies` answers: each side a statement reads, and the transitions an update is held to. */
|
|
134
|
+
export type ExplainedPolicies<E> = {
|
|
135
|
+
readonly $old?: QueryWhere<E>;
|
|
136
|
+
readonly $new?: QueryWhere<E>;
|
|
137
|
+
readonly $and?: readonly QueryWhere<E>[];
|
|
103
138
|
};
|
|
139
|
+
/**
|
|
140
|
+
* What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset, as a
|
|
141
|
+
* policy states it: `$old`, the rows it reaches (`{}` for every one), `$new`, what a row it writes must hold, and an
|
|
142
|
+
* update's transitions. None for an entity with no policies. It answers why a read under a context reaches no row.
|
|
143
|
+
*/
|
|
144
|
+
export declare function explainPolicies<E>(entity: AbstractType<E>, access: EntityAccess, context?: UqlContext | undefined): ExplainedPolicies<E>;
|
|
104
145
|
export {};
|