@zenstackhq/runtime 3.0.0-beta.7 → 3.0.0-beta.9

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.
@@ -1,3203 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/plugins/policy/errors.ts
5
- var RejectedByPolicyReason = /* @__PURE__ */ function(RejectedByPolicyReason2) {
6
- RejectedByPolicyReason2["NO_ACCESS"] = "no-access";
7
- RejectedByPolicyReason2["CANNOT_READ_BACK"] = "cannot-read-back";
8
- RejectedByPolicyReason2["OTHER"] = "other";
9
- return RejectedByPolicyReason2;
10
- }({});
11
- var RejectedByPolicyError = class extends Error {
12
- static {
13
- __name(this, "RejectedByPolicyError");
14
- }
15
- model;
16
- reason;
17
- constructor(model, reason = "no-access", message) {
18
- super(message ?? `Operation rejected by policy${model ? ": " + model : ""}`), this.model = model, this.reason = reason;
19
- }
20
- };
21
-
22
- // src/plugins/policy/functions.ts
23
- import { invariant as invariant8 } from "@zenstackhq/common-helpers";
24
- import { ExpressionWrapper as ExpressionWrapper2, ValueNode as ValueNode4 } from "kysely";
25
-
26
- // src/client/contract.ts
27
- var CRUD = [
28
- "create",
29
- "read",
30
- "update",
31
- "delete"
32
- ];
33
-
34
- // src/client/kysely-utils.ts
35
- import { AliasNode, ColumnNode, ReferenceNode, TableNode } from "kysely";
36
- function extractFieldName(node) {
37
- if (ReferenceNode.is(node) && ColumnNode.is(node.column)) {
38
- return node.column.column.name;
39
- } else if (ColumnNode.is(node)) {
40
- return node.column.name;
41
- } else {
42
- return void 0;
43
- }
44
- }
45
- __name(extractFieldName, "extractFieldName");
46
-
47
- // src/client/query-utils.ts
48
- import { invariant } from "@zenstackhq/common-helpers";
49
- import { match } from "ts-pattern";
50
-
51
- // src/schema/expression.ts
52
- var ExpressionUtils = {
53
- literal: /* @__PURE__ */ __name((value) => {
54
- return {
55
- kind: "literal",
56
- value
57
- };
58
- }, "literal"),
59
- array: /* @__PURE__ */ __name((items) => {
60
- return {
61
- kind: "array",
62
- items
63
- };
64
- }, "array"),
65
- call: /* @__PURE__ */ __name((functionName, args) => {
66
- return {
67
- kind: "call",
68
- function: functionName,
69
- args
70
- };
71
- }, "call"),
72
- binary: /* @__PURE__ */ __name((left, op, right) => {
73
- return {
74
- kind: "binary",
75
- op,
76
- left,
77
- right
78
- };
79
- }, "binary"),
80
- unary: /* @__PURE__ */ __name((op, operand) => {
81
- return {
82
- kind: "unary",
83
- op,
84
- operand
85
- };
86
- }, "unary"),
87
- field: /* @__PURE__ */ __name((field) => {
88
- return {
89
- kind: "field",
90
- field
91
- };
92
- }, "field"),
93
- member: /* @__PURE__ */ __name((receiver, members) => {
94
- return {
95
- kind: "member",
96
- receiver,
97
- members
98
- };
99
- }, "member"),
100
- _this: /* @__PURE__ */ __name(() => {
101
- return {
102
- kind: "this"
103
- };
104
- }, "_this"),
105
- _null: /* @__PURE__ */ __name(() => {
106
- return {
107
- kind: "null"
108
- };
109
- }, "_null"),
110
- and: /* @__PURE__ */ __name((expr2, ...expressions) => {
111
- return expressions.reduce((acc, exp) => ExpressionUtils.binary(acc, "&&", exp), expr2);
112
- }, "and"),
113
- or: /* @__PURE__ */ __name((expr2, ...expressions) => {
114
- return expressions.reduce((acc, exp) => ExpressionUtils.binary(acc, "||", exp), expr2);
115
- }, "or"),
116
- not: /* @__PURE__ */ __name((expr2) => {
117
- return ExpressionUtils.unary("!", expr2);
118
- }, "not"),
119
- is: /* @__PURE__ */ __name((value, kind) => {
120
- return !!value && typeof value === "object" && "kind" in value && value.kind === kind;
121
- }, "is"),
122
- isLiteral: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "literal"), "isLiteral"),
123
- isArray: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "array"), "isArray"),
124
- isCall: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "call"), "isCall"),
125
- isNull: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "null"), "isNull"),
126
- isThis: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "this"), "isThis"),
127
- isUnary: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "unary"), "isUnary"),
128
- isBinary: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "binary"), "isBinary"),
129
- isField: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "field"), "isField"),
130
- isMember: /* @__PURE__ */ __name((value) => ExpressionUtils.is(value, "member"), "isMember"),
131
- getLiteralValue: /* @__PURE__ */ __name((expr2) => {
132
- return ExpressionUtils.isLiteral(expr2) ? expr2.value : void 0;
133
- }, "getLiteralValue")
134
- };
135
-
136
- // src/client/errors.ts
137
- var QueryError = class extends Error {
138
- static {
139
- __name(this, "QueryError");
140
- }
141
- constructor(message, cause) {
142
- super(message, {
143
- cause
144
- });
145
- }
146
- };
147
- var InternalError = class extends Error {
148
- static {
149
- __name(this, "InternalError");
150
- }
151
- };
152
-
153
- // src/client/query-utils.ts
154
- function getModel(schema, model) {
155
- return Object.values(schema.models).find((m) => m.name.toLowerCase() === model.toLowerCase());
156
- }
157
- __name(getModel, "getModel");
158
- function getTypeDef(schema, type) {
159
- return schema.typeDefs?.[type];
160
- }
161
- __name(getTypeDef, "getTypeDef");
162
- function requireModel(schema, model) {
163
- const modelDef = getModel(schema, model);
164
- if (!modelDef) {
165
- throw new QueryError(`Model "${model}" not found in schema`);
166
- }
167
- return modelDef;
168
- }
169
- __name(requireModel, "requireModel");
170
- function getField(schema, model, field) {
171
- const modelDef = getModel(schema, model);
172
- return modelDef?.fields[field];
173
- }
174
- __name(getField, "getField");
175
- function requireField(schema, modelOrType, field) {
176
- const modelDef = getModel(schema, modelOrType);
177
- if (modelDef) {
178
- if (!modelDef.fields[field]) {
179
- throw new QueryError(`Field "${field}" not found in model "${modelOrType}"`);
180
- } else {
181
- return modelDef.fields[field];
182
- }
183
- }
184
- const typeDef = getTypeDef(schema, modelOrType);
185
- if (typeDef) {
186
- if (!typeDef.fields[field]) {
187
- throw new QueryError(`Field "${field}" not found in type "${modelOrType}"`);
188
- } else {
189
- return typeDef.fields[field];
190
- }
191
- }
192
- throw new QueryError(`Model or type "${modelOrType}" not found in schema`);
193
- }
194
- __name(requireField, "requireField");
195
- function requireIdFields(schema, model) {
196
- const modelDef = requireModel(schema, model);
197
- const result = modelDef?.idFields;
198
- if (!result) {
199
- throw new InternalError(`Model "${model}" does not have ID field(s)`);
200
- }
201
- return result;
202
- }
203
- __name(requireIdFields, "requireIdFields");
204
- function getRelationForeignKeyFieldPairs(schema, model, relationField) {
205
- const fieldDef = requireField(schema, model, relationField);
206
- if (!fieldDef?.relation) {
207
- throw new InternalError(`Field "${relationField}" is not a relation`);
208
- }
209
- if (fieldDef.relation.fields) {
210
- if (!fieldDef.relation.references) {
211
- throw new InternalError(`Relation references not defined for field "${relationField}"`);
212
- }
213
- return {
214
- keyPairs: fieldDef.relation.fields.map((f, i) => ({
215
- fk: f,
216
- pk: fieldDef.relation.references[i]
217
- })),
218
- ownedByModel: true
219
- };
220
- } else {
221
- if (!fieldDef.relation.opposite) {
222
- throw new InternalError(`Opposite relation not defined for field "${relationField}"`);
223
- }
224
- const oppositeField = requireField(schema, fieldDef.type, fieldDef.relation.opposite);
225
- if (!oppositeField.relation) {
226
- throw new InternalError(`Field "${fieldDef.relation.opposite}" is not a relation`);
227
- }
228
- if (!oppositeField.relation.fields) {
229
- throw new InternalError(`Relation fields not defined for field "${relationField}"`);
230
- }
231
- if (!oppositeField.relation.references) {
232
- throw new InternalError(`Relation references not defined for field "${relationField}"`);
233
- }
234
- return {
235
- keyPairs: oppositeField.relation.fields.map((f, i) => ({
236
- fk: f,
237
- pk: oppositeField.relation.references[i]
238
- })),
239
- ownedByModel: false
240
- };
241
- }
242
- }
243
- __name(getRelationForeignKeyFieldPairs, "getRelationForeignKeyFieldPairs");
244
- function isRelationField(schema, model, field) {
245
- const fieldDef = getField(schema, model, field);
246
- return !!fieldDef?.relation;
247
- }
248
- __name(isRelationField, "isRelationField");
249
- function isInheritedField(schema, model, field) {
250
- const fieldDef = getField(schema, model, field);
251
- return !!fieldDef?.originModel;
252
- }
253
- __name(isInheritedField, "isInheritedField");
254
- function getUniqueFields(schema, model) {
255
- const modelDef = requireModel(schema, model);
256
- const result = [];
257
- for (const [key, value] of Object.entries(modelDef.uniqueFields)) {
258
- if (typeof value !== "object") {
259
- throw new InternalError(`Invalid unique field definition for "${key}"`);
260
- }
261
- if (typeof value.type === "string") {
262
- result.push({
263
- name: key,
264
- def: requireField(schema, model, key)
265
- });
266
- } else {
267
- result.push({
268
- name: key,
269
- defs: Object.fromEntries(Object.keys(value).map((k) => [
270
- k,
271
- requireField(schema, model, k)
272
- ]))
273
- });
274
- }
275
- }
276
- return result;
277
- }
278
- __name(getUniqueFields, "getUniqueFields");
279
- function buildFieldRef(schema, model, field, options, eb, modelAlias, inlineComputedField = true) {
280
- const fieldDef = requireField(schema, model, field);
281
- if (!fieldDef.computed) {
282
- return eb.ref(modelAlias ? `${modelAlias}.${field}` : field);
283
- } else {
284
- if (!inlineComputedField) {
285
- return eb.ref(modelAlias ? `${modelAlias}.${field}` : field);
286
- }
287
- let computer;
288
- if ("computedFields" in options) {
289
- const computedFields = options.computedFields;
290
- computer = computedFields?.[model]?.[field];
291
- }
292
- if (!computer) {
293
- throw new QueryError(`Computed field "${field}" implementation not provided for model "${model}"`);
294
- }
295
- return computer(eb, {
296
- modelAlias
297
- });
298
- }
299
- }
300
- __name(buildFieldRef, "buildFieldRef");
301
- function isEnum(schema, type) {
302
- return !!schema.enums?.[type];
303
- }
304
- __name(isEnum, "isEnum");
305
- function buildJoinPairs(schema, model, modelAlias, relationField, relationModelAlias) {
306
- const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(schema, model, relationField);
307
- return keyPairs.map(({ fk, pk }) => {
308
- if (ownedByModel) {
309
- return [
310
- `${relationModelAlias}.${pk}`,
311
- `${modelAlias}.${fk}`
312
- ];
313
- } else {
314
- return [
315
- `${relationModelAlias}.${fk}`,
316
- `${modelAlias}.${pk}`
317
- ];
318
- }
319
- });
320
- }
321
- __name(buildJoinPairs, "buildJoinPairs");
322
- function makeDefaultOrderBy(schema, model) {
323
- const idFields = requireIdFields(schema, model);
324
- return idFields.map((f) => ({
325
- [f]: "asc"
326
- }));
327
- }
328
- __name(makeDefaultOrderBy, "makeDefaultOrderBy");
329
- function getManyToManyRelation(schema, model, field) {
330
- const fieldDef = requireField(schema, model, field);
331
- if (!fieldDef.array || !fieldDef.relation?.opposite) {
332
- return void 0;
333
- }
334
- const oppositeFieldDef = requireField(schema, fieldDef.type, fieldDef.relation.opposite);
335
- if (oppositeFieldDef.array) {
336
- const sortedModelNames = [
337
- model,
338
- fieldDef.type
339
- ].sort();
340
- let orderedFK;
341
- if (model !== fieldDef.type) {
342
- orderedFK = sortedModelNames[0] === model ? [
343
- "A",
344
- "B"
345
- ] : [
346
- "B",
347
- "A"
348
- ];
349
- } else {
350
- const sortedFieldNames = [
351
- field,
352
- oppositeFieldDef.name
353
- ].sort();
354
- orderedFK = sortedFieldNames[0] === field ? [
355
- "A",
356
- "B"
357
- ] : [
358
- "B",
359
- "A"
360
- ];
361
- }
362
- const modelIdFields = requireIdFields(schema, model);
363
- invariant(modelIdFields.length === 1, "Only single-field ID is supported for many-to-many relation");
364
- const otherIdFields = requireIdFields(schema, fieldDef.type);
365
- invariant(otherIdFields.length === 1, "Only single-field ID is supported for many-to-many relation");
366
- return {
367
- parentFkName: orderedFK[0],
368
- parentPKName: modelIdFields[0],
369
- otherModel: fieldDef.type,
370
- otherField: fieldDef.relation.opposite,
371
- otherFkName: orderedFK[1],
372
- otherPKName: otherIdFields[0],
373
- joinTable: fieldDef.relation.name ? `_${fieldDef.relation.name}` : `_${sortedModelNames[0]}To${sortedModelNames[1]}`
374
- };
375
- } else {
376
- return void 0;
377
- }
378
- }
379
- __name(getManyToManyRelation, "getManyToManyRelation");
380
- function flattenCompoundUniqueFilters(schema, model, filter) {
381
- if (typeof filter !== "object" || !filter) {
382
- return filter;
383
- }
384
- const uniqueFields = getUniqueFields(schema, model);
385
- const compoundUniques = uniqueFields.filter((u) => "defs" in u);
386
- if (compoundUniques.length === 0) {
387
- return filter;
388
- }
389
- const result = {};
390
- for (const [key, value] of Object.entries(filter)) {
391
- if (compoundUniques.some(({ name }) => name === key)) {
392
- Object.assign(result, value);
393
- } else {
394
- result[key] = value;
395
- }
396
- }
397
- return result;
398
- }
399
- __name(flattenCompoundUniqueFilters, "flattenCompoundUniqueFilters");
400
- function ensureArray(value) {
401
- if (Array.isArray(value)) {
402
- return value;
403
- } else {
404
- return [
405
- value
406
- ];
407
- }
408
- }
409
- __name(ensureArray, "ensureArray");
410
- function getDelegateDescendantModels(schema, model, collected = /* @__PURE__ */ new Set()) {
411
- const subModels = Object.values(schema.models).filter((m) => m.baseModel === model);
412
- subModels.forEach((def) => {
413
- if (!collected.has(def)) {
414
- collected.add(def);
415
- getDelegateDescendantModels(schema, def.name, collected);
416
- }
417
- });
418
- return [
419
- ...collected
420
- ];
421
- }
422
- __name(getDelegateDescendantModels, "getDelegateDescendantModels");
423
- function aggregate(eb, expr2, op) {
424
- return match(op).with("_count", () => eb.fn.count(expr2)).with("_sum", () => eb.fn.sum(expr2)).with("_avg", () => eb.fn.avg(expr2)).with("_min", () => eb.fn.min(expr2)).with("_max", () => eb.fn.max(expr2)).exhaustive();
425
- }
426
- __name(aggregate, "aggregate");
427
-
428
- // src/plugins/policy/policy-handler.ts
429
- import { invariant as invariant7 } from "@zenstackhq/common-helpers";
430
- import { AliasNode as AliasNode4, BinaryOperationNode as BinaryOperationNode3, ColumnNode as ColumnNode3, DeleteQueryNode, expressionBuilder as expressionBuilder3, ExpressionWrapper, FromNode as FromNode2, FunctionNode as FunctionNode3, IdentifierNode as IdentifierNode2, InsertQueryNode, OperationNodeTransformer, OperatorNode as OperatorNode3, ParensNode as ParensNode2, PrimitiveValueListNode, RawNode, ReturningNode, SelectionNode as SelectionNode2, SelectQueryNode as SelectQueryNode2, sql as sql4, TableNode as TableNode4, UpdateQueryNode, ValueListNode as ValueListNode2, ValueNode as ValueNode3, ValuesNode, WhereNode as WhereNode2 } from "kysely";
431
- import { match as match8 } from "ts-pattern";
432
-
433
- // src/client/crud/dialects/index.ts
434
- import { match as match5 } from "ts-pattern";
435
-
436
- // src/client/crud/dialects/postgresql.ts
437
- import { invariant as invariant3 } from "@zenstackhq/common-helpers";
438
- import Decimal from "decimal.js";
439
- import { sql as sql2 } from "kysely";
440
- import { match as match3 } from "ts-pattern";
441
-
442
- // src/client/constants.ts
443
- var DELEGATE_JOINED_FIELD_PREFIX = "$delegate$";
444
- var LOGICAL_COMBINATORS = [
445
- "AND",
446
- "OR",
447
- "NOT"
448
- ];
449
- var AGGREGATE_OPERATORS = [
450
- "_count",
451
- "_sum",
452
- "_avg",
453
- "_min",
454
- "_max"
455
- ];
456
-
457
- // src/client/crud/dialects/base-dialect.ts
458
- import { invariant as invariant2, isPlainObject } from "@zenstackhq/common-helpers";
459
- import { expressionBuilder, sql } from "kysely";
460
- import { match as match2, P } from "ts-pattern";
461
-
462
- // src/utils/enumerate.ts
463
- function enumerate(x) {
464
- if (x === null || x === void 0) {
465
- return [];
466
- } else if (Array.isArray(x)) {
467
- return x;
468
- } else {
469
- return [
470
- x
471
- ];
472
- }
473
- }
474
- __name(enumerate, "enumerate");
475
-
476
- // src/client/crud/dialects/base-dialect.ts
477
- var BaseCrudDialect = class {
478
- static {
479
- __name(this, "BaseCrudDialect");
480
- }
481
- schema;
482
- options;
483
- constructor(schema, options) {
484
- this.schema = schema;
485
- this.options = options;
486
- }
487
- transformPrimitive(value, _type, _forArrayField) {
488
- return value;
489
- }
490
- transformOutput(value, _type) {
491
- return value;
492
- }
493
- // #region common query builders
494
- buildSelectModel(eb, model, modelAlias) {
495
- const modelDef = requireModel(this.schema, model);
496
- let result = eb.selectFrom(model === modelAlias ? model : `${model} as ${modelAlias}`);
497
- let joinBase = modelDef.baseModel;
498
- while (joinBase) {
499
- result = this.buildDelegateJoin(model, modelAlias, joinBase, result);
500
- joinBase = requireModel(this.schema, joinBase).baseModel;
501
- }
502
- return result;
503
- }
504
- buildFilterSortTake(model, args, query, modelAlias) {
505
- let result = query;
506
- if (args.where) {
507
- result = result.where((eb) => this.buildFilter(eb, model, modelAlias, args?.where));
508
- }
509
- let negateOrderBy = false;
510
- const skip = args.skip;
511
- let take = args.take;
512
- if (take !== void 0 && take < 0) {
513
- negateOrderBy = true;
514
- take = -take;
515
- }
516
- result = this.buildSkipTake(result, skip, take);
517
- result = this.buildOrderBy(result, model, modelAlias, args.orderBy, skip !== void 0 || take !== void 0, negateOrderBy);
518
- if ("distinct" in args && args.distinct) {
519
- const distinct = ensureArray(args.distinct);
520
- if (this.supportsDistinctOn) {
521
- result = result.distinctOn(distinct.map((f) => sql.ref(`${modelAlias}.${f}`)));
522
- } else {
523
- throw new QueryError(`"distinct" is not supported by "${this.schema.provider.type}" provider`);
524
- }
525
- }
526
- if (args.cursor) {
527
- result = this.buildCursorFilter(model, result, args.cursor, args.orderBy, negateOrderBy, modelAlias);
528
- }
529
- return result;
530
- }
531
- buildFilter(eb, model, modelAlias, where) {
532
- if (where === true || where === void 0) {
533
- return this.true(eb);
534
- }
535
- if (where === false) {
536
- return this.false(eb);
537
- }
538
- let result = this.true(eb);
539
- const _where = flattenCompoundUniqueFilters(this.schema, model, where);
540
- for (const [key, payload] of Object.entries(_where)) {
541
- if (payload === void 0) {
542
- continue;
543
- }
544
- if (key.startsWith("$")) {
545
- continue;
546
- }
547
- if (this.isLogicalCombinator(key)) {
548
- result = this.and(eb, result, this.buildCompositeFilter(eb, model, modelAlias, key, payload));
549
- continue;
550
- }
551
- const fieldDef = requireField(this.schema, model, key);
552
- if (fieldDef.relation) {
553
- result = this.and(eb, result, this.buildRelationFilter(eb, model, modelAlias, key, fieldDef, payload));
554
- } else {
555
- const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, eb, fieldDef.originModel ?? modelAlias);
556
- if (fieldDef.array) {
557
- result = this.and(eb, result, this.buildArrayFilter(eb, fieldRef, fieldDef, payload));
558
- } else {
559
- result = this.and(eb, result, this.buildPrimitiveFilter(eb, fieldRef, fieldDef, payload));
560
- }
561
- }
562
- }
563
- if ("$expr" in _where && typeof _where["$expr"] === "function") {
564
- result = this.and(eb, result, _where["$expr"](eb));
565
- }
566
- return result;
567
- }
568
- buildCursorFilter(model, query, cursor, orderBy, negateOrderBy, modelAlias) {
569
- const _orderBy = orderBy ?? makeDefaultOrderBy(this.schema, model);
570
- const orderByItems = ensureArray(_orderBy).flatMap((obj) => Object.entries(obj));
571
- const eb = expressionBuilder();
572
- const subQueryAlias = `${model}$cursor$sub`;
573
- const cursorFilter = this.buildFilter(eb, model, subQueryAlias, cursor);
574
- let result = query;
575
- const filters = [];
576
- for (let i = orderByItems.length - 1; i >= 0; i--) {
577
- const andFilters = [];
578
- for (let j = 0; j <= i; j++) {
579
- const [field, order] = orderByItems[j];
580
- const _order = negateOrderBy ? order === "asc" ? "desc" : "asc" : order;
581
- const op = j === i ? _order === "asc" ? ">=" : "<=" : "=";
582
- andFilters.push(eb(eb.ref(`${modelAlias}.${field}`), op, this.buildSelectModel(eb, model, subQueryAlias).select(`${subQueryAlias}.${field}`).where(cursorFilter)));
583
- }
584
- filters.push(eb.and(andFilters));
585
- }
586
- result = result.where((eb2) => eb2.or(filters));
587
- return result;
588
- }
589
- isLogicalCombinator(key) {
590
- return LOGICAL_COMBINATORS.includes(key);
591
- }
592
- buildCompositeFilter(eb, model, modelAlias, key, payload) {
593
- return match2(key).with("AND", () => this.and(eb, ...enumerate(payload).map((subPayload) => this.buildFilter(eb, model, modelAlias, subPayload)))).with("OR", () => this.or(eb, ...enumerate(payload).map((subPayload) => this.buildFilter(eb, model, modelAlias, subPayload)))).with("NOT", () => eb.not(this.buildCompositeFilter(eb, model, modelAlias, "AND", payload))).exhaustive();
594
- }
595
- buildRelationFilter(eb, model, modelAlias, field, fieldDef, payload) {
596
- if (!fieldDef.array) {
597
- return this.buildToOneRelationFilter(eb, model, modelAlias, field, fieldDef, payload);
598
- } else {
599
- return this.buildToManyRelationFilter(eb, model, modelAlias, field, fieldDef, payload);
600
- }
601
- }
602
- buildToOneRelationFilter(eb, model, modelAlias, field, fieldDef, payload) {
603
- if (payload === null) {
604
- const { ownedByModel, keyPairs } = getRelationForeignKeyFieldPairs(this.schema, model, field);
605
- if (ownedByModel && !fieldDef.originModel) {
606
- return this.and(eb, ...keyPairs.map(({ fk }) => eb(sql.ref(`${modelAlias}.${fk}`), "is", null)));
607
- } else {
608
- return this.buildToOneRelationFilter(eb, model, modelAlias, field, fieldDef, {
609
- is: null
610
- });
611
- }
612
- }
613
- const joinAlias = `${modelAlias}$${field}`;
614
- const joinPairs = buildJoinPairs(
615
- this.schema,
616
- model,
617
- // if field is from a base, use the base model to join
618
- fieldDef.originModel ?? modelAlias,
619
- field,
620
- joinAlias
621
- );
622
- const filterResultField = `${field}$filter`;
623
- const joinSelect = eb.selectFrom(`${fieldDef.type} as ${joinAlias}`).where(() => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql.ref(left), "=", sql.ref(right))))).select(() => eb.fn.count(eb.lit(1)).as(filterResultField));
624
- const conditions = [];
625
- if ("is" in payload || "isNot" in payload) {
626
- if ("is" in payload) {
627
- if (payload.is === null) {
628
- conditions.push(eb(joinSelect, "=", 0));
629
- } else {
630
- conditions.push(eb(joinSelect.where(() => this.buildFilter(eb, fieldDef.type, joinAlias, payload.is)), ">", 0));
631
- }
632
- }
633
- if ("isNot" in payload) {
634
- if (payload.isNot === null) {
635
- conditions.push(eb(joinSelect, ">", 0));
636
- } else {
637
- conditions.push(this.or(
638
- eb,
639
- // is null
640
- eb(joinSelect, "=", 0),
641
- // found one that matches the filter
642
- eb(joinSelect.where(() => this.buildFilter(eb, fieldDef.type, joinAlias, payload.isNot)), "=", 0)
643
- ));
644
- }
645
- }
646
- } else {
647
- conditions.push(eb(joinSelect.where(() => this.buildFilter(eb, fieldDef.type, joinAlias, payload)), ">", 0));
648
- }
649
- return this.and(eb, ...conditions);
650
- }
651
- buildToManyRelationFilter(eb, model, modelAlias, field, fieldDef, payload) {
652
- if (payload === null) {
653
- return eb(sql.ref(`${modelAlias}.${field}`), "is", null);
654
- }
655
- const relationModel = fieldDef.type;
656
- const relationFilterSelectAlias = `${modelAlias}$${field}$filter`;
657
- const buildPkFkWhereRefs = /* @__PURE__ */ __name((eb2) => {
658
- const m2m = getManyToManyRelation(this.schema, model, field);
659
- if (m2m) {
660
- const modelIdFields = requireIdFields(this.schema, model);
661
- invariant2(modelIdFields.length === 1, "many-to-many relation must have exactly one id field");
662
- const relationIdFields = requireIdFields(this.schema, relationModel);
663
- invariant2(relationIdFields.length === 1, "many-to-many relation must have exactly one id field");
664
- return eb2(sql.ref(`${relationFilterSelectAlias}.${relationIdFields[0]}`), "in", eb2.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(sql.ref(`${m2m.joinTable}.${m2m.parentFkName}`), "=", sql.ref(`${modelAlias}.${modelIdFields[0]}`)));
665
- } else {
666
- const relationKeyPairs = getRelationForeignKeyFieldPairs(this.schema, model, field);
667
- let result2 = this.true(eb2);
668
- for (const { fk, pk } of relationKeyPairs.keyPairs) {
669
- if (relationKeyPairs.ownedByModel) {
670
- result2 = this.and(eb2, result2, eb2(sql.ref(`${modelAlias}.${fk}`), "=", sql.ref(`${relationFilterSelectAlias}.${pk}`)));
671
- } else {
672
- result2 = this.and(eb2, result2, eb2(sql.ref(`${modelAlias}.${pk}`), "=", sql.ref(`${relationFilterSelectAlias}.${fk}`)));
673
- }
674
- }
675
- return result2;
676
- }
677
- }, "buildPkFkWhereRefs");
678
- let result = this.true(eb);
679
- for (const [key, subPayload] of Object.entries(payload)) {
680
- if (!subPayload) {
681
- continue;
682
- }
683
- switch (key) {
684
- case "some": {
685
- result = this.and(eb, result, eb(this.buildSelectModel(eb, relationModel, relationFilterSelectAlias).select((eb1) => eb1.fn.count(eb1.lit(1)).as("$count")).where(buildPkFkWhereRefs(eb)).where((eb1) => this.buildFilter(eb1, relationModel, relationFilterSelectAlias, subPayload)), ">", 0));
686
- break;
687
- }
688
- case "every": {
689
- result = this.and(eb, result, eb(this.buildSelectModel(eb, relationModel, relationFilterSelectAlias).select((eb1) => eb1.fn.count(eb1.lit(1)).as("$count")).where(buildPkFkWhereRefs(eb)).where((eb1) => eb1.not(this.buildFilter(eb1, relationModel, relationFilterSelectAlias, subPayload))), "=", 0));
690
- break;
691
- }
692
- case "none": {
693
- result = this.and(eb, result, eb(this.buildSelectModel(eb, relationModel, relationFilterSelectAlias).select((eb1) => eb1.fn.count(eb1.lit(1)).as("$count")).where(buildPkFkWhereRefs(eb)).where((eb1) => this.buildFilter(eb1, relationModel, relationFilterSelectAlias, subPayload)), "=", 0));
694
- break;
695
- }
696
- }
697
- }
698
- return result;
699
- }
700
- buildArrayFilter(eb, fieldRef, fieldDef, payload) {
701
- const clauses = [];
702
- const fieldType = fieldDef.type;
703
- for (const [key, _value] of Object.entries(payload)) {
704
- if (_value === void 0) {
705
- continue;
706
- }
707
- const value = this.transformPrimitive(_value, fieldType, !!fieldDef.array);
708
- switch (key) {
709
- case "equals": {
710
- clauses.push(this.buildLiteralFilter(eb, fieldRef, fieldType, eb.val(value)));
711
- break;
712
- }
713
- case "has": {
714
- clauses.push(eb(fieldRef, "@>", eb.val([
715
- value
716
- ])));
717
- break;
718
- }
719
- case "hasEvery": {
720
- clauses.push(eb(fieldRef, "@>", eb.val(value)));
721
- break;
722
- }
723
- case "hasSome": {
724
- clauses.push(eb(fieldRef, "&&", eb.val(value)));
725
- break;
726
- }
727
- case "isEmpty": {
728
- clauses.push(eb(fieldRef, value === true ? "=" : "!=", eb.val([])));
729
- break;
730
- }
731
- default: {
732
- throw new InternalError(`Invalid array filter key: ${key}`);
733
- }
734
- }
735
- }
736
- return this.and(eb, ...clauses);
737
- }
738
- buildPrimitiveFilter(eb, fieldRef, fieldDef, payload) {
739
- if (payload === null) {
740
- return eb(fieldRef, "is", null);
741
- }
742
- if (isEnum(this.schema, fieldDef.type)) {
743
- return this.buildEnumFilter(eb, fieldRef, fieldDef, payload);
744
- }
745
- return match2(fieldDef.type).with("String", () => this.buildStringFilter(eb, fieldRef, payload)).with(P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.buildNumberFilter(eb, fieldRef, type, payload)).with("Boolean", () => this.buildBooleanFilter(eb, fieldRef, payload)).with("DateTime", () => this.buildDateTimeFilter(eb, fieldRef, payload)).with("Bytes", () => this.buildBytesFilter(eb, fieldRef, payload)).with("Json", () => {
746
- throw new InternalError("JSON filters are not supported yet");
747
- }).with("Unsupported", () => {
748
- throw new QueryError(`Unsupported field cannot be used in filters`);
749
- }).exhaustive();
750
- }
751
- buildLiteralFilter(eb, lhs, type, rhs) {
752
- return eb(lhs, "=", rhs !== null && rhs !== void 0 ? this.transformPrimitive(rhs, type, false) : rhs);
753
- }
754
- buildStandardFilter(eb, type, payload, lhs, getRhs, recurse, throwIfInvalid = false, onlyForKeys = void 0, excludeKeys = []) {
755
- if (payload === null || !isPlainObject(payload)) {
756
- return {
757
- conditions: [
758
- this.buildLiteralFilter(eb, lhs, type, payload)
759
- ],
760
- consumedKeys: []
761
- };
762
- }
763
- const conditions = [];
764
- const consumedKeys = [];
765
- for (const [op, value] of Object.entries(payload)) {
766
- if (onlyForKeys && !onlyForKeys.includes(op)) {
767
- continue;
768
- }
769
- if (excludeKeys.includes(op)) {
770
- continue;
771
- }
772
- const rhs = Array.isArray(value) ? value.map(getRhs) : getRhs(value);
773
- const condition = match2(op).with("equals", () => rhs === null ? eb(lhs, "is", null) : eb(lhs, "=", rhs)).with("in", () => {
774
- invariant2(Array.isArray(rhs), "right hand side must be an array");
775
- if (rhs.length === 0) {
776
- return this.false(eb);
777
- } else {
778
- return eb(lhs, "in", rhs);
779
- }
780
- }).with("notIn", () => {
781
- invariant2(Array.isArray(rhs), "right hand side must be an array");
782
- if (rhs.length === 0) {
783
- return this.true(eb);
784
- } else {
785
- return eb.not(eb(lhs, "in", rhs));
786
- }
787
- }).with("lt", () => eb(lhs, "<", rhs)).with("lte", () => eb(lhs, "<=", rhs)).with("gt", () => eb(lhs, ">", rhs)).with("gte", () => eb(lhs, ">=", rhs)).with("not", () => eb.not(recurse(value))).with(P.union(...AGGREGATE_OPERATORS), (op2) => {
788
- const innerResult = this.buildStandardFilter(eb, type, value, aggregate(eb, lhs, op2), getRhs, recurse, throwIfInvalid);
789
- consumedKeys.push(...innerResult.consumedKeys);
790
- return this.and(eb, ...innerResult.conditions);
791
- }).otherwise(() => {
792
- if (throwIfInvalid) {
793
- throw new QueryError(`Invalid filter key: ${op}`);
794
- } else {
795
- return void 0;
796
- }
797
- });
798
- if (condition) {
799
- conditions.push(condition);
800
- consumedKeys.push(op);
801
- }
802
- }
803
- return {
804
- conditions,
805
- consumedKeys
806
- };
807
- }
808
- buildStringFilter(eb, fieldRef, payload) {
809
- let mode;
810
- if (payload && typeof payload === "object" && "mode" in payload) {
811
- mode = payload.mode;
812
- }
813
- const { conditions, consumedKeys } = this.buildStandardFilter(eb, "String", payload, mode === "insensitive" ? eb.fn("lower", [
814
- fieldRef
815
- ]) : fieldRef, (value) => this.prepStringCasing(eb, value, mode), (value) => this.buildStringFilter(eb, fieldRef, value));
816
- if (payload && typeof payload === "object") {
817
- for (const [key, value] of Object.entries(payload)) {
818
- if (key === "mode" || consumedKeys.includes(key)) {
819
- continue;
820
- }
821
- const condition = match2(key).with("contains", () => mode === "insensitive" ? eb(fieldRef, "ilike", sql.val(`%${value}%`)) : eb(fieldRef, "like", sql.val(`%${value}%`))).with("startsWith", () => mode === "insensitive" ? eb(fieldRef, "ilike", sql.val(`${value}%`)) : eb(fieldRef, "like", sql.val(`${value}%`))).with("endsWith", () => mode === "insensitive" ? eb(fieldRef, "ilike", sql.val(`%${value}`)) : eb(fieldRef, "like", sql.val(`%${value}`))).otherwise(() => {
822
- throw new QueryError(`Invalid string filter key: ${key}`);
823
- });
824
- if (condition) {
825
- conditions.push(condition);
826
- }
827
- }
828
- }
829
- return this.and(eb, ...conditions);
830
- }
831
- prepStringCasing(eb, value, mode) {
832
- if (!mode || mode === "default") {
833
- return value === null ? value : sql.val(value);
834
- }
835
- if (typeof value === "string") {
836
- return eb.fn("lower", [
837
- sql.val(value)
838
- ]);
839
- } else if (Array.isArray(value)) {
840
- return value.map((v) => this.prepStringCasing(eb, v, mode));
841
- } else {
842
- return value === null ? null : sql.val(value);
843
- }
844
- }
845
- buildNumberFilter(eb, fieldRef, type, payload) {
846
- const { conditions } = this.buildStandardFilter(eb, type, payload, fieldRef, (value) => this.transformPrimitive(value, type, false), (value) => this.buildNumberFilter(eb, fieldRef, type, value));
847
- return this.and(eb, ...conditions);
848
- }
849
- buildBooleanFilter(eb, fieldRef, payload) {
850
- const { conditions } = this.buildStandardFilter(eb, "Boolean", payload, fieldRef, (value) => this.transformPrimitive(value, "Boolean", false), (value) => this.buildBooleanFilter(eb, fieldRef, value), true, [
851
- "equals",
852
- "not"
853
- ]);
854
- return this.and(eb, ...conditions);
855
- }
856
- buildDateTimeFilter(eb, fieldRef, payload) {
857
- const { conditions } = this.buildStandardFilter(eb, "DateTime", payload, fieldRef, (value) => this.transformPrimitive(value, "DateTime", false), (value) => this.buildDateTimeFilter(eb, fieldRef, value), true);
858
- return this.and(eb, ...conditions);
859
- }
860
- buildBytesFilter(eb, fieldRef, payload) {
861
- const conditions = this.buildStandardFilter(eb, "Bytes", payload, fieldRef, (value) => this.transformPrimitive(value, "Bytes", false), (value) => this.buildBytesFilter(eb, fieldRef, value), true, [
862
- "equals",
863
- "in",
864
- "notIn",
865
- "not"
866
- ]);
867
- return this.and(eb, ...conditions.conditions);
868
- }
869
- buildEnumFilter(eb, fieldRef, fieldDef, payload) {
870
- const conditions = this.buildStandardFilter(eb, "String", payload, fieldRef, (value) => value, (value) => this.buildEnumFilter(eb, fieldRef, fieldDef, value), true, [
871
- "equals",
872
- "in",
873
- "notIn",
874
- "not"
875
- ]);
876
- return this.and(eb, ...conditions.conditions);
877
- }
878
- buildOrderBy(query, model, modelAlias, orderBy, useDefaultIfEmpty, negated) {
879
- if (!orderBy) {
880
- if (useDefaultIfEmpty) {
881
- orderBy = makeDefaultOrderBy(this.schema, model);
882
- } else {
883
- return query;
884
- }
885
- }
886
- let result = query;
887
- enumerate(orderBy).forEach((orderBy2) => {
888
- for (const [field, value] of Object.entries(orderBy2)) {
889
- if (!value) {
890
- continue;
891
- }
892
- if ([
893
- "_count",
894
- "_avg",
895
- "_sum",
896
- "_min",
897
- "_max"
898
- ].includes(field)) {
899
- invariant2(value && typeof value === "object", `invalid orderBy value for field "${field}"`);
900
- for (const [k, v] of Object.entries(value)) {
901
- invariant2(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
902
- result = result.orderBy((eb) => aggregate(eb, this.fieldRef(model, k, eb, modelAlias), field), sql.raw(this.negateSort(v, negated)));
903
- }
904
- continue;
905
- }
906
- switch (field) {
907
- case "_count": {
908
- invariant2(value && typeof value === "object", 'invalid orderBy value for field "_count"');
909
- for (const [k, v] of Object.entries(value)) {
910
- invariant2(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
911
- result = result.orderBy((eb) => eb.fn.count(this.fieldRef(model, k, eb, modelAlias)), sql.raw(this.negateSort(v, negated)));
912
- }
913
- continue;
914
- }
915
- default:
916
- break;
917
- }
918
- const fieldDef = requireField(this.schema, model, field);
919
- if (!fieldDef.relation) {
920
- const fieldRef = this.fieldRef(model, field, expressionBuilder(), modelAlias);
921
- if (value === "asc" || value === "desc") {
922
- result = result.orderBy(fieldRef, this.negateSort(value, negated));
923
- } else if (value && typeof value === "object" && "nulls" in value && "sort" in value && (value.sort === "asc" || value.sort === "desc") && (value.nulls === "first" || value.nulls === "last")) {
924
- result = result.orderBy(fieldRef, sql.raw(`${this.negateSort(value.sort, negated)} nulls ${value.nulls}`));
925
- }
926
- } else {
927
- const relationModel = fieldDef.type;
928
- if (fieldDef.array) {
929
- if (typeof value !== "object") {
930
- throw new QueryError(`invalid orderBy value for field "${field}"`);
931
- }
932
- if ("_count" in value) {
933
- invariant2(value._count === "asc" || value._count === "desc", 'invalid orderBy value for field "_count"');
934
- const sort = this.negateSort(value._count, negated);
935
- result = result.orderBy((eb) => {
936
- const subQueryAlias = `${modelAlias}$orderBy$${field}$count`;
937
- let subQuery = this.buildSelectModel(eb, relationModel, subQueryAlias);
938
- const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, subQueryAlias);
939
- subQuery = subQuery.where(() => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql.ref(left), "=", sql.ref(right)))));
940
- subQuery = subQuery.select(() => eb.fn.count(eb.lit(1)).as("_count"));
941
- return subQuery;
942
- }, sort);
943
- }
944
- } else {
945
- result = result.leftJoin(relationModel, (join) => {
946
- const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, relationModel);
947
- return join.on((eb) => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql.ref(left), "=", sql.ref(right)))));
948
- });
949
- result = this.buildOrderBy(result, fieldDef.type, relationModel, value, false, negated);
950
- }
951
- }
952
- }
953
- });
954
- return result;
955
- }
956
- buildSelectAllFields(model, query, omit, modelAlias) {
957
- const modelDef = requireModel(this.schema, model);
958
- let result = query;
959
- for (const field of Object.keys(modelDef.fields)) {
960
- if (isRelationField(this.schema, model, field)) {
961
- continue;
962
- }
963
- if (omit?.[field] === true) {
964
- continue;
965
- }
966
- result = this.buildSelectField(result, model, modelAlias, field);
967
- }
968
- const descendants = getDelegateDescendantModels(this.schema, model);
969
- for (const subModel of descendants) {
970
- result = this.buildDelegateJoin(model, modelAlias, subModel.name, result);
971
- result = result.select((eb) => {
972
- const jsonObject = {};
973
- for (const field of Object.keys(subModel.fields)) {
974
- if (isRelationField(this.schema, subModel.name, field) || isInheritedField(this.schema, subModel.name, field)) {
975
- continue;
976
- }
977
- jsonObject[field] = eb.ref(`${subModel.name}.${field}`);
978
- }
979
- return this.buildJsonObject(eb, jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
980
- });
981
- }
982
- return result;
983
- }
984
- buildModelSelect(eb, model, subQueryAlias, payload, selectAllFields) {
985
- let subQuery = this.buildSelectModel(eb, model, subQueryAlias);
986
- if (selectAllFields) {
987
- subQuery = this.buildSelectAllFields(model, subQuery, typeof payload === "object" ? payload?.omit : void 0, subQueryAlias);
988
- }
989
- if (payload && typeof payload === "object") {
990
- subQuery = this.buildFilterSortTake(model, payload, subQuery, subQueryAlias);
991
- }
992
- return subQuery;
993
- }
994
- buildSelectField(query, model, modelAlias, field) {
995
- const fieldDef = requireField(this.schema, model, field);
996
- if (fieldDef.computed) {
997
- return query.select((eb) => this.fieldRef(model, field, eb, modelAlias).as(field));
998
- } else if (!fieldDef.originModel) {
999
- return query.select(sql.ref(`${modelAlias}.${field}`).as(field));
1000
- } else {
1001
- return this.buildSelectField(query, fieldDef.originModel, fieldDef.originModel, field);
1002
- }
1003
- }
1004
- buildDelegateJoin(thisModel, thisModelAlias, otherModelAlias, query) {
1005
- const idFields = requireIdFields(this.schema, thisModel);
1006
- query = query.leftJoin(otherModelAlias, (qb) => {
1007
- for (const idField of idFields) {
1008
- qb = qb.onRef(`${thisModelAlias}.${idField}`, "=", `${otherModelAlias}.${idField}`);
1009
- }
1010
- return qb;
1011
- });
1012
- return query;
1013
- }
1014
- buildCountJson(model, eb, parentAlias, payload) {
1015
- const modelDef = requireModel(this.schema, model);
1016
- const toManyRelations = Object.entries(modelDef.fields).filter(([, field]) => field.relation && field.array);
1017
- const selections = payload === true ? {
1018
- select: toManyRelations.reduce((acc, [field]) => {
1019
- acc[field] = true;
1020
- return acc;
1021
- }, {})
1022
- } : payload;
1023
- const jsonObject = {};
1024
- for (const [field, value] of Object.entries(selections.select)) {
1025
- const fieldDef = requireField(this.schema, model, field);
1026
- const fieldModel = fieldDef.type;
1027
- let fieldCountQuery;
1028
- const m2m = getManyToManyRelation(this.schema, model, field);
1029
- if (m2m) {
1030
- fieldCountQuery = eb.selectFrom(fieldModel).innerJoin(m2m.joinTable, (join) => join.onRef(`${m2m.joinTable}.${m2m.otherFkName}`, "=", `${fieldModel}.${m2m.otherPKName}`).onRef(`${m2m.joinTable}.${m2m.parentFkName}`, "=", `${parentAlias}.${m2m.parentPKName}`)).select(eb.fn.countAll().as(`_count$${field}`));
1031
- } else {
1032
- fieldCountQuery = eb.selectFrom(fieldModel).select(eb.fn.countAll().as(`_count$${field}`));
1033
- const joinPairs = buildJoinPairs(this.schema, model, parentAlias, field, fieldModel);
1034
- for (const [left, right] of joinPairs) {
1035
- fieldCountQuery = fieldCountQuery.whereRef(left, "=", right);
1036
- }
1037
- }
1038
- if (value && typeof value === "object" && "where" in value && value.where && typeof value.where === "object") {
1039
- const filter = this.buildFilter(eb, fieldModel, fieldModel, value.where);
1040
- fieldCountQuery = fieldCountQuery.where(filter);
1041
- }
1042
- jsonObject[field] = fieldCountQuery;
1043
- }
1044
- return this.buildJsonObject(eb, jsonObject);
1045
- }
1046
- // #endregion
1047
- // #region utils
1048
- negateSort(sort, negated) {
1049
- return negated ? sort === "asc" ? "desc" : "asc" : sort;
1050
- }
1051
- true(eb) {
1052
- return eb.lit(this.transformPrimitive(true, "Boolean", false));
1053
- }
1054
- false(eb) {
1055
- return eb.lit(this.transformPrimitive(false, "Boolean", false));
1056
- }
1057
- isTrue(expression) {
1058
- const node = expression.toOperationNode();
1059
- if (node.kind !== "ValueNode") {
1060
- return false;
1061
- }
1062
- return node.value === true || node.value === 1;
1063
- }
1064
- isFalse(expression) {
1065
- const node = expression.toOperationNode();
1066
- if (node.kind !== "ValueNode") {
1067
- return false;
1068
- }
1069
- return node.value === false || node.value === 0;
1070
- }
1071
- and(eb, ...args) {
1072
- const nonTrueArgs = args.filter((arg) => !this.isTrue(arg));
1073
- if (nonTrueArgs.length === 0) {
1074
- return this.true(eb);
1075
- } else if (nonTrueArgs.length === 1) {
1076
- return nonTrueArgs[0];
1077
- } else {
1078
- return eb.and(nonTrueArgs);
1079
- }
1080
- }
1081
- or(eb, ...args) {
1082
- const nonFalseArgs = args.filter((arg) => !this.isFalse(arg));
1083
- if (nonFalseArgs.length === 0) {
1084
- return this.false(eb);
1085
- } else if (nonFalseArgs.length === 1) {
1086
- return nonFalseArgs[0];
1087
- } else {
1088
- return eb.or(nonFalseArgs);
1089
- }
1090
- }
1091
- not(eb, ...args) {
1092
- return eb.not(this.and(eb, ...args));
1093
- }
1094
- fieldRef(model, field, eb, modelAlias, inlineComputedField = true) {
1095
- return buildFieldRef(this.schema, model, field, this.options, eb, modelAlias, inlineComputedField);
1096
- }
1097
- canJoinWithoutNestedSelect(modelDef, payload) {
1098
- if (modelDef.computedFields) {
1099
- return false;
1100
- }
1101
- if (modelDef.baseModel || modelDef.isDelegate) {
1102
- return false;
1103
- }
1104
- if (typeof payload === "object" && (payload.orderBy || payload.skip !== void 0 || payload.take !== void 0 || payload.cursor || payload.distinct)) {
1105
- return false;
1106
- }
1107
- return true;
1108
- }
1109
- };
1110
-
1111
- // src/client/crud/dialects/postgresql.ts
1112
- var PostgresCrudDialect = class extends BaseCrudDialect {
1113
- static {
1114
- __name(this, "PostgresCrudDialect");
1115
- }
1116
- constructor(schema, options) {
1117
- super(schema, options);
1118
- }
1119
- get provider() {
1120
- return "postgresql";
1121
- }
1122
- transformPrimitive(value, type, forArrayField) {
1123
- if (value === void 0) {
1124
- return value;
1125
- }
1126
- if (Array.isArray(value)) {
1127
- if (type === "Json" && !forArrayField) {
1128
- return JSON.stringify(value);
1129
- } else {
1130
- return value.map((v) => this.transformPrimitive(v, type, false));
1131
- }
1132
- } else {
1133
- return match3(type).with("DateTime", () => value instanceof Date ? value.toISOString() : typeof value === "string" ? new Date(value).toISOString() : value).with("Decimal", () => value !== null ? value.toString() : value).otherwise(() => value);
1134
- }
1135
- }
1136
- transformOutput(value, type) {
1137
- if (value === null || value === void 0) {
1138
- return value;
1139
- }
1140
- return match3(type).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Decimal", () => this.transformDecimal(value)).otherwise(() => super.transformOutput(value, type));
1141
- }
1142
- transformOutputBigInt(value) {
1143
- if (typeof value === "bigint") {
1144
- return value;
1145
- }
1146
- invariant3(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
1147
- return BigInt(value);
1148
- }
1149
- transformDecimal(value) {
1150
- if (value instanceof Decimal) {
1151
- return value;
1152
- }
1153
- invariant3(typeof value === "string" || typeof value === "number" || value instanceof Decimal, `Expected string, number or Decimal, got ${typeof value}`);
1154
- return new Decimal(value);
1155
- }
1156
- transformOutputDate(value) {
1157
- if (typeof value === "string") {
1158
- return new Date(value);
1159
- } else if (value instanceof Date && this.options.fixPostgresTimezone !== false) {
1160
- return new Date(value.getTime() - value.getTimezoneOffset() * 60 * 1e3);
1161
- } else {
1162
- return value;
1163
- }
1164
- }
1165
- transformOutputBytes(value) {
1166
- return Buffer.isBuffer(value) ? Uint8Array.from(value) : value;
1167
- }
1168
- buildRelationSelection(query, model, relationField, parentAlias, payload) {
1169
- const relationResultName = `${parentAlias}$${relationField}`;
1170
- const joinedQuery = this.buildRelationJSON(model, query, relationField, parentAlias, payload, relationResultName);
1171
- return joinedQuery.select(`${relationResultName}.$data as ${relationField}`);
1172
- }
1173
- buildRelationJSON(model, qb, relationField, parentAlias, payload, resultName) {
1174
- const relationFieldDef = requireField(this.schema, model, relationField);
1175
- const relationModel = relationFieldDef.type;
1176
- return qb.leftJoinLateral((eb) => {
1177
- const relationSelectName = `${resultName}$sub`;
1178
- const relationModelDef = requireModel(this.schema, relationModel);
1179
- let tbl;
1180
- if (this.canJoinWithoutNestedSelect(relationModelDef, payload)) {
1181
- tbl = this.buildModelSelect(eb, relationModel, relationSelectName, payload, false);
1182
- tbl = this.buildRelationJoinFilter(tbl, model, relationField, relationModel, relationSelectName, parentAlias);
1183
- } else {
1184
- tbl = eb.selectFrom(() => {
1185
- let subQuery = this.buildModelSelect(eb, relationModel, `${relationSelectName}$t`, payload, true);
1186
- subQuery = this.buildRelationJoinFilter(subQuery, model, relationField, relationModel, `${relationSelectName}$t`, parentAlias);
1187
- return subQuery.as(relationSelectName);
1188
- });
1189
- }
1190
- tbl = this.buildRelationObjectSelect(relationModel, relationSelectName, relationFieldDef, tbl, payload, resultName);
1191
- tbl = this.buildRelationJoins(tbl, relationModel, relationSelectName, payload, resultName);
1192
- return tbl.as(resultName);
1193
- }, (join) => join.onTrue());
1194
- }
1195
- buildRelationJoinFilter(query, model, relationField, relationModel, relationModelAlias, parentAlias) {
1196
- const m2m = getManyToManyRelation(this.schema, model, relationField);
1197
- if (m2m) {
1198
- const parentIds = requireIdFields(this.schema, model);
1199
- const relationIds = requireIdFields(this.schema, relationModel);
1200
- invariant3(parentIds.length === 1, "many-to-many relation must have exactly one id field");
1201
- invariant3(relationIds.length === 1, "many-to-many relation must have exactly one id field");
1202
- query = query.where((eb) => eb(eb.ref(`${relationModelAlias}.${relationIds[0]}`), "in", eb.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(`${parentAlias}.${parentIds[0]}`, "=", `${m2m.joinTable}.${m2m.parentFkName}`)));
1203
- } else {
1204
- const joinPairs = buildJoinPairs(this.schema, model, parentAlias, relationField, relationModelAlias);
1205
- query = query.where((eb) => this.and(eb, ...joinPairs.map(([left, right]) => eb(sql2.ref(left), "=", sql2.ref(right)))));
1206
- }
1207
- return query;
1208
- }
1209
- buildRelationObjectSelect(relationModel, relationModelAlias, relationFieldDef, qb, payload, parentResultName) {
1210
- qb = qb.select((eb) => {
1211
- const objArgs = this.buildRelationObjectArgs(relationModel, relationModelAlias, eb, payload, parentResultName);
1212
- if (relationFieldDef.array) {
1213
- return eb.fn.coalesce(sql2`jsonb_agg(jsonb_build_object(${sql2.join(objArgs)}))`, sql2`'[]'::jsonb`).as("$data");
1214
- } else {
1215
- return sql2`jsonb_build_object(${sql2.join(objArgs)})`.as("$data");
1216
- }
1217
- });
1218
- return qb;
1219
- }
1220
- buildRelationObjectArgs(relationModel, relationModelAlias, eb, payload, parentResultName) {
1221
- const relationModelDef = requireModel(this.schema, relationModel);
1222
- const objArgs = [];
1223
- const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
1224
- if (descendantModels.length > 0) {
1225
- objArgs.push(...descendantModels.map((subModel) => [
1226
- sql2.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`),
1227
- eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)
1228
- ]).flatMap((v) => v));
1229
- }
1230
- if (payload === true || !payload.select) {
1231
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !(typeof payload === "object" && payload.omit?.[name] === true)).map(([field]) => [
1232
- sql2.lit(field),
1233
- this.fieldRef(relationModel, field, eb, relationModelAlias, false)
1234
- ]).flatMap((v) => v));
1235
- } else if (payload.select) {
1236
- objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
1237
- if (field === "_count") {
1238
- const subJson = this.buildCountJson(relationModel, eb, relationModelAlias, value);
1239
- return [
1240
- sql2.lit(field),
1241
- subJson
1242
- ];
1243
- } else {
1244
- const fieldDef = requireField(this.schema, relationModel, field);
1245
- const fieldValue = fieldDef.relation ? eb.ref(`${parentResultName}$${field}.$data`) : this.fieldRef(relationModel, field, eb, relationModelAlias, false);
1246
- return [
1247
- sql2.lit(field),
1248
- fieldValue
1249
- ];
1250
- }
1251
- }).flatMap((v) => v));
1252
- }
1253
- if (typeof payload === "object" && payload.include && typeof payload.include === "object") {
1254
- objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field]) => [
1255
- sql2.lit(field),
1256
- // reference the synthesized JSON field
1257
- eb.ref(`${parentResultName}$${field}.$data`)
1258
- ]).flatMap((v) => v));
1259
- }
1260
- return objArgs;
1261
- }
1262
- buildRelationJoins(query, relationModel, relationModelAlias, payload, parentResultName) {
1263
- let result = query;
1264
- if (typeof payload === "object") {
1265
- const selectInclude = payload.include ?? payload.select;
1266
- if (selectInclude && typeof selectInclude === "object") {
1267
- Object.entries(selectInclude).filter(([, value]) => value).filter(([field]) => isRelationField(this.schema, relationModel, field)).forEach(([field, value]) => {
1268
- result = this.buildRelationJSON(relationModel, result, field, relationModelAlias, value, `${parentResultName}$${field}`);
1269
- });
1270
- }
1271
- }
1272
- return result;
1273
- }
1274
- buildSkipTake(query, skip, take) {
1275
- if (take !== void 0) {
1276
- query = query.limit(take);
1277
- }
1278
- if (skip !== void 0) {
1279
- query = query.offset(skip);
1280
- }
1281
- return query;
1282
- }
1283
- buildJsonObject(eb, value) {
1284
- return eb.fn("jsonb_build_object", Object.entries(value).flatMap(([key, value2]) => [
1285
- sql2.lit(key),
1286
- value2
1287
- ]));
1288
- }
1289
- get supportsUpdateWithLimit() {
1290
- return false;
1291
- }
1292
- get supportsDeleteWithLimit() {
1293
- return false;
1294
- }
1295
- get supportsDistinctOn() {
1296
- return true;
1297
- }
1298
- buildArrayLength(eb, array) {
1299
- return eb.fn("array_length", [
1300
- array
1301
- ]);
1302
- }
1303
- buildArrayLiteralSQL(values) {
1304
- if (values.length === 0) {
1305
- return "{}";
1306
- } else {
1307
- return `ARRAY[${values.map((v) => typeof v === "string" ? `'${v}'` : v)}]`;
1308
- }
1309
- }
1310
- get supportInsertWithDefault() {
1311
- return true;
1312
- }
1313
- getFieldSqlType(fieldDef) {
1314
- if (fieldDef.relation) {
1315
- throw new QueryError("Cannot get SQL type of a relation field");
1316
- }
1317
- let result;
1318
- if (this.schema.enums?.[fieldDef.type]) {
1319
- result = "text";
1320
- } else {
1321
- result = match3(fieldDef.type).with("String", () => "text").with("Boolean", () => "boolean").with("Int", () => "integer").with("BigInt", () => "bigint").with("Float", () => "double precision").with("Decimal", () => "decimal").with("DateTime", () => "timestamp").with("Bytes", () => "bytea").with("Json", () => "jsonb").otherwise(() => "text");
1322
- }
1323
- if (fieldDef.array) {
1324
- result += "[]";
1325
- }
1326
- return result;
1327
- }
1328
- getStringCasingBehavior() {
1329
- return {
1330
- supportsILike: true,
1331
- likeCaseSensitive: true
1332
- };
1333
- }
1334
- };
1335
-
1336
- // src/client/crud/dialects/sqlite.ts
1337
- import { invariant as invariant4 } from "@zenstackhq/common-helpers";
1338
- import Decimal2 from "decimal.js";
1339
- import { sql as sql3 } from "kysely";
1340
- import { match as match4 } from "ts-pattern";
1341
- var SqliteCrudDialect = class extends BaseCrudDialect {
1342
- static {
1343
- __name(this, "SqliteCrudDialect");
1344
- }
1345
- get provider() {
1346
- return "sqlite";
1347
- }
1348
- transformPrimitive(value, type, _forArrayField) {
1349
- if (value === void 0) {
1350
- return value;
1351
- }
1352
- if (Array.isArray(value)) {
1353
- return value.map((v) => this.transformPrimitive(v, type, false));
1354
- } else {
1355
- if (this.schema.typeDefs && type in this.schema.typeDefs) {
1356
- return JSON.stringify(value);
1357
- } else {
1358
- return match4(type).with("Boolean", () => value ? 1 : 0).with("DateTime", () => value instanceof Date ? value.toISOString() : typeof value === "string" ? new Date(value).toISOString() : value).with("Decimal", () => value.toString()).with("Bytes", () => Buffer.from(value)).with("Json", () => JSON.stringify(value)).otherwise(() => value);
1359
- }
1360
- }
1361
- }
1362
- transformOutput(value, type) {
1363
- if (value === null || value === void 0) {
1364
- return value;
1365
- } else if (this.schema.typeDefs && type in this.schema.typeDefs) {
1366
- return this.transformOutputJson(value);
1367
- } else {
1368
- return match4(type).with("Boolean", () => this.transformOutputBoolean(value)).with("DateTime", () => this.transformOutputDate(value)).with("Bytes", () => this.transformOutputBytes(value)).with("Decimal", () => this.transformOutputDecimal(value)).with("BigInt", () => this.transformOutputBigInt(value)).with("Json", () => this.transformOutputJson(value)).otherwise(() => super.transformOutput(value, type));
1369
- }
1370
- }
1371
- transformOutputDecimal(value) {
1372
- if (value instanceof Decimal2) {
1373
- return value;
1374
- }
1375
- invariant4(typeof value === "string" || typeof value === "number" || value instanceof Decimal2, `Expected string, number or Decimal, got ${typeof value}`);
1376
- return new Decimal2(value);
1377
- }
1378
- transformOutputBigInt(value) {
1379
- if (typeof value === "bigint") {
1380
- return value;
1381
- }
1382
- invariant4(typeof value === "string" || typeof value === "number", `Expected string or number, got ${typeof value}`);
1383
- return BigInt(value);
1384
- }
1385
- transformOutputBoolean(value) {
1386
- return !!value;
1387
- }
1388
- transformOutputDate(value) {
1389
- if (typeof value === "number") {
1390
- return new Date(value);
1391
- } else if (typeof value === "string") {
1392
- return new Date(value);
1393
- } else {
1394
- return value;
1395
- }
1396
- }
1397
- transformOutputBytes(value) {
1398
- return Buffer.isBuffer(value) ? Uint8Array.from(value) : value;
1399
- }
1400
- transformOutputJson(value) {
1401
- if (typeof value === "string") {
1402
- try {
1403
- return JSON.parse(value);
1404
- } catch (e) {
1405
- throw new QueryError("Invalid JSON returned", e);
1406
- }
1407
- }
1408
- return value;
1409
- }
1410
- buildRelationSelection(query, model, relationField, parentAlias, payload) {
1411
- return query.select((eb) => this.buildRelationJSON(model, eb, relationField, parentAlias, payload).as(relationField));
1412
- }
1413
- buildRelationJSON(model, eb, relationField, parentAlias, payload) {
1414
- const relationFieldDef = requireField(this.schema, model, relationField);
1415
- const relationModel = relationFieldDef.type;
1416
- const relationModelDef = requireModel(this.schema, relationModel);
1417
- const subQueryName = `${parentAlias}$${relationField}`;
1418
- let tbl;
1419
- if (this.canJoinWithoutNestedSelect(relationModelDef, payload)) {
1420
- tbl = this.buildModelSelect(eb, relationModel, subQueryName, payload, false);
1421
- tbl = this.buildRelationJoinFilter(tbl, model, relationField, subQueryName, parentAlias);
1422
- } else {
1423
- tbl = eb.selectFrom(() => {
1424
- const selectModelAlias = `${parentAlias}$${relationField}$sub`;
1425
- let selectModelQuery = this.buildModelSelect(eb, relationModel, selectModelAlias, payload, true);
1426
- selectModelQuery = this.buildRelationJoinFilter(selectModelQuery, model, relationField, selectModelAlias, parentAlias);
1427
- return selectModelQuery.as(subQueryName);
1428
- });
1429
- }
1430
- tbl = tbl.select(() => {
1431
- const objArgs = [];
1432
- const descendantModels = getDelegateDescendantModels(this.schema, relationModel);
1433
- if (descendantModels.length > 0) {
1434
- objArgs.push(...descendantModels.map((subModel) => [
1435
- sql3.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`),
1436
- eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)
1437
- ]).flatMap((v) => v));
1438
- }
1439
- if (payload === true || !payload.select) {
1440
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !(typeof payload === "object" && payload.omit?.[name] === true)).map(([field]) => [
1441
- sql3.lit(field),
1442
- this.fieldRef(relationModel, field, eb, subQueryName, false)
1443
- ]).flatMap((v) => v));
1444
- } else if (payload.select) {
1445
- objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
1446
- if (field === "_count") {
1447
- const subJson = this.buildCountJson(relationModel, eb, `${parentAlias}$${relationField}`, value);
1448
- return [
1449
- sql3.lit(field),
1450
- subJson
1451
- ];
1452
- } else {
1453
- const fieldDef = requireField(this.schema, relationModel, field);
1454
- if (fieldDef.relation) {
1455
- const subJson = this.buildRelationJSON(relationModel, eb, field, `${parentAlias}$${relationField}`, value);
1456
- return [
1457
- sql3.lit(field),
1458
- subJson
1459
- ];
1460
- } else {
1461
- return [
1462
- sql3.lit(field),
1463
- this.fieldRef(relationModel, field, eb, subQueryName, false)
1464
- ];
1465
- }
1466
- }
1467
- }).flatMap((v) => v));
1468
- }
1469
- if (typeof payload === "object" && payload.include && typeof payload.include === "object") {
1470
- objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
1471
- const subJson = this.buildRelationJSON(relationModel, eb, field, `${parentAlias}$${relationField}`, value);
1472
- return [
1473
- sql3.lit(field),
1474
- subJson
1475
- ];
1476
- }).flatMap((v) => v));
1477
- }
1478
- if (relationFieldDef.array) {
1479
- return eb.fn.coalesce(sql3`json_group_array(json_object(${sql3.join(objArgs)}))`, sql3`json_array()`).as("$data");
1480
- } else {
1481
- return sql3`json_object(${sql3.join(objArgs)})`.as("$data");
1482
- }
1483
- });
1484
- return tbl;
1485
- }
1486
- buildRelationJoinFilter(selectModelQuery, model, relationField, relationModelAlias, parentAlias) {
1487
- const fieldDef = requireField(this.schema, model, relationField);
1488
- const relationModel = fieldDef.type;
1489
- const m2m = getManyToManyRelation(this.schema, model, relationField);
1490
- if (m2m) {
1491
- const parentIds = requireIdFields(this.schema, model);
1492
- const relationIds = requireIdFields(this.schema, relationModel);
1493
- invariant4(parentIds.length === 1, "many-to-many relation must have exactly one id field");
1494
- invariant4(relationIds.length === 1, "many-to-many relation must have exactly one id field");
1495
- selectModelQuery = selectModelQuery.where((eb) => eb(eb.ref(`${relationModelAlias}.${relationIds[0]}`), "in", eb.selectFrom(m2m.joinTable).select(`${m2m.joinTable}.${m2m.otherFkName}`).whereRef(`${parentAlias}.${parentIds[0]}`, "=", `${m2m.joinTable}.${m2m.parentFkName}`)));
1496
- } else {
1497
- const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(this.schema, model, relationField);
1498
- keyPairs.forEach(({ fk, pk }) => {
1499
- if (ownedByModel) {
1500
- selectModelQuery = selectModelQuery.whereRef(`${relationModelAlias}.${pk}`, "=", `${parentAlias}.${fk}`);
1501
- } else {
1502
- selectModelQuery = selectModelQuery.whereRef(`${relationModelAlias}.${fk}`, "=", `${parentAlias}.${pk}`);
1503
- }
1504
- });
1505
- }
1506
- return selectModelQuery;
1507
- }
1508
- buildSkipTake(query, skip, take) {
1509
- if (take !== void 0) {
1510
- query = query.limit(take);
1511
- }
1512
- if (skip !== void 0) {
1513
- query = query.offset(skip);
1514
- if (take === void 0) {
1515
- query = query.limit(-1);
1516
- }
1517
- }
1518
- return query;
1519
- }
1520
- buildJsonObject(eb, value) {
1521
- return eb.fn("json_object", Object.entries(value).flatMap(([key, value2]) => [
1522
- sql3.lit(key),
1523
- value2
1524
- ]));
1525
- }
1526
- get supportsUpdateWithLimit() {
1527
- return false;
1528
- }
1529
- get supportsDeleteWithLimit() {
1530
- return false;
1531
- }
1532
- get supportsDistinctOn() {
1533
- return false;
1534
- }
1535
- buildArrayLength(eb, array) {
1536
- return eb.fn("json_array_length", [
1537
- array
1538
- ]);
1539
- }
1540
- buildArrayLiteralSQL(_values) {
1541
- throw new Error("SQLite does not support array literals");
1542
- }
1543
- get supportInsertWithDefault() {
1544
- return false;
1545
- }
1546
- getFieldSqlType(fieldDef) {
1547
- if (fieldDef.relation) {
1548
- throw new QueryError("Cannot get SQL type of a relation field");
1549
- }
1550
- if (fieldDef.array) {
1551
- throw new QueryError("SQLite does not support scalar list type");
1552
- }
1553
- if (this.schema.enums?.[fieldDef.type]) {
1554
- return "text";
1555
- }
1556
- return match4(fieldDef.type).with("String", () => "text").with("Boolean", () => "integer").with("Int", () => "integer").with("BigInt", () => "integer").with("Float", () => "real").with("Decimal", () => "decimal").with("DateTime", () => "numeric").with("Bytes", () => "blob").with("Json", () => "jsonb").otherwise(() => "text");
1557
- }
1558
- getStringCasingBehavior() {
1559
- return {
1560
- supportsILike: false,
1561
- likeCaseSensitive: false
1562
- };
1563
- }
1564
- };
1565
-
1566
- // src/client/crud/dialects/index.ts
1567
- function getCrudDialect(schema, options) {
1568
- return match5(schema.provider.type).with("sqlite", () => new SqliteCrudDialect(schema, options)).with("postgresql", () => new PostgresCrudDialect(schema, options)).exhaustive();
1569
- }
1570
- __name(getCrudDialect, "getCrudDialect");
1571
-
1572
- // src/utils/default-operation-node-visitor.ts
1573
- import { OperationNodeVisitor } from "kysely";
1574
- var DefaultOperationNodeVisitor = class extends OperationNodeVisitor {
1575
- static {
1576
- __name(this, "DefaultOperationNodeVisitor");
1577
- }
1578
- defaultVisit(node) {
1579
- Object.values(node).forEach((value) => {
1580
- if (!value) {
1581
- return;
1582
- }
1583
- if (Array.isArray(value)) {
1584
- value.forEach((el) => this.defaultVisit(el));
1585
- }
1586
- if (typeof value === "object" && "kind" in value && typeof value.kind === "string") {
1587
- this.visitNode(value);
1588
- }
1589
- });
1590
- }
1591
- visitSelectQuery(node) {
1592
- this.defaultVisit(node);
1593
- }
1594
- visitSelection(node) {
1595
- this.defaultVisit(node);
1596
- }
1597
- visitColumn(node) {
1598
- this.defaultVisit(node);
1599
- }
1600
- visitAlias(node) {
1601
- this.defaultVisit(node);
1602
- }
1603
- visitTable(node) {
1604
- this.defaultVisit(node);
1605
- }
1606
- visitFrom(node) {
1607
- this.defaultVisit(node);
1608
- }
1609
- visitReference(node) {
1610
- this.defaultVisit(node);
1611
- }
1612
- visitAnd(node) {
1613
- this.defaultVisit(node);
1614
- }
1615
- visitOr(node) {
1616
- this.defaultVisit(node);
1617
- }
1618
- visitValueList(node) {
1619
- this.defaultVisit(node);
1620
- }
1621
- visitParens(node) {
1622
- this.defaultVisit(node);
1623
- }
1624
- visitJoin(node) {
1625
- this.defaultVisit(node);
1626
- }
1627
- visitRaw(node) {
1628
- this.defaultVisit(node);
1629
- }
1630
- visitWhere(node) {
1631
- this.defaultVisit(node);
1632
- }
1633
- visitInsertQuery(node) {
1634
- this.defaultVisit(node);
1635
- }
1636
- visitDeleteQuery(node) {
1637
- this.defaultVisit(node);
1638
- }
1639
- visitReturning(node) {
1640
- this.defaultVisit(node);
1641
- }
1642
- visitCreateTable(node) {
1643
- this.defaultVisit(node);
1644
- }
1645
- visitAddColumn(node) {
1646
- this.defaultVisit(node);
1647
- }
1648
- visitColumnDefinition(node) {
1649
- this.defaultVisit(node);
1650
- }
1651
- visitDropTable(node) {
1652
- this.defaultVisit(node);
1653
- }
1654
- visitOrderBy(node) {
1655
- this.defaultVisit(node);
1656
- }
1657
- visitOrderByItem(node) {
1658
- this.defaultVisit(node);
1659
- }
1660
- visitGroupBy(node) {
1661
- this.defaultVisit(node);
1662
- }
1663
- visitGroupByItem(node) {
1664
- this.defaultVisit(node);
1665
- }
1666
- visitUpdateQuery(node) {
1667
- this.defaultVisit(node);
1668
- }
1669
- visitColumnUpdate(node) {
1670
- this.defaultVisit(node);
1671
- }
1672
- visitLimit(node) {
1673
- this.defaultVisit(node);
1674
- }
1675
- visitOffset(node) {
1676
- this.defaultVisit(node);
1677
- }
1678
- visitOnConflict(node) {
1679
- this.defaultVisit(node);
1680
- }
1681
- visitOnDuplicateKey(node) {
1682
- this.defaultVisit(node);
1683
- }
1684
- visitCheckConstraint(node) {
1685
- this.defaultVisit(node);
1686
- }
1687
- visitDataType(node) {
1688
- this.defaultVisit(node);
1689
- }
1690
- visitSelectAll(node) {
1691
- this.defaultVisit(node);
1692
- }
1693
- visitIdentifier(node) {
1694
- this.defaultVisit(node);
1695
- }
1696
- visitSchemableIdentifier(node) {
1697
- this.defaultVisit(node);
1698
- }
1699
- visitValue(node) {
1700
- this.defaultVisit(node);
1701
- }
1702
- visitPrimitiveValueList(node) {
1703
- this.defaultVisit(node);
1704
- }
1705
- visitOperator(node) {
1706
- this.defaultVisit(node);
1707
- }
1708
- visitCreateIndex(node) {
1709
- this.defaultVisit(node);
1710
- }
1711
- visitDropIndex(node) {
1712
- this.defaultVisit(node);
1713
- }
1714
- visitList(node) {
1715
- this.defaultVisit(node);
1716
- }
1717
- visitPrimaryKeyConstraint(node) {
1718
- this.defaultVisit(node);
1719
- }
1720
- visitUniqueConstraint(node) {
1721
- this.defaultVisit(node);
1722
- }
1723
- visitReferences(node) {
1724
- this.defaultVisit(node);
1725
- }
1726
- visitWith(node) {
1727
- this.defaultVisit(node);
1728
- }
1729
- visitCommonTableExpression(node) {
1730
- this.defaultVisit(node);
1731
- }
1732
- visitCommonTableExpressionName(node) {
1733
- this.defaultVisit(node);
1734
- }
1735
- visitHaving(node) {
1736
- this.defaultVisit(node);
1737
- }
1738
- visitCreateSchema(node) {
1739
- this.defaultVisit(node);
1740
- }
1741
- visitDropSchema(node) {
1742
- this.defaultVisit(node);
1743
- }
1744
- visitAlterTable(node) {
1745
- this.defaultVisit(node);
1746
- }
1747
- visitDropColumn(node) {
1748
- this.defaultVisit(node);
1749
- }
1750
- visitRenameColumn(node) {
1751
- this.defaultVisit(node);
1752
- }
1753
- visitAlterColumn(node) {
1754
- this.defaultVisit(node);
1755
- }
1756
- visitModifyColumn(node) {
1757
- this.defaultVisit(node);
1758
- }
1759
- visitAddConstraint(node) {
1760
- this.defaultVisit(node);
1761
- }
1762
- visitDropConstraint(node) {
1763
- this.defaultVisit(node);
1764
- }
1765
- visitForeignKeyConstraint(node) {
1766
- this.defaultVisit(node);
1767
- }
1768
- visitCreateView(node) {
1769
- this.defaultVisit(node);
1770
- }
1771
- visitDropView(node) {
1772
- this.defaultVisit(node);
1773
- }
1774
- visitGenerated(node) {
1775
- this.defaultVisit(node);
1776
- }
1777
- visitDefaultValue(node) {
1778
- this.defaultVisit(node);
1779
- }
1780
- visitOn(node) {
1781
- this.defaultVisit(node);
1782
- }
1783
- visitValues(node) {
1784
- this.defaultVisit(node);
1785
- }
1786
- visitSelectModifier(node) {
1787
- this.defaultVisit(node);
1788
- }
1789
- visitCreateType(node) {
1790
- this.defaultVisit(node);
1791
- }
1792
- visitDropType(node) {
1793
- this.defaultVisit(node);
1794
- }
1795
- visitExplain(node) {
1796
- this.defaultVisit(node);
1797
- }
1798
- visitDefaultInsertValue(node) {
1799
- this.defaultVisit(node);
1800
- }
1801
- visitAggregateFunction(node) {
1802
- this.defaultVisit(node);
1803
- }
1804
- visitOver(node) {
1805
- this.defaultVisit(node);
1806
- }
1807
- visitPartitionBy(node) {
1808
- this.defaultVisit(node);
1809
- }
1810
- visitPartitionByItem(node) {
1811
- this.defaultVisit(node);
1812
- }
1813
- visitSetOperation(node) {
1814
- this.defaultVisit(node);
1815
- }
1816
- visitBinaryOperation(node) {
1817
- this.defaultVisit(node);
1818
- }
1819
- visitUnaryOperation(node) {
1820
- this.defaultVisit(node);
1821
- }
1822
- visitUsing(node) {
1823
- this.defaultVisit(node);
1824
- }
1825
- visitFunction(node) {
1826
- this.defaultVisit(node);
1827
- }
1828
- visitCase(node) {
1829
- this.defaultVisit(node);
1830
- }
1831
- visitWhen(node) {
1832
- this.defaultVisit(node);
1833
- }
1834
- visitJSONReference(node) {
1835
- this.defaultVisit(node);
1836
- }
1837
- visitJSONPath(node) {
1838
- this.defaultVisit(node);
1839
- }
1840
- visitJSONPathLeg(node) {
1841
- this.defaultVisit(node);
1842
- }
1843
- visitJSONOperatorChain(node) {
1844
- this.defaultVisit(node);
1845
- }
1846
- visitTuple(node) {
1847
- this.defaultVisit(node);
1848
- }
1849
- visitMergeQuery(node) {
1850
- this.defaultVisit(node);
1851
- }
1852
- visitMatched(node) {
1853
- this.defaultVisit(node);
1854
- }
1855
- visitAddIndex(node) {
1856
- this.defaultVisit(node);
1857
- }
1858
- visitCast(node) {
1859
- this.defaultVisit(node);
1860
- }
1861
- visitFetch(node) {
1862
- this.defaultVisit(node);
1863
- }
1864
- visitTop(node) {
1865
- this.defaultVisit(node);
1866
- }
1867
- visitOutput(node) {
1868
- this.defaultVisit(node);
1869
- }
1870
- };
1871
-
1872
- // src/plugins/policy/column-collector.ts
1873
- var ColumnCollector = class extends DefaultOperationNodeVisitor {
1874
- static {
1875
- __name(this, "ColumnCollector");
1876
- }
1877
- columns = [];
1878
- collect(node) {
1879
- this.columns = [];
1880
- this.visitNode(node);
1881
- return this.columns;
1882
- }
1883
- visitColumn(node) {
1884
- if (!this.columns.includes(node.column.name)) {
1885
- this.columns.push(node.column.name);
1886
- }
1887
- }
1888
- };
1889
-
1890
- // src/plugins/policy/expression-transformer.ts
1891
- import { invariant as invariant6 } from "@zenstackhq/common-helpers";
1892
- import { AliasNode as AliasNode3, BinaryOperationNode as BinaryOperationNode2, ColumnNode as ColumnNode2, expressionBuilder as expressionBuilder2, FromNode, FunctionNode as FunctionNode2, IdentifierNode, OperatorNode as OperatorNode2, ReferenceNode as ReferenceNode3, SelectionNode, SelectQueryNode, TableNode as TableNode3, ValueListNode, ValueNode as ValueNode2, WhereNode } from "kysely";
1893
- import { match as match7 } from "ts-pattern";
1894
-
1895
- // src/plugins/policy/expression-evaluator.ts
1896
- import { invariant as invariant5 } from "@zenstackhq/common-helpers";
1897
- import { match as match6 } from "ts-pattern";
1898
- var ExpressionEvaluator = class {
1899
- static {
1900
- __name(this, "ExpressionEvaluator");
1901
- }
1902
- evaluate(expression, context) {
1903
- const result = match6(expression).when(ExpressionUtils.isArray, (expr2) => this.evaluateArray(expr2, context)).when(ExpressionUtils.isBinary, (expr2) => this.evaluateBinary(expr2, context)).when(ExpressionUtils.isField, (expr2) => this.evaluateField(expr2, context)).when(ExpressionUtils.isLiteral, (expr2) => this.evaluateLiteral(expr2)).when(ExpressionUtils.isMember, (expr2) => this.evaluateMember(expr2, context)).when(ExpressionUtils.isUnary, (expr2) => this.evaluateUnary(expr2, context)).when(ExpressionUtils.isCall, (expr2) => this.evaluateCall(expr2, context)).when(ExpressionUtils.isThis, () => context.thisValue).when(ExpressionUtils.isNull, () => null).exhaustive();
1904
- return result ?? null;
1905
- }
1906
- evaluateCall(expr2, context) {
1907
- if (expr2.function === "auth") {
1908
- return context.auth;
1909
- } else {
1910
- throw new Error(`Unsupported call expression function: ${expr2.function}`);
1911
- }
1912
- }
1913
- evaluateUnary(expr2, context) {
1914
- return match6(expr2.op).with("!", () => !this.evaluate(expr2.operand, context)).exhaustive();
1915
- }
1916
- evaluateMember(expr2, context) {
1917
- let val = this.evaluate(expr2.receiver, context);
1918
- for (const member of expr2.members) {
1919
- val = val?.[member];
1920
- }
1921
- return val;
1922
- }
1923
- evaluateLiteral(expr2) {
1924
- return expr2.value;
1925
- }
1926
- evaluateField(expr2, context) {
1927
- return context.thisValue?.[expr2.field];
1928
- }
1929
- evaluateArray(expr2, context) {
1930
- return expr2.items.map((item) => this.evaluate(item, context));
1931
- }
1932
- evaluateBinary(expr2, context) {
1933
- if (expr2.op === "?" || expr2.op === "!" || expr2.op === "^") {
1934
- return this.evaluateCollectionPredicate(expr2, context);
1935
- }
1936
- const left = this.evaluate(expr2.left, context);
1937
- const right = this.evaluate(expr2.right, context);
1938
- return match6(expr2.op).with("==", () => left === right).with("!=", () => left !== right).with(">", () => left > right).with(">=", () => left >= right).with("<", () => left < right).with("<=", () => left <= right).with("&&", () => left && right).with("||", () => left || right).with("in", () => {
1939
- const _right = right ?? [];
1940
- invariant5(Array.isArray(_right), 'expected array for "in" operator');
1941
- return _right.includes(left);
1942
- }).exhaustive();
1943
- }
1944
- evaluateCollectionPredicate(expr2, context) {
1945
- const op = expr2.op;
1946
- invariant5(op === "?" || op === "!" || op === "^", 'expected "?" or "!" or "^" operator');
1947
- const left = this.evaluate(expr2.left, context);
1948
- if (!left) {
1949
- return false;
1950
- }
1951
- invariant5(Array.isArray(left), "expected array");
1952
- return match6(op).with("?", () => left.some((item) => this.evaluate(expr2.right, {
1953
- ...context,
1954
- thisValue: item
1955
- }))).with("!", () => left.every((item) => this.evaluate(expr2.right, {
1956
- ...context,
1957
- thisValue: item
1958
- }))).with("^", () => !left.some((item) => this.evaluate(expr2.right, {
1959
- ...context,
1960
- thisValue: item
1961
- }))).exhaustive();
1962
- }
1963
- };
1964
-
1965
- // src/plugins/policy/utils.ts
1966
- import { AliasNode as AliasNode2, AndNode, BinaryOperationNode, FunctionNode, OperatorNode, OrNode, ParensNode, ReferenceNode as ReferenceNode2, TableNode as TableNode2, UnaryOperationNode, ValueNode } from "kysely";
1967
- function trueNode(dialect) {
1968
- return ValueNode.createImmediate(dialect.transformPrimitive(true, "Boolean", false));
1969
- }
1970
- __name(trueNode, "trueNode");
1971
- function falseNode(dialect) {
1972
- return ValueNode.createImmediate(dialect.transformPrimitive(false, "Boolean", false));
1973
- }
1974
- __name(falseNode, "falseNode");
1975
- function isTrueNode(node) {
1976
- return ValueNode.is(node) && (node.value === true || node.value === 1);
1977
- }
1978
- __name(isTrueNode, "isTrueNode");
1979
- function isFalseNode(node) {
1980
- return ValueNode.is(node) && (node.value === false || node.value === 0);
1981
- }
1982
- __name(isFalseNode, "isFalseNode");
1983
- function conjunction(dialect, nodes) {
1984
- if (nodes.length === 0) {
1985
- return trueNode(dialect);
1986
- }
1987
- if (nodes.length === 1) {
1988
- return nodes[0];
1989
- }
1990
- if (nodes.some(isFalseNode)) {
1991
- return falseNode(dialect);
1992
- }
1993
- const items = nodes.filter((n) => !isTrueNode(n));
1994
- if (items.length === 0) {
1995
- return trueNode(dialect);
1996
- }
1997
- return items.reduce((acc, node) => AndNode.create(wrapParensIf(acc, OrNode.is), wrapParensIf(node, OrNode.is)));
1998
- }
1999
- __name(conjunction, "conjunction");
2000
- function disjunction(dialect, nodes) {
2001
- if (nodes.length === 0) {
2002
- return falseNode(dialect);
2003
- }
2004
- if (nodes.length === 1) {
2005
- return nodes[0];
2006
- }
2007
- if (nodes.some(isTrueNode)) {
2008
- return trueNode(dialect);
2009
- }
2010
- const items = nodes.filter((n) => !isFalseNode(n));
2011
- if (items.length === 0) {
2012
- return falseNode(dialect);
2013
- }
2014
- return items.reduce((acc, node) => OrNode.create(wrapParensIf(acc, AndNode.is), wrapParensIf(node, AndNode.is)));
2015
- }
2016
- __name(disjunction, "disjunction");
2017
- function logicalNot(dialect, node) {
2018
- if (isTrueNode(node)) {
2019
- return falseNode(dialect);
2020
- }
2021
- if (isFalseNode(node)) {
2022
- return trueNode(dialect);
2023
- }
2024
- return UnaryOperationNode.create(OperatorNode.create("not"), wrapParensIf(node, (n) => AndNode.is(n) || OrNode.is(n)));
2025
- }
2026
- __name(logicalNot, "logicalNot");
2027
- function wrapParensIf(node, predicate) {
2028
- return predicate(node) ? ParensNode.create(node) : node;
2029
- }
2030
- __name(wrapParensIf, "wrapParensIf");
2031
- function buildIsFalse(node, dialect) {
2032
- if (isFalseNode(node)) {
2033
- return trueNode(dialect);
2034
- } else if (isTrueNode(node)) {
2035
- return falseNode(dialect);
2036
- }
2037
- return BinaryOperationNode.create(
2038
- // coalesce so null is treated as false
2039
- FunctionNode.create("coalesce", [
2040
- node,
2041
- falseNode(dialect)
2042
- ]),
2043
- OperatorNode.create("="),
2044
- falseNode(dialect)
2045
- );
2046
- }
2047
- __name(buildIsFalse, "buildIsFalse");
2048
- function getTableName(node) {
2049
- if (!node) {
2050
- return node;
2051
- }
2052
- if (TableNode2.is(node)) {
2053
- return node.table.identifier.name;
2054
- } else if (AliasNode2.is(node)) {
2055
- return getTableName(node.node);
2056
- } else if (ReferenceNode2.is(node) && node.table) {
2057
- return getTableName(node.table);
2058
- }
2059
- return void 0;
2060
- }
2061
- __name(getTableName, "getTableName");
2062
-
2063
- // src/plugins/policy/expression-transformer.ts
2064
- function _ts_decorate(decorators, target, key, desc) {
2065
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2066
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2067
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2068
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2069
- }
2070
- __name(_ts_decorate, "_ts_decorate");
2071
- function _ts_metadata(k, v) {
2072
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2073
- }
2074
- __name(_ts_metadata, "_ts_metadata");
2075
- var expressionHandlers = /* @__PURE__ */ new Map();
2076
- function expr(kind) {
2077
- return function(_target, _propertyKey, descriptor) {
2078
- if (!expressionHandlers.get(kind)) {
2079
- expressionHandlers.set(kind, descriptor);
2080
- }
2081
- return descriptor;
2082
- };
2083
- }
2084
- __name(expr, "expr");
2085
- var ExpressionTransformer = class {
2086
- static {
2087
- __name(this, "ExpressionTransformer");
2088
- }
2089
- client;
2090
- dialect;
2091
- constructor(client) {
2092
- this.client = client;
2093
- this.dialect = getCrudDialect(this.schema, this.clientOptions);
2094
- }
2095
- get schema() {
2096
- return this.client.$schema;
2097
- }
2098
- get clientOptions() {
2099
- return this.client.$options;
2100
- }
2101
- get auth() {
2102
- return this.client.$auth;
2103
- }
2104
- get authType() {
2105
- if (!this.schema.authType) {
2106
- throw new InternalError('Schema does not have an "authType" specified');
2107
- }
2108
- return this.schema.authType;
2109
- }
2110
- transform(expression, context) {
2111
- const handler = expressionHandlers.get(expression.kind);
2112
- if (!handler) {
2113
- throw new Error(`Unsupported expression kind: ${expression.kind}`);
2114
- }
2115
- return handler.value.call(this, expression, context);
2116
- }
2117
- _literal(expr2) {
2118
- return this.transformValue(expr2.value, typeof expr2.value === "string" ? "String" : typeof expr2.value === "boolean" ? "Boolean" : "Int");
2119
- }
2120
- _array(expr2, context) {
2121
- return ValueListNode.create(expr2.items.map((item) => this.transform(item, context)));
2122
- }
2123
- _field(expr2, context) {
2124
- const fieldDef = requireField(this.schema, context.model, expr2.field);
2125
- if (!fieldDef.relation) {
2126
- return this.createColumnRef(expr2.field, context);
2127
- } else {
2128
- const { memberFilter, memberSelect, ...restContext } = context;
2129
- const relation = this.transformRelationAccess(expr2.field, fieldDef.type, restContext);
2130
- return {
2131
- ...relation,
2132
- where: this.mergeWhere(relation.where, memberFilter),
2133
- selections: memberSelect ? [
2134
- memberSelect
2135
- ] : relation.selections
2136
- };
2137
- }
2138
- }
2139
- mergeWhere(where, memberFilter) {
2140
- if (!where) {
2141
- return WhereNode.create(memberFilter ?? trueNode(this.dialect));
2142
- }
2143
- if (!memberFilter) {
2144
- return where;
2145
- }
2146
- return WhereNode.create(conjunction(this.dialect, [
2147
- where.where,
2148
- memberFilter
2149
- ]));
2150
- }
2151
- _null() {
2152
- return ValueNode2.createImmediate(null);
2153
- }
2154
- _binary(expr2, context) {
2155
- if (expr2.op === "&&") {
2156
- return conjunction(this.dialect, [
2157
- this.transform(expr2.left, context),
2158
- this.transform(expr2.right, context)
2159
- ]);
2160
- } else if (expr2.op === "||") {
2161
- return disjunction(this.dialect, [
2162
- this.transform(expr2.left, context),
2163
- this.transform(expr2.right, context)
2164
- ]);
2165
- }
2166
- if (this.isAuthCall(expr2.left) || this.isAuthCall(expr2.right)) {
2167
- return this.transformAuthBinary(expr2, context);
2168
- }
2169
- const op = expr2.op;
2170
- if (op === "?" || op === "!" || op === "^") {
2171
- return this.transformCollectionPredicate(expr2, context);
2172
- }
2173
- const { normalizedLeft, normalizedRight } = this.normalizeBinaryOperationOperands(expr2, context);
2174
- const left = this.transform(normalizedLeft, context);
2175
- const right = this.transform(normalizedRight, context);
2176
- if (op === "in") {
2177
- if (this.isNullNode(left)) {
2178
- return this.transformValue(false, "Boolean");
2179
- } else {
2180
- if (ValueListNode.is(right)) {
2181
- return BinaryOperationNode2.create(left, OperatorNode2.create("in"), right);
2182
- } else {
2183
- return BinaryOperationNode2.create(left, OperatorNode2.create("="), FunctionNode2.create("any", [
2184
- right
2185
- ]));
2186
- }
2187
- }
2188
- }
2189
- if (this.isNullNode(right)) {
2190
- return this.transformNullCheck(left, expr2.op);
2191
- } else if (this.isNullNode(left)) {
2192
- return this.transformNullCheck(right, expr2.op);
2193
- } else {
2194
- return BinaryOperationNode2.create(left, this.transformOperator(op), right);
2195
- }
2196
- }
2197
- transformNullCheck(expr2, operator) {
2198
- invariant6(operator === "==" || operator === "!=", 'operator must be "==" or "!=" for null comparison');
2199
- if (ValueNode2.is(expr2)) {
2200
- if (expr2.value === null) {
2201
- return operator === "==" ? trueNode(this.dialect) : falseNode(this.dialect);
2202
- } else {
2203
- return operator === "==" ? falseNode(this.dialect) : trueNode(this.dialect);
2204
- }
2205
- } else {
2206
- return operator === "==" ? BinaryOperationNode2.create(expr2, OperatorNode2.create("is"), ValueNode2.createImmediate(null)) : BinaryOperationNode2.create(expr2, OperatorNode2.create("is not"), ValueNode2.createImmediate(null));
2207
- }
2208
- }
2209
- normalizeBinaryOperationOperands(expr2, context) {
2210
- let normalizedLeft = expr2.left;
2211
- if (this.isRelationField(expr2.left, context.model)) {
2212
- invariant6(ExpressionUtils.isNull(expr2.right), "only null comparison is supported for relation field");
2213
- const leftRelDef = this.getFieldDefFromFieldRef(expr2.left, context.model);
2214
- invariant6(leftRelDef, "failed to get relation field definition");
2215
- const idFields = requireIdFields(this.schema, leftRelDef.type);
2216
- normalizedLeft = this.makeOrAppendMember(normalizedLeft, idFields[0]);
2217
- }
2218
- let normalizedRight = expr2.right;
2219
- if (this.isRelationField(expr2.right, context.model)) {
2220
- invariant6(ExpressionUtils.isNull(expr2.left), "only null comparison is supported for relation field");
2221
- const rightRelDef = this.getFieldDefFromFieldRef(expr2.right, context.model);
2222
- invariant6(rightRelDef, "failed to get relation field definition");
2223
- const idFields = requireIdFields(this.schema, rightRelDef.type);
2224
- normalizedRight = this.makeOrAppendMember(normalizedRight, idFields[0]);
2225
- }
2226
- return {
2227
- normalizedLeft,
2228
- normalizedRight
2229
- };
2230
- }
2231
- transformCollectionPredicate(expr2, context) {
2232
- invariant6(expr2.op === "?" || expr2.op === "!" || expr2.op === "^", 'expected "?" or "!" or "^" operator');
2233
- if (this.isAuthCall(expr2.left) || this.isAuthMember(expr2.left)) {
2234
- const value = new ExpressionEvaluator().evaluate(expr2, {
2235
- auth: this.auth
2236
- });
2237
- return this.transformValue(value, "Boolean");
2238
- }
2239
- invariant6(ExpressionUtils.isField(expr2.left) || ExpressionUtils.isMember(expr2.left), "left operand must be field or member access");
2240
- let newContextModel;
2241
- const fieldDef = this.getFieldDefFromFieldRef(expr2.left, context.model);
2242
- if (fieldDef) {
2243
- invariant6(fieldDef.relation, `field is not a relation: ${JSON.stringify(expr2.left)}`);
2244
- newContextModel = fieldDef.type;
2245
- } else {
2246
- invariant6(ExpressionUtils.isMember(expr2.left) && ExpressionUtils.isField(expr2.left.receiver), "left operand must be member access with field receiver");
2247
- const fieldDef2 = requireField(this.schema, context.model, expr2.left.receiver.field);
2248
- newContextModel = fieldDef2.type;
2249
- for (const member of expr2.left.members) {
2250
- const memberDef = requireField(this.schema, newContextModel, member);
2251
- newContextModel = memberDef.type;
2252
- }
2253
- }
2254
- let predicateFilter = this.transform(expr2.right, {
2255
- ...context,
2256
- model: newContextModel,
2257
- alias: void 0
2258
- });
2259
- if (expr2.op === "!") {
2260
- predicateFilter = logicalNot(this.dialect, predicateFilter);
2261
- }
2262
- const count = FunctionNode2.create("count", [
2263
- ValueNode2.createImmediate(1)
2264
- ]);
2265
- const predicateResult = match7(expr2.op).with("?", () => BinaryOperationNode2.create(count, OperatorNode2.create(">"), ValueNode2.createImmediate(0))).with("!", () => BinaryOperationNode2.create(count, OperatorNode2.create("="), ValueNode2.createImmediate(0))).with("^", () => BinaryOperationNode2.create(count, OperatorNode2.create("="), ValueNode2.createImmediate(0))).exhaustive();
2266
- return this.transform(expr2.left, {
2267
- ...context,
2268
- memberSelect: SelectionNode.create(AliasNode3.create(predicateResult, IdentifierNode.create("$t"))),
2269
- memberFilter: predicateFilter
2270
- });
2271
- }
2272
- transformAuthBinary(expr2, context) {
2273
- if (expr2.op !== "==" && expr2.op !== "!=") {
2274
- throw new QueryError(`Unsupported operator for \`auth()\` in policy of model "${context.model}": ${expr2.op}`);
2275
- }
2276
- let authExpr;
2277
- let other;
2278
- if (this.isAuthCall(expr2.left)) {
2279
- authExpr = expr2.left;
2280
- other = expr2.right;
2281
- } else {
2282
- authExpr = expr2.right;
2283
- other = expr2.left;
2284
- }
2285
- if (ExpressionUtils.isNull(other)) {
2286
- return this.transformValue(expr2.op === "==" ? !this.auth : !!this.auth, "Boolean");
2287
- } else {
2288
- const authModel = getModel(this.schema, this.authType);
2289
- if (!authModel) {
2290
- throw new QueryError(`Unsupported use of \`auth()\` in policy of model "${context.model}", comparing with \`auth()\` is only possible when auth type is a model`);
2291
- }
2292
- const idFields = Object.values(authModel.fields).filter((f) => f.id).map((f) => f.name);
2293
- invariant6(idFields.length > 0, "auth type model must have at least one id field");
2294
- const conditions = idFields.map((fieldName) => ExpressionUtils.binary(ExpressionUtils.member(authExpr, [
2295
- fieldName
2296
- ]), "==", this.makeOrAppendMember(other, fieldName)));
2297
- let result = this.buildAnd(conditions);
2298
- if (expr2.op === "!=") {
2299
- result = this.buildLogicalNot(result);
2300
- }
2301
- return this.transform(result, context);
2302
- }
2303
- }
2304
- makeOrAppendMember(other, fieldName) {
2305
- if (ExpressionUtils.isMember(other)) {
2306
- return ExpressionUtils.member(other.receiver, [
2307
- ...other.members,
2308
- fieldName
2309
- ]);
2310
- } else {
2311
- return ExpressionUtils.member(other, [
2312
- fieldName
2313
- ]);
2314
- }
2315
- }
2316
- transformValue(value, type) {
2317
- if (value === true) {
2318
- return trueNode(this.dialect);
2319
- } else if (value === false) {
2320
- return falseNode(this.dialect);
2321
- } else {
2322
- return ValueNode2.create(this.dialect.transformPrimitive(value, type, false) ?? null);
2323
- }
2324
- }
2325
- _unary(expr2, context) {
2326
- invariant6(expr2.op === "!", 'only "!" operator is supported');
2327
- return logicalNot(this.dialect, this.transform(expr2.operand, context));
2328
- }
2329
- transformOperator(op) {
2330
- const mappedOp = match7(op).with("==", () => "=").otherwise(() => op);
2331
- return OperatorNode2.create(mappedOp);
2332
- }
2333
- _call(expr2, context) {
2334
- const result = this.transformCall(expr2, context);
2335
- return result.toOperationNode();
2336
- }
2337
- transformCall(expr2, context) {
2338
- const func = this.getFunctionImpl(expr2.function);
2339
- if (!func) {
2340
- throw new QueryError(`Function not implemented: ${expr2.function}`);
2341
- }
2342
- const eb = expressionBuilder2();
2343
- return func(eb, (expr2.args ?? []).map((arg) => this.transformCallArg(eb, arg, context)), {
2344
- client: this.client,
2345
- dialect: this.dialect,
2346
- model: context.model,
2347
- modelAlias: context.alias ?? context.model,
2348
- operation: context.operation
2349
- });
2350
- }
2351
- getFunctionImpl(functionName) {
2352
- let func = this.clientOptions.functions?.[functionName];
2353
- if (!func) {
2354
- for (const plugin of this.clientOptions.plugins ?? []) {
2355
- if (plugin.functions?.[functionName]) {
2356
- func = plugin.functions[functionName];
2357
- break;
2358
- }
2359
- }
2360
- }
2361
- return func;
2362
- }
2363
- transformCallArg(eb, arg, context) {
2364
- if (ExpressionUtils.isLiteral(arg)) {
2365
- return eb.val(arg.value);
2366
- }
2367
- if (ExpressionUtils.isField(arg)) {
2368
- return eb.ref(arg.field);
2369
- }
2370
- if (ExpressionUtils.isCall(arg)) {
2371
- return this.transformCall(arg, context);
2372
- }
2373
- if (this.isAuthMember(arg)) {
2374
- const valNode = this.valueMemberAccess(context.auth, arg, this.authType);
2375
- return valNode ? eb.val(valNode.value) : eb.val(null);
2376
- }
2377
- throw new InternalError(`Unsupported argument expression: ${arg.kind}`);
2378
- }
2379
- _member(expr2, context) {
2380
- if (this.isAuthCall(expr2.receiver)) {
2381
- return this.valueMemberAccess(this.auth, expr2, this.authType);
2382
- }
2383
- invariant6(ExpressionUtils.isField(expr2.receiver) || ExpressionUtils.isThis(expr2.receiver), 'expect receiver to be field expression or "this"');
2384
- let members = expr2.members;
2385
- let receiver;
2386
- const { memberFilter, memberSelect, ...restContext } = context;
2387
- if (ExpressionUtils.isThis(expr2.receiver)) {
2388
- if (expr2.members.length === 1) {
2389
- return this._field(ExpressionUtils.field(expr2.members[0]), context);
2390
- } else {
2391
- const firstMemberFieldDef = requireField(this.schema, context.model, expr2.members[0]);
2392
- receiver = this.transformRelationAccess(expr2.members[0], firstMemberFieldDef.type, restContext);
2393
- members = expr2.members.slice(1);
2394
- }
2395
- } else {
2396
- receiver = this.transform(expr2.receiver, restContext);
2397
- }
2398
- invariant6(SelectQueryNode.is(receiver), "expected receiver to be select query");
2399
- let startType;
2400
- if (ExpressionUtils.isField(expr2.receiver)) {
2401
- const receiverField = requireField(this.schema, context.model, expr2.receiver.field);
2402
- startType = receiverField.type;
2403
- } else {
2404
- startType = context.model;
2405
- }
2406
- const memberFields = [];
2407
- let currType = startType;
2408
- for (const member of members) {
2409
- const fieldDef = requireField(this.schema, currType, member);
2410
- memberFields.push({
2411
- fieldDef,
2412
- fromModel: currType
2413
- });
2414
- currType = fieldDef.type;
2415
- }
2416
- let currNode = void 0;
2417
- for (let i = members.length - 1; i >= 0; i--) {
2418
- const member = members[i];
2419
- const { fieldDef, fromModel } = memberFields[i];
2420
- if (fieldDef.relation) {
2421
- const relation = this.transformRelationAccess(member, fieldDef.type, {
2422
- ...restContext,
2423
- model: fromModel,
2424
- alias: void 0
2425
- });
2426
- if (currNode) {
2427
- invariant6(SelectQueryNode.is(currNode), "expected select query node");
2428
- currNode = {
2429
- ...relation,
2430
- selections: [
2431
- SelectionNode.create(AliasNode3.create(currNode, IdentifierNode.create(members[i + 1])))
2432
- ]
2433
- };
2434
- } else {
2435
- currNode = {
2436
- ...relation,
2437
- where: this.mergeWhere(relation.where, memberFilter),
2438
- selections: memberSelect ? [
2439
- memberSelect
2440
- ] : relation.selections
2441
- };
2442
- }
2443
- } else {
2444
- invariant6(i === members.length - 1, "plain field access must be the last segment");
2445
- invariant6(!currNode, "plain field access must be the last segment");
2446
- currNode = ColumnNode2.create(member);
2447
- }
2448
- }
2449
- return {
2450
- ...receiver,
2451
- selections: [
2452
- SelectionNode.create(AliasNode3.create(currNode, IdentifierNode.create("$t")))
2453
- ]
2454
- };
2455
- }
2456
- valueMemberAccess(receiver, expr2, receiverType) {
2457
- if (!receiver) {
2458
- return ValueNode2.createImmediate(null);
2459
- }
2460
- if (expr2.members.length !== 1) {
2461
- throw new Error(`Only single member access is supported`);
2462
- }
2463
- const field = expr2.members[0];
2464
- const fieldDef = requireField(this.schema, receiverType, field);
2465
- const fieldValue = receiver[field] ?? null;
2466
- return this.transformValue(fieldValue, fieldDef.type);
2467
- }
2468
- transformRelationAccess(field, relationModel, context) {
2469
- const m2m = getManyToManyRelation(this.schema, context.model, field);
2470
- if (m2m) {
2471
- return this.transformManyToManyRelationAccess(m2m, context);
2472
- }
2473
- const fromModel = context.model;
2474
- const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(this.schema, fromModel, field);
2475
- let condition;
2476
- if (ownedByModel) {
2477
- condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode2.create(ReferenceNode3.create(ColumnNode2.create(fk), TableNode3.create(context.alias ?? fromModel)), OperatorNode2.create("="), ReferenceNode3.create(ColumnNode2.create(pk), TableNode3.create(relationModel)))));
2478
- } else {
2479
- condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => BinaryOperationNode2.create(ReferenceNode3.create(ColumnNode2.create(pk), TableNode3.create(context.alias ?? fromModel)), OperatorNode2.create("="), ReferenceNode3.create(ColumnNode2.create(fk), TableNode3.create(relationModel)))));
2480
- }
2481
- return {
2482
- kind: "SelectQueryNode",
2483
- from: FromNode.create([
2484
- TableNode3.create(relationModel)
2485
- ]),
2486
- where: WhereNode.create(condition)
2487
- };
2488
- }
2489
- transformManyToManyRelationAccess(m2m, context) {
2490
- const eb = expressionBuilder2();
2491
- const relationQuery = eb.selectFrom(m2m.otherModel).innerJoin(m2m.joinTable, (join) => join.onRef(`${m2m.otherModel}.${m2m.otherPKName}`, "=", `${m2m.joinTable}.${m2m.otherFkName}`).onRef(`${m2m.joinTable}.${m2m.parentFkName}`, "=", `${context.alias ?? context.model}.${m2m.parentPKName}`));
2492
- return relationQuery.toOperationNode();
2493
- }
2494
- createColumnRef(column, context) {
2495
- return ReferenceNode3.create(ColumnNode2.create(column), TableNode3.create(context.alias ?? context.model));
2496
- }
2497
- isAuthCall(value) {
2498
- return ExpressionUtils.isCall(value) && value.function === "auth";
2499
- }
2500
- isAuthMember(expr2) {
2501
- return ExpressionUtils.isMember(expr2) && this.isAuthCall(expr2.receiver);
2502
- }
2503
- isNullNode(node) {
2504
- return ValueNode2.is(node) && node.value === null;
2505
- }
2506
- buildLogicalNot(result) {
2507
- return ExpressionUtils.unary("!", result);
2508
- }
2509
- buildAnd(conditions) {
2510
- if (conditions.length === 0) {
2511
- return ExpressionUtils.literal(true);
2512
- } else if (conditions.length === 1) {
2513
- return conditions[0];
2514
- } else {
2515
- return conditions.reduce((acc, condition) => ExpressionUtils.binary(acc, "&&", condition));
2516
- }
2517
- }
2518
- isRelationField(expr2, model) {
2519
- const fieldDef = this.getFieldDefFromFieldRef(expr2, model);
2520
- return !!fieldDef?.relation;
2521
- }
2522
- getFieldDefFromFieldRef(expr2, model) {
2523
- if (ExpressionUtils.isField(expr2)) {
2524
- return requireField(this.schema, model, expr2.field);
2525
- } else if (ExpressionUtils.isMember(expr2) && expr2.members.length === 1 && ExpressionUtils.isThis(expr2.receiver)) {
2526
- return requireField(this.schema, model, expr2.members[0]);
2527
- } else {
2528
- return void 0;
2529
- }
2530
- }
2531
- };
2532
- _ts_decorate([
2533
- expr("literal"),
2534
- _ts_metadata("design:type", Function),
2535
- _ts_metadata("design:paramtypes", [
2536
- typeof LiteralExpression === "undefined" ? Object : LiteralExpression
2537
- ]),
2538
- _ts_metadata("design:returntype", void 0)
2539
- ], ExpressionTransformer.prototype, "_literal", null);
2540
- _ts_decorate([
2541
- expr("array"),
2542
- _ts_metadata("design:type", Function),
2543
- _ts_metadata("design:paramtypes", [
2544
- typeof ArrayExpression === "undefined" ? Object : ArrayExpression,
2545
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
2546
- ]),
2547
- _ts_metadata("design:returntype", void 0)
2548
- ], ExpressionTransformer.prototype, "_array", null);
2549
- _ts_decorate([
2550
- expr("field"),
2551
- _ts_metadata("design:type", Function),
2552
- _ts_metadata("design:paramtypes", [
2553
- typeof FieldExpression === "undefined" ? Object : FieldExpression,
2554
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
2555
- ]),
2556
- _ts_metadata("design:returntype", void 0)
2557
- ], ExpressionTransformer.prototype, "_field", null);
2558
- _ts_decorate([
2559
- expr("null"),
2560
- _ts_metadata("design:type", Function),
2561
- _ts_metadata("design:paramtypes", []),
2562
- _ts_metadata("design:returntype", void 0)
2563
- ], ExpressionTransformer.prototype, "_null", null);
2564
- _ts_decorate([
2565
- expr("binary"),
2566
- _ts_metadata("design:type", Function),
2567
- _ts_metadata("design:paramtypes", [
2568
- typeof BinaryExpression === "undefined" ? Object : BinaryExpression,
2569
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
2570
- ]),
2571
- _ts_metadata("design:returntype", void 0)
2572
- ], ExpressionTransformer.prototype, "_binary", null);
2573
- _ts_decorate([
2574
- expr("unary"),
2575
- _ts_metadata("design:type", Function),
2576
- _ts_metadata("design:paramtypes", [
2577
- typeof UnaryExpression === "undefined" ? Object : UnaryExpression,
2578
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
2579
- ]),
2580
- _ts_metadata("design:returntype", void 0)
2581
- ], ExpressionTransformer.prototype, "_unary", null);
2582
- _ts_decorate([
2583
- expr("call"),
2584
- _ts_metadata("design:type", Function),
2585
- _ts_metadata("design:paramtypes", [
2586
- typeof CallExpression === "undefined" ? Object : CallExpression,
2587
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
2588
- ]),
2589
- _ts_metadata("design:returntype", void 0)
2590
- ], ExpressionTransformer.prototype, "_call", null);
2591
- _ts_decorate([
2592
- expr("member"),
2593
- _ts_metadata("design:type", Function),
2594
- _ts_metadata("design:paramtypes", [
2595
- typeof MemberExpression === "undefined" ? Object : MemberExpression,
2596
- typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
2597
- ]),
2598
- _ts_metadata("design:returntype", void 0)
2599
- ], ExpressionTransformer.prototype, "_member", null);
2600
-
2601
- // src/plugins/policy/policy-handler.ts
2602
- var PolicyHandler = class extends OperationNodeTransformer {
2603
- static {
2604
- __name(this, "PolicyHandler");
2605
- }
2606
- client;
2607
- dialect;
2608
- constructor(client) {
2609
- super(), this.client = client;
2610
- this.dialect = getCrudDialect(this.client.$schema, this.client.$options);
2611
- }
2612
- get kysely() {
2613
- return this.client.$qb;
2614
- }
2615
- async handle(node, proceed) {
2616
- if (!this.isCrudQueryNode(node)) {
2617
- throw new RejectedByPolicyError(void 0, RejectedByPolicyReason.OTHER, "non-CRUD queries are not allowed");
2618
- }
2619
- if (!this.isMutationQueryNode(node)) {
2620
- return proceed(this.transformNode(node));
2621
- }
2622
- const { mutationModel } = this.getMutationModel(node);
2623
- if (InsertQueryNode.is(node)) {
2624
- const isManyToManyJoinTable = this.isManyToManyJoinTable(mutationModel);
2625
- let needCheckPreCreate = true;
2626
- if (!isManyToManyJoinTable) {
2627
- const constCondition = this.tryGetConstantPolicy(mutationModel, "create");
2628
- if (constCondition === true) {
2629
- needCheckPreCreate = false;
2630
- } else if (constCondition === false) {
2631
- throw new RejectedByPolicyError(mutationModel);
2632
- }
2633
- }
2634
- if (needCheckPreCreate) {
2635
- await this.enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed);
2636
- }
2637
- }
2638
- const result = await proceed(this.transformNode(node));
2639
- if (!node.returning || this.onlyReturningId(node)) {
2640
- return result;
2641
- } else {
2642
- const readBackResult = await this.processReadBack(node, result, proceed);
2643
- if (readBackResult.rows.length !== result.rows.length) {
2644
- throw new RejectedByPolicyError(mutationModel, RejectedByPolicyReason.CANNOT_READ_BACK, "result is not allowed to be read back");
2645
- }
2646
- return readBackResult;
2647
- }
2648
- }
2649
- // #region overrides
2650
- transformSelectQuery(node) {
2651
- let whereNode = this.transformNode(node.where);
2652
- const policyFilter = this.createPolicyFilterForFrom(node.from);
2653
- if (policyFilter) {
2654
- whereNode = WhereNode2.create(whereNode?.where ? conjunction(this.dialect, [
2655
- whereNode.where,
2656
- policyFilter
2657
- ]) : policyFilter);
2658
- }
2659
- const baseResult = super.transformSelectQuery({
2660
- ...node,
2661
- where: void 0
2662
- });
2663
- return {
2664
- ...baseResult,
2665
- where: whereNode
2666
- };
2667
- }
2668
- transformJoin(node) {
2669
- const table = this.extractTableName(node.table);
2670
- if (!table) {
2671
- return super.transformJoin(node);
2672
- }
2673
- const filter = this.buildPolicyFilter(table.model, table.alias, "read");
2674
- const nestedSelect = {
2675
- kind: "SelectQueryNode",
2676
- from: FromNode2.create([
2677
- node.table
2678
- ]),
2679
- selections: [
2680
- SelectionNode2.createSelectAll()
2681
- ],
2682
- where: WhereNode2.create(filter)
2683
- };
2684
- return {
2685
- ...node,
2686
- table: AliasNode4.create(ParensNode2.create(nestedSelect), IdentifierNode2.create(table.alias ?? table.model))
2687
- };
2688
- }
2689
- transformInsertQuery(node) {
2690
- let onConflict = node.onConflict;
2691
- if (onConflict?.updates) {
2692
- const { mutationModel, alias } = this.getMutationModel(node);
2693
- const filter = this.buildPolicyFilter(mutationModel, alias, "update");
2694
- if (onConflict.updateWhere) {
2695
- onConflict = {
2696
- ...onConflict,
2697
- updateWhere: WhereNode2.create(conjunction(this.dialect, [
2698
- onConflict.updateWhere.where,
2699
- filter
2700
- ]))
2701
- };
2702
- } else {
2703
- onConflict = {
2704
- ...onConflict,
2705
- updateWhere: WhereNode2.create(filter)
2706
- };
2707
- }
2708
- }
2709
- const processedNode = onConflict ? {
2710
- ...node,
2711
- onConflict
2712
- } : node;
2713
- const result = super.transformInsertQuery(processedNode);
2714
- if (!node.returning) {
2715
- return result;
2716
- }
2717
- if (this.onlyReturningId(node)) {
2718
- return result;
2719
- } else {
2720
- const { mutationModel } = this.getMutationModel(node);
2721
- const idFields = requireIdFields(this.client.$schema, mutationModel);
2722
- return {
2723
- ...result,
2724
- returning: ReturningNode.create(idFields.map((field) => SelectionNode2.create(ColumnNode3.create(field))))
2725
- };
2726
- }
2727
- }
2728
- transformUpdateQuery(node) {
2729
- const result = super.transformUpdateQuery(node);
2730
- const { mutationModel, alias } = this.getMutationModel(node);
2731
- let filter = this.buildPolicyFilter(mutationModel, alias, "update");
2732
- if (node.from) {
2733
- const joinFilter = this.createPolicyFilterForFrom(node.from);
2734
- if (joinFilter) {
2735
- filter = conjunction(this.dialect, [
2736
- filter,
2737
- joinFilter
2738
- ]);
2739
- }
2740
- }
2741
- return {
2742
- ...result,
2743
- where: WhereNode2.create(result.where ? conjunction(this.dialect, [
2744
- result.where.where,
2745
- filter
2746
- ]) : filter)
2747
- };
2748
- }
2749
- transformDeleteQuery(node) {
2750
- const result = super.transformDeleteQuery(node);
2751
- const { mutationModel, alias } = this.getMutationModel(node);
2752
- let filter = this.buildPolicyFilter(mutationModel, alias, "delete");
2753
- if (node.using) {
2754
- const joinFilter = this.createPolicyFilterForTables(node.using.tables);
2755
- if (joinFilter) {
2756
- filter = conjunction(this.dialect, [
2757
- filter,
2758
- joinFilter
2759
- ]);
2760
- }
2761
- }
2762
- return {
2763
- ...result,
2764
- where: WhereNode2.create(result.where ? conjunction(this.dialect, [
2765
- result.where.where,
2766
- filter
2767
- ]) : filter)
2768
- };
2769
- }
2770
- // #endregion
2771
- // #region helpers
2772
- onlyReturningId(node) {
2773
- if (!node.returning) {
2774
- return true;
2775
- }
2776
- const { mutationModel } = this.getMutationModel(node);
2777
- const idFields = requireIdFields(this.client.$schema, mutationModel);
2778
- const collector = new ColumnCollector();
2779
- const selectedColumns = collector.collect(node.returning);
2780
- return selectedColumns.every((c) => idFields.includes(c));
2781
- }
2782
- async enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed) {
2783
- const fields = node.columns?.map((c) => c.column.name) ?? [];
2784
- const valueRows = node.values ? this.unwrapCreateValueRows(node.values, mutationModel, fields, isManyToManyJoinTable) : [
2785
- []
2786
- ];
2787
- for (const values of valueRows) {
2788
- if (isManyToManyJoinTable) {
2789
- await this.enforcePreCreatePolicyForManyToManyJoinTable(mutationModel, fields, values.map((v) => v.node), proceed);
2790
- } else {
2791
- await this.enforcePreCreatePolicyForOne(mutationModel, fields, values.map((v) => v.node), proceed);
2792
- }
2793
- }
2794
- }
2795
- async enforcePreCreatePolicyForManyToManyJoinTable(tableName, fields, values, proceed) {
2796
- const m2m = this.resolveManyToManyJoinTable(tableName);
2797
- invariant7(m2m);
2798
- invariant7(fields.includes("A") && fields.includes("B"), "many-to-many join table must have A and B fk fields");
2799
- const aIndex = fields.indexOf("A");
2800
- const aNode = values[aIndex];
2801
- const bIndex = fields.indexOf("B");
2802
- const bNode = values[bIndex];
2803
- invariant7(ValueNode3.is(aNode) && ValueNode3.is(bNode), "A and B values must be ValueNode");
2804
- const aValue = aNode.value;
2805
- const bValue = bNode.value;
2806
- invariant7(aValue !== null && aValue !== void 0, "A value cannot be null or undefined");
2807
- invariant7(bValue !== null && bValue !== void 0, "B value cannot be null or undefined");
2808
- const eb = expressionBuilder3();
2809
- const filterA = this.buildPolicyFilter(m2m.firstModel, void 0, "update");
2810
- const queryA = eb.selectFrom(m2m.firstModel).where(eb(eb.ref(`${m2m.firstModel}.${m2m.firstIdField}`), "=", aValue)).select(() => new ExpressionWrapper(filterA).as("$t"));
2811
- const filterB = this.buildPolicyFilter(m2m.secondModel, void 0, "update");
2812
- const queryB = eb.selectFrom(m2m.secondModel).where(eb(eb.ref(`${m2m.secondModel}.${m2m.secondIdField}`), "=", bValue)).select(() => new ExpressionWrapper(filterB).as("$t"));
2813
- const queryNode = {
2814
- kind: "SelectQueryNode",
2815
- selections: [
2816
- SelectionNode2.create(AliasNode4.create(queryA.toOperationNode(), IdentifierNode2.create("$conditionA"))),
2817
- SelectionNode2.create(AliasNode4.create(queryB.toOperationNode(), IdentifierNode2.create("$conditionB")))
2818
- ]
2819
- };
2820
- const result = await proceed(queryNode);
2821
- if (!result.rows[0]?.$conditionA) {
2822
- throw new RejectedByPolicyError(m2m.firstModel, RejectedByPolicyReason.CANNOT_READ_BACK, `many-to-many relation participant model "${m2m.firstModel}" not updatable`);
2823
- }
2824
- if (!result.rows[0]?.$conditionB) {
2825
- throw new RejectedByPolicyError(m2m.secondModel, RejectedByPolicyReason.NO_ACCESS, `many-to-many relation participant model "${m2m.secondModel}" not updatable`);
2826
- }
2827
- }
2828
- async enforcePreCreatePolicyForOne(model, fields, values, proceed) {
2829
- const allFields = Object.entries(requireModel(this.client.$schema, model).fields).filter(([, def]) => !def.relation);
2830
- const allValues = [];
2831
- for (const [name, _def] of allFields) {
2832
- const index = fields.indexOf(name);
2833
- if (index >= 0) {
2834
- allValues.push(values[index]);
2835
- } else {
2836
- allValues.push(ValueNode3.createImmediate(null));
2837
- }
2838
- }
2839
- const eb = expressionBuilder3();
2840
- const constTable = {
2841
- kind: "SelectQueryNode",
2842
- from: FromNode2.create([
2843
- AliasNode4.create(ParensNode2.create(ValuesNode.create([
2844
- ValueListNode2.create(allValues)
2845
- ])), IdentifierNode2.create("$t"))
2846
- ]),
2847
- selections: allFields.map(([name, def], index) => {
2848
- const castedColumnRef = sql4`CAST(${eb.ref(`column${index + 1}`)} as ${sql4.raw(this.dialect.getFieldSqlType(def))})`.as(name);
2849
- return SelectionNode2.create(castedColumnRef.toOperationNode());
2850
- })
2851
- };
2852
- const filter = this.buildPolicyFilter(model, void 0, "create");
2853
- const preCreateCheck = {
2854
- kind: "SelectQueryNode",
2855
- from: FromNode2.create([
2856
- AliasNode4.create(constTable, IdentifierNode2.create(model))
2857
- ]),
2858
- selections: [
2859
- SelectionNode2.create(AliasNode4.create(BinaryOperationNode3.create(FunctionNode3.create("COUNT", [
2860
- ValueNode3.createImmediate(1)
2861
- ]), OperatorNode3.create(">"), ValueNode3.createImmediate(0)), IdentifierNode2.create("$condition")))
2862
- ],
2863
- where: WhereNode2.create(filter)
2864
- };
2865
- const result = await proceed(preCreateCheck);
2866
- if (!result.rows[0]?.$condition) {
2867
- throw new RejectedByPolicyError(model);
2868
- }
2869
- }
2870
- unwrapCreateValueRows(node, model, fields, isManyToManyJoinTable) {
2871
- if (ValuesNode.is(node)) {
2872
- return node.values.map((v) => this.unwrapCreateValueRow(v.values, model, fields, isManyToManyJoinTable));
2873
- } else if (PrimitiveValueListNode.is(node)) {
2874
- return [
2875
- this.unwrapCreateValueRow(node.values, model, fields, isManyToManyJoinTable)
2876
- ];
2877
- } else {
2878
- throw new InternalError(`Unexpected node kind: ${node.kind} for unwrapping create values`);
2879
- }
2880
- }
2881
- unwrapCreateValueRow(data, model, fields, isImplicitManyToManyJoinTable) {
2882
- invariant7(data.length === fields.length, "data length must match fields length");
2883
- const result = [];
2884
- for (let i = 0; i < data.length; i++) {
2885
- const item = data[i];
2886
- if (typeof item === "object" && item && "kind" in item) {
2887
- const fieldDef = requireField(this.client.$schema, model, fields[i]);
2888
- invariant7(item.kind === "ValueNode", "expecting a ValueNode");
2889
- result.push({
2890
- node: ValueNode3.create(this.dialect.transformPrimitive(item.value, fieldDef.type, !!fieldDef.array)),
2891
- raw: item.value
2892
- });
2893
- } else {
2894
- let value = item;
2895
- if (!isImplicitManyToManyJoinTable) {
2896
- const fieldDef = requireField(this.client.$schema, model, fields[i]);
2897
- value = this.dialect.transformPrimitive(item, fieldDef.type, !!fieldDef.array);
2898
- }
2899
- if (Array.isArray(value)) {
2900
- result.push({
2901
- node: RawNode.createWithSql(this.dialect.buildArrayLiteralSQL(value)),
2902
- raw: value
2903
- });
2904
- } else {
2905
- result.push({
2906
- node: ValueNode3.create(value),
2907
- raw: value
2908
- });
2909
- }
2910
- }
2911
- }
2912
- return result;
2913
- }
2914
- tryGetConstantPolicy(model, operation) {
2915
- const policies = this.getModelPolicies(model, operation);
2916
- if (!policies.some((p) => p.kind === "allow")) {
2917
- return false;
2918
- } else if (
2919
- // unconditional deny
2920
- policies.some((p) => p.kind === "deny" && this.isTrueExpr(p.condition))
2921
- ) {
2922
- return false;
2923
- } else if (
2924
- // unconditional allow
2925
- !policies.some((p) => p.kind === "deny") && policies.some((p) => p.kind === "allow" && this.isTrueExpr(p.condition))
2926
- ) {
2927
- return true;
2928
- } else {
2929
- return void 0;
2930
- }
2931
- }
2932
- isTrueExpr(expr2) {
2933
- return ExpressionUtils.isLiteral(expr2) && expr2.value === true;
2934
- }
2935
- async processReadBack(node, result, proceed) {
2936
- if (result.rows.length === 0) {
2937
- return result;
2938
- }
2939
- if (!this.isMutationQueryNode(node) || !node.returning) {
2940
- return result;
2941
- }
2942
- const { mutationModel } = this.getMutationModel(node);
2943
- const idConditions = this.buildIdConditions(mutationModel, result.rows);
2944
- const policyFilter = this.buildPolicyFilter(mutationModel, void 0, "read");
2945
- const select = {
2946
- kind: "SelectQueryNode",
2947
- from: FromNode2.create([
2948
- TableNode4.create(mutationModel)
2949
- ]),
2950
- where: WhereNode2.create(conjunction(this.dialect, [
2951
- idConditions,
2952
- policyFilter
2953
- ])),
2954
- selections: node.returning.selections
2955
- };
2956
- const selectResult = await proceed(select);
2957
- return selectResult;
2958
- }
2959
- buildIdConditions(table, rows) {
2960
- const idFields = requireIdFields(this.client.$schema, table);
2961
- return disjunction(this.dialect, rows.map((row) => conjunction(this.dialect, idFields.map((field) => BinaryOperationNode3.create(ColumnNode3.create(field), OperatorNode3.create("="), ValueNode3.create(row[field]))))));
2962
- }
2963
- getMutationModel(node) {
2964
- const r = match8(node).when(InsertQueryNode.is, (node2) => ({
2965
- mutationModel: getTableName(node2.into),
2966
- alias: void 0
2967
- })).when(UpdateQueryNode.is, (node2) => {
2968
- if (!node2.table) {
2969
- throw new QueryError("Update query must have a table");
2970
- }
2971
- const r2 = this.extractTableName(node2.table);
2972
- return r2 ? {
2973
- mutationModel: r2.model,
2974
- alias: r2.alias
2975
- } : void 0;
2976
- }).when(DeleteQueryNode.is, (node2) => {
2977
- if (node2.from.froms.length !== 1) {
2978
- throw new QueryError("Only one from table is supported for delete");
2979
- }
2980
- const r2 = this.extractTableName(node2.from.froms[0]);
2981
- return r2 ? {
2982
- mutationModel: r2.model,
2983
- alias: r2.alias
2984
- } : void 0;
2985
- }).exhaustive();
2986
- if (!r) {
2987
- throw new InternalError(`Unable to get table name for query node: ${node}`);
2988
- }
2989
- return r;
2990
- }
2991
- isCrudQueryNode(node) {
2992
- return SelectQueryNode2.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node);
2993
- }
2994
- isMutationQueryNode(node) {
2995
- return InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node);
2996
- }
2997
- buildPolicyFilter(model, alias, operation) {
2998
- const m2mFilter = this.getModelPolicyFilterForManyToManyJoinTable(model, alias, operation);
2999
- if (m2mFilter) {
3000
- return m2mFilter;
3001
- }
3002
- const policies = this.getModelPolicies(model, operation);
3003
- if (policies.length === 0) {
3004
- return falseNode(this.dialect);
3005
- }
3006
- const allows = policies.filter((policy) => policy.kind === "allow").map((policy) => this.compilePolicyCondition(model, alias, operation, policy));
3007
- const denies = policies.filter((policy) => policy.kind === "deny").map((policy) => this.compilePolicyCondition(model, alias, operation, policy));
3008
- let combinedPolicy;
3009
- if (allows.length === 0) {
3010
- combinedPolicy = falseNode(this.dialect);
3011
- } else {
3012
- combinedPolicy = disjunction(this.dialect, allows);
3013
- if (denies.length !== 0) {
3014
- const combinedDenies = conjunction(this.dialect, denies.map((d) => buildIsFalse(d, this.dialect)));
3015
- combinedPolicy = conjunction(this.dialect, [
3016
- combinedPolicy,
3017
- combinedDenies
3018
- ]);
3019
- }
3020
- }
3021
- return combinedPolicy;
3022
- }
3023
- extractTableName(node) {
3024
- if (TableNode4.is(node)) {
3025
- return {
3026
- model: node.table.identifier.name
3027
- };
3028
- }
3029
- if (AliasNode4.is(node)) {
3030
- const inner = this.extractTableName(node.node);
3031
- if (!inner) {
3032
- return void 0;
3033
- }
3034
- return {
3035
- model: inner.model,
3036
- alias: IdentifierNode2.is(node.alias) ? node.alias.name : void 0
3037
- };
3038
- } else {
3039
- return void 0;
3040
- }
3041
- }
3042
- createPolicyFilterForFrom(node) {
3043
- if (!node) {
3044
- return void 0;
3045
- }
3046
- return this.createPolicyFilterForTables(node.froms);
3047
- }
3048
- createPolicyFilterForTables(tables) {
3049
- return tables.reduce((acc, table) => {
3050
- const extractResult = this.extractTableName(table);
3051
- if (extractResult) {
3052
- const { model, alias } = extractResult;
3053
- const filter = this.buildPolicyFilter(model, alias, "read");
3054
- return acc ? conjunction(this.dialect, [
3055
- acc,
3056
- filter
3057
- ]) : filter;
3058
- }
3059
- return acc;
3060
- }, void 0);
3061
- }
3062
- compilePolicyCondition(model, alias, operation, policy) {
3063
- return new ExpressionTransformer(this.client).transform(policy.condition, {
3064
- model,
3065
- alias,
3066
- operation,
3067
- auth: this.client.$auth
3068
- });
3069
- }
3070
- getModelPolicies(model, operation) {
3071
- const modelDef = requireModel(this.client.$schema, model);
3072
- const result = [];
3073
- const extractOperations = /* @__PURE__ */ __name((expr2) => {
3074
- invariant7(ExpressionUtils.isLiteral(expr2), "expecting a literal");
3075
- invariant7(typeof expr2.value === "string", "expecting a string literal");
3076
- return expr2.value.split(",").filter((v) => !!v).map((v) => v.trim());
3077
- }, "extractOperations");
3078
- if (modelDef.attributes) {
3079
- result.push(...modelDef.attributes.filter((attr) => attr.name === "@@allow" || attr.name === "@@deny").map((attr) => ({
3080
- kind: attr.name === "@@allow" ? "allow" : "deny",
3081
- operations: extractOperations(attr.args[0].value),
3082
- condition: attr.args[1].value
3083
- })).filter((policy) => policy.operations.includes("all") || policy.operations.includes(operation)));
3084
- }
3085
- return result;
3086
- }
3087
- resolveManyToManyJoinTable(tableName) {
3088
- for (const model of Object.values(this.client.$schema.models)) {
3089
- for (const field of Object.values(model.fields)) {
3090
- const m2m = getManyToManyRelation(this.client.$schema, model.name, field.name);
3091
- if (m2m?.joinTable === tableName) {
3092
- const sortedRecord = [
3093
- {
3094
- model: model.name,
3095
- field: field.name
3096
- },
3097
- {
3098
- model: m2m.otherModel,
3099
- field: m2m.otherField
3100
- }
3101
- ].sort(this.manyToManySorter);
3102
- const firstIdFields = requireIdFields(this.client.$schema, sortedRecord[0].model);
3103
- const secondIdFields = requireIdFields(this.client.$schema, sortedRecord[1].model);
3104
- invariant7(firstIdFields.length === 1 && secondIdFields.length === 1, "only single-field id is supported for implicit many-to-many join table");
3105
- return {
3106
- firstModel: sortedRecord[0].model,
3107
- firstField: sortedRecord[0].field,
3108
- firstIdField: firstIdFields[0],
3109
- secondModel: sortedRecord[1].model,
3110
- secondField: sortedRecord[1].field,
3111
- secondIdField: secondIdFields[0]
3112
- };
3113
- }
3114
- }
3115
- }
3116
- return void 0;
3117
- }
3118
- manyToManySorter(a, b) {
3119
- return a.model !== b.model ? a.model.localeCompare(b.model) : a.field.localeCompare(b.field);
3120
- }
3121
- isManyToManyJoinTable(tableName) {
3122
- return !!this.resolveManyToManyJoinTable(tableName);
3123
- }
3124
- getModelPolicyFilterForManyToManyJoinTable(tableName, alias, operation) {
3125
- const m2m = this.resolveManyToManyJoinTable(tableName);
3126
- if (!m2m) {
3127
- return void 0;
3128
- }
3129
- const checkForOperation = operation === "read" ? "read" : "update";
3130
- const eb = expressionBuilder3();
3131
- const joinTable = alias ?? tableName;
3132
- const aQuery = eb.selectFrom(m2m.firstModel).whereRef(`${m2m.firstModel}.${m2m.firstIdField}`, "=", `${joinTable}.A`).select(() => new ExpressionWrapper(this.buildPolicyFilter(m2m.firstModel, void 0, checkForOperation)).as("$conditionA"));
3133
- const bQuery = eb.selectFrom(m2m.secondModel).whereRef(`${m2m.secondModel}.${m2m.secondIdField}`, "=", `${joinTable}.B`).select(() => new ExpressionWrapper(this.buildPolicyFilter(m2m.secondModel, void 0, checkForOperation)).as("$conditionB"));
3134
- return eb.and([
3135
- aQuery,
3136
- bQuery
3137
- ]).toOperationNode();
3138
- }
3139
- };
3140
-
3141
- // src/plugins/policy/functions.ts
3142
- var check = /* @__PURE__ */ __name((eb, args, { client, model, modelAlias, operation }) => {
3143
- invariant8(args.length === 1 || args.length === 2, '"check" function requires 1 or 2 arguments');
3144
- const arg1Node = args[0].toOperationNode();
3145
- const arg2Node = args.length === 2 ? args[1].toOperationNode() : void 0;
3146
- if (arg2Node) {
3147
- invariant8(ValueNode4.is(arg2Node) && typeof arg2Node.value === "string", '"operation" parameter must be a string literal when provided');
3148
- invariant8(CRUD.includes(arg2Node.value), '"operation" parameter must be one of "create", "read", "update", "delete"');
3149
- }
3150
- const fieldName = extractFieldName(arg1Node);
3151
- invariant8(fieldName, 'Failed to extract field name from the first argument of "check" function');
3152
- const fieldDef = requireField(client.$schema, model, fieldName);
3153
- invariant8(fieldDef.relation, `Field "${fieldName}" is not a relation field in model "${model}"`);
3154
- invariant8(!fieldDef.array, `Field "${fieldName}" is a to-many relation, which is not supported by "check"`);
3155
- const relationModel = fieldDef.type;
3156
- const op = arg2Node ? arg2Node.value : operation;
3157
- const policyHandler = new PolicyHandler(client);
3158
- const joinPairs = buildJoinPairs(client.$schema, model, modelAlias, fieldName, relationModel);
3159
- const joinCondition = joinPairs.length === 1 ? eb(eb.ref(joinPairs[0][0]), "=", eb.ref(joinPairs[0][1])) : eb.and(joinPairs.map(([left, right]) => eb(eb.ref(left), "=", eb.ref(right))));
3160
- const policyCondition = policyHandler.buildPolicyFilter(relationModel, void 0, op);
3161
- const result = eb.selectFrom(relationModel).where(joinCondition).select(new ExpressionWrapper2(policyCondition).as("$condition"));
3162
- return result;
3163
- }, "check");
3164
-
3165
- // src/plugins/policy/plugin.ts
3166
- var PolicyPlugin = class {
3167
- static {
3168
- __name(this, "PolicyPlugin");
3169
- }
3170
- get id() {
3171
- return "policy";
3172
- }
3173
- get name() {
3174
- return "Access Policy";
3175
- }
3176
- get description() {
3177
- return "Enforces access policies defined in the schema.";
3178
- }
3179
- get functions() {
3180
- return {
3181
- check
3182
- };
3183
- }
3184
- onKyselyQuery({
3185
- query,
3186
- client,
3187
- proceed
3188
- /*, transaction*/
3189
- }) {
3190
- const handler = new PolicyHandler(client);
3191
- return handler.handle(
3192
- query,
3193
- proceed
3194
- /*, transaction*/
3195
- );
3196
- }
3197
- };
3198
- export {
3199
- PolicyPlugin,
3200
- RejectedByPolicyError,
3201
- RejectedByPolicyReason
3202
- };
3203
- //# sourceMappingURL=index.js.map