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