uql-orm 0.114.3 → 0.115.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.
Files changed (85) 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 +2 -5
  39. package/dist/mongodb/mongodbQuerier.js +14 -26
  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 +68 -30
  47. package/dist/querier/abstractQuerier.js +249 -168
  48. package/dist/querier/abstractQuerierPool.js +2 -0
  49. package/dist/querier/abstractSqlQuerier.d.ts +22 -13
  50. package/dist/querier/abstractSqlQuerier.js +75 -27
  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 +16 -2
  71. package/dist/type/querierPool.d.ts +2 -2
  72. package/dist/type/query.d.ts +20 -35
  73. package/dist/type/query.js +2 -0
  74. package/dist/type/universalQuerier.d.ts +6 -6
  75. package/dist/util/contextRefs.d.ts +6 -0
  76. package/dist/util/contextRefs.js +5 -0
  77. package/dist/util/dialect.util.d.ts +10 -16
  78. package/dist/util/dialect.util.js +70 -64
  79. package/dist/util/fieldOption.util.js +1 -0
  80. package/dist/util/policy.util.d.ts +100 -0
  81. package/dist/util/policy.util.js +234 -0
  82. package/dist/util/uqlError.d.ts +2 -5
  83. package/dist/util/uqlError.js +2 -5
  84. package/package.json +1 -1
  85. package/skills/uql-orm/SKILL.md +24 -14
@@ -0,0 +1,100 @@
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';
2
+ /**
3
+ * What the querier does to hold statements to the policies, under each {@link PolicyMode}: whether it ANDs their
4
+ * scope in (`scopes`), fills and refuses pinned fields (`guards`), reads written rows back against a check (`checks`),
5
+ * and leaves the rest to the database, which it binds the context for (`database`).
6
+ */
7
+ export type PolicyEnforcement = {
8
+ readonly scopes: boolean;
9
+ readonly guards: boolean;
10
+ readonly checks: boolean;
11
+ readonly database: boolean;
12
+ };
13
+ /** How a pool built with `{ policies: mode }` holds its statements to the policies, the querier's way where unset. */
14
+ export declare function enforcementOf(mode: PolicyMode | undefined): PolicyEnforcement;
15
+ /** Every statement a policy holds where it names none. */
16
+ export declare const POLICY_OPS: readonly EntityAccess[];
17
+ /** A declared policy as metadata keeps it, its effect read off the key holding its predicate. */
18
+ export declare function policyMeta<E>({ allow, must, ops, ...rest }: Policy<E>): PolicyMeta<E> | undefined;
19
+ /** `value` with each `{ $context }` ref replaced by what `onRef` answers, every other node copied as it was. */
20
+ export declare function mapContextRefs(value: unknown, onRef: (ref: ContextKeyRef) => unknown): unknown;
21
+ /** The context keys `value` reads, in the order met. */
22
+ export declare function contextKeys(value: unknown): Set<string>;
23
+ /**
24
+ * `where` with each context key it reads replaced by the value `context` holds, `undefined` where it holds none for
25
+ * one: a filter reading what the context lacks is skipped, where a policy reaching no row is not.
26
+ */
27
+ export declare function withContextValues<E>(where: PolicyWhere<E>, context: UqlContext | undefined): QueryWhere<E> | undefined;
28
+ /** A predicate once its context is read: a `$where`, or what it reduced to, every row or none. */
29
+ export type BoundWhere<E> = QueryWhere<E> | boolean;
30
+ /** `bound` as a `$where` of `meta`: `{}` for every row, {@link noRows} for none. */
31
+ export declare function asWhere<E>(meta: EntityMeta<E>, bound: BoundWhere<E>): QueryWhere<E>;
32
+ /** The predicates `where` ANDs: its `$and`'s where that is all it holds and none is SQL, else itself. */
33
+ export declare function conjuncts<E>(where: QueryWhere<E>): QueryWhere<E>[];
34
+ /**
35
+ * What a context key a policy compares `field` against reads as: its value, {@link MISSING} where the context holds
36
+ * none, or SQL reading it in the database. `field` is `undefined` where the key names no field of the entity.
37
+ */
38
+ export type ContextRead = (ref: ContextKeyRef, field: FieldMeta | undefined) => unknown;
39
+ /** Reads each key off `context`: an absent key and a null alike are {@link MISSING}, which matches nothing. */
40
+ export declare function fromContext(context: UqlContext | undefined): (ref: ContextKeyRef) => unknown;
41
+ /**
42
+ * `where` with each context key it reads replaced by what `read` answers, the way the database reads a policy: a
43
+ * comparison against a {@link MISSING} key is SQL's unknown, never true, whatever negates it. `positive` is whether
44
+ * the predicate counts where it stands (`false` under a `$not`); a relation's subquery restarts it.
45
+ */
46
+ export declare function bindContext<E>(meta: EntityMeta<E>, where: PolicyWhere<E>, read: ContextRead, positive?: boolean): BoundWhere<E>;
47
+ /** The database setting a context key is bound to for the policies the database holds. */
48
+ export declare function contextSetting(key: string): string;
49
+ /** A context key a policy may read, which names a database setting as it is. */
50
+ export declare const POLICY_CONTEXT_KEY: RegExp;
51
+ /**
52
+ * The keys of `context` a database binds for the policies it holds, each with its value as text: a scalar or a date,
53
+ * under a key a policy may read. Any other is left unbound, which a policy reads as NULL.
54
+ */
55
+ export declare function contextEntries(context: UqlContext | undefined): [string, string][];
56
+ /** The context of a transaction that bound none yet, or whose binding a savepoint's rollback undid. */
57
+ declare const UNBOUND: unique symbol;
58
+ /** What a transaction bound for the database's policies: the context it last bound, and every key it bound so far. */
59
+ export type BoundContext = {
60
+ readonly context: UqlContext | undefined | typeof UNBOUND;
61
+ readonly keys: readonly string[];
62
+ };
63
+ export declare const NOTHING_BOUND: BoundContext;
64
+ /** `bound` after a savepoint's rollback, which may bring back any key bound before it: the next statement binds again. */
65
+ export declare function unsettled(bound: BoundContext): BoundContext;
66
+ /**
67
+ * What binds `context` over `bound`: its entries, each key the transaction bound that it lacks set empty, and what is
68
+ * bound once they are sent. No entry where `context` is the one bound.
69
+ */
70
+ export declare function nextBinding(bound: BoundContext, context: UqlContext | undefined): {
71
+ entries: [string, string][];
72
+ bound: BoundContext;
73
+ };
74
+ /** The name of the policy a `tenant()` column registers, and of the `allow` an entity declaring none is given. */
75
+ export declare const TENANT_POLICY = "tenant";
76
+ export declare const EVERY_ROW_POLICY = "everyRow";
77
+ /** The `must` holding each row of `meta` to the tenant `key` stores, read off context key `contextKey`. */
78
+ export declare function tenantPolicy<E>(key: FieldKey<E>, contextKey: string): PolicyMeta<E>;
79
+ /**
80
+ * The policies holding `meta`: its own, and where none of them is an `allow`, one reaching every row, so its `must`s
81
+ * alone narrow what it reaches. An entity declaring an `allow` reaches no row in a statement none of them holds.
82
+ */
83
+ export declare function policiesOf<E>(policies: readonly PolicyMeta<E>[]): readonly PolicyMeta<E>[];
84
+ /**
85
+ * The rows a statement doing `access` may reach under `context`, `undefined` for an entity with no policies. An update
86
+ * and a delete are held to the `read` policies too, as Postgres holds them.
87
+ */
88
+ export declare function policyScope<E>(meta: EntityMeta<E>, access: ScopedAccess, context: UqlContext | undefined): BoundWhere<E> | undefined;
89
+ /** What a row an insert or an update writes must hold under `context`, `undefined` for an entity with no policies. */
90
+ export declare function policyCheck<E>(meta: EntityMeta<E>, access: 'insert' | 'update', context: UqlContext | undefined): BoundWhere<E> | undefined;
91
+ /**
92
+ * What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset: `where`,
93
+ * the rows it reaches (`{}` for every one), and `check`, what a row it writes must hold. Neither for an entity with no
94
+ * policies. What the querier ANDs in, so it answers why a read under a context reaches no row.
95
+ */
96
+ export declare function explainPolicies<E>(entity: AbstractType<E>, access: EntityAccess, context?: UqlContext | undefined): {
97
+ readonly where?: QueryWhere<E>;
98
+ readonly check?: QueryWhere<E>;
99
+ };
100
+ export {};
@@ -0,0 +1,234 @@
1
+ import { getContext } from '../context/context.js';
2
+ import { GROUP_OPS, groupClauses, isGroupOp } from '../dialect/operators.js';
3
+ import { getMeta } from '../entity/metadata/definition.js';
4
+ import { QuerySql, } from '../type/index.js';
5
+ import { utcTimestamp } from './date.js';
6
+ import { isPlainObject } from './object.util.js';
7
+ import { whereAnd, whereAnyOf, whereWith } from './query.util.js';
8
+ const ENFORCEMENT = {
9
+ app: { scopes: true, guards: true, checks: true, database: false },
10
+ native: { scopes: false, guards: true, checks: false, database: true },
11
+ off: { scopes: false, guards: false, checks: false, database: false },
12
+ };
13
+ /** How a pool built with `{ policies: mode }` holds its statements to the policies, the querier's way where unset. */
14
+ export function enforcementOf(mode) {
15
+ return ENFORCEMENT[mode === false ? 'off' : (mode ?? 'app')];
16
+ }
17
+ /** Every statement a policy holds where it names none. */
18
+ export const POLICY_OPS = ['read', 'insert', 'update', 'delete'];
19
+ /** A declared policy as metadata keeps it, its effect read off the key holding its predicate. */
20
+ export function policyMeta({ allow, must, ops = POLICY_OPS, ...rest }) {
21
+ const where = allow ?? must;
22
+ return where && { effect: allow === undefined ? 'must' : 'allow', ops, where, ...rest };
23
+ }
24
+ /** Whether `value` reads a context key, `{ $context: 'tenantId' }`, and nothing else. */
25
+ function isContextRef(value) {
26
+ return isPlainObject(value) && typeof value['$context'] === 'string' && Object.keys(value).length === 1;
27
+ }
28
+ /** `value` with each `{ $context }` ref replaced by what `onRef` answers, every other node copied as it was. */
29
+ export function mapContextRefs(value, onRef) {
30
+ if (isContextRef(value)) {
31
+ return onRef(value);
32
+ }
33
+ if (Array.isArray(value)) {
34
+ return value.map((item) => mapContextRefs(item, onRef));
35
+ }
36
+ return isPlainObject(value)
37
+ ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapContextRefs(item, onRef)]))
38
+ : value;
39
+ }
40
+ /** The context keys `value` reads, in the order met. */
41
+ export function contextKeys(value) {
42
+ const keys = new Set();
43
+ mapContextRefs(value, (ref) => keys.add(ref.$context));
44
+ return keys;
45
+ }
46
+ /**
47
+ * `where` with each context key it reads replaced by the value `context` holds, `undefined` where it holds none for
48
+ * one: a filter reading what the context lacks is skipped, where a policy reaching no row is not.
49
+ */
50
+ export function withContextValues(where, context) {
51
+ const bound = bindField(where, fromContext(context));
52
+ return bound === MISSING ? undefined : bound;
53
+ }
54
+ /** No row of `meta`: `$where` has no false, and an empty `$or` reads as no condition at all. */
55
+ function noRows(meta) {
56
+ return whereWith(meta.ids[0], { $in: [] });
57
+ }
58
+ /** `bound` as a `$where` of `meta`: `{}` for every row, {@link noRows} for none. */
59
+ export function asWhere(meta, bound) {
60
+ return bound === true ? {} : bound === false ? noRows(meta) : bound;
61
+ }
62
+ /** Every one of `parts`, as one predicate, an `$and` among them spliced in. */
63
+ function andBound(parts) {
64
+ if (parts.includes(false)) {
65
+ return false;
66
+ }
67
+ const kept = parts.filter((part) => part !== true).flatMap(conjuncts);
68
+ return kept.length === 0 ? true : kept.length === 1 ? kept[0] : whereAnd(undefined, kept);
69
+ }
70
+ /** The predicates `where` ANDs: its `$and`'s where that is all it holds and none is SQL, else itself. */
71
+ export function conjuncts(where) {
72
+ const parts = Object.keys(where).length === 1 ? where.$and : undefined;
73
+ return parts?.every((part) => !(part instanceof QuerySql)) ? [...parts] : [where];
74
+ }
75
+ /** Any one of `parts`, as one predicate. */
76
+ function orBound(parts) {
77
+ if (parts.includes(true)) {
78
+ return true;
79
+ }
80
+ const kept = parts.filter((part) => part !== false);
81
+ return kept.length === 0 ? false : kept.length === 1 ? kept[0] : whereAnyOf(kept);
82
+ }
83
+ /** Not `bound`. */
84
+ function notBound(bound) {
85
+ return typeof bound === 'boolean' ? !bound : { $not: [bound] };
86
+ }
87
+ /** What a context key reads as where the context holds none. */
88
+ const MISSING = Symbol('missing');
89
+ /** Reads each key off `context`: an absent key and a null alike are {@link MISSING}, which matches nothing. */
90
+ export function fromContext(context) {
91
+ return (ref) => context?.[ref.$context] ?? MISSING;
92
+ }
93
+ /**
94
+ * `where` with each context key it reads replaced by what `read` answers, the way the database reads a policy: a
95
+ * comparison against a {@link MISSING} key is SQL's unknown, never true, whatever negates it. `positive` is whether
96
+ * the predicate counts where it stands (`false` under a `$not`); a relation's subquery restarts it.
97
+ */
98
+ export function bindContext(meta, where, read, positive = true) {
99
+ if (!contextKeys(where).size) {
100
+ return Object.keys(where).length === 0 || where;
101
+ }
102
+ const parts = Object.entries(where).map(([key, value]) => {
103
+ 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;
108
+ }
109
+ const relation = meta.relations[key];
110
+ if (relation) {
111
+ const bound = bindContext(getMeta(relation.entity()), value, read);
112
+ return bound === false ? false : { [key]: bound === true ? {} : bound };
113
+ }
114
+ const field = bindField(value, (ref) => read(ref, meta.fields[key]));
115
+ return field === MISSING ? !positive : { [key]: field };
116
+ });
117
+ return andBound(parts);
118
+ }
119
+ /** One field's condition with its context read, or {@link MISSING} where a key it compares against is absent. */
120
+ function bindField(value, read) {
121
+ let missing = false;
122
+ const bound = mapContextRefs(value, (ref) => {
123
+ const held = read(ref);
124
+ missing ||= held === MISSING;
125
+ return held;
126
+ });
127
+ return missing ? MISSING : bound;
128
+ }
129
+ /** The database setting a context key is bound to for the policies the database holds. */
130
+ export function contextSetting(key) {
131
+ return `uql.${key}`;
132
+ }
133
+ /** A context key a policy may read, which names a database setting as it is. */
134
+ export const POLICY_CONTEXT_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
135
+ /**
136
+ * The keys of `context` a database binds for the policies it holds, each with its value as text: a scalar or a date,
137
+ * under a key a policy may read. Any other is left unbound, which a policy reads as NULL.
138
+ */
139
+ export function contextEntries(context) {
140
+ return Object.entries(context ?? {}).flatMap(([key, value]) => {
141
+ if (!POLICY_CONTEXT_KEY.test(key)) {
142
+ return [];
143
+ }
144
+ if (value instanceof Date) {
145
+ return [[key, utcTimestamp(value)]];
146
+ }
147
+ const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint' || typeof value === 'boolean';
148
+ return scalar ? [[key, String(value)]] : [];
149
+ });
150
+ }
151
+ /** The context of a transaction that bound none yet, or whose binding a savepoint's rollback undid. */
152
+ const UNBOUND = Symbol('unbound');
153
+ export const NOTHING_BOUND = { context: UNBOUND, keys: [] };
154
+ /** `bound` after a savepoint's rollback, which may bring back any key bound before it: the next statement binds again. */
155
+ export function unsettled(bound) {
156
+ return { context: UNBOUND, keys: bound.keys };
157
+ }
158
+ /**
159
+ * What binds `context` over `bound`: its entries, each key the transaction bound that it lacks set empty, and what is
160
+ * bound once they are sent. No entry where `context` is the one bound.
161
+ */
162
+ export function nextBinding(bound, context) {
163
+ if (bound.context === context) {
164
+ return { entries: [], bound };
165
+ }
166
+ const entries = contextEntries(context);
167
+ const keys = entries.map(([key]) => key);
168
+ const stale = bound.keys.filter((key) => !keys.includes(key));
169
+ return {
170
+ entries: [...entries, ...stale.map((key) => [key, ''])],
171
+ bound: { context, keys: [...keys, ...stale] },
172
+ };
173
+ }
174
+ /** Whether `context` holds every key `when` names at its value, or at one of them where it lists several. */
175
+ function holdsWhen(when, context) {
176
+ return Object.entries(when ?? {}).every(([key, value]) => Array.isArray(value) ? value.includes(context?.[key]) : context?.[key] === value);
177
+ }
178
+ /** The name of the policy a `tenant()` column registers, and of the `allow` an entity declaring none is given. */
179
+ export const TENANT_POLICY = 'tenant';
180
+ export const EVERY_ROW_POLICY = 'everyRow';
181
+ /** The `must` holding each row of `meta` to the tenant `key` stores, read off context key `contextKey`. */
182
+ export function tenantPolicy(key, contextKey) {
183
+ return { effect: 'must', ops: POLICY_OPS, where: whereWith(key, { $context: contextKey }), name: TENANT_POLICY };
184
+ }
185
+ /**
186
+ * The policies holding `meta`: its own, and where none of them is an `allow`, one reaching every row, so its `must`s
187
+ * alone narrow what it reaches. An entity declaring an `allow` reaches no row in a statement none of them holds.
188
+ */
189
+ export function policiesOf(policies) {
190
+ return policies.some((policy) => policy.effect === 'allow')
191
+ ? policies
192
+ : [...policies, { effect: 'allow', ops: POLICY_OPS, where: {}, name: EVERY_ROW_POLICY }];
193
+ }
194
+ /** The rows the `allow`s holding `access` reach and every `must` holds, each policy read by `pick`. */
195
+ function joined(meta, declared, access, context, pick) {
196
+ const policies = policiesOf(declared).filter((policy) => policy.ops.includes(access) && holdsWhen(policy.when, context));
197
+ const read = fromContext(context);
198
+ const bound = (policy) => bindContext(meta, pick(policy), read);
199
+ const allows = orBound(policies.filter((policy) => policy.effect === 'allow').map(bound));
200
+ return andBound([...policies.filter((policy) => policy.effect === 'must').map(bound), allows]);
201
+ }
202
+ /**
203
+ * The rows a statement doing `access` may reach under `context`, `undefined` for an entity with no policies. An update
204
+ * and a delete are held to the `read` policies too, as Postgres holds them.
205
+ */
206
+ export function policyScope(meta, access, context) {
207
+ const { policies } = meta;
208
+ if (!policies?.length) {
209
+ return undefined;
210
+ }
211
+ const read = joined(meta, policies, 'read', context, (policy) => policy.where);
212
+ return access === 'read' ? read : andBound([read, joined(meta, policies, access, context, (policy) => policy.where)]);
213
+ }
214
+ /** What a row an insert or an update writes must hold under `context`, `undefined` for an entity with no policies. */
215
+ export function policyCheck(meta, access, context) {
216
+ const { policies } = meta;
217
+ return policies?.length
218
+ ? joined(meta, policies, access, context, (policy) => policy.check ?? policy.where)
219
+ : undefined;
220
+ }
221
+ /**
222
+ * What `entity`'s policies hold a statement doing `access` to under `context`, the ambient one where unset: `where`,
223
+ * the rows it reaches (`{}` for every one), and `check`, what a row it writes must hold. Neither for an entity with no
224
+ * policies. What the querier ANDs in, so it answers why a read under a context reaches no row.
225
+ */
226
+ export function explainPolicies(entity, access, context = getContext()) {
227
+ const meta = getMeta(entity);
228
+ const scope = access === 'insert' ? undefined : policyScope(meta, access, context);
229
+ const check = access === 'insert' || access === 'update' ? policyCheck(meta, access, context) : undefined;
230
+ return {
231
+ ...(scope === undefined ? {} : { where: asWhere(meta, scope) }),
232
+ ...(check === undefined ? {} : { check: asWhere(meta, check) }),
233
+ };
234
+ }
@@ -2,7 +2,7 @@
2
2
  * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
3
3
  * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
4
4
  * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
5
- * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
5
+ * caller's own mistake, which running it again will not fix. `security` is access refused: see {@link UqlSecurityError}.
6
6
  */
7
7
  export declare const QUERY_ERROR_KINDS: readonly ['uniqueViolation', 'foreignKeyViolation', 'notNullViolation', 'checkViolation', 'optimisticLock', 'retryable', 'usage', 'security'];
8
8
  export type QueryErrorKind = (typeof QUERY_ERROR_KINDS)[number];
@@ -46,10 +46,7 @@ export declare class UqlRequestError extends UqlError {
46
46
  readonly kind = "usage";
47
47
  constructor(message: string, status: number, opts?: UqlErrorOptions);
48
48
  }
49
- /**
50
- * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
51
- * Fails the statement closed.
52
- */
49
+ /** Thrown where access is refused: the policies refuse a write, or an API exposes nothing a call names. */
53
50
  export declare class UqlSecurityError extends UqlError {
54
51
  name: string;
55
52
  readonly kind = "security";
@@ -2,7 +2,7 @@
2
2
  * What a failed query ran into, named the same on every engine - what {@link queryErrorKind} answers
3
3
  * with, whether a driver raised the error or UQL did. `retryable` is a deadlock, a serialization
4
4
  * failure, a lock timeout or a busy database: the transaction can simply run again. `usage` is the
5
- * caller's own mistake, which running it again will not fix. `security` is a `security` filter refusing.
5
+ * caller's own mistake, which running it again will not fix. `security` is access refused: see {@link UqlSecurityError}.
6
6
  */
7
7
  export const QUERY_ERROR_KINDS = [
8
8
  'uniqueViolation',
@@ -54,10 +54,7 @@ export class UqlRequestError extends UqlError {
54
54
  this.status = status;
55
55
  }
56
56
  }
57
- /**
58
- * Thrown where a `security` filter refuses: its context is missing, or a write would leave a row outside it.
59
- * Fails the statement closed.
60
- */
57
+ /** Thrown where access is refused: the policies refuse a write, or an API exposes nothing a call names. */
61
58
  export class UqlSecurityError extends UqlError {
62
59
  name = 'UqlSecurityError';
63
60
  kind = 'security';
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.114.3",
6
+ "version": "0.115.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -89,7 +89,7 @@ export class Post {
89
89
  ```
90
90
 
91
91
  - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal(precision?, scale?)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other SQL type uql names (`f.column('smallint')`, `f.column('date')` for a day with no time, `f.column('timestamptz')`), typed by its family, and `f.references(() => Target)` for a foreign key typed as the target's key. A type uql does not name is ``.columnType(sql`citext`)``. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A builder is immutable, so `const money = f.decimal(12, 2)` is shared across fields, each chaining its own `.nullable()`.
92
- - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `insertOne`, `insertMany`, `saveOne` and `saveMany` resolve to a defined key, so no `!`; an upsert's may be `undefined`. On SQL engines an insert leaving out a key nothing declared fills throws before writing. `defineEntity` works all of this out.
92
+ - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the version uql fills. A key the database generates is `@Field(f.number().autoIncrement()) id?: number` (`f.bigint().autoIncrement()` past 2^53); `.id()` alone generates nothing, so `f.number().id()` is a key the caller supplies and `@Field` refuses `?` on it, as on a `.references()` key. A NOT NULL field something fills (`.default()`, `.onInsert()`, a generated key) stays `!` when listed in the class's `[filledKey]?: 'id' | 'createdAt'`: inserts may omit it, reads always have it. MongoDB fills a text key declared `?` and `_id`. `insertOne`, `insertMany`, `saveOne`, `saveMany`, `upsertOne` and `upsertMany` resolve to a defined key, so no `!`. On SQL engines an insert leaving out a key nothing declared fills throws before writing. `defineEntity` works all of this out.
93
93
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
94
94
  - `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
95
95
  - A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
@@ -140,44 +140,53 @@ export const Book = defineEntity({
140
140
  ```
141
141
 
142
142
  - Columns are the same builders. No `!` or `?` to write: a `.nullable()` column reads `| null`, a default makes it optional on insert, `f.enum()` gives the literal union. A constructor's type argument narrows the column, a brand or a JSON payload with no runtime schema: `f.uuid<UserId>().id()`, `f.json<Settings>()`. It checks the type against the column and exists only in types; a default is written as that type. A filter then takes the branded type, and a foreign key to a branded key must carry the same brand, whether a relation or a decorated property declares it. Name its rows with an interface, `export interface Author extends InstanceType<typeof Author> {}`: hovers and errors then print `Author`, which a type alias expands.
143
- - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `hooks`, then `relations` last; only a `filters` reading through relations follows it.
143
+ - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `policies`, `hooks`, then `relations` last; only `filters` and `policies` follow it, and of two reading through relations the one chained last may read them.
144
144
  - A relation is a thunk, so entities pointing at each other can sit in any order and file. A foreign key is a plain field that a `manyToOne` names as `references`, checked against the target's key type. `relations`' second callback declares aggregate fields: aggregates over a to-many, or expressions mixing them with columns.
145
145
  - A JSON column's payload is any Standard Schema (Zod, Valibot, ArkType), typed by its output. uql never runs it, so a write is not validated.
146
146
  - A hook is a function of the row and the same second argument. Behaviour is a plain function of the row (`label(author: Author)`): a row reads back as a plain object, so a method would never be there.
147
147
 
148
- ### Filters, soft delete and tenants
148
+ ### Filters, soft delete, tenants and policies
149
149
 
150
- A filter is a named `$where` fragment applied to every read, update and delete of its entity, so never repeat it in a query.
150
+ A filter is a named `$where` fragment applied to every read, update and delete of its entity, so never repeat it in a query. A policy is what must hold whatever a call asks: tenants and row-level security.
151
151
 
152
152
  ```ts
153
- import { Entity, f, Field, withContext } from 'uql-orm';
153
+ import { $context, Entity, explainPolicies, f, Field, withContext } from 'uql-orm';
154
154
 
155
155
  declare module 'uql-orm' {
156
156
  interface UqlContext {
157
157
  tenantId?: number;
158
+ userId?: string;
159
+ role?: string;
158
160
  }
159
161
  }
160
162
 
161
163
  @Entity({
162
- filters: {
163
- active: { where: { status: 'active' }, default: false },
164
- tenant: { where: (ctx) => (ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined), security: true },
165
- },
164
+ filters: { active: { where: { status: 'active' }, default: false } },
165
+ policies: [
166
+ { allow: { ownerId: $context.userId }, check: { status: { $ne: 'void' } } },
167
+ { allow: {}, ops: ['read'], when: { role: ['auditor', 'admin'] } },
168
+ ],
166
169
  })
167
170
  export class Invoice {
168
171
  @Field(f.number().autoIncrement()) id?: number;
169
- @Field(f.number()) companyId!: number;
172
+ @Field(f.number().tenant()) companyId?: number;
173
+ @Field(f.string()) ownerId!: string;
170
174
  @Field(f.string().nullable()) status?: string | null;
171
175
  @Field(f.date().nullable().softDelete()) deletedAt?: Date | null;
172
176
  }
173
177
 
174
- await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
178
+ await withContext({ tenantId: 42, userId: 'u1' }, () => pool.findMany(Invoice, {}));
175
179
  ```
176
180
 
177
181
  - A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
178
182
  - `.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.
179
- - A `where` 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()`.
180
- - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. `ops: ['insert', 'update', 'delete']` makes one hold those statements alone (anyone reads a row, only its author writes it); an update or delete is also held to the read ones. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
183
+ - 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
+ - `.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.
187
+ - `$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 }`.
189
+ - `{ 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. 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
181
190
 
182
191
  ## Queries
183
192
 
@@ -196,6 +205,7 @@ const users = await pool.findMany(User, {
196
205
  ```
197
206
 
198
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
208
+ - `$` 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 }`).
199
209
  - 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.
200
210
  - 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>[]>`.
201
211
  - `$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.
@@ -287,7 +297,7 @@ export const handler = toFetchHandler(api); // on a catch-all under /api/v1
287
297
  - What a client may do is the definition's `wire`, every operation where unset. An entity's (`@Entity({ wire: ['read', 'update'] })`, `defineEntity({ wire })`) lists what it takes of `'read'`, `'insert'`, `'update'`, `'delete'`, a subclass declaring none taking its base's; `wire: false` keeps it off every API, and `createApi` refuses one in `include`. A member's: `f.string().wire(false)` hides a field, `.wire(['read'])` makes it read-only, `.wire(['insert'])` write-once; a relation takes `wire` in its options (`rel.oneToMany(Session, { mappedBy, wire: false })`, `@OneToMany(() => Session, { mappedBy, wire: false })`). It holds wherever the entity is reached, through any relation. A write the querier would drop, to a computed field or an update of an `updatable(false)` one, is refused instead; a save may insert, so it takes the latter.
288
298
  - `read` covers every clause naming the member (`$select`, `$where`, `$sort`, `$count`, `$populate`), and a read with no `$select` leaves out what it may not read. `.eager(false)` is no guard, since a client's `$select` still reads it: hide a secret with `.wire(false)`.
289
299
  - A middleware is `(call, context, next) => next(call)`, run after the call is checked: reshape the call before `next`, or what `next` resolves to after it. The API's `use` runs on every call, and `serve(Entity, { use })` in `include` on that entity's alone, typed by it (`call.op === 'insertOne'` types `call.payload` as a row). Refuse a client with `throw new UqlRequestError('unauthorized', 401)` from `uql-orm`; any other error answers generically by its kind, or `500`.
290
- - Scope tenants with a `security` filter and `contextOf`, never with a middleware adding to `$where`. Without `contextOf` a call keeps its caller's context. On NestJS, `UqlModule.forRoot({ pool, contextOf })` does the same for your own routes.
300
+ - Scope tenants with a policy and `contextOf`, never with a middleware adding to `$where`. Without `contextOf` a call keeps its caller's context. On NestJS, `UqlModule.forRoot({ pool, contextOf })` does the same for your own routes.
291
301
  - The API serves one entity per call: no `aggregate`, upsert, stream or transaction. Write your own routes for those beside it; `toFetchHandler` answers `404` and `toExpress` falls through to `next()` on paths it does not serve.
292
302
  - The client is `createClientQuerier(httpTransport('/api/v1'))` from `uql-orm/browser`, or `createClientQuerier((call) => trpc.uql.mutate(call))` over any transport. It has the pool's find, `count`, `exists`, insert, save, update and delete methods and answers what they answer (rows, not `{ data }`), reading each row back by its entity, which must be registered (importing it does): a `Date` field is a `Date` and a `bigint` exact, so a cache persisting rows needs a serializer. `httpTransport` rejects with a `RequestError` carrying `status`, `kind` and `path`.
293
303
  - For TanStack Query, `const uql = createQueryOptions(transport)` and `useQuery(uql((db) => db.findMany(User, q)))`: the key is the call the read makes (`['uql', 'user', 'findMany', { query }]`), so it cannot drift from the fetch, and `uql.key(User)` invalidates every read of `User`.