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.
- package/dist/cockroachdb/cockroachDialect.d.ts +2 -0
- package/dist/cockroachdb/cockroachDialect.js +5 -0
- package/dist/d1/d1Querier.d.ts +2 -4
- package/dist/d1/d1Querier.js +0 -4
- package/dist/d1/d1SqliteDialect.js +1 -1
- package/dist/dialect/abstractDialect.d.ts +17 -8
- package/dist/dialect/abstractDialect.js +30 -16
- package/dist/dialect/abstractSqlDialect.d.ts +11 -2
- package/dist/dialect/abstractSqlDialect.js +17 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +2 -0
- package/dist/dialect/operators.d.ts +2 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +8 -1
- package/dist/dialect/pgLikeSqlDialect.js +20 -0
- package/dist/entity/columnOptionsBuilder.d.ts +2 -1
- package/dist/entity/columnOptionsBuilder.js +3 -0
- package/dist/entity/metadata/definedFixture/author.d.ts +1 -1
- package/dist/entity/metadata/definedFixture/book.d.ts +2 -2
- package/dist/entity/metadata/definedFixture/folder.d.ts +1 -1
- package/dist/entity/metadata/definition.js +69 -30
- package/dist/http/api.d.ts +1 -1
- package/dist/http/wireQuery.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/migrate/ddl/tableDdl.d.ts +5 -0
- package/dist/migrate/ddl/tableDdl.js +9 -0
- package/dist/migrate/drift/driftDetector.js +2 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +3 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +7 -1
- package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -1
- package/dist/migrate/introspection/postgresIntrospector.js +14 -1
- package/dist/migrate/introspection/tableSchemaAST.js +1 -0
- package/dist/migrate/policySql.d.ts +12 -0
- package/dist/migrate/policySql.js +74 -0
- package/dist/migrate/schemaChange.js +1 -0
- package/dist/migrate/schemaGenerator.d.ts +2 -0
- package/dist/migrate/schemaGenerator.js +37 -11
- package/dist/mongodb/mongoDialect.js +3 -1
- package/dist/mongodb/mongodbQuerier.d.ts +2 -5
- package/dist/mongodb/mongodbQuerier.js +14 -26
- package/dist/mssql/mssqlDialect.js +2 -0
- package/dist/neon/neonQuerier.d.ts +1 -2
- package/dist/nestjs/uqlContextInterceptor.d.ts +1 -1
- package/dist/nestjs/uqlContextInterceptor.js +1 -1
- package/dist/nestjs/uqlModule.d.ts +2 -2
- package/dist/nestjs/uqlModule.js +1 -1
- package/dist/querier/abstractQuerier.d.ts +68 -30
- package/dist/querier/abstractQuerier.js +249 -168
- package/dist/querier/abstractQuerierPool.js +2 -0
- package/dist/querier/abstractSqlQuerier.d.ts +22 -13
- package/dist/querier/abstractSqlQuerier.js +75 -27
- package/dist/querier/queryError.js +1 -0
- package/dist/schema/schemaAST.js +1 -0
- package/dist/schema/schemaASTBuilder.d.ts +3 -1
- package/dist/schema/schemaASTBuilder.js +1 -0
- package/dist/schema/schemaASTDiffer.js +4 -2
- package/dist/schema/types.d.ts +12 -4
- package/dist/sqlite/bindValues.d.ts +1 -1
- package/dist/sqlite/hranaQuerier.d.ts +2 -2
- package/dist/sqlite/sqliteDialect.js +2 -0
- package/dist/turso/tursoSessionQuerier.d.ts +2 -2
- package/dist/type/column.d.ts +10 -0
- package/dist/type/definedEntity.d.ts +9 -4
- package/dist/type/dialect.d.ts +13 -0
- package/dist/type/entity.d.ts +10 -0
- package/dist/type/index.d.ts +1 -0
- package/dist/type/index.js +1 -0
- package/dist/type/migration.d.ts +5 -1
- package/dist/type/policy.d.ts +91 -0
- package/dist/type/policy.js +1 -0
- package/dist/type/querier.d.ts +16 -2
- package/dist/type/querierPool.d.ts +2 -2
- package/dist/type/query.d.ts +20 -35
- package/dist/type/query.js +2 -0
- package/dist/type/universalQuerier.d.ts +6 -6
- package/dist/util/contextRefs.d.ts +6 -0
- package/dist/util/contextRefs.js +5 -0
- package/dist/util/dialect.util.d.ts +10 -16
- package/dist/util/dialect.util.js +70 -64
- package/dist/util/fieldOption.util.js +1 -0
- package/dist/util/policy.util.d.ts +100 -0
- package/dist/util/policy.util.js +234 -0
- package/dist/util/uqlError.d.ts +2 -5
- package/dist/util/uqlError.js +2 -5
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +24 -14
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { EntityAccess, UqlContext } from './query.js';
|
|
2
|
+
import type { QuerySql, SQL_VALUE_TYPE } from './querySql.js';
|
|
3
|
+
import type { QueryWhere } from './queryWhere.js';
|
|
4
|
+
/**
|
|
5
|
+
* A context key read where a policy's predicate takes a value, as data: `{ $context: 'tenantId' }`. Read off
|
|
6
|
+
* {@link $context}, which types it by {@link UqlContext}, so a key holding a string never meets a number column.
|
|
7
|
+
*/
|
|
8
|
+
export type ContextRef<T = unknown> = unknown extends T ? ContextKeyRef : ContextKeyRef & {
|
|
9
|
+
readonly [SQL_VALUE_TYPE]?: NonNullable<T>;
|
|
10
|
+
};
|
|
11
|
+
/** A {@link ContextRef} whatever its value's type. */
|
|
12
|
+
export type ContextKeyRef = {
|
|
13
|
+
readonly $context: string;
|
|
14
|
+
};
|
|
15
|
+
/** The keys a declaration of {@link UqlContext} names, its index signature left out. */
|
|
16
|
+
type DeclaredContextKey = keyof {
|
|
17
|
+
[K in keyof UqlContext as string extends K ? never : number extends K ? never : K]: unknown;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* A context key a policy may read: one {@link UqlContext} declares, so a misspelled key does not compile. Any string
|
|
21
|
+
* where the app declares none.
|
|
22
|
+
*/
|
|
23
|
+
export type ContextKey = [DeclaredContextKey] extends [never] ? string : DeclaredContextKey & string;
|
|
24
|
+
/** The value context key `K` holds, `unknown` for one no declaration names. */
|
|
25
|
+
type ContextValue<K extends string> = K extends keyof UqlContext ? UqlContext[K] : unknown;
|
|
26
|
+
/**
|
|
27
|
+
* The context's keys as {@link ContextRef}s, each read as `$context.tenantId`: mapped over {@link UqlContext} itself, so
|
|
28
|
+
* a rename of a declared key reaches every read of it. Any key where the app declares none.
|
|
29
|
+
*/
|
|
30
|
+
export type ContextRefs = string extends ContextKey ? {
|
|
31
|
+
readonly [key: string]: ContextRef;
|
|
32
|
+
} : {
|
|
33
|
+
readonly [K in keyof UqlContext as K extends ContextKey ? K : never]-?: ContextRef<UqlContext[K]>;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* What `tenant()` takes: a column of value `V` reads its tenant off `$context.tenantId` unless given another key, which
|
|
37
|
+
* must hold such a value; required where `tenantId` holds none.
|
|
38
|
+
*/
|
|
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
|
+
/** What a policy's predicate interpolates where a query takes SQL: SQL itself, or a context key. */
|
|
41
|
+
export type PolicySql = QuerySql | ContextKeyRef;
|
|
42
|
+
/** A policy's predicate: a `$where` over the entity, its relations included, whose values may read the context. */
|
|
43
|
+
export type PolicyWhere<E> = QueryWhere<E, PolicySql>;
|
|
44
|
+
/**
|
|
45
|
+
* How a policy joins the others holding a statement: rows any `allow` reaches, and of them only those every `must`
|
|
46
|
+
* holds, Postgres's permissive and restrictive policies. An entity with policies and no `allow` for a statement
|
|
47
|
+
* reaches no row in it.
|
|
48
|
+
*/
|
|
49
|
+
export type PolicyEffect = 'allow' | 'must';
|
|
50
|
+
/**
|
|
51
|
+
* The context a policy holds under, each key at its value or at one it lists: `{ role: ['admin', 'owner'] }`. Folded
|
|
52
|
+
* before the statement is written.
|
|
53
|
+
*/
|
|
54
|
+
export type PolicyWhen = string extends ContextKey ? {
|
|
55
|
+
readonly [key: string]: unknown;
|
|
56
|
+
} : {
|
|
57
|
+
readonly [K in keyof UqlContext as K extends ContextKey ? K : never]?: UqlContext[K] | readonly UqlContext[K][];
|
|
58
|
+
};
|
|
59
|
+
/** What a policy states beyond its predicate. */
|
|
60
|
+
export type PolicyOptions<E> = {
|
|
61
|
+
/** The statements it holds, every one where unset. An update and a delete are held to the `read` ones too. */
|
|
62
|
+
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
|
+
readonly when?: PolicyWhen;
|
|
66
|
+
/** Names it in the database; derived from its effect and position where unset. */
|
|
67
|
+
readonly name?: string;
|
|
68
|
+
};
|
|
69
|
+
/** A policy as entity metadata keeps it, its effect and statements stated. */
|
|
70
|
+
export type PolicyMeta<E = object> = Omit<PolicyOptions<E>, 'ops'> & {
|
|
71
|
+
readonly effect: PolicyEffect;
|
|
72
|
+
readonly ops: readonly EntityAccess[];
|
|
73
|
+
readonly where: PolicyWhere<E>;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* One policy as an entity declares it: its effect keyed to the rows it reaches, `{}` for all, beside its options.
|
|
77
|
+
* Data throughout, a context key read off {@link $context}: `{ must: { tenantId: $context.tenantId } }`.
|
|
78
|
+
*/
|
|
79
|
+
export type Policy<E> = PolicyOptions<E> & ({
|
|
80
|
+
readonly allow: PolicyWhere<E>;
|
|
81
|
+
readonly must?: never;
|
|
82
|
+
} | {
|
|
83
|
+
readonly must: PolicyWhere<E>;
|
|
84
|
+
readonly allow?: never;
|
|
85
|
+
});
|
|
86
|
+
/**
|
|
87
|
+
* An entity's row-level policies, in order: `[{ must: { tenantId: $context.tenantId } }, { allow: { ownerId:
|
|
88
|
+
* $context.userId } }]`. See architecture/row-level-security.md.
|
|
89
|
+
*/
|
|
90
|
+
export type PolicySection<E> = readonly Policy<E>[];
|
|
91
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -84,10 +84,10 @@ export interface Querier extends UniversalQuerier {
|
|
|
84
84
|
}, opts?: QueryOptions & WriteOptions<E, S, V, W>) => Promise<WriteResults<E, S, V, W>['affectedMany']>) & UniversalQuerier['deleteMany'];
|
|
85
85
|
upsertOne: (<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(q: QueryUpsert<E> & {
|
|
86
86
|
$entity: Type<E>;
|
|
87
|
-
}, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>) => Promise<WriteResults<E, S, V, W>['
|
|
87
|
+
}, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>) => Promise<WriteResults<E, S, V, W>['written']>) & UniversalQuerier['upsertOne'];
|
|
88
88
|
upsertMany: (<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(q: QueryUpsert<E> & {
|
|
89
89
|
$entity: Type<E>;
|
|
90
|
-
}, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>) => Promise<WriteResults<E, S, V, W>['
|
|
90
|
+
}, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>) => Promise<WriteResults<E, S, V, W>['written'][]>) & UniversalQuerier['upsertMany'];
|
|
91
91
|
/**
|
|
92
92
|
* whether this querier is in a transaction or not.
|
|
93
93
|
*/
|
|
@@ -161,6 +161,18 @@ export type ListenerContext<E extends object = object> = {
|
|
|
161
161
|
export type QuerierListener = {
|
|
162
162
|
readonly [K in HookEvent]?: (ctx: ListenerContext) => Promise<void> | void;
|
|
163
163
|
};
|
|
164
|
+
/** A statement as it is sent: its SQL and the values it binds. */
|
|
165
|
+
export type BoundStatement = {
|
|
166
|
+
readonly sql: string;
|
|
167
|
+
readonly values: unknown[];
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* Who holds statements to the entities' policies. `'app'`, the querier, on every engine. `'native'`, the database (the
|
|
171
|
+
* Postgres family): migrations install the policies, each transaction binds the context, and a role the database lets
|
|
172
|
+
* past them is refused under a context. `false`, nothing: a trusted pool, a job working across tenants, pointed at a
|
|
173
|
+
* role that bypasses row-level security. See architecture/row-level-security.md.
|
|
174
|
+
*/
|
|
175
|
+
export type PolicyMode = 'app' | 'native' | false;
|
|
164
176
|
export type ExtraOptions = {
|
|
165
177
|
readonly logger?: LoggingOptions;
|
|
166
178
|
/**
|
|
@@ -178,5 +190,7 @@ export type ExtraOptions = {
|
|
|
178
190
|
*/
|
|
179
191
|
readonly schema?: string;
|
|
180
192
|
readonly listeners?: readonly QuerierListener[];
|
|
193
|
+
/** Who holds this pool's statements to the entities' policies: see {@link PolicyMode}. `'app'` where unset. */
|
|
194
|
+
readonly policies?: PolicyMode;
|
|
181
195
|
};
|
|
182
196
|
export {};
|
|
@@ -5,7 +5,7 @@ import type { UniversalQuerier } from './universalQuerier.js';
|
|
|
5
5
|
/** Options for a pool-level unit of work ({@link QuerierPool.withQuerier} / {@link QuerierPool.transaction}). */
|
|
6
6
|
export interface PoolRunOptions {
|
|
7
7
|
/**
|
|
8
|
-
* {@link UqlContext} to run the callback under, so parameterized
|
|
8
|
+
* {@link UqlContext} to run the callback under, so policies and parameterized filters scope every
|
|
9
9
|
* query inside it. Same mechanism as `withContext`, scoped to this unit of work - ideal where no
|
|
10
10
|
* ambient request context exists (background pipelines, queue consumers, webhooks) and the tenant
|
|
11
11
|
* is known locally: `pool.withQuerier((q) => q.findMany(Invoice, {}), { context: { tenantId } })`.
|
|
@@ -50,7 +50,7 @@ export interface QuerierPool<Q extends Querier = Querier, D extends AbstractDial
|
|
|
50
50
|
*/
|
|
51
51
|
end(): Promise<void>;
|
|
52
52
|
}
|
|
53
|
-
/** A SQL pool, adding raw `all`/`run`, which no
|
|
53
|
+
/** A SQL pool, adding raw `all`/`run`, which no policy scopes but the database's own. */
|
|
54
54
|
export interface SqlQuerierPool<Q extends SqlQuerier = SqlQuerier, D extends AbstractSqlDialect = AbstractSqlDialect> extends QuerierPool<Q, D>, Pick<SqlQuerier, 'all' | 'run'> {
|
|
55
55
|
}
|
|
56
56
|
/**
|
package/dist/type/query.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { FieldKey, FieldKeyOf, JsonFieldPaths, MethodKey, RelationKey, RelationTarget, ToManyRelationKey, UpdateWrite, WrittenId } from './entity.js';
|
|
2
|
+
import type { PolicyWhere } from './policy.js';
|
|
2
3
|
import type { QueryLock } from './queryLock.js';
|
|
3
4
|
import type { QuerySql } from './querySql.js';
|
|
4
5
|
import type { QueryWhere } from './queryWhere.js';
|
|
@@ -8,7 +9,7 @@ export type QueryOptions = {
|
|
|
8
9
|
/**
|
|
9
10
|
* Toggle named entity filters for this query. `false` disables all filters;
|
|
10
11
|
* `{ softDelete: false }` disables one; `{ myFilter: true }` force-enables a `default: false` filter.
|
|
11
|
-
*
|
|
12
|
+
* Policies are no filters, and nothing here turns one off.
|
|
12
13
|
*/
|
|
13
14
|
filters?: false | Record<string, boolean>;
|
|
14
15
|
/**
|
|
@@ -23,13 +24,17 @@ export type QueryOptions = {
|
|
|
23
24
|
*/
|
|
24
25
|
unfiltered?: boolean;
|
|
25
26
|
};
|
|
27
|
+
/** Marks a statement as reading past the policies. A symbol, so no options a call or a client carries can name it. */
|
|
28
|
+
export declare const PAST_POLICIES: unique symbol;
|
|
26
29
|
/**
|
|
27
30
|
* What a statement runs with, on top of the options its caller passed. Kept apart from {@link QueryOptions}
|
|
28
31
|
* because that one is public, the third argument of every querier method, and none of this is a caller's to set.
|
|
29
32
|
*/
|
|
30
33
|
export type StatementOptions = QueryOptions & {
|
|
31
|
-
/** What the statement does, which picks the
|
|
32
|
-
readonly access?:
|
|
34
|
+
/** What the statement does, which picks the policies scoping it: a read by default. A write's reads take its own. */
|
|
35
|
+
readonly access?: ScopedAccess;
|
|
36
|
+
/** Reads past the policies: the querier's own read-back of what a policy check settled, or a pool not holding them. */
|
|
37
|
+
readonly [PAST_POLICIES]?: true;
|
|
33
38
|
};
|
|
34
39
|
/** What a statement is rendered with: an alias is the dialect's to choose and to spell. */
|
|
35
40
|
export type QueryRenderOptions = StatementOptions & {
|
|
@@ -94,26 +99,24 @@ export type QueryPopulateRelationOptions<V, Sql = QuerySql> = IsMany<V> extends
|
|
|
94
99
|
$required?: boolean;
|
|
95
100
|
};
|
|
96
101
|
/**
|
|
97
|
-
* The per-request context parameterized filters read, set with `withContext(ctx, cb)`. An interface,
|
|
102
|
+
* The per-request context policies and parameterized filters read, set with `withContext(ctx, cb)`. An interface,
|
|
98
103
|
* so its keys can be typed once: `declare module 'uql-orm' { interface UqlContext { tenantId: number } }`.
|
|
99
104
|
*/
|
|
100
105
|
export interface UqlContext {
|
|
101
106
|
[key: string]: unknown;
|
|
102
107
|
}
|
|
103
108
|
/**
|
|
104
|
-
* A filter's `$where` fragment
|
|
105
|
-
*
|
|
109
|
+
* A filter's `$where` fragment, whose values may read the context as a policy's do (`{ authorId: $context.userId }`),
|
|
110
|
+
* the filter skipped where the context lacks a key it reads; or a function of the ambient {@link UqlContext}, skipped
|
|
111
|
+
* where it answers `undefined`.
|
|
106
112
|
*/
|
|
107
|
-
export type FilterWhere<E> =
|
|
108
|
-
/**
|
|
109
|
-
* What to do when a filter's condition returns `undefined`. `skip` omits it (convenience filters);
|
|
110
|
-
* `throw` fails closed (the default for `security` filters).
|
|
111
|
-
*/
|
|
112
|
-
export type FilterOnMissing = 'skip' | 'throw';
|
|
113
|
+
export type FilterWhere<E> = PolicyWhere<E> | ((context: UqlContext | undefined) => QueryWhere<E> | undefined);
|
|
113
114
|
/** What a field takes: reading it (select, filter, sort, distinct, aggregate) and writing it. */
|
|
114
115
|
export type FieldAccess = 'read' | 'insert' | 'update';
|
|
115
116
|
/** What a statement does to an entity's rows: a field's access, and deleting rows, which no field has a part in. */
|
|
116
117
|
export type EntityAccess = FieldAccess | 'delete';
|
|
118
|
+
/** What a statement reading stored rows does, which the policies scope it by: an insert reads none. */
|
|
119
|
+
export type ScopedAccess = Exclude<EntityAccess, 'insert'>;
|
|
117
120
|
/**
|
|
118
121
|
* What a client may do to an entity, or one of its members, over an API: what it lists, nothing for `false`, and
|
|
119
122
|
* everything where unset. Nothing is served by default: an entity reaches the wire only when an API's `include`
|
|
@@ -121,30 +124,14 @@ export type EntityAccess = FieldAccess | 'delete';
|
|
|
121
124
|
*/
|
|
122
125
|
export type Wire<A extends EntityAccess = FieldAccess> = false | readonly A[];
|
|
123
126
|
/**
|
|
124
|
-
*
|
|
127
|
+
* A convenience scope, `@Entity({ filters })` and `defineEntity`'s `.filters()`: switched off by name, and yielding
|
|
128
|
+
* to a `$where` on its own field. What must hold whatever a call asks is a policy: see {@link PolicySection}.
|
|
125
129
|
*/
|
|
126
130
|
export type FilterOptions<E = unknown> = {
|
|
127
131
|
readonly where: FilterWhere<E>;
|
|
128
132
|
/** Applied to every query unless bypassed via `QueryOptions.filters`. Defaults to `true`. */
|
|
129
133
|
readonly default?: boolean;
|
|
130
|
-
}
|
|
131
|
-
readonly security?: false;
|
|
132
|
-
/** What to do when {@link FilterOptions.where} returns `undefined`. Defaults to `skip`. */
|
|
133
|
-
readonly onMissing?: FilterOnMissing;
|
|
134
|
-
readonly ops?: never;
|
|
135
|
-
} | {
|
|
136
|
-
/**
|
|
137
|
-
* Row-level-security filter: always applied (ignores `QueryOptions.filters` bypass) and
|
|
138
|
-
* AND-merged so a client `$where` on the same field can't override it. It fails closed.
|
|
139
|
-
*/
|
|
140
|
-
readonly security: true;
|
|
141
|
-
readonly onMissing?: 'throw';
|
|
142
|
-
/**
|
|
143
|
-
* The statements it holds, every one by default: `['insert', 'update', 'delete']` lets anyone read a row
|
|
144
|
-
* and only its author write it. An update or a delete reads the rows it changes, so read ones hold it too.
|
|
145
|
-
*/
|
|
146
|
-
readonly ops?: readonly EntityAccess[];
|
|
147
|
-
});
|
|
134
|
+
};
|
|
148
135
|
/**
|
|
149
136
|
* direction for the sort, and where nulls land in it.
|
|
150
137
|
*
|
|
@@ -525,14 +512,12 @@ export type WriteOptions<E, S extends FieldKey<E> = FieldKey<E>, V = BooleanLike
|
|
|
525
512
|
/** What each kind of write resolves to: its ids or its count where it reads nothing back, else the rows it reads. */
|
|
526
513
|
export type WriteResults<E, S, V, W = false> = [W] extends [true] ? ReturnedRows<Pick<E, FieldKey<E>>> : [W] extends [false] ? WrittenIds<E> : [S] extends [never] ? WrittenIds<E> : ReturnedRows<ReturnedRow<E, S, V>>;
|
|
527
514
|
type WrittenIds<E> = {
|
|
528
|
-
readonly
|
|
529
|
-
readonly upserted: WrittenId<E> | undefined;
|
|
515
|
+
readonly written: NonNullable<WrittenId<E>>;
|
|
530
516
|
readonly affected: number;
|
|
531
517
|
readonly affectedMany: number;
|
|
532
518
|
};
|
|
533
519
|
type ReturnedRows<R> = {
|
|
534
|
-
readonly
|
|
535
|
-
readonly upserted: R;
|
|
520
|
+
readonly written: R;
|
|
536
521
|
readonly affected: R | undefined;
|
|
537
522
|
readonly affectedMany: R[];
|
|
538
523
|
};
|
package/dist/type/query.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Marks a statement as reading past the policies. A symbol, so no options a call or a client carries can name it. */
|
|
2
|
+
export const PAST_POLICIES = Symbol('pastPolicies');
|
|
1
3
|
/**
|
|
2
4
|
* The key a read carries its relation tallies under. One spelling for the type and the runtime that
|
|
3
5
|
* fills it: they sit in different modules, so a drift would type-check and answer `undefined`.
|
|
@@ -84,12 +84,12 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
|
|
|
84
84
|
*/
|
|
85
85
|
findManyStream: EntityRead<'many', 'stream', 'server', QueryOptions>;
|
|
86
86
|
/** Insert a record and resolve to its id, or the row `returning` reads back. See {@link UniversalQuerier.insertMany}. */
|
|
87
|
-
insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['
|
|
87
|
+
insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written']>;
|
|
88
88
|
/**
|
|
89
89
|
* Insert records in as few statements as the bind limit allows, resolving to their ids in payload order, or
|
|
90
90
|
* the rows `returning` reads back.
|
|
91
91
|
*/
|
|
92
|
-
insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['
|
|
92
|
+
insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written'][]>;
|
|
93
93
|
/** Update the record with the given primary key; resolves to the number of affected rows, or the row `returning` reads back. */
|
|
94
94
|
updateOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['affected']>;
|
|
95
95
|
/** Update the records matching the query; resolves to the number of affected rows, or the rows `returning` reads back. */
|
|
@@ -103,13 +103,13 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
|
|
|
103
103
|
* conflicting row matching `q.$where` takes the payload less those keys, or `q.$update` as `updateMany` takes an
|
|
104
104
|
* update: `{ uses: { $inc: 1 } }` counts, and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
|
|
105
105
|
*/
|
|
106
|
-
upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QueryUpsert<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['
|
|
106
|
+
upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QueryUpsert<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written']>;
|
|
107
107
|
/** Insert or update records by `q.$conflict`'s keys, as `upsertOne` does; resolves to their ids in payload order, or the rows. */
|
|
108
|
-
upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QueryUpsert<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['
|
|
108
|
+
upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QueryUpsert<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written'][]>;
|
|
109
109
|
/** Insert a record, or upsert one naming its key; resolves to its id, or the row `returning` reads back. */
|
|
110
|
-
saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['
|
|
110
|
+
saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written']>;
|
|
111
111
|
/** Insert records, or upsert those naming their key; resolves to their ids in payload order, or the rows. */
|
|
112
|
-
saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['
|
|
112
|
+
saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['written'][]>;
|
|
113
113
|
/**
|
|
114
114
|
* Restore soft-deleted records (sets the soft-delete field back to `null`). Throws if the
|
|
115
115
|
* entity has no soft-delete field.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ContextRefs } from '../type/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* The context's keys as a policy reads them, each `{ $context: key }`, typed by `UqlContext`:
|
|
4
|
+
* `{ must: { tenantId: $context.tenantId } }`. A leaf module, so the root entry does not reach the metadata through it.
|
|
5
|
+
*/
|
|
6
|
+
export declare const $context: ContextRefs;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The context's keys as a policy reads them, each `{ $context: key }`, typed by `UqlContext`:
|
|
3
|
+
* `{ must: { tenantId: $context.tenantId } }`. A leaf module, so the root entry does not reach the metadata through it.
|
|
4
|
+
*/
|
|
5
|
+
export const $context = new Proxy({}, { get: (_, key) => (typeof key === 'string' ? { $context: key } : undefined) });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IndexType } from '../schema/types.js';
|
|
2
|
-
import { type AggregateCall, type CascadeType, type
|
|
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';
|
|
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>[];
|
|
@@ -35,11 +35,6 @@ export declare function deletionOf<E, O extends QueryOptions>(meta: EntityMeta<E
|
|
|
35
35
|
* does, and by default the payload less its key and what it matched on.
|
|
36
36
|
*/
|
|
37
37
|
export declare function foundRowAssigned<E>(meta: EntityMeta<E>, q: QueryUpsert<E>, row: EntityData<E>): UpdatePayload<E> | undefined;
|
|
38
|
-
/**
|
|
39
|
-
* Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
|
|
40
|
-
* has that key too. Elsewhere the key is the found row's, which the upsert reads back.
|
|
41
|
-
*/
|
|
42
|
-
export declare function upsertKeepsOwnKey<E>(meta: EntityMeta<E>, conflictKeys: QueryConflictKeys<E>, row: E): boolean;
|
|
43
38
|
/**
|
|
44
39
|
* Where a write runs: a statement uql sends, or a trigger's body, which runs no JavaScript, so a fill there is
|
|
45
40
|
* only a value or SQL; calling a callback would bake one value into the trigger.
|
|
@@ -132,22 +127,21 @@ export declare function isFieldUpdateOp(value: unknown): value is FieldUpdateOp;
|
|
|
132
127
|
*/
|
|
133
128
|
export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint | QuerySql];
|
|
134
129
|
/**
|
|
135
|
-
* `$where` with the entity's active filters merged in,
|
|
136
|
-
* filter yields to a `$where` on its key; a
|
|
130
|
+
* `$where` with the entity's active filters merged in, then ANDed with the rows its policies let the statement reach
|
|
131
|
+
* under the ambient {@link UqlContext}. A filter yields to a `$where` on its key; a policy yields to nothing.
|
|
137
132
|
*/
|
|
138
133
|
export declare function applyFilters<E>(meta: EntityMeta<E>, whereMap: QueryWhere<E>, opts?: StatementOptions): QueryWhere<E>;
|
|
139
134
|
/**
|
|
140
|
-
*
|
|
141
|
-
*
|
|
135
|
+
* Holds rows an insert or an update writes to the entity's policies under the ambient context, before the write: a
|
|
136
|
+
* 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.
|
|
142
138
|
*/
|
|
143
|
-
export declare function
|
|
139
|
+
export declare function pinWrite<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, rows: readonly R[], write: 'insert' | 'update'): void;
|
|
144
140
|
/**
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
* A condition other than field equalities refuses the write, having nothing a row can be checked against.
|
|
148
|
-
* See architecture/security-filter-writes.md.
|
|
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.
|
|
149
143
|
*/
|
|
150
|
-
export declare function guardWrite<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, rows: readonly R[], write: 'insert' | 'update'):
|
|
144
|
+
export declare function guardWrite<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, rows: readonly R[], write: 'insert' | 'update'): QueryWhere<E> | undefined;
|
|
151
145
|
/**
|
|
152
146
|
* Parsed entry from a `$group` map - either a raw group key or an aggregate function call.
|
|
153
147
|
*/
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { getContext } from '../context/context.js';
|
|
2
|
-
import {
|
|
3
|
-
import { QuerySql, resolveAggregateOp, } from '../type/index.js';
|
|
2
|
+
import { QuerySql, PAST_POLICIES, resolveAggregateOp, } from '../type/index.js';
|
|
4
3
|
import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
|
|
5
4
|
import { defaultReadKeys, fieldKeys, isDatabaseWritten, isWrittenOn, jsonKey, jsonPathKeys, } from './field.util.js';
|
|
6
5
|
import { withDeleted } from './filters.util.js';
|
|
7
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';
|
|
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. */
|
|
@@ -88,13 +88,6 @@ export function foundRowAssigned(meta, q, row) {
|
|
|
88
88
|
}
|
|
89
89
|
return hasKeys(update) ? { ...update } : undefined;
|
|
90
90
|
}
|
|
91
|
-
/**
|
|
92
|
-
* Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
|
|
93
|
-
* has that key too. Elsewhere the key is the found row's, which the upsert reads back.
|
|
94
|
-
*/
|
|
95
|
-
export function upsertKeepsOwnKey(meta, conflictKeys, row) {
|
|
96
|
-
return namesKey(meta, row) && meta.ids.every((key) => Object.hasOwn(conflictKeys, key));
|
|
97
|
-
}
|
|
98
91
|
/** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset, as `scope` can. */
|
|
99
92
|
export function fillOnFields(meta, payload, callbackKey, scope = 'statement') {
|
|
100
93
|
const payloads = Array.isArray(payload) ? payload : [payload];
|
|
@@ -412,20 +405,17 @@ export function fieldUpdateOf(key, value) {
|
|
|
412
405
|
return value.$inc === undefined ? ['$mul', value.$mul] : ['$inc', value.$inc];
|
|
413
406
|
}
|
|
414
407
|
/**
|
|
415
|
-
* `$where` with the entity's active filters merged in,
|
|
416
|
-
* filter yields to a `$where` on its key; a
|
|
408
|
+
* `$where` with the entity's active filters merged in, then ANDed with the rows its policies let the statement reach
|
|
409
|
+
* under the ambient {@link UqlContext}. A filter yields to a `$where` on its key; a policy yields to nothing.
|
|
417
410
|
*/
|
|
418
411
|
export function applyFilters(meta, whereMap, opts) {
|
|
419
|
-
if (!meta.filters) {
|
|
412
|
+
if (!meta.filters && !meta.policies?.length) {
|
|
420
413
|
return whereMap;
|
|
421
414
|
}
|
|
422
415
|
const result = { ...whereMap };
|
|
423
|
-
for (const [name, filter] of Object.entries(meta.filters)) {
|
|
416
|
+
for (const [name, filter] of Object.entries(meta.filters ?? {})) {
|
|
424
417
|
const active = opts?.filters !== false && (opts?.filters?.[name] ?? filter.default !== false);
|
|
425
|
-
|
|
426
|
-
continue;
|
|
427
|
-
}
|
|
428
|
-
const condition = resolveFilter(meta, name, filter) ?? {};
|
|
418
|
+
const condition = (active && filterCondition(filter)) || {};
|
|
429
419
|
for (const key of getKeys(condition)) {
|
|
430
420
|
if (result[key] === undefined) {
|
|
431
421
|
result[key] = condition[key];
|
|
@@ -433,63 +423,79 @@ export function applyFilters(meta, whereMap, opts) {
|
|
|
433
423
|
}
|
|
434
424
|
}
|
|
435
425
|
const merged = result;
|
|
436
|
-
const
|
|
437
|
-
return
|
|
438
|
-
}
|
|
439
|
-
/**
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
delete: ['read', 'delete'],
|
|
445
|
-
};
|
|
426
|
+
const scope = opts?.[PAST_POLICIES] ? undefined : policyScope(meta, opts?.access ?? 'read', getContext());
|
|
427
|
+
return scope === undefined || scope === true ? merged : whereAnd(merged, conjuncts(asWhere(meta, scope)));
|
|
428
|
+
}
|
|
429
|
+
/** A filter's condition under the ambient context, `undefined` where it reads what the context lacks, which skips it. */
|
|
430
|
+
function filterCondition(filter) {
|
|
431
|
+
const context = getContext();
|
|
432
|
+
return typeof filter.where === 'function' ? filter.where(context) : withContextValues(filter.where, context);
|
|
433
|
+
}
|
|
446
434
|
/**
|
|
447
|
-
*
|
|
448
|
-
*
|
|
435
|
+
* Holds rows an insert or an update writes to the entity's policies under the ambient context, before the write: a
|
|
436
|
+
* 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.
|
|
449
438
|
*/
|
|
450
|
-
export function
|
|
451
|
-
|
|
452
|
-
const holds = filter.security && (!filter.ops || filter.ops.some((op) => accesses.includes(op)));
|
|
453
|
-
const condition = holds ? resolveFilter(meta, name, filter) : undefined;
|
|
454
|
-
return condition && hasKeys(condition) ? [[name, condition]] : [];
|
|
455
|
-
});
|
|
456
|
-
}
|
|
457
|
-
/** A filter's condition, `undefined` where it resolves to nothing and may skip; throws where it may not. */
|
|
458
|
-
function resolveFilter(meta, name, filter) {
|
|
459
|
-
const condition = typeof filter.where === 'function' ? filter.where(getContext()) : filter.where;
|
|
460
|
-
const onMissing = filter.onMissing ?? (filter.security ? 'throw' : 'skip');
|
|
461
|
-
if (condition === undefined && onMissing === 'throw') {
|
|
462
|
-
throw new UqlSecurityError(`filter '${name}' on '${entityName(meta)}' could not resolve (missing context)`);
|
|
463
|
-
}
|
|
464
|
-
return condition;
|
|
439
|
+
export function pinWrite(meta, rows, write) {
|
|
440
|
+
pinRows(meta, rows, write, getContext());
|
|
465
441
|
}
|
|
466
442
|
/**
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
* A condition other than field equalities refuses the write, having nothing a row can be checked against.
|
|
470
|
-
* See architecture/security-filter-writes.md.
|
|
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.
|
|
471
445
|
*/
|
|
472
446
|
export function guardWrite(meta, rows, write) {
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
447
|
+
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);
|
|
463
|
+
if (check === undefined || check === true) {
|
|
464
|
+
return undefined;
|
|
465
|
+
}
|
|
466
|
+
if (check === false) {
|
|
467
|
+
throw new UqlSecurityError(`no policy of '${entityName(meta)}' lets this context ${write} a row`);
|
|
468
|
+
}
|
|
469
|
+
const { pinned, rest } = pinnedFields(meta, check);
|
|
470
|
+
for (const [key, value] of pinned) {
|
|
471
|
+
for (const row of rows) {
|
|
472
|
+
if (row[key] === undefined) {
|
|
473
|
+
if (write === 'insert') {
|
|
474
|
+
row[key] = value;
|
|
489
475
|
}
|
|
490
476
|
}
|
|
477
|
+
else if (row[key] !== value) {
|
|
478
|
+
throw new UqlSecurityError(`'${entityName(meta)}' row sets '${key}' where its policies do not let it`);
|
|
479
|
+
}
|
|
491
480
|
}
|
|
492
481
|
}
|
|
482
|
+
return { check, pinned, rest };
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The fields `where` pins to one value, each a top-level equality it ANDs, and whether anything else is left of it:
|
|
486
|
+
* an operator, a list, a relation, SQL or an `$or`, which only the database answers for a row.
|
|
487
|
+
*/
|
|
488
|
+
function pinnedFields(meta, where) {
|
|
489
|
+
const entries = conjuncts(where).flatMap((part) => Object.entries(part));
|
|
490
|
+
const pinned = entries.filter((entry) => {
|
|
491
|
+
const [key, value] = entry;
|
|
492
|
+
return !!meta.fields[key] && isScalarValue(value);
|
|
493
|
+
});
|
|
494
|
+
return { pinned, rest: pinned.length < entries.length };
|
|
495
|
+
}
|
|
496
|
+
/** A value a field is compared to as it is: no operator map, list or SQL. */
|
|
497
|
+
function isScalarValue(value) {
|
|
498
|
+
return !(value instanceof QuerySql) && !Array.isArray(value) && !isOperatorObject(value) && value !== null;
|
|
493
499
|
}
|
|
494
500
|
/**
|
|
495
501
|
* The `$size` of a relation condition, `{ comments: { $size: { $gte: 2 } } }`, or `undefined` where it
|