uql-orm 0.115.5 → 0.116.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.
@@ -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 an insert or an update writes to the entity's policies under the ambient context, before the write: a
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. See architecture/row-level-security.md.
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 pinWrite<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, rows: readonly R[], write: 'insert' | 'update'): void;
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, policyCheck, policyScope, withContextValues } from './policy.util.js';
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 : policyScope(meta, opts?.access ?? 'read', getContext());
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 an insert or an update writes to the entity's policies under the ambient context, before the write: a
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. See architecture/row-level-security.md.
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 pins = pinRows(meta, rows, write, context);
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
- return { check, pinned, rest };
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 PolicyWhere, type QueryWhere, type ScopedAccess, type UqlContext } from '../type/index.js';
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: PolicyWhere<E>, context: UqlContext | undefined): QueryWhere<E> | undefined;
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 rows a statement doing `access` may reach under `context`, `undefined` for an entity with no policies. An update
90
- * and a delete are held to the `read` policies too, as Postgres holds them.
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 function policyScope<E>(meta: EntityMeta<E>, access: ScopedAccess, context: UqlContext | undefined): BoundWhere<E> | undefined;
93
- /** What a row an insert or an update writes must hold under `context`, `undefined` for an entity with no policies. */
94
- export declare function policyCheck<E>(meta: EntityMeta<E>, access: 'insert' | 'update', context: UqlContext | undefined): BoundWhere<E> | undefined;
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
- * What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset: `where`,
97
- * the rows it reaches (`{}` for every one), and `check`, what a row it writes must hold. Neither for an entity with no
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 explainPolicies<E>(entity: AbstractType<E>, access: EntityAccess, context?: UqlContext | undefined): {
101
- readonly where?: QueryWhere<E>;
102
- readonly check?: QueryWhere<E>;
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 {};
@@ -80,6 +80,12 @@ function orBound(parts) {
80
80
  const kept = parts.filter((part) => part !== false);
81
81
  return kept.length === 0 ? false : kept.length === 1 ? kept[0] : whereAnyOf(kept);
82
82
  }
83
+ /** `clauses` joined as the group `key` joins them. */
84
+ function boundGroup(key, clauses) {
85
+ const { join, negate } = GROUP_OPS[key];
86
+ const group = join === '$and' ? andBound(clauses) : orBound(clauses);
87
+ return negate ? notBound(group) : group;
88
+ }
83
89
  /** Not `bound`. */
84
90
  function notBound(bound) {
85
91
  return typeof bound === 'boolean' ? !bound : { $not: [bound] };
@@ -101,10 +107,13 @@ export function bindContext(meta, where, read, positive = true) {
101
107
  }
102
108
  const parts = Object.entries(where).map(([key, value]) => {
103
109
  if (isGroupOp(key)) {
104
- const { join, negate } = GROUP_OPS[key];
105
- const clauses = groupClauses(key, value).map((item) => item instanceof QuerySql ? whereAnd(undefined, [item]) : bindContext(meta, item, read, positive !== negate));
106
- const group = join === '$and' ? andBound(clauses) : orBound(clauses);
107
- return negate ? notBound(group) : group;
110
+ const inner = positive !== GROUP_OPS[key].negate;
111
+ const clauses = groupClauses(key, value).map((item) => item instanceof QuerySql ? whereAnd(undefined, [item]) : bindContext(meta, item, read, inner));
112
+ return boundGroup(key, clauses);
113
+ }
114
+ if (isRowSide(key)) {
115
+ const side = bindContext(meta, value, read, positive);
116
+ return typeof side === 'boolean' ? side : { [key]: side };
108
117
  }
109
118
  const relation = meta.relations[key];
110
119
  if (relation) {
@@ -196,13 +205,89 @@ export function policiesOf(policies) {
196
205
  : [...policies, { effect: 'allow', ops: POLICY_OPS, where: {}, name: EVERY_ROW_POLICY }];
197
206
  }
198
207
  /**
199
- * The rows every statement in `accesses` may reach: each `must` holding one, and for each, an `allow` holding it,
200
- * statements the same allows hold ORing them in once.
208
+ * The policies each side a statement reads is held to: `$old`, the row as found, and `$new`, the row as written. An
209
+ * update and a delete find their rows as a read does, as Postgres holds them.
210
+ */
211
+ export const POLICY_SIDES = {
212
+ read: { $old: ['read'] },
213
+ delete: { $old: ['read', 'delete'] },
214
+ insert: { $new: ['insert'] },
215
+ update: { $old: ['read', 'update'], $new: ['update'] },
216
+ };
217
+ /** Whether a statement doing `access` has both rows, the only one a predicate may pair them for: an update. */
218
+ export function pairsRows(access) {
219
+ const sides = POLICY_SIDES[access];
220
+ return !!(sides.$old && sides.$new);
221
+ }
222
+ /** The refusal of a row an update moves where no transition of `entity`'s lets it, in the querier and the database. */
223
+ export function movesRefused(entity) {
224
+ return `a row of '${entity}' moves where its policies do not let it`;
225
+ }
226
+ /** Whether `key` names a row of a policy's predicate. */
227
+ export function isRowSide(key) {
228
+ return key === '$old' || key === '$new';
229
+ }
230
+ /** The conditions `where` ANDs, each `$and`'s spliced in, as one-key predicates. */
231
+ function conjunctParts(where) {
232
+ return Object.entries(where).flatMap(([key, value]) => key === '$and' && Array.isArray(value)
233
+ ? value.flatMap((clause) => clause instanceof QuerySql ? [{ $and: [clause] }] : conjunctParts(clause))
234
+ : [{ [key]: value }]);
235
+ }
236
+ /** Whether `part` pairs both rows: a group reading a side, which no one side answers. */
237
+ function pairs(part) {
238
+ return Object.keys(part).some(isGroupOp) && sidesOf(part).size > 0;
239
+ }
240
+ /** The groups of `where` pairing both rows: the transitions an update is held to. */
241
+ export function transitionsOf(where) {
242
+ return conjunctParts(where).filter(pairs);
243
+ }
244
+ /** The sides `where` reads at its root or in a group, where a policy may read them. */
245
+ export function sidesOf(where) {
246
+ const sides = new Set();
247
+ if (isPlainObject(where)) {
248
+ for (const [key, value] of Object.entries(where)) {
249
+ if (isRowSide(key)) {
250
+ sides.add(key);
251
+ }
252
+ else if (isGroupOp(key)) {
253
+ groupClauses(key, value).forEach((clause) => sidesOf(clause).forEach((side) => sides.add(side)));
254
+ }
255
+ }
256
+ }
257
+ return sides;
258
+ }
259
+ /** `parts` as one predicate: merged where their keys differ, else an `$and`. */
260
+ function allOf(parts) {
261
+ const keys = parts.flatMap((part) => Object.keys(part));
262
+ if (parts.length === 1 || new Set(keys).size === keys.length) {
263
+ return Object.assign({}, ...parts);
264
+ }
265
+ return { $and: parts };
266
+ }
267
+ /**
268
+ * `where` as one side reads it: its conditions on every row and those on `side`, those on the other side left out, as
269
+ * is a group pairing both rows, which {@link policyTransitions} holds.
270
+ */
271
+ export function project(where, side) {
272
+ if (!sidesOf(where).size) {
273
+ return where;
274
+ }
275
+ return allOf(conjunctParts(where).flatMap((part) => {
276
+ const [key] = Object.keys(part);
277
+ if (isRowSide(key)) {
278
+ return key === side ? [part[key]] : [];
279
+ }
280
+ return pairs(part) ? [] : [part];
281
+ }));
282
+ }
283
+ /**
284
+ * The rows `side` of every statement in `accesses` may be: each `must` holding one, and for each, an `allow` holding
285
+ * it, statements the same allows hold ORing them in once.
201
286
  */
202
- function joined(meta, declared, accesses, context, pick) {
287
+ function joined(meta, declared, accesses, context, side) {
203
288
  const policies = policiesOf(declared).filter((policy) => accesses.some((access) => policy.ops.includes(access)) && holdsWhen(policy.when, context));
204
289
  const read = fromContext(context);
205
- const bound = policies.map((policy) => bindContext(meta, pick(policy), read));
290
+ const bound = policies.map((policy) => bindContext(meta, project(policy.where, side), read));
206
291
  const allowSets = new Map(accesses.map((access) => {
207
292
  const set = policies.flatMap((policy, at) => policy.effect === 'allow' && policy.ops.includes(access) ? [at] : []);
208
293
  return [set.join(), set];
@@ -213,31 +298,89 @@ function joined(meta, declared, accesses, context, pick) {
213
298
  ]);
214
299
  }
215
300
  /**
216
- * The rows a statement doing `access` may reach under `context`, `undefined` for an entity with no policies. An update
217
- * and a delete are held to the `read` policies too, as Postgres holds them.
301
+ * What `side` of a row a statement doing `access` touches must be under `context`: the rows it reaches as found, and
302
+ * what it writes. `undefined` for an entity with no policies, or a side the statement has none of.
218
303
  */
219
- export function policyScope(meta, access, context) {
304
+ export function policyWhere(meta, access, side, context) {
305
+ const accesses = POLICY_SIDES[access][side];
220
306
  const { policies } = meta;
221
- return policies?.length ? joined(meta, policies, ['read', access], context, (policy) => policy.where) : undefined;
307
+ return policies?.length && accesses ? joined(meta, policies, accesses, context, side) : undefined;
222
308
  }
223
- /** What a row an insert or an update writes must hold under `context`, `undefined` for an entity with no policies. */
224
- export function policyCheck(meta, access, context) {
225
- const { policies } = meta;
226
- return policies?.length
227
- ? joined(meta, policies, [access], context, (policy) => policy.check ?? policy.where)
228
- : undefined;
309
+ /**
310
+ * The transitions an update is held to under `context`: each group pairing both rows of a `must` holding updates, its
311
+ * context read, `$old` the row as found and `$new` as written. None that holds whatever the rows.
312
+ */
313
+ export function policyTransitions(meta, context) {
314
+ const read = fromContext(context);
315
+ return (meta.policies ?? [])
316
+ .filter((policy) => holdsWhen(policy.when, context))
317
+ .flatMap((policy) => boundTransitions(meta, policy, read));
318
+ }
319
+ /**
320
+ * `policy`'s transitions, each with its context read by `read`, those holding whatever the rows left out. Only a `must`
321
+ * holding updates states one, which registering a policy enforces.
322
+ */
323
+ export function boundTransitions(meta, policy, read) {
324
+ return transitionsOf(policy.where)
325
+ .map((part) => bindContext(meta, part, read))
326
+ .filter((bound) => bound !== true);
327
+ }
328
+ /**
329
+ * `transition` with each read of the row as found answered by `held`, whether the row holds it, met in the order
330
+ * {@link oldReads} lists them: what is left holds the row as written. A condition beside no side holds both rows.
331
+ */
332
+ export function onWritten(transition, held) {
333
+ let at = 0;
334
+ return walkTransition(transition, true, () => held(at++));
335
+ }
336
+ /**
337
+ * What `transition` reads of the row as found, in the order {@link onWritten} meets them. A condition under a
338
+ * negation is read negated, so a null the condition cannot decide lets nothing go, as the database's `IS NOT TRUE`.
339
+ */
340
+ export function oldReads(transition) {
341
+ const reads = [];
342
+ walkTransition(transition, true, (read) => {
343
+ reads.push(read);
344
+ return true;
345
+ });
346
+ return reads;
347
+ }
348
+ /**
349
+ * One walk of a transition for both {@link oldReads} and {@link onWritten}, so the two meet its conditions alike:
350
+ * `held` answers whether the row as found holds each read, which is the condition itself where `positive`.
351
+ */
352
+ function walkTransition(where, positive, held) {
353
+ const found = (condition) => positive ? held(condition) : !held({ $not: [condition] });
354
+ const parts = Object.entries(where).map(([key, value]) => {
355
+ if (isGroupOp(key)) {
356
+ const inner = positive !== GROUP_OPS[key].negate;
357
+ const clauses = groupClauses(key, value).map((clause) => walkTransition(clause, inner, held));
358
+ return boundGroup(key, clauses);
359
+ }
360
+ if (key === '$old') {
361
+ return found(value);
362
+ }
363
+ if (key === '$new') {
364
+ return value;
365
+ }
366
+ const leaf = { [key]: value };
367
+ return andBound([found(leaf), leaf]);
368
+ });
369
+ return andBound(parts);
229
370
  }
230
371
  /**
231
- * What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset: `where`,
232
- * the rows it reaches (`{}` for every one), and `check`, what a row it writes must hold. Neither for an entity with no
233
- * policies. What the querier ANDs in, so it answers why a read under a context reaches no row.
372
+ * What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset, as a
373
+ * policy states it: `$old`, the rows it reaches (`{}` for every one), `$new`, what a row it writes must hold, and an
374
+ * update's transitions. None for an entity with no policies. It answers why a read under a context reaches no row.
234
375
  */
235
376
  export function explainPolicies(entity, access, context = getContext()) {
236
377
  const meta = getMeta(entity);
237
- const scope = access === 'insert' ? undefined : policyScope(meta, access, context);
238
- const check = access === 'insert' || access === 'update' ? policyCheck(meta, access, context) : undefined;
378
+ const found = policyWhere(meta, access, '$old', context);
379
+ const written = policyWhere(meta, access, '$new', context);
380
+ const transitions = pairsRows(access) ? policyTransitions(meta, context) : [];
239
381
  return {
240
- ...(scope === undefined ? {} : { where: asWhere(meta, scope) }),
241
- ...(check === undefined ? {} : { check: asWhere(meta, check) }),
382
+ ...(found === undefined ? {} : { $old: asWhere(meta, found) }),
383
+ ...(written === undefined ? {} : { $new: asWhere(meta, written) }),
384
+ ...(transitions.length ? { $and: transitions.map((bound) => asWhere(meta, bound)) } : {}),
242
385
  };
243
386
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.115.5",
6
+ "version": "0.116.1",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -63,7 +63,7 @@
63
63
  "mongodb": ">=6.0.0 <8",
64
64
  "mssql": ">=11.0.0 <13",
65
65
  "mysql2": ">=3.0.0 <4",
66
- "pg": ">=8.0.0 <9",
66
+ "pg": ">=8.5.0 <9",
67
67
  "pg-query-stream": ">=4.0.0 <5",
68
68
  "rxjs": ">=7.0.0 <8"
69
69
  },
@@ -98,7 +98,7 @@ export class Post {
98
98
  - Optimistic lock: `@Field(f.version())` with `[versionKey]?: 'version'` on the class. An update, and an upsert or save of a row that exists, must carry the version it read; a stale one throws `UqlOptimisticLockError`.
99
99
  - Computed fields are `readonly`: ``@Computed((u) => f.string().as(sql`${u.first} || ' ' || ${u.last}`))``, `.stored()` for a generated column, or a relation aggregate, `@Computed((user) => user.posts.count())`.
100
100
  - Indexes, checks, filters and triggers are `@Entity` options, each entry made by the helper the callback is handed. A partial index's predicate is a query: `indexes: (post, index) => [index([post.authorId], { where: { archived: { $ne: true } } })]`. A JSON path is indexed off the column's ref, `index([user.settings.theme])`: https://uql-orm.dev/entities/indexes.md
101
- - Triggers run in the database: `triggers: (post, trigger) => [trigger({ on: 'afterUpdate', of: [post.status], run })]`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. `on` is one event: a body several events share is one `run` passed to each entry. They skip entity filters and run no JavaScript: an insert fills an `.onInsert()` value or SQL, but an `insertInto` names every required column a callback fills (`.onInsert(() => crypto.randomUUID())`) where no database default does. MongoDB has none: https://uql-orm.dev/entities/triggers.md
101
+ - Triggers run in the database: `triggers: (post, trigger) => [trigger({ on: 'afterUpdate', of: [post.status], run })]`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. `on` is one event: a body several events share is one `run` passed to each entry. `where` reads `$new: {...}` and `$old: {...}`; an update's may group them (`$or: [{ $old: ... }, { $new: ... }]`), and a condition under neither holds on both rows, as in a policy. They skip entity filters and run no JavaScript: an insert fills an `.onInsert()` value or SQL, but an `insertInto` names every required column a callback fills (`.onInsert(() => crypto.randomUUID())`) where no database default does. MongoDB has none: https://uql-orm.dev/entities/triggers.md
102
102
  - Hooks are methods with `this` bound to the payload: `@BeforeInsert()`, `@AfterInsert()`, and the same pairs for update, upsert and delete, plus `@AfterLoad()`. Changes to `this` in a before-hook are written. `upsert*` runs only the upsert pair, and `save*` the upsert pair for a row carrying its key. Each receives `{ querier, onCommit }`.
103
103
  - **MongoDB:** a `f.number()` key left to the database is refused, since MongoDB only generates ObjectIds. Declare it a string, or give it an `.onInsert()` generator.
104
104
 
@@ -163,8 +163,12 @@ declare module 'uql-orm' {
163
163
  @Entity({
164
164
  filters: { active: { where: { status: 'active' }, default: false } },
165
165
  policies: [
166
- { allow: { ownerId: $context.userId }, check: { status: { $ne: 'void' } } },
166
+ { allow: { ownerId: $context.userId, $new: { status: { $ne: 'void' } } } },
167
167
  { allow: {}, ops: ['read'], when: { role: ['auditor', 'admin'] } },
168
+ {
169
+ must: { $or: [{ $old: { status: 'draft' } }, { $new: { status: { $ne: 'draft' } } }] },
170
+ ops: ['update'],
171
+ },
168
172
  ],
169
173
  })
170
174
  export class Invoice {
@@ -182,10 +186,10 @@ await withContext({ tenantId: 42, userId: 'u1' }, () => pool.findMany(Invoice, {
182
186
  - `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
183
187
  - A filter's `where` may read the context as data, `{ authorId: $context.userId }`, and is skipped where the context lacks a key it reads; or it may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
184
188
  - `.tenant()` on one column makes it the row's tenant, read off `$context.tenantId` (`.tenant($context.orgId)` names another, which must hold the column's type): every statement is held to it, and an insert leaving it out is given it.
185
- - A policy is data: `{ allow: where }` or `{ must: where }`, beside `ops` (`'read'`, `'insert'`, `'update'`, `'delete'`, every one where unset), `check` (what a written row must hold, the `where` where unset), `when` (context keys at a value, or one of a list) and `name`. A row is reached when any `allow` holding the statement reaches it and every `must` holds. An entity declaring no `allow` is allowed every row its `must`s (and tenant) leave; one declaring some reaches no row in a statement none of them holds. An update or delete is held to the `read` ones too. `{}` reaches every row. A policy stated once as a constant serves every entity with the fields it names.
186
- - `explainPolicies(Invoice, 'read')` answers the `where` the querier ANDs in under the ambient context (and `check` for a write): what to look at when a read reaches no row.
189
+ - A policy is data: `{ allow: where }` or `{ must: where }`, beside `ops` (`'read'`, `'insert'`, `'update'`, `'delete'`, every one where unset), `when` (context keys at a value, or one of a list) and `name`. Its `where` holds every row a statement touches, found and written; `$old: {...}` in it holds only the row as found (a row failing it is not reached) and `$new: {...}` only the row as written (a write failing it is refused). A read or delete sees `$old`, an insert `$new`, an update both. A group pairing both, `$or: [{ $old: ... }, { $new: ... }]`, is a transition: only in a `must` with `ops: ['update']`, held on every engine (natively by a trigger), soft deletes included. There is no `check`. A row is reached when any `allow` holding the statement reaches it and every `must` holds. An entity declaring no `allow` is allowed every row its `must`s (and tenant) leave; one declaring some reaches no row in a statement none of them holds. An update or delete is held to the `read` ones too. A soft delete is an update: the `update` policies hold it, and `delete` ones a hard delete. `{}` reaches every row. A policy stated once as a constant serves every entity with the fields it names.
190
+ - `explainPolicies(Invoice, 'update')` answers what the policies hold a statement to under the ambient context, as a policy states it: `$old` the rows it reaches, `$new` what a row it writes must hold, `$and` an update's transitions. What to look at when a read reaches no row.
187
191
  - `$context.tenantId` reads the context key in a predicate, typed by `UqlContext`: once it declares keys, a misspelled one, or one in `when`, does not compile; a relation is read like any `$where` (`{ allow: { members: { userId: $context.userId } } }`). A key the context lacks or holds null matches nothing, as SQL's NULL compares: no context, no rows.
188
- - Policies hold every read, populate, relation filter and count, and every write: an insert gets each field a policy pins to one value (`companyId`), a write setting another is refused with `UqlSecurityError`, and a check the row alone cannot settle is read back in the write's transaction (MongoDB needs `transaction()` for one; D1 refuses it). Nothing per call turns a policy off: run trusted, cross-tenant work on a pool built with `{ policies: false }`.
192
+ - Policies hold every read, populate, relation filter and count, and every write: an insert gets each field a policy pins to one value (`companyId`), a write setting another is refused with `UqlSecurityError`, and a `$new` condition the row alone cannot settle, or a transition, is read in the write's transaction (MongoDB needs `transaction()` for one; D1 refuses it). Nothing per call turns a policy off: run trusted, cross-tenant work on a pool built with `{ policies: false }`.
189
193
  - `{ policies: 'native' }` on a Postgres or CockroachDB pool has the database hold them: migrations install `CREATE POLICY` (RLS enabled and forced), each transaction binds the context with `set_config`, and raw SQL is held too. Connect it as a role that is no superuser and lacks `BYPASSRLS`; a statement under a context is refused otherwise. `role: $context.role` beside it runs each transaction as the database role the context names, and a `when` on that key compares that role exactly (`current_user`). CockroachDB takes no relation in a native policy, and a Postgres insert must be readable by the context inserting it. https://uql-orm.dev/multi-tenancy.md
190
194
 
191
195
  ## Queries
@@ -204,13 +208,13 @@ const users = await pool.findMany(User, {
204
208
  });
205
209
  ```
206
210
 
207
- - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `estimatedCount`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Whether anything matches is `exists`, which stops at the first row, never `count(...) > 0`. Signatures: https://uql-orm.dev/querying/methods.md
211
+ - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `estimatedCount`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`, `restoreOneById`, `restoreMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Whether anything matches is `exists`, which stops at the first row, never `count(...) > 0`. Signatures: https://uql-orm.dev/querying/methods.md
208
212
  - `$` marks the query language: clauses, operators, `$old`/`$new` in a trigger's predicate and `$context` reads. Field, relation and context key names never take it, and neither do a definition's or a call's options (`policies: [{ allow, ops, when }]`, `{ filters: false }`).
209
213
  - Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`, `$lock`. `$select: { password: false }` reads every field but `password`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
210
214
  - Results are narrowed to what the query selected and populated, at every depth. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing typed `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`.
211
215
  - `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
212
216
  - `$sort` takes `'asc'`/`1`, `'desc'`/`-1`, or `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`.
213
- - `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique NOT NULL field; no `$skip`.
217
+ - `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`; `$before: startCursor` reads the page before. `$sort` must end in the key or a unique NOT NULL field; no `$skip`.
214
218
  - `$lock: true` locks the rows a read returns, inside an open transaction; `{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds. The SQLite family and MongoDB refuse it.
215
219
 
216
220
  ### `$where`
@@ -218,9 +222,9 @@ const users = await pool.findMany(User, {
218
222
  - `$where` takes a value for equality, a list as an implicit `$in`, or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$between`, `$in`, `$nin`, `$isNull`, `$isNotNull`. Combine with `$and`, `$or`, `$not`, `$nor`. A field takes only the operators its type allows.
219
223
  - Text: `$like`, `$startsWith`, `$endsWith`, `$includes`, each with a case-insensitive `i` form (`$ilike`, `$istartsWith`, ...). `$like` reads `%`, `_` and `\` the same on every engine; the other three take their text literally. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
220
224
  - Arrays and JSON: `$all: ['a', 'b']`, `$size: 3` or `{ $gte: 2 }`, `$elemMatch: { city: 'NYC', zip: { $startsWith: '10' } }`. A JSON path filters like a field: `{ 'settings.billing.plan': 'pro' }`.
221
- - A relation key keeps the parents with a matching related row, as an `EXISTS`, never duplicating them: `{ posts: { title: { $iincludes: 'orm' } } }`, or by count: `{ posts: { $size: { $gte: 5 } } }`. For a subquery no relation covers, `$exists` / `$nexists` take a `sql` fragment.
222
- - Full-text: `$where: { $text: { $value: 'wireless keyboard' } }` searches the entity's fulltext index; `$sort: { $text: 'desc' }` ranks by relevance.
223
- - Vectors: `$sort: { embedding: { $vector: v } }` with a `$limit` returns the nearest; `$where: { embedding: { $near: { $vector: v, $lt: 0.35 } } }` keeps only close rows; `$candidates` tunes ANN recall.
225
+ - A relation key keeps the parents with a matching related row, as an `EXISTS`, never duplicating them: `{ posts: { title: { $iincludes: 'orm' } } }`, or by count: `{ posts: { $size: { $gte: 5 } } }`. For a subquery no relation covers, `$exists` / `$nexists` take a `sql` fragment: ``const user = refs(User), o = refs(Order, 'o'); $where: { $exists: sql`SELECT 1 FROM ${tableOf(o)} WHERE ${o.userId} = ${user.id}` }``.
226
+ - Full-text: `$where: { $text: { $value: 'wireless keyboard' } }` searches the entity's fulltext index; `$fields: { title: true }` narrows the columns and `$config: 'simple'` sets the language. `$sort: { $text: 'desc' }` ranks by relevance, and `{ $text: { $project: 'rank' } }` also returns the score as `rank`.
227
+ - Vectors: `$sort: { embedding: { $vector: v } }` with a `$limit` returns the nearest; `$where: { embedding: { $near: { $vector: v, $lt: 0.35 } } }` keeps only close rows; `$distance: 'cosine' | 'l2' | 'inner' | 'l1'` overrides the field's metric, `$project: 'distance'` in `$sort` returns it, and `$candidates` tunes ANN recall.
224
228
  - An operator compares a field with another column of the row wherever it takes a value: `const rate = refs(Rate); pool.findMany(Rate, { $where: { effectiveTo: { $gt: rate.effectiveFrom } } })`. A check's refs work the same. A JSON path compared with a ref reads as that column's type. A ref of another entity than the one queried is refused: in raw SQL, read it off its own alias, `refs(Other, 'o')`.
225
229
  - An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
226
230
  - On SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.