@cerbos/orm-prisma 4.1.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +598 -603
- package/lib/collections.d.ts +30 -0
- package/lib/collections.d.ts.map +1 -0
- package/lib/collections.js +421 -0
- package/lib/collections.js.map +1 -0
- package/lib/comparison.d.ts +24 -0
- package/lib/comparison.d.ts.map +1 -0
- package/lib/comparison.js +731 -0
- package/lib/comparison.js.map +1 -0
- package/lib/errors.d.ts +13 -0
- package/lib/errors.d.ts.map +1 -0
- package/lib/errors.js +17 -0
- package/lib/errors.js.map +1 -0
- package/lib/evaluate.d.ts +5 -0
- package/lib/evaluate.d.ts.map +1 -0
- package/lib/evaluate.js +118 -0
- package/lib/evaluate.js.map +1 -0
- package/lib/fields.d.ts +34 -0
- package/lib/fields.d.ts.map +1 -0
- package/lib/fields.js +253 -0
- package/lib/fields.js.map +1 -0
- package/lib/functions.d.ts +5 -0
- package/lib/functions.d.ts.map +1 -0
- package/lib/functions.js +408 -0
- package/lib/functions.js.map +1 -0
- package/lib/hierarchy.d.ts +6 -0
- package/lib/hierarchy.d.ts.map +1 -0
- package/lib/hierarchy.js +266 -0
- package/lib/hierarchy.js.map +1 -0
- package/lib/index.d.ts +23 -13
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +34 -2555
- package/lib/index.js.map +1 -1
- package/lib/literals.d.ts +20 -0
- package/lib/literals.d.ts.map +1 -0
- package/lib/literals.js +290 -0
- package/lib/literals.js.map +1 -0
- package/lib/mapping.d.ts +95 -0
- package/lib/mapping.d.ts.map +1 -0
- package/lib/mapping.js +316 -0
- package/lib/mapping.js.map +1 -0
- package/lib/narrowing.d.ts +12 -0
- package/lib/narrowing.d.ts.map +1 -0
- package/lib/narrowing.js +32 -0
- package/lib/narrowing.js.map +1 -0
- package/lib/plan.d.ts +49 -0
- package/lib/plan.d.ts.map +1 -0
- package/lib/plan.js +86 -0
- package/lib/plan.js.map +1 -0
- package/lib/presence.d.ts +25 -0
- package/lib/presence.d.ts.map +1 -0
- package/lib/presence.js +82 -0
- package/lib/presence.js.map +1 -0
- package/lib/regex.d.ts +33 -0
- package/lib/regex.d.ts.map +1 -0
- package/lib/regex.js +480 -0
- package/lib/regex.js.map +1 -0
- package/lib/relations.d.ts +58 -0
- package/lib/relations.d.ts.map +1 -0
- package/lib/relations.js +175 -0
- package/lib/relations.js.map +1 -0
- package/lib/rewrite.d.ts +36 -0
- package/lib/rewrite.d.ts.map +1 -0
- package/lib/rewrite.js +366 -0
- package/lib/rewrite.js.map +1 -0
- package/lib/solve.d.ts +20 -0
- package/lib/solve.d.ts.map +1 -0
- package/lib/solve.js +77 -0
- package/lib/solve.js.map +1 -0
- package/lib/strings.d.ts +12 -0
- package/lib/strings.d.ts.map +1 -0
- package/lib/strings.js +110 -0
- package/lib/strings.js.map +1 -0
- package/lib/ternary.d.ts +12 -0
- package/lib/ternary.d.ts.map +1 -0
- package/lib/ternary.js +192 -0
- package/lib/ternary.js.map +1 -0
- package/lib/timestamp.d.ts +45 -0
- package/lib/timestamp.d.ts.map +1 -0
- package/lib/timestamp.js +225 -0
- package/lib/timestamp.js.map +1 -0
- package/lib/translate.d.ts +20 -0
- package/lib/translate.d.ts.map +1 -0
- package/lib/translate.js +287 -0
- package/lib/translate.js.map +1 -0
- package/lib/types.d.ts +29 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +980 -0
- package/lib/types.js.map +1 -0
- package/lib/value.d.ts +8 -0
- package/lib/value.d.ts.map +1 -0
- package/lib/value.js +7 -0
- package/lib/value.js.map +1 -0
- package/package.json +27 -17
- package/src/adversarial.test.ts +376 -1071
- package/src/collections.ts +738 -0
- package/src/comparison.ts +1157 -0
- package/src/corpus.ts +433 -250
- package/src/errors.ts +12 -0
- package/src/evaluate.ts +170 -0
- package/src/fields.ts +373 -0
- package/src/functions.ts +548 -0
- package/src/generated/prisma-adversarial/browser.ts +10 -0
- package/src/generated/prisma-adversarial/client.ts +10 -0
- package/src/generated/prisma-adversarial/commonInputTypes.ts +116 -127
- package/src/generated/prisma-adversarial/internal/class.ts +24 -4
- package/src/generated/prisma-adversarial/internal/prismaNamespace.ts +174 -3
- package/src/generated/prisma-adversarial/internal/prismaNamespaceBrowser.ts +23 -2
- package/src/generated/prisma-adversarial/models/AdversarialBoolListElement.ts +1272 -0
- package/src/generated/prisma-adversarial/models/AdversarialInner.ts +54 -54
- package/src/generated/prisma-adversarial/models/AdversarialNumberListElement.ts +1316 -0
- package/src/generated/prisma-adversarial/models/AdversarialParent.ts +66 -66
- package/src/generated/prisma-adversarial/models/AdversarialResource.ts +435 -87
- package/src/generated/prisma-adversarial/models.ts +2 -0
- package/src/generated/prisma-adversarial-mysql/browser.ts +64 -0
- package/src/generated/prisma-adversarial-mysql/client.ts +86 -0
- package/src/generated/prisma-adversarial-mysql/commonInputTypes.ts +349 -0
- package/src/generated/prisma-adversarial-mysql/enums.ts +15 -0
- package/src/generated/prisma-adversarial-mysql/internal/class.ts +284 -0
- package/src/generated/prisma-adversarial-mysql/internal/prismaNamespace.ts +1518 -0
- package/src/generated/prisma-adversarial-mysql/internal/prismaNamespaceBrowser.ts +274 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialBoolListElement.ts +1157 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialCategory.ts +1286 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialInner.ts +1247 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialLabel.ts +1157 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialNumberListElement.ts +1201 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialParent.ts +1352 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialResource.ts +2021 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialSubCategory.ts +1286 -0
- package/src/generated/prisma-adversarial-mysql/models/AdversarialTag.ts +1190 -0
- package/src/generated/prisma-adversarial-mysql/models.ts +20 -0
- package/src/generated/prisma-adversarial-mysql-v6/client.d.ts +1 -0
- package/src/generated/prisma-adversarial-mysql-v6/default.d.ts +1 -0
- package/src/generated/prisma-adversarial-mysql-v6/edge.d.ts +1 -0
- package/src/generated/prisma-adversarial-mysql-v6/index.d.ts +13822 -0
- package/src/generated/prisma-adversarial-mysql-v6/runtime/index-browser.d.ts +370 -0
- package/src/generated/prisma-adversarial-mysql-v6/runtime/library.d.ts +3982 -0
- package/src/generated/prisma-adversarial-mysql-v6/wasm.d.ts +1 -0
- package/src/generated/prisma-adversarial-pg/browser.ts +10 -0
- package/src/generated/prisma-adversarial-pg/client.ts +10 -0
- package/src/generated/prisma-adversarial-pg/commonInputTypes.ts +118 -129
- package/src/generated/prisma-adversarial-pg/internal/class.ts +24 -4
- package/src/generated/prisma-adversarial-pg/internal/prismaNamespace.ts +174 -3
- package/src/generated/prisma-adversarial-pg/internal/prismaNamespaceBrowser.ts +23 -2
- package/src/generated/prisma-adversarial-pg/models/AdversarialBoolListElement.ts +1275 -0
- package/src/generated/prisma-adversarial-pg/models/AdversarialInner.ts +54 -54
- package/src/generated/prisma-adversarial-pg/models/AdversarialNumberListElement.ts +1319 -0
- package/src/generated/prisma-adversarial-pg/models/AdversarialParent.ts +66 -66
- package/src/generated/prisma-adversarial-pg/models/AdversarialResource.ts +435 -87
- package/src/generated/prisma-adversarial-pg/models.ts +2 -0
- package/src/generated/prisma-adversarial-pg-v6/index.d.ts +3476 -388
- package/src/generated/prisma-adversarial-v6/index.d.ts +3465 -383
- package/src/hierarchy.ts +405 -0
- package/src/index.ts +66 -3646
- package/src/literals.ts +363 -0
- package/src/mapping.ts +474 -0
- package/src/narrowing.ts +33 -0
- package/src/plan.ts +125 -0
- package/src/presence.ts +114 -0
- package/src/regex.ts +596 -0
- package/src/relations.ts +226 -0
- package/src/rewrite.ts +524 -0
- package/src/solve.ts +96 -0
- package/src/strings.ts +152 -0
- package/src/ternary.ts +359 -0
- package/src/test-setup.adversarial-url.ts +6 -3
- package/src/test-setup.adversarial.mysql.v6.ts +13 -0
- package/src/test-setup.adversarial.mysql.v7.ts +12 -0
- package/src/test-setup.adversarial.v7.ts +1 -0
- package/src/timestamp.ts +308 -0
- package/src/translate.ts +419 -0
- package/src/translator.test.ts +497 -1317
- package/src/types.ts +1310 -0
- package/src/value.ts +16 -0
package/lib/index.js
CHANGED
|
@@ -1,2581 +1,60 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.PlanKind = void 0;
|
|
3
|
+
exports.UnsupportedQueryPlanError = exports.PlanKind = void 0;
|
|
4
4
|
exports.queryPlanToPrisma = queryPlanToPrisma;
|
|
5
5
|
const core_1 = require("@cerbos/core");
|
|
6
6
|
Object.defineProperty(exports, "PlanKind", { enumerable: true, get: function () { return core_1.PlanKind; } });
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
lt: "gt",
|
|
18
|
-
gt: "lt",
|
|
19
|
-
le: "ge",
|
|
20
|
-
ge: "le",
|
|
21
|
-
};
|
|
22
|
-
const RFC3339_MILLISECOND_TIMESTAMP = /^((?!0000)\d{4})-(\d{2})-(\d{2})[Tt](?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.(\d{1,9}))?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
|
|
23
|
-
const MIN_RFC3339_TIMESTAMP_MILLISECONDS = Date.parse("0001-01-01T00:00:00.000Z");
|
|
24
|
-
const MAX_RFC3339_TIMESTAMP_MILLISECONDS = Date.parse("9999-12-31T23:59:59.999Z");
|
|
25
|
-
function normalizeRfc3339Milliseconds(value) {
|
|
26
|
-
const match = RFC3339_MILLISECOND_TIMESTAMP.exec(value);
|
|
27
|
-
const yearText = match?.[1];
|
|
28
|
-
const monthText = match?.[2];
|
|
29
|
-
const dayText = match?.[3];
|
|
30
|
-
const fraction = match?.[4] ?? "";
|
|
31
|
-
if (!yearText || !monthText || !dayText) {
|
|
32
|
-
throw new Error(`Invalid RFC 3339 timestamp value: ${value}`);
|
|
33
|
-
}
|
|
34
|
-
if ([...fraction.slice(3)].some((digit) => digit !== "0")) {
|
|
35
|
-
throw new Error(`Timestamp value exceeds millisecond precision: ${value}`);
|
|
36
|
-
}
|
|
37
|
-
const year = Number(yearText);
|
|
38
|
-
const month = Number(monthText);
|
|
39
|
-
const day = Number(dayText);
|
|
40
|
-
const calendarDate = new Date(0);
|
|
41
|
-
calendarDate.setUTCHours(0, 0, 0, 0);
|
|
42
|
-
calendarDate.setUTCFullYear(year, month - 1, day);
|
|
43
|
-
if (calendarDate.getUTCFullYear() !== year ||
|
|
44
|
-
calendarDate.getUTCMonth() !== month - 1 ||
|
|
45
|
-
calendarDate.getUTCDate() !== day) {
|
|
46
|
-
throw new Error(`Invalid RFC 3339 timestamp value: ${value}`);
|
|
47
|
-
}
|
|
48
|
-
const milliseconds = Date.parse(value);
|
|
49
|
-
if (Number.isNaN(milliseconds)) {
|
|
50
|
-
throw new Error(`Invalid RFC 3339 timestamp value: ${value}`);
|
|
51
|
-
}
|
|
52
|
-
if (milliseconds < MIN_RFC3339_TIMESTAMP_MILLISECONDS ||
|
|
53
|
-
milliseconds > MAX_RFC3339_TIMESTAMP_MILLISECONDS) {
|
|
54
|
-
throw new Error(`Timestamp value is outside CEL's supported instant range: ${value}`);
|
|
55
|
-
}
|
|
56
|
-
return new Date(milliseconds).toISOString();
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Normalize a binary comparison to field-side-first. The planner preserves policy source
|
|
60
|
-
* order, so a constant may precede the field it constrains (`1 < R.attr.x` arrives as
|
|
61
|
-
* `lt(value, variable)`) — swap the operands and mirror directional operators so downstream
|
|
62
|
-
* handlers can assume the field/expression side is first. Without this, value-first
|
|
63
|
-
* comparisons are silently inverted (#256).
|
|
64
|
-
*/
|
|
65
|
-
function normalizeBinaryOperands(operator, operands) {
|
|
66
|
-
const first = operands[0];
|
|
67
|
-
const second = operands[1];
|
|
68
|
-
if (operands.length === 2 &&
|
|
69
|
-
first !== undefined &&
|
|
70
|
-
second !== undefined &&
|
|
71
|
-
isValueOperand(first) &&
|
|
72
|
-
!isValueOperand(second)) {
|
|
73
|
-
return {
|
|
74
|
-
operator: MIRRORED_OPERATOR[operator] ?? operator,
|
|
75
|
-
operands: [second, first],
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
return { operator, operands };
|
|
79
|
-
}
|
|
80
|
-
function isNamedOperand(operand) {
|
|
81
|
-
return "name" in operand && typeof operand.name === "string";
|
|
82
|
-
}
|
|
83
|
-
function isValueOperand(operand) {
|
|
84
|
-
return "value" in operand && operand.value !== undefined;
|
|
85
|
-
}
|
|
86
|
-
function isOperatorOperand(operand) {
|
|
87
|
-
return ("operator" in operand &&
|
|
88
|
-
typeof operand.operator === "string" &&
|
|
89
|
-
"operands" in operand &&
|
|
90
|
-
Array.isArray(operand.operands));
|
|
91
|
-
}
|
|
92
|
-
function assertDefined(value, message) {
|
|
93
|
-
if (value === undefined) {
|
|
94
|
-
throw new Error(message);
|
|
95
|
-
}
|
|
96
|
-
return value;
|
|
97
|
-
}
|
|
98
|
-
// Operators whose second operand is a lambda that binds an iteration variable.
|
|
99
|
-
const LAMBDA_BINDING_OPERATORS = new Set([
|
|
100
|
-
"exists",
|
|
101
|
-
"exists_one",
|
|
102
|
-
"all",
|
|
103
|
-
"filter",
|
|
104
|
-
"map",
|
|
105
|
-
"except",
|
|
106
|
-
]);
|
|
107
|
-
/**
|
|
108
|
-
* Substitute a lambda iteration variable with a concrete collection element
|
|
109
|
-
* inside a lambda body. A bare reference to the variable becomes the element
|
|
110
|
-
* itself; a `variable.path.to.field` reference drills into the element. A
|
|
111
|
-
* nested collection macro whose lambda rebinds the same variable name shadows
|
|
112
|
-
* the outer variable, so substitution only descends into its collection
|
|
113
|
-
* operand.
|
|
114
|
-
*/
|
|
115
|
-
function substituteLambdaVariable(operand, variableName, element) {
|
|
116
|
-
if (isNamedOperand(operand)) {
|
|
117
|
-
if (operand.name === variableName) {
|
|
118
|
-
return { value: element };
|
|
119
|
-
}
|
|
120
|
-
if (operand.name.startsWith(`${variableName}.`)) {
|
|
121
|
-
let current = element;
|
|
122
|
-
for (const segment of operand.name
|
|
123
|
-
.slice(variableName.length + 1)
|
|
124
|
-
.split(".")) {
|
|
125
|
-
if (current === null ||
|
|
126
|
-
typeof current !== "object" ||
|
|
127
|
-
Array.isArray(current) ||
|
|
128
|
-
!(segment in current) ||
|
|
129
|
-
current[segment] === undefined) {
|
|
130
|
-
throw new Error(`Cannot resolve "${operand.name}": collection element has no field "${segment}"`);
|
|
131
|
-
}
|
|
132
|
-
current = current[segment];
|
|
133
|
-
}
|
|
134
|
-
return { value: current };
|
|
135
|
-
}
|
|
136
|
-
return operand;
|
|
137
|
-
}
|
|
138
|
-
if (isOperatorOperand(operand)) {
|
|
139
|
-
if (LAMBDA_BINDING_OPERATORS.has(operand.operator) &&
|
|
140
|
-
operand.operands.length === 2) {
|
|
141
|
-
const [nestedCollection, nestedLambda] = operand.operands;
|
|
142
|
-
if (nestedCollection !== undefined &&
|
|
143
|
-
nestedLambda !== undefined &&
|
|
144
|
-
isOperatorOperand(nestedLambda) &&
|
|
145
|
-
nestedLambda.operator === "lambda") {
|
|
146
|
-
const nestedVariable = nestedLambda.operands[1];
|
|
147
|
-
if (nestedVariable !== undefined &&
|
|
148
|
-
isNamedOperand(nestedVariable) &&
|
|
149
|
-
nestedVariable.name === variableName) {
|
|
150
|
-
// The nested lambda shadows our variable: substitute only in the
|
|
151
|
-
// collection operand.
|
|
152
|
-
return {
|
|
153
|
-
operator: operand.operator,
|
|
154
|
-
operands: [
|
|
155
|
-
substituteLambdaVariable(nestedCollection, variableName, element),
|
|
156
|
-
nestedLambda,
|
|
157
|
-
],
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
return {
|
|
163
|
-
operator: operand.operator,
|
|
164
|
-
operands: operand.operands.map((o) => substituteLambdaVariable(o, variableName, element)),
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
return operand;
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Fold a collection macro whose collection operand is a literal value list.
|
|
171
|
-
*
|
|
172
|
-
* The planner emits this shape when a known-value collection (typically a
|
|
173
|
-
* folded principal attribute) has more than 10 elements — at 10 or fewer it
|
|
174
|
-
* unrolls `exists`/`all` into an or/and chain itself (cerbos/cerbos#2570,
|
|
175
|
-
* cerbos/cerbos#2817; `maxItems = 10` in the planner's struct matcher). Apply
|
|
176
|
-
* the same fold here so the translated filter does not depend on which side of
|
|
177
|
-
* that threshold the collection lands: substitute each element into the lambda
|
|
178
|
-
* body and combine the per-element filters with OR (`exists`) or AND (`all`).
|
|
179
|
-
*
|
|
180
|
-
* An empty list yields `{OR: []}` / `{AND: []}`, which Prisma evaluates to
|
|
181
|
-
* match-nothing / match-everything — exactly CEL's `exists`/`all` semantics
|
|
182
|
-
* over an empty collection.
|
|
183
|
-
*/
|
|
184
|
-
function handleKnownValueCollectionOperator(operator, collection, lambda, mapper, negated) {
|
|
185
|
-
if (operator !== "exists" && operator !== "all") {
|
|
186
|
-
throw new Error(`${operator} over a literal collection value is not supported. ` +
|
|
187
|
-
"Only exists() and all() can be folded into a flat filter.");
|
|
188
|
-
}
|
|
189
|
-
const elements = collection.value;
|
|
190
|
-
if (!Array.isArray(elements)) {
|
|
191
|
-
throw new Error(`${operator} over a literal collection requires a list value`);
|
|
192
|
-
}
|
|
193
|
-
if (!isOperatorOperand(lambda) || lambda.operator !== "lambda") {
|
|
194
|
-
throw new Error(`Second operand of ${operator} must be a lambda expression`);
|
|
195
|
-
}
|
|
196
|
-
if (lambda.operands.length !== 2) {
|
|
197
|
-
throw new Error(`${operator} over a literal collection supports single-variable lambdas only`);
|
|
198
|
-
}
|
|
199
|
-
const body = assertDefined(lambda.operands[0], "Lambda expression must provide a condition");
|
|
200
|
-
const variable = assertDefined(lambda.operands[1], "Lambda variable must have a name");
|
|
201
|
-
if (!isNamedOperand(variable)) {
|
|
202
|
-
throw new Error("Lambda variable must have a name");
|
|
203
|
-
}
|
|
204
|
-
const filters = elements.map((element) => {
|
|
205
|
-
const substituted = substituteLambdaVariable(body, variable.name, element);
|
|
206
|
-
return negated
|
|
207
|
-
? buildNegatedFilter(substituted, mapper)
|
|
208
|
-
: buildPrismaFilterFromCerbosExpression(substituted, mapper);
|
|
209
|
-
});
|
|
210
|
-
const combinesWithOr = operator === "exists" ? !negated : negated;
|
|
211
|
-
return combinesWithOr ? { OR: filters } : { AND: filters };
|
|
212
|
-
}
|
|
213
|
-
function tryHandleKnownValueCollectionOperator(operator, operands, mapper, negated) {
|
|
214
|
-
if (operands.length !== 2) {
|
|
215
|
-
return undefined;
|
|
216
|
-
}
|
|
217
|
-
const collection = operands[0];
|
|
218
|
-
const lambda = operands[1];
|
|
219
|
-
if (collection === undefined ||
|
|
220
|
-
lambda === undefined ||
|
|
221
|
-
!isValueOperand(collection)) {
|
|
222
|
-
return undefined;
|
|
223
|
-
}
|
|
224
|
-
// A literal value list arrives when the planner could not unroll a macro
|
|
225
|
-
// over a known collection (more than 10 elements). Fold it before attempting
|
|
226
|
-
// relation resolution because there is no relation mapping for a literal.
|
|
227
|
-
return handleKnownValueCollectionOperator(operator, collection, lambda, mapper, negated);
|
|
228
|
-
}
|
|
229
|
-
function getLeafField(path) {
|
|
230
|
-
const fieldName = path[path.length - 1];
|
|
231
|
-
if (!fieldName) {
|
|
232
|
-
throw new Error("Field path cannot be empty");
|
|
233
|
-
}
|
|
234
|
-
return fieldName;
|
|
235
|
-
}
|
|
236
|
-
function getFilterEntry(filter) {
|
|
237
|
-
const entry = Object.entries(filter)[0];
|
|
238
|
-
if (!entry) {
|
|
239
|
-
throw new Error("Filter must contain at least one entry");
|
|
240
|
-
}
|
|
241
|
-
return entry;
|
|
242
|
-
}
|
|
243
|
-
/** Whether this reference is one the caller sends as an explicit `null` when the column is NULL. */
|
|
244
|
-
function isExplicitNullReference(fieldRef) {
|
|
245
|
-
return fieldRef.nullAttributeRepresentation === "explicit";
|
|
246
|
-
}
|
|
247
|
-
function isResolvedFieldReference(operand) {
|
|
248
|
-
return "path" in operand;
|
|
249
|
-
}
|
|
250
|
-
function isResolvedValue(operand) {
|
|
251
|
-
return "value" in operand;
|
|
252
|
-
}
|
|
253
|
-
function requireResolvedValue(operand, message) {
|
|
254
|
-
if (!isResolvedValue(operand)) {
|
|
255
|
-
throw new Error(message);
|
|
256
|
-
}
|
|
257
|
-
return operand;
|
|
258
|
-
}
|
|
259
|
-
function wrapRelations(relations, filter) {
|
|
260
|
-
if (!relations || relations.length === 0) {
|
|
261
|
-
return filter;
|
|
262
|
-
}
|
|
263
|
-
return buildNestedRelationFilter(relations, filter);
|
|
264
|
-
}
|
|
265
|
-
function buildFieldEqualsFilter(fieldRef, value) {
|
|
266
|
-
const fieldName = getLeafField(fieldRef.path);
|
|
267
|
-
return wrapRelations(fieldRef.relations, { [fieldName]: { equals: value } });
|
|
268
|
-
}
|
|
269
|
-
function buildDirectOrInLeaf(fieldRef, values) {
|
|
270
|
-
const fieldName = getLeafField(fieldRef.path);
|
|
271
|
-
return values.length === 1
|
|
272
|
-
? { [fieldName]: values[0] }
|
|
273
|
-
: { [fieldName]: { in: values } };
|
|
274
|
-
}
|
|
275
|
-
function buildFieldDirectOrInFilter(fieldRef, values) {
|
|
276
|
-
return wrapRelations(fieldRef.relations, buildDirectOrInLeaf(fieldRef, values));
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* `field IS NOT NULL AND <leaf>`, so a NULL column makes the whole thing definitely FALSE rather
|
|
280
|
-
* than merely unmatched — which is what lets an enclosing `NOT` include the row.
|
|
281
|
-
*
|
|
282
|
-
* Prisma has no three-valued logic to expose: a record either matches a `where` or it does not.
|
|
283
|
-
* That is exactly why the guard has to be explicit — `{ NOT: { field: { equals: "x" } } }` leans on
|
|
284
|
-
* the generated SQL's UNKNOWN, which excludes the record under both polarities, and an
|
|
285
|
-
* explicit-null attribute needs the negation to include it.
|
|
286
|
-
*
|
|
287
|
-
* The guard is ANDed with the leaf BEFORE the relation wrapping, so both halves are evaluated
|
|
288
|
-
* against the same element rather than against two independently-matched ones.
|
|
289
|
-
*/
|
|
290
|
-
function guardedFieldFilter(fieldRef, leaf) {
|
|
291
|
-
const fieldName = getLeafField(fieldRef.path);
|
|
292
|
-
return wrapRelations(fieldRef.relations, {
|
|
293
|
-
AND: [{ [fieldName]: { not: null } }, leaf],
|
|
294
|
-
});
|
|
295
|
-
}
|
|
296
|
-
function buildMembershipFilter(fieldRef, values) {
|
|
297
|
-
const nonNullValues = values.filter((value) => value !== null);
|
|
298
|
-
const carriesNull = nonNullValues.length !== values.length;
|
|
299
|
-
if (carriesNull) {
|
|
300
|
-
assertNullOperandTranslatable("a null element in an `in` list", fieldRef.nullAttributeRepresentation);
|
|
301
|
-
}
|
|
302
|
-
const filters = [];
|
|
303
|
-
if (nonNullValues.length > 0 || values.length === 0) {
|
|
304
|
-
// Without a null element nothing has made the membership definite yet: a NULL column is
|
|
305
|
-
// dropped by `{ in: [...] }` under BOTH polarities, while CEL compares a null VALUE against
|
|
306
|
-
// each element and gets a definite false, so its negation is TRUE. With a null element the
|
|
307
|
-
// `[null]` disjunct below already settles it.
|
|
308
|
-
filters.push(carriesNull || !isExplicitNullReference(fieldRef)
|
|
309
|
-
? buildFieldDirectOrInFilter(fieldRef, nonNullValues)
|
|
310
|
-
: guardedFieldFilter(fieldRef, buildDirectOrInLeaf(fieldRef, nonNullValues)));
|
|
311
|
-
}
|
|
312
|
-
if (carriesNull) {
|
|
313
|
-
filters.push(buildFieldDirectOrInFilter(fieldRef, [null]));
|
|
314
|
-
}
|
|
315
|
-
if (filters.length === 1) {
|
|
316
|
-
return assertDefined(filters[0], "Membership filter is missing");
|
|
317
|
-
}
|
|
318
|
-
return { OR: filters };
|
|
319
|
-
}
|
|
320
|
-
function buildAlwaysTrueFilter() {
|
|
321
|
-
return {};
|
|
322
|
-
}
|
|
323
|
-
let lambdaScopes = [];
|
|
324
|
-
let rootModelName;
|
|
325
|
-
let nullRepresentation = "explicit";
|
|
326
|
-
/**
|
|
327
|
-
* Guards every site that would emit a NULL-selecting predicate out of a `null` comparison
|
|
328
|
-
* operand.
|
|
329
|
-
*
|
|
330
|
-
* Under the `"omitted"` representation a NULL column carries no attribute, so CEL raises a
|
|
331
|
-
* missing-attribute error and `check()` denies the row — `IS NULL` would return exactly the rows
|
|
332
|
-
* the PDP refuses. The rejection is deliberately wider than the over-granting shapes: `ne(x,
|
|
333
|
-
* null)` on its own is aligned, but Prisma applies negation by wrapping (`{ NOT: ... }`) rather
|
|
334
|
-
* than by pushing it into the leaf, so a leaf cannot tell whether an enclosing `not` will flip
|
|
335
|
-
* `IS NOT NULL` back into a NULL-selecting predicate. Rejecting every null operand is correct
|
|
336
|
-
* under any nesting; narrowing it requires negation-parity tracking.
|
|
337
|
-
*/
|
|
338
|
-
function assertNullOperandTranslatable(context, declared) {
|
|
339
|
-
if ((declared ?? nullRepresentation) === "omitted") {
|
|
340
|
-
throw new Error(`Cannot translate ${context} under nullAttributeRepresentation "omitted": a NULL column ` +
|
|
341
|
-
"sends no attribute, so Cerbos evaluates the comparison as a missing-attribute error " +
|
|
342
|
-
"(deny) while a NULL-selecting filter would return those rows. Send NULL columns as " +
|
|
343
|
-
'explicit nulls and use "explicit", or keep this shape out of the policy.');
|
|
344
|
-
}
|
|
345
|
-
}
|
|
7
|
+
const fields_1 = require("./fields");
|
|
8
|
+
const mapping_1 = require("./mapping");
|
|
9
|
+
const plan_1 = require("./plan");
|
|
10
|
+
const rewrite_1 = require("./rewrite");
|
|
11
|
+
const translate_1 = require("./translate");
|
|
12
|
+
const functions_1 = require("./functions");
|
|
13
|
+
const literals_1 = require("./literals");
|
|
14
|
+
const types_1 = require("./types");
|
|
15
|
+
const errors_1 = require("./errors");
|
|
16
|
+
Object.defineProperty(exports, "UnsupportedQueryPlanError", { enumerable: true, get: function () { return errors_1.UnsupportedQueryPlanError; } });
|
|
346
17
|
/**
|
|
347
18
|
* Converts a Cerbos query plan to a Prisma filter.
|
|
348
19
|
*/
|
|
349
|
-
function queryPlanToPrisma({ queryPlan, mapper = {}, model, nullAttributeRepresentation = "
|
|
350
|
-
|
|
20
|
+
function queryPlanToPrisma({ queryPlan, mapper = {}, model, nullAttributeRepresentation = "omitted", }) {
|
|
21
|
+
const context = {
|
|
22
|
+
mapper,
|
|
23
|
+
rootModel: model,
|
|
24
|
+
nullRepresentation: nullAttributeRepresentation,
|
|
25
|
+
scopes: [],
|
|
26
|
+
};
|
|
351
27
|
switch (queryPlan.kind) {
|
|
352
28
|
case core_1.PlanKind.ALWAYS_ALLOWED:
|
|
353
29
|
return { kind: core_1.PlanKind.ALWAYS_ALLOWED };
|
|
354
30
|
case core_1.PlanKind.ALWAYS_DENIED:
|
|
355
31
|
return { kind: core_1.PlanKind.ALWAYS_DENIED };
|
|
356
32
|
case core_1.PlanKind.CONDITIONAL: {
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
33
|
+
const settled = (0, types_1.settleTypeMismatches)((0, rewrite_1.hoistOuterScopeReferences)((0, literals_1.expandLiteralCollections)((0, functions_1.rewriteFunctionCalls)(queryPlan.condition, context)), []), context);
|
|
34
|
+
// After settling: a struct literal compared with a column of another type is decided by
|
|
35
|
+
// the types alone (`aString == {"a": null}` is false, or an error on a missing column), so
|
|
36
|
+
// its null member never reaches a filter and must not refuse the plan.
|
|
37
|
+
(0, mapping_1.assertStructuralNulls)(settled, context);
|
|
38
|
+
const condition = (0, rewrite_1.constantFoldExpression)(settled);
|
|
39
|
+
if ((0, plan_1.isValueOperand)(condition)) {
|
|
40
|
+
// The planner folds a condition that is constant on its own, but not one the mapped
|
|
41
|
+
// column types decide (`R.attr.aNumber == "5"` is false for every row): that surfaces
|
|
42
|
+
// here, and is answered as the planner would have answered it.
|
|
363
43
|
if (condition.value === true) {
|
|
364
44
|
return { kind: core_1.PlanKind.CONDITIONAL, filters: {} };
|
|
365
45
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
throw new Error("A constant-false conditional predicate must be folded by the Cerbos planner");
|
|
369
|
-
}
|
|
370
|
-
// A `map()` at the ROOT of the condition returns a list, not a boolean. Translating it
|
|
371
|
-
// produces a projection filter that is not a valid Prisma `where` clause — the shape
|
|
372
|
-
// must be refused HERE rather than left for findMany to reject at query time, because
|
|
373
|
-
// a projection that happened to coerce would be a silently-wrong filter. (`filter()`
|
|
374
|
-
// as a condition is already rejected inside handleCollectionOperator with its own
|
|
375
|
-
// message; nested inside a comparison or size() both remain translatable.)
|
|
376
|
-
if (isOperatorOperand(condition) && condition.operator === "map") {
|
|
377
|
-
throw new Error("map() returns a list, not a boolean, so it cannot be a condition on its own; " +
|
|
378
|
-
"only comparisons or size() over its result have a boolean meaning");
|
|
379
|
-
}
|
|
380
|
-
return {
|
|
381
|
-
kind: core_1.PlanKind.CONDITIONAL,
|
|
382
|
-
filters: buildPrismaFilterFromCerbosExpression(condition, mapper),
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
default:
|
|
386
|
-
throw Error(`Invalid query plan.`);
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
const COLLECTION_OPERATORS = new Set([
|
|
390
|
-
"exists",
|
|
391
|
-
"exists_one",
|
|
392
|
-
"all",
|
|
393
|
-
"except",
|
|
394
|
-
"filter",
|
|
395
|
-
]);
|
|
396
|
-
function mentionsVariable(expr, variableName) {
|
|
397
|
-
if (isNamedOperand(expr)) {
|
|
398
|
-
return (expr.name === variableName || expr.name.startsWith(variableName + "."));
|
|
399
|
-
}
|
|
400
|
-
if (isOperatorOperand(expr)) {
|
|
401
|
-
return expr.operands.some((operand) => mentionsVariable(operand, variableName));
|
|
402
|
-
}
|
|
403
|
-
return false;
|
|
404
|
-
}
|
|
405
|
-
function isOuterScopeName(name, enclosingVariables) {
|
|
406
|
-
return !enclosingVariables.some((variable) => name === variable || name.startsWith(variable + "."));
|
|
407
|
-
}
|
|
408
|
-
/** Replaces every occurrence of the bare named operand `name` with a boolean constant. */
|
|
409
|
-
function substituteNamedOperand(expr, name, value) {
|
|
410
|
-
if (isNamedOperand(expr)) {
|
|
411
|
-
return expr.name === name ? { value } : expr;
|
|
412
|
-
}
|
|
413
|
-
if (isOperatorOperand(expr)) {
|
|
414
|
-
return {
|
|
415
|
-
operator: expr.operator,
|
|
416
|
-
operands: expr.operands.map((operand) => substituteNamedOperand(operand, name, value)),
|
|
417
|
-
};
|
|
418
|
-
}
|
|
419
|
-
return expr;
|
|
420
|
-
}
|
|
421
|
-
/**
|
|
422
|
-
* Finds a bare boolean reference to an OUTER column (root or enclosing lambda scope) in a
|
|
423
|
-
* boolean position of a lambda body: a direct operand of and/or/not, a ternary condition, or
|
|
424
|
-
* the body itself.
|
|
425
|
-
*/
|
|
426
|
-
function findOuterBooleanReference(expr, enclosingVariables) {
|
|
427
|
-
if (isNamedOperand(expr)) {
|
|
428
|
-
return isOuterScopeName(expr.name, enclosingVariables)
|
|
429
|
-
? expr.name
|
|
430
|
-
: undefined;
|
|
431
|
-
}
|
|
432
|
-
if (!isOperatorOperand(expr)) {
|
|
433
|
-
return undefined;
|
|
434
|
-
}
|
|
435
|
-
const booleanPositions = [];
|
|
436
|
-
switch (expr.operator) {
|
|
437
|
-
case "and":
|
|
438
|
-
case "or":
|
|
439
|
-
case "not":
|
|
440
|
-
booleanPositions.push(...expr.operands);
|
|
441
|
-
break;
|
|
442
|
-
case "if":
|
|
443
|
-
booleanPositions.push(...expr.operands);
|
|
444
|
-
break;
|
|
445
|
-
default:
|
|
446
|
-
// Comparisons wrapping a ternary keep the outer reference in the ternary condition.
|
|
447
|
-
booleanPositions.push(...expr.operands.filter((operand) => isOperatorOperand(operand) &&
|
|
448
|
-
(operand.operator === "if" ||
|
|
449
|
-
operand.operator === "and" ||
|
|
450
|
-
operand.operator === "or" ||
|
|
451
|
-
operand.operator === "not")));
|
|
452
|
-
break;
|
|
453
|
-
}
|
|
454
|
-
for (const operand of booleanPositions) {
|
|
455
|
-
const found = findOuterBooleanReference(operand, enclosingVariables);
|
|
456
|
-
if (found !== undefined) {
|
|
457
|
-
return found;
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
return undefined;
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* Rewrites lambda bodies that reference columns of an ENCLOSING scope (the root row, or an
|
|
464
|
-
* outer lambda's element) so that every filter lands on the model it belongs to. Without this,
|
|
465
|
-
* an outer column referenced inside `tags.exists(t, ...)` would be emitted as a field of the
|
|
466
|
-
* tag model. Two sound transforms, applied bottom-up:
|
|
467
|
-
*
|
|
468
|
-
* - Conjunct hoisting (exists only): `exists(c, P(c) && Q)` with row-constant Q becomes
|
|
469
|
-
* `exists(c, P(c)) && Q`. Valid in three-valued logic (AND distributes over the per-element
|
|
470
|
-
* OR), including the empty-collection case (both sides are FALSE).
|
|
471
|
-
* - Case split (any collection op): a bare outer boolean reference Q in a boolean position
|
|
472
|
-
* becomes `(Q && op[Q:=true]) || (!Q && op[Q:=false]) || (Q && !Q)`. The contradiction arm
|
|
473
|
-
* keeps the whole expression UNKNOWN (not FALSE) when Q is NULL-derived, mirroring the
|
|
474
|
-
* guarded-ternary encoding.
|
|
475
|
-
*/
|
|
476
|
-
function hoistOuterScopeReferences(expr, enclosingVariables) {
|
|
477
|
-
if (!isOperatorOperand(expr)) {
|
|
478
|
-
return expr;
|
|
479
|
-
}
|
|
480
|
-
if (COLLECTION_OPERATORS.has(expr.operator) && expr.operands.length === 2) {
|
|
481
|
-
const [collection, lambda] = expr.operands;
|
|
482
|
-
if (collection !== undefined &&
|
|
483
|
-
lambda !== undefined &&
|
|
484
|
-
isOperatorOperand(lambda) &&
|
|
485
|
-
lambda.operator === "lambda" &&
|
|
486
|
-
lambda.operands.length === 2 &&
|
|
487
|
-
lambda.operands[1] !== undefined &&
|
|
488
|
-
isNamedOperand(lambda.operands[1])) {
|
|
489
|
-
const variable = lambda.operands[1];
|
|
490
|
-
const body = hoistOuterScopeReferences(assertDefined(lambda.operands[0], "Lambda requires a condition"), [...enclosingVariables, variable.name]);
|
|
491
|
-
const rebuild = (newBody) => ({
|
|
492
|
-
operator: expr.operator,
|
|
493
|
-
operands: [
|
|
494
|
-
collection,
|
|
495
|
-
{ operator: "lambda", operands: [newBody, variable] },
|
|
496
|
-
],
|
|
497
|
-
});
|
|
498
|
-
// Conjunct hoisting out of exists().
|
|
499
|
-
if (expr.operator === "exists" &&
|
|
500
|
-
isOperatorOperand(body) &&
|
|
501
|
-
body.operator === "and") {
|
|
502
|
-
const elementConjuncts = body.operands.filter((operand) => mentionsVariable(operand, variable.name));
|
|
503
|
-
const outerConjuncts = body.operands.filter((operand) => !mentionsVariable(operand, variable.name));
|
|
504
|
-
if (outerConjuncts.length > 0 && elementConjuncts.length > 0) {
|
|
505
|
-
const innerBody = elementConjuncts.length === 1
|
|
506
|
-
? elementConjuncts[0]
|
|
507
|
-
: { operator: "and", operands: elementConjuncts };
|
|
508
|
-
return {
|
|
509
|
-
operator: "and",
|
|
510
|
-
operands: [rebuild(innerBody), ...outerConjuncts],
|
|
511
|
-
};
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
// Case split on a bare outer boolean reference.
|
|
515
|
-
const outerRef = findOuterBooleanReference(body, [
|
|
516
|
-
...enclosingVariables,
|
|
517
|
-
variable.name,
|
|
518
|
-
]);
|
|
519
|
-
if (outerRef !== undefined) {
|
|
520
|
-
const q = { name: outerRef };
|
|
521
|
-
const notQ = { operator: "not", operands: [q] };
|
|
522
|
-
return {
|
|
523
|
-
operator: "or",
|
|
524
|
-
operands: [
|
|
525
|
-
{
|
|
526
|
-
operator: "and",
|
|
527
|
-
operands: [
|
|
528
|
-
q,
|
|
529
|
-
rebuild(substituteNamedOperand(body, outerRef, true)),
|
|
530
|
-
],
|
|
531
|
-
},
|
|
532
|
-
{
|
|
533
|
-
operator: "and",
|
|
534
|
-
operands: [
|
|
535
|
-
notQ,
|
|
536
|
-
rebuild(substituteNamedOperand(body, outerRef, false)),
|
|
537
|
-
],
|
|
538
|
-
},
|
|
539
|
-
// Contradiction arm: UNKNOWN when the reference is NULL-derived, never TRUE.
|
|
540
|
-
{ operator: "and", operands: [q, notQ] },
|
|
541
|
-
],
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
return rebuild(body);
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
return {
|
|
548
|
-
operator: expr.operator,
|
|
549
|
-
operands: expr.operands.map((operand) => hoistOuterScopeReferences(operand, enclosingVariables)),
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
const FOLDABLE_COMPARISON_OPERATORS = new Set([
|
|
553
|
-
"eq",
|
|
554
|
-
"ne",
|
|
555
|
-
"lt",
|
|
556
|
-
"le",
|
|
557
|
-
"gt",
|
|
558
|
-
"ge",
|
|
559
|
-
]);
|
|
560
|
-
/**
|
|
561
|
-
* Bottom-up constant folding over the plan AST. Only shapes the case-split transform can
|
|
562
|
-
* produce need folding (constant ternary conditions, comparisons between two constants,
|
|
563
|
-
* logical operators with constant operands, collection macros with constant bodies); real
|
|
564
|
-
* planner output arrives pre-folded.
|
|
565
|
-
*/
|
|
566
|
-
function constantFoldExpression(expr) {
|
|
567
|
-
if (!isOperatorOperand(expr)) {
|
|
568
|
-
return expr;
|
|
569
|
-
}
|
|
570
|
-
const operands = expr.operands.map(constantFoldExpression);
|
|
571
|
-
const folded = { operator: expr.operator, operands };
|
|
572
|
-
switch (expr.operator) {
|
|
573
|
-
case "if": {
|
|
574
|
-
const [condition, thenBranch, elseBranch] = operands;
|
|
575
|
-
if (condition !== undefined && isValueOperand(condition)) {
|
|
576
|
-
if (typeof condition.value !== "boolean") {
|
|
577
|
-
throw new Error("if (ternary) condition must be a boolean expression");
|
|
578
|
-
}
|
|
579
|
-
return assertDefined(condition.value ? thenBranch : elseBranch, "if (ternary) requires branch operands");
|
|
580
|
-
}
|
|
581
|
-
return folded;
|
|
582
|
-
}
|
|
583
|
-
case "and": {
|
|
584
|
-
if (operands.some((o) => isValueOperand(o) && o.value === false)) {
|
|
585
|
-
return { value: false };
|
|
586
|
-
}
|
|
587
|
-
const remaining = operands.filter((o) => !isValueOperand(o));
|
|
588
|
-
if (remaining.length === 0)
|
|
589
|
-
return { value: true };
|
|
590
|
-
if (remaining.length === 1)
|
|
591
|
-
return remaining[0];
|
|
592
|
-
return { operator: "and", operands: remaining };
|
|
593
|
-
}
|
|
594
|
-
case "or": {
|
|
595
|
-
if (operands.some((o) => isValueOperand(o) && o.value === true)) {
|
|
596
|
-
return { value: true };
|
|
597
|
-
}
|
|
598
|
-
const remaining = operands.filter((o) => !isValueOperand(o));
|
|
599
|
-
if (remaining.length === 0)
|
|
600
|
-
return { value: false };
|
|
601
|
-
if (remaining.length === 1)
|
|
602
|
-
return remaining[0];
|
|
603
|
-
return { operator: "or", operands: remaining };
|
|
604
|
-
}
|
|
605
|
-
case "not": {
|
|
606
|
-
const operand = operands[0];
|
|
607
|
-
if (operand !== undefined && isValueOperand(operand)) {
|
|
608
|
-
return { value: operand.value !== true };
|
|
609
|
-
}
|
|
610
|
-
return folded;
|
|
611
|
-
}
|
|
612
|
-
case "add":
|
|
613
|
-
case "sub":
|
|
614
|
-
case "mult":
|
|
615
|
-
case "div": {
|
|
616
|
-
const [left, right] = operands;
|
|
617
|
-
if (left !== undefined &&
|
|
618
|
-
right !== undefined &&
|
|
619
|
-
isValueOperand(left) &&
|
|
620
|
-
isValueOperand(right)) {
|
|
621
|
-
return {
|
|
622
|
-
value: foldArithmetic(expr.operator, left.value, right.value),
|
|
623
|
-
};
|
|
624
|
-
}
|
|
625
|
-
return folded;
|
|
626
|
-
}
|
|
627
|
-
case "contains":
|
|
628
|
-
case "startsWith":
|
|
629
|
-
case "endsWith": {
|
|
630
|
-
const [receiver, needle] = operands;
|
|
631
|
-
if (receiver !== undefined &&
|
|
632
|
-
needle !== undefined &&
|
|
633
|
-
isValueOperand(receiver) &&
|
|
634
|
-
isValueOperand(needle) &&
|
|
635
|
-
typeof receiver.value === "string" &&
|
|
636
|
-
typeof needle.value === "string") {
|
|
637
|
-
const r = receiver.value;
|
|
638
|
-
const n = needle.value;
|
|
639
|
-
return {
|
|
640
|
-
value: expr.operator === "contains"
|
|
641
|
-
? r.includes(n)
|
|
642
|
-
: expr.operator === "startsWith"
|
|
643
|
-
? r.startsWith(n)
|
|
644
|
-
: r.endsWith(n),
|
|
645
|
-
};
|
|
646
|
-
}
|
|
647
|
-
return folded;
|
|
648
|
-
}
|
|
649
|
-
case "exists":
|
|
650
|
-
case "all": {
|
|
651
|
-
const [collection, lambda] = operands;
|
|
652
|
-
if (collection !== undefined &&
|
|
653
|
-
lambda !== undefined &&
|
|
654
|
-
isOperatorOperand(lambda) &&
|
|
655
|
-
lambda.operator === "lambda" &&
|
|
656
|
-
lambda.operands[0] !== undefined &&
|
|
657
|
-
isValueOperand(lambda.operands[0])) {
|
|
658
|
-
const bodyValue = lambda.operands[0].value === true;
|
|
659
|
-
if (expr.operator === "exists" && !bodyValue)
|
|
660
|
-
return { value: false };
|
|
661
|
-
if (expr.operator === "all" && bodyValue)
|
|
662
|
-
return { value: true };
|
|
663
|
-
const sizeExpr = {
|
|
664
|
-
operator: "size",
|
|
665
|
-
operands: [collection],
|
|
666
|
-
};
|
|
667
|
-
// exists(c, true) is "collection is non-empty"; all(c, false) is "collection is empty".
|
|
668
|
-
return expr.operator === "exists"
|
|
669
|
-
? { operator: "gt", operands: [sizeExpr, { value: 0 }] }
|
|
670
|
-
: { operator: "eq", operands: [sizeExpr, { value: 0 }] };
|
|
671
|
-
}
|
|
672
|
-
return folded;
|
|
673
|
-
}
|
|
674
|
-
default: {
|
|
675
|
-
if (FOLDABLE_COMPARISON_OPERATORS.has(expr.operator)) {
|
|
676
|
-
const [left, right] = operands;
|
|
677
|
-
if (left !== undefined &&
|
|
678
|
-
right !== undefined &&
|
|
679
|
-
isValueOperand(left) &&
|
|
680
|
-
isValueOperand(right)) {
|
|
681
|
-
return {
|
|
682
|
-
value: evaluateConstantComparison(expr.operator, left.value, right.value),
|
|
683
|
-
};
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
return folded;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
/**
|
|
691
|
-
* Resolves a field reference considering relations and nested fields.
|
|
692
|
-
*/
|
|
693
|
-
function resolveFieldReference(reference, mapper) {
|
|
694
|
-
const parts = reference.split(".");
|
|
695
|
-
const config = typeof mapper === "function" ? mapper(reference) : mapper[reference];
|
|
696
|
-
let matchedPrefix = "";
|
|
697
|
-
let matchedConfig;
|
|
698
|
-
// If no direct match, look for partial matches
|
|
699
|
-
if (!config) {
|
|
700
|
-
for (let i = parts.length - 1; i >= 0; i--) {
|
|
701
|
-
const prefix = parts.slice(0, i + 1).join(".");
|
|
702
|
-
const prefixConfig = typeof mapper === "function" ? mapper(prefix) : mapper[prefix];
|
|
703
|
-
if (prefixConfig) {
|
|
704
|
-
matchedPrefix = prefix;
|
|
705
|
-
matchedConfig = prefixConfig;
|
|
706
|
-
break;
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
const activeConfig = config ?? matchedConfig;
|
|
711
|
-
// Handle relation mapping
|
|
712
|
-
if (activeConfig?.relation) {
|
|
713
|
-
const { name, type, fields } = activeConfig.relation;
|
|
714
|
-
const matchedParts = matchedPrefix ? matchedPrefix.split(".") : [];
|
|
715
|
-
const remainingParts = matchedPrefix
|
|
716
|
-
? parts.slice(matchedParts.length)
|
|
717
|
-
: parts.slice(1);
|
|
718
|
-
let field;
|
|
719
|
-
const relations = [
|
|
720
|
-
{
|
|
721
|
-
name,
|
|
722
|
-
type,
|
|
723
|
-
model: activeConfig.relation.model,
|
|
724
|
-
field: activeConfig.relation.field,
|
|
725
|
-
nestedMapper: fields,
|
|
726
|
-
subqueryFilter: activeConfig.relation.subqueryFilter,
|
|
727
|
-
},
|
|
728
|
-
];
|
|
729
|
-
// Process nested relations
|
|
730
|
-
if (fields && remainingParts.length > 0) {
|
|
731
|
-
let currentMapper = fields;
|
|
732
|
-
let currentParts = remainingParts;
|
|
733
|
-
while (currentParts.length > 0) {
|
|
734
|
-
if (!currentMapper) {
|
|
735
|
-
break;
|
|
736
|
-
}
|
|
737
|
-
const currentPart = currentParts[0];
|
|
738
|
-
if (!currentPart) {
|
|
739
|
-
break;
|
|
740
|
-
}
|
|
741
|
-
const nextConfig = currentMapper[currentPart];
|
|
742
|
-
if (nextConfig?.relation) {
|
|
743
|
-
relations.push({
|
|
744
|
-
name: nextConfig.relation.name,
|
|
745
|
-
type: nextConfig.relation.type,
|
|
746
|
-
model: nextConfig.relation.model,
|
|
747
|
-
field: nextConfig.relation.field,
|
|
748
|
-
nestedMapper: nextConfig.relation.fields,
|
|
749
|
-
subqueryFilter: nextConfig.relation.subqueryFilter,
|
|
750
|
-
});
|
|
751
|
-
currentMapper = nextConfig.relation.fields || {};
|
|
752
|
-
currentParts = currentParts.slice(1);
|
|
753
|
-
}
|
|
754
|
-
else {
|
|
755
|
-
const lastPart = currentParts[currentParts.length - 1];
|
|
756
|
-
if (!lastPart) {
|
|
757
|
-
break;
|
|
758
|
-
}
|
|
759
|
-
field = nextConfig?.field || lastPart;
|
|
760
|
-
break;
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
return {
|
|
765
|
-
path: field ? [field] : remainingParts,
|
|
766
|
-
relations,
|
|
767
|
-
valueType: activeConfig.valueType,
|
|
768
|
-
nullAttributeRepresentation: activeConfig.nullAttributeRepresentation,
|
|
769
|
-
};
|
|
770
|
-
}
|
|
771
|
-
// Simple field mapping
|
|
772
|
-
return {
|
|
773
|
-
path: [activeConfig?.field || reference],
|
|
774
|
-
valueType: activeConfig?.valueType,
|
|
775
|
-
nullAttributeRepresentation: activeConfig?.nullAttributeRepresentation,
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Determines the appropriate Prisma operator based on relation type.
|
|
780
|
-
*/
|
|
781
|
-
function getPrismaRelationOperator(relation) {
|
|
782
|
-
return relation.type === "one" ? "is" : "some";
|
|
783
|
-
}
|
|
784
|
-
/**
|
|
785
|
-
* One relation-scoped filter (`{ tags: { some: … } }`), narrowed by the store-side predicate the
|
|
786
|
-
* caller declared on the mapping.
|
|
787
|
-
*
|
|
788
|
-
* Every nested relation filter the adapter emits goes through here, so a declared
|
|
789
|
-
* `subqueryFilter` reaches the collection macros, the membership shapes, the emptiness checks and
|
|
790
|
-
* the hop-existence guard alike. Adding a new relation shape means routing it through here, or
|
|
791
|
-
* the declaration silently stops applying to it.
|
|
792
|
-
*
|
|
793
|
-
* `every` is the one operator that cannot simply absorb the predicate. `{ every: AND(W, P) }`
|
|
794
|
-
* would REQUIRE every record to satisfy W, which is the opposite of "ignore the records W hides",
|
|
795
|
-
* so it is rewritten to `{ none: AND(W, NOT P) }` — no visible record violates P. Both agree with
|
|
796
|
-
* `every` when nothing is declared, and both stay vacuously true over an empty relation.
|
|
797
|
-
*/
|
|
798
|
-
function relationFilter(relation, operator, inner) {
|
|
799
|
-
const declared = relation.subqueryFilter;
|
|
800
|
-
if (declared === undefined) {
|
|
801
|
-
return { [relation.name]: { [operator]: inner } };
|
|
802
|
-
}
|
|
803
|
-
const narrow = (filter) => Object.keys(filter).length === 0 ? declared : { AND: [declared, filter] };
|
|
804
|
-
if (operator === "every") {
|
|
805
|
-
return Object.keys(inner).length === 0
|
|
806
|
-
? { [relation.name]: { every: inner } }
|
|
807
|
-
: { [relation.name]: { none: { AND: [declared, { NOT: inner }] } } };
|
|
808
|
-
}
|
|
809
|
-
return { [relation.name]: { [operator]: narrow(inner) } };
|
|
810
|
-
}
|
|
811
|
-
/**
|
|
812
|
-
* Builds a nested relation filter for Prisma queries.
|
|
813
|
-
*/
|
|
814
|
-
/**
|
|
815
|
-
* "Every intermediate hop of a dotted path exists", as a Prisma filter.
|
|
816
|
-
*
|
|
817
|
-
* CEL cannot dot through a list, so each intermediate segment of `a.b.c` is a to-ONE
|
|
818
|
-
* parent: absent, the caller sends no attribute and CEL raises a missing-path error, which
|
|
819
|
-
* denies. `NOT { categories: { some: { subCategories: { some: P } } } }` is TRUE for a row
|
|
820
|
-
* with no category at all, so the negation returns rows the PDP denies — the parent must be
|
|
821
|
-
* required separately (cerbos/query-plan-adapters#309).
|
|
822
|
-
*
|
|
823
|
-
* Returns undefined when the reference has no intermediate hop, so a direct relation keeps
|
|
824
|
-
* its empty-collection semantics (`!tags.exists(...)` over zero tags is still TRUE).
|
|
825
|
-
*/
|
|
826
|
-
function buildLeadingHopsExistFilter(head, restRelations) {
|
|
827
|
-
if (restRelations.length === 0) {
|
|
828
|
-
return undefined;
|
|
829
|
-
}
|
|
830
|
-
// The last entry is the collection being iterated; everything before it is a hop.
|
|
831
|
-
return buildHopsExistFilter([head, ...restRelations.slice(0, -1)]);
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* "Every one of these relations exists", as a nested Prisma filter with an empty innermost
|
|
835
|
-
* predicate — `{ parent: { is: { inner: { is: {} } } } }`.
|
|
836
|
-
*/
|
|
837
|
-
function buildHopsExistFilter(hops) {
|
|
838
|
-
if (hops.length === 0) {
|
|
839
|
-
return undefined;
|
|
840
|
-
}
|
|
841
|
-
let inner = {};
|
|
842
|
-
for (let i = hops.length - 1; i >= 0; i--) {
|
|
843
|
-
const relation = assertDefined(hops[i], "Relation mapping is missing");
|
|
844
|
-
inner = relationFilter(relation, getPrismaRelationOperator(relation), inner);
|
|
845
|
-
}
|
|
846
|
-
return inner;
|
|
847
|
-
}
|
|
848
|
-
/**
|
|
849
|
-
* "Every to-one hop this expression dots through exists", as a Prisma filter, or undefined
|
|
850
|
-
* when it dots through none.
|
|
851
|
-
*
|
|
852
|
-
* Prisma has no UNKNOWN: a chained relation filter is exact under the POSITIVE polarity —
|
|
853
|
-
* `categories: { some: { subCategories: { some: P } } }` cannot hold without the category —
|
|
854
|
-
* but `NOT` inverts the hop requirement along with the predicate, so every operator built on
|
|
855
|
-
* a chain readmits the parentless rows once negated. #309 fixed that inside the collection
|
|
856
|
-
* macros, which left the sibling operators reached through the same chain unguarded:
|
|
857
|
-
* membership and `hasIntersection` (cerbos/query-plan-adapters#315), and the negated count
|
|
858
|
-
* spelling `!(size(chain) > 0)` (#316), all of which the macros' guard never saw.
|
|
859
|
-
*
|
|
860
|
-
* Requiring the hops OUTSIDE the negation is what fixes all of them at once, and it is
|
|
861
|
-
* unconditionally faithful to CEL rather than a per-operator patch: a missing hop is a
|
|
862
|
-
* missing-path error, which denies under BOTH polarities, so the requirement never depends
|
|
863
|
-
* on which operator sits above the chain.
|
|
864
|
-
*
|
|
865
|
-
* Lambda bodies are deliberately not walked — their references resolve against a scoped
|
|
866
|
-
* mapper, and a negated macro carries its own guard through buildNegatedCollectionFilter.
|
|
867
|
-
*/
|
|
868
|
-
function buildExpressionHopsExistFilter(operand, mapper) {
|
|
869
|
-
const hops = [];
|
|
870
|
-
const seen = new Set();
|
|
871
|
-
const visit = (expr) => {
|
|
872
|
-
if (isNamedOperand(expr)) {
|
|
873
|
-
if (seen.has(expr.name)) {
|
|
874
|
-
return;
|
|
875
|
-
}
|
|
876
|
-
seen.add(expr.name);
|
|
877
|
-
const { relations } = resolveFieldReference(expr.name, mapper);
|
|
878
|
-
if (!relations || relations.length === 0) {
|
|
879
|
-
return;
|
|
880
|
-
}
|
|
881
|
-
// Every to-ONE relation on the path is a hop that must EXIST — including a TRAILING one,
|
|
882
|
-
// which is the case a chain of to-many relations never produces. `parent.aBool` resolves
|
|
883
|
-
// to a single to-one relation, and `NOT { parent: { is: { aBool: true } } }` is TRUE for
|
|
884
|
-
// a row with no parent at all, so the negation returns rows the PDP denies. A trailing
|
|
885
|
-
// to-MANY relation is the collection being iterated rather than a hop, and keeps its
|
|
886
|
-
// empty-collection semantics (`!tags.exists(...)` over zero tags is still TRUE).
|
|
887
|
-
const last = assertDefined(relations[relations.length - 1], "Relation mapping is missing");
|
|
888
|
-
const hopFilter = buildHopsExistFilter(last.type === "one" ? relations : relations.slice(0, -1));
|
|
889
|
-
if (hopFilter !== undefined) {
|
|
890
|
-
hops.push(hopFilter);
|
|
891
|
-
}
|
|
892
|
-
return;
|
|
893
|
-
}
|
|
894
|
-
if (!isOperatorOperand(expr) || expr.operator === "lambda") {
|
|
895
|
-
return;
|
|
896
|
-
}
|
|
897
|
-
expr.operands.forEach(visit);
|
|
898
|
-
};
|
|
899
|
-
visit(operand);
|
|
900
|
-
if (hops.length === 0) {
|
|
901
|
-
return undefined;
|
|
902
|
-
}
|
|
903
|
-
return hops.length === 1
|
|
904
|
-
? assertDefined(hops[0], "Leading-hops filter is missing")
|
|
905
|
-
: { AND: hops };
|
|
906
|
-
}
|
|
907
|
-
/**
|
|
908
|
-
* `{ NOT: filter }`, with every to-one hop `operand` dots through required OUTSIDE the
|
|
909
|
-
* negation so an absent parent stays denied (see buildExpressionHopsExistFilter).
|
|
910
|
-
*/
|
|
911
|
-
function negateRequiringHops(operand, filter, mapper) {
|
|
912
|
-
const hops = buildExpressionHopsExistFilter(operand, mapper);
|
|
913
|
-
return hops === undefined ? { NOT: filter } : { AND: [hops, { NOT: filter }] };
|
|
914
|
-
}
|
|
915
|
-
function buildNestedRelationFilter(relations, fieldFilter) {
|
|
916
|
-
if (relations.length === 0)
|
|
917
|
-
return fieldFilter;
|
|
918
|
-
let currentFilter = fieldFilter;
|
|
919
|
-
// Build nested structure from inside out
|
|
920
|
-
for (let i = relations.length - 1; i >= 0; i--) {
|
|
921
|
-
const relation = relations[i];
|
|
922
|
-
if (!relation) {
|
|
923
|
-
throw new Error("Relation mapping is missing");
|
|
924
|
-
}
|
|
925
|
-
const relationOperator = getPrismaRelationOperator(relation);
|
|
926
|
-
// Handle special case for the deepest relation
|
|
927
|
-
if (relation.field && i === relations.length - 1) {
|
|
928
|
-
const [key, filterValue] = getFilterEntry(currentFilter);
|
|
929
|
-
if (key === "NOT") {
|
|
930
|
-
currentFilter = { NOT: { [relation.field]: filterValue } };
|
|
931
|
-
}
|
|
932
|
-
else {
|
|
933
|
-
currentFilter = { [relation.field]: filterValue };
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
currentFilter = relationFilter(relation, relationOperator, currentFilter);
|
|
937
|
-
}
|
|
938
|
-
return currentFilter;
|
|
939
|
-
}
|
|
940
|
-
/**
|
|
941
|
-
* Resolves a PlanExpressionOperand into a ResolvedOperand.
|
|
942
|
-
*/
|
|
943
|
-
function resolveOperand(operand, mapper) {
|
|
944
|
-
if (isNamedOperand(operand)) {
|
|
945
|
-
return resolveFieldReference(operand.name, mapper);
|
|
946
|
-
}
|
|
947
|
-
else if (isValueOperand(operand)) {
|
|
948
|
-
return { value: operand.value };
|
|
949
|
-
}
|
|
950
|
-
else if (isOperatorOperand(operand)) {
|
|
951
|
-
if (operand.operator === "timestamp") {
|
|
952
|
-
return resolveTimestampOperand(operand, mapper);
|
|
953
|
-
}
|
|
954
|
-
const folded = tryFoldValueExpression(operand, mapper);
|
|
955
|
-
if (folded !== null)
|
|
956
|
-
return { value: folded };
|
|
957
|
-
const nestedResult = buildPrismaFilterFromCerbosExpression(operand, mapper);
|
|
958
|
-
return { value: nestedResult };
|
|
959
|
-
}
|
|
960
|
-
throw new Error("Operand must have name, value, or be an expression");
|
|
961
|
-
}
|
|
962
|
-
function resolveTimestampOperand(expression, mapper) {
|
|
963
|
-
if (expression.operands.length !== 1) {
|
|
964
|
-
throw new Error("timestamp() requires exactly one operand");
|
|
965
|
-
}
|
|
966
|
-
const operand = assertDefined(expression.operands[0], "timestamp() requires an operand");
|
|
967
|
-
if (isNamedOperand(operand)) {
|
|
968
|
-
const fieldRef = resolveFieldReference(operand.name, mapper);
|
|
969
|
-
if (fieldRef.valueType !== "dateTime") {
|
|
970
|
-
throw new Error(`timestamp() field ${operand.name} must be mapped with valueType: \"dateTime\"`);
|
|
971
|
-
}
|
|
972
|
-
return fieldRef;
|
|
973
|
-
}
|
|
974
|
-
if (!isValueOperand(operand) || typeof operand.value !== "string") {
|
|
975
|
-
throw new Error("timestamp() requires a field reference or RFC 3339 string");
|
|
976
|
-
}
|
|
977
|
-
return { value: normalizeRfc3339Milliseconds(operand.value) };
|
|
978
|
-
}
|
|
979
|
-
function tryFoldValueExpression(expr, mapper) {
|
|
980
|
-
if (!ARITHMETIC_OPERATORS.has(expr.operator))
|
|
981
|
-
return null;
|
|
982
|
-
const leftOp = expr.operands[0];
|
|
983
|
-
const rightOp = expr.operands[1];
|
|
984
|
-
if (!leftOp || !rightOp)
|
|
985
|
-
return null;
|
|
986
|
-
const left = resolveOperand(leftOp, mapper);
|
|
987
|
-
if (!isResolvedValue(left))
|
|
988
|
-
return null;
|
|
989
|
-
const right = resolveOperand(rightOp, mapper);
|
|
990
|
-
if (!isResolvedValue(right))
|
|
991
|
-
return null;
|
|
992
|
-
try {
|
|
993
|
-
return foldArithmetic(expr.operator, left.value, right.value);
|
|
994
|
-
}
|
|
995
|
-
catch {
|
|
996
|
-
return null;
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
/**
|
|
1000
|
-
* Records that the lambda body being built touches a nullable element column, so the
|
|
1001
|
-
* enclosing collection operator can add its three-valued-logic guard.
|
|
1002
|
-
*/
|
|
1003
|
-
function recordNullableElementField(config, defaultField) {
|
|
1004
|
-
if (!config.nullable) {
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
const scope = lambdaScopes[lambdaScopes.length - 1];
|
|
1008
|
-
scope?.nullableFields.add(config.field || defaultField);
|
|
1009
|
-
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Creates a scoped mapper for collection operations
|
|
1012
|
-
*/
|
|
1013
|
-
function createScopedMapper(collectionPath, variableName, fullMapper) {
|
|
1014
|
-
return (key) => {
|
|
1015
|
-
// If the key starts with the variable name, it's accessing the collection item
|
|
1016
|
-
if (key.startsWith(variableName + ".")) {
|
|
1017
|
-
const strippedKey = key.replace(variableName + ".", "");
|
|
1018
|
-
const parts = strippedKey.split(".");
|
|
1019
|
-
// Get the collection's relation config
|
|
1020
|
-
const collectionConfig = typeof fullMapper === "function"
|
|
1021
|
-
? fullMapper(collectionPath)
|
|
1022
|
-
: fullMapper[collectionPath];
|
|
1023
|
-
if (collectionConfig?.relation?.fields) {
|
|
1024
|
-
// For nested paths, traverse the fields configuration
|
|
1025
|
-
const baseConfig = collectionConfig.relation.fields;
|
|
1026
|
-
if (!baseConfig) {
|
|
1027
|
-
return { field: strippedKey };
|
|
1028
|
-
}
|
|
1029
|
-
let currentConfig = baseConfig;
|
|
1030
|
-
let field = parts[0] || strippedKey;
|
|
1031
|
-
for (let i = 0; i < parts.length - 1; i++) {
|
|
1032
|
-
const part = parts[i];
|
|
1033
|
-
const nextPart = parts[i + 1];
|
|
1034
|
-
if (!part || !nextPart) {
|
|
1035
|
-
break;
|
|
1036
|
-
}
|
|
1037
|
-
const nextConfig = currentConfig[part];
|
|
1038
|
-
if (nextConfig?.relation?.fields) {
|
|
1039
|
-
currentConfig = nextConfig.relation.fields;
|
|
1040
|
-
field = nextPart;
|
|
1041
|
-
}
|
|
1042
|
-
else {
|
|
1043
|
-
break;
|
|
1044
|
-
}
|
|
1045
|
-
}
|
|
1046
|
-
if (!field) {
|
|
1047
|
-
field = strippedKey;
|
|
46
|
+
if (condition.value === false) {
|
|
47
|
+
return { kind: core_1.PlanKind.ALWAYS_DENIED };
|
|
1048
48
|
}
|
|
1049
|
-
|
|
1050
|
-
const fieldConfig = currentConfig[field] || { field };
|
|
1051
|
-
recordNullableElementField(fieldConfig, field);
|
|
1052
|
-
return fieldConfig;
|
|
49
|
+
(0, fields_1.rejectConstantFalse)();
|
|
1053
50
|
}
|
|
1054
|
-
return { field: strippedKey };
|
|
1055
|
-
}
|
|
1056
|
-
// For keys not referencing the collection item, use the full mapper
|
|
1057
|
-
if (typeof fullMapper === "function") {
|
|
1058
|
-
return fullMapper(key);
|
|
1059
|
-
}
|
|
1060
|
-
return fullMapper[key] || { field: key };
|
|
1061
|
-
};
|
|
1062
|
-
}
|
|
1063
|
-
/**
|
|
1064
|
-
* Builds a Prisma filter from a Cerbos expression.
|
|
1065
|
-
*/
|
|
1066
|
-
function buildPrismaFilterFromCerbosExpression(expression, mapper) {
|
|
1067
|
-
// A bare named operand represents a boolean field reference (e.g. `R.attr.booleanAttr`)
|
|
1068
|
-
if (isNamedOperand(expression)) {
|
|
1069
|
-
const fieldRef = resolveFieldReference(expression.name, mapper);
|
|
1070
|
-
return buildFieldEqualsFilter(fieldRef, true);
|
|
1071
|
-
}
|
|
1072
|
-
if (!isOperatorOperand(expression)) {
|
|
1073
|
-
throw new Error("Invalid Cerbos expression structure");
|
|
1074
|
-
}
|
|
1075
|
-
const { operator, operands } = expression;
|
|
1076
|
-
// Process different operator types
|
|
1077
|
-
switch (operator) {
|
|
1078
|
-
case "and":
|
|
1079
51
|
return {
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
case "or":
|
|
1083
|
-
return {
|
|
1084
|
-
OR: operands.map((operand) => buildPrismaFilterFromCerbosExpression(operand, mapper)),
|
|
52
|
+
kind: core_1.PlanKind.CONDITIONAL,
|
|
53
|
+
filters: (0, translate_1.buildPrismaFilterFromCerbosExpression)(condition, context),
|
|
1085
54
|
};
|
|
1086
|
-
case "not": {
|
|
1087
|
-
const operand = operands[0];
|
|
1088
|
-
if (!operand) {
|
|
1089
|
-
throw new Error("not operator requires an operand");
|
|
1090
|
-
}
|
|
1091
|
-
return buildNegatedFilter(operand, mapper);
|
|
1092
|
-
}
|
|
1093
|
-
case "if": {
|
|
1094
|
-
return handleBooleanTernaryOperator(operands, mapper);
|
|
1095
|
-
}
|
|
1096
|
-
case "eq":
|
|
1097
|
-
case "ne":
|
|
1098
|
-
case "lt":
|
|
1099
|
-
case "le":
|
|
1100
|
-
case "gt":
|
|
1101
|
-
case "ge": {
|
|
1102
|
-
return handleRelationalOperator(operator, operands, mapper);
|
|
1103
|
-
}
|
|
1104
|
-
case "in": {
|
|
1105
|
-
return handleInOperator(operands, mapper);
|
|
1106
|
-
}
|
|
1107
|
-
case "contains":
|
|
1108
|
-
case "startsWith":
|
|
1109
|
-
case "endsWith": {
|
|
1110
|
-
return handleStringOperator(operator, operands, mapper);
|
|
1111
|
-
}
|
|
1112
|
-
case "hasIntersection": {
|
|
1113
|
-
return handleHasIntersectionOperator(operands, mapper);
|
|
1114
|
-
}
|
|
1115
|
-
case "lambda": {
|
|
1116
|
-
return handleLambdaOperator(operands);
|
|
1117
|
-
}
|
|
1118
|
-
case "exists":
|
|
1119
|
-
case "exists_one":
|
|
1120
|
-
case "all":
|
|
1121
|
-
case "except":
|
|
1122
|
-
case "filter": {
|
|
1123
|
-
return handleCollectionOperator(operator, operands, mapper);
|
|
1124
|
-
}
|
|
1125
|
-
case "map": {
|
|
1126
|
-
return handleMapOperator(operands, mapper);
|
|
1127
|
-
}
|
|
1128
|
-
case "overlaps": {
|
|
1129
|
-
return handleOverlapsOperator(operands, mapper);
|
|
1130
|
-
}
|
|
1131
|
-
case "ancestorOf": {
|
|
1132
|
-
return handleAncestorDescendantOperator(operands, mapper, "ancestor");
|
|
1133
|
-
}
|
|
1134
|
-
case "descendentOf": {
|
|
1135
|
-
return handleAncestorDescendantOperator(operands, mapper, "descendant");
|
|
1136
55
|
}
|
|
1137
56
|
default:
|
|
1138
|
-
throw new
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
function containsCollectionOperator(expr) {
|
|
1142
|
-
if (!isOperatorOperand(expr)) {
|
|
1143
|
-
return false;
|
|
1144
|
-
}
|
|
1145
|
-
if (COLLECTION_OPERATORS.has(expr.operator)) {
|
|
1146
|
-
return true;
|
|
1147
|
-
}
|
|
1148
|
-
return expr.operands.some(containsCollectionOperator);
|
|
1149
|
-
}
|
|
1150
|
-
/**
|
|
1151
|
-
* Whether `expr` dots through at least one intermediate to-one hop, so negating it needs the
|
|
1152
|
-
* hop requirement of buildExpressionHopsExistFilter.
|
|
1153
|
-
*/
|
|
1154
|
-
function referencesChainedRelation(expr, mapper) {
|
|
1155
|
-
if (isNamedOperand(expr)) {
|
|
1156
|
-
const { relations } = resolveFieldReference(expr.name, mapper);
|
|
1157
|
-
return relations !== undefined && relations.length > 1;
|
|
1158
|
-
}
|
|
1159
|
-
if (!isOperatorOperand(expr) || expr.operator === "lambda") {
|
|
1160
|
-
return false;
|
|
1161
|
-
}
|
|
1162
|
-
return expr.operands.some((operand) => referencesChainedRelation(operand, mapper));
|
|
1163
|
-
}
|
|
1164
|
-
/**
|
|
1165
|
-
* Builds the filter for `!expr`. Plain field predicates negate correctly with Prisma's NOT
|
|
1166
|
-
* (SQL three-valued logic keeps NULL rows excluded under both polarities), but relation
|
|
1167
|
-
* subqueries collapse UNKNOWN to false at the EXISTS boundary, so `NOT(some(P))` would
|
|
1168
|
-
* wrongly include rows whose elements make P UNKNOWN (a NULL element column is a missing
|
|
1169
|
-
* attribute — a CEL error — on the check side, which Cerbos treats as deny). Negation is
|
|
1170
|
-
* therefore pushed down to the collection operators, which encode CEL's exact error
|
|
1171
|
-
* semantics:
|
|
1172
|
-
*
|
|
1173
|
-
* - exists(c,P) is TRUE with a true witness, FALSE if every element is definitively false,
|
|
1174
|
-
* and an ERROR otherwise — so `!exists` admits only rows with no P-match AND no
|
|
1175
|
-
* UNKNOWN-element (the nullable-field guard).
|
|
1176
|
-
* - all(c,P) is FALSE only with a definitive false witness (a false witness absorbs error
|
|
1177
|
-
* elements) — so `!all` is `some(NOT P)`, which SQL already evaluates definitively.
|
|
1178
|
-
*/
|
|
1179
|
-
function buildNegatedFilter(operand, mapper) {
|
|
1180
|
-
if (isNamedOperand(operand)) {
|
|
1181
|
-
const { relations, ...fieldRef } = resolveFieldReference(operand.name, mapper);
|
|
1182
|
-
if (!relations || relations.length === 0) {
|
|
1183
|
-
return buildFieldEqualsFilter(fieldRef, false);
|
|
1184
|
-
}
|
|
1185
|
-
return negateRequiringHops(operand, buildPrismaFilterFromCerbosExpression(operand, mapper), mapper);
|
|
1186
|
-
}
|
|
1187
|
-
// `and`/`or` must be pushed through with De Morgan whenever a branch can be UNKNOWN, so
|
|
1188
|
-
// CEL's error absorption survives: `!(A && B)` with A erroring and B false is TRUE in CEL,
|
|
1189
|
-
// and `OR[!A, !B]` reproduces that where a single outer NOT over the conjunction — with the
|
|
1190
|
-
// hop requirement ANDed outside it — would deny. A chained relation is the second source of
|
|
1191
|
-
// UNKNOWN besides the collection macros, so it opens the same push-down.
|
|
1192
|
-
if (isOperatorOperand(operand) &&
|
|
1193
|
-
(containsCollectionOperator(operand) ||
|
|
1194
|
-
referencesChainedRelation(operand, mapper))) {
|
|
1195
|
-
switch (operand.operator) {
|
|
1196
|
-
case "and":
|
|
1197
|
-
return {
|
|
1198
|
-
OR: operand.operands.map((o) => buildNegatedFilter(o, mapper)),
|
|
1199
|
-
};
|
|
1200
|
-
case "or":
|
|
1201
|
-
return {
|
|
1202
|
-
AND: operand.operands.map((o) => buildNegatedFilter(o, mapper)),
|
|
1203
|
-
};
|
|
1204
|
-
case "not":
|
|
1205
|
-
return buildPrismaFilterFromCerbosExpression(assertDefined(operand.operands[0], "not operator requires an operand"), mapper);
|
|
1206
|
-
case "exists":
|
|
1207
|
-
case "all":
|
|
1208
|
-
case "except":
|
|
1209
|
-
case "exists_one":
|
|
1210
|
-
case "filter":
|
|
1211
|
-
return buildNegatedCollectionFilter(operand.operator, operand.operands, mapper);
|
|
1212
|
-
}
|
|
1213
|
-
}
|
|
1214
|
-
return negateRequiringHops(operand, buildPrismaFilterFromCerbosExpression(operand, mapper), mapper);
|
|
1215
|
-
}
|
|
1216
|
-
function getTernaryOperands(operands) {
|
|
1217
|
-
if (operands.length !== 3) {
|
|
1218
|
-
throw new Error(`if (ternary) requires exactly 3 operands (condition, then, else), got ${operands.length}`);
|
|
1219
|
-
}
|
|
1220
|
-
return {
|
|
1221
|
-
condition: assertDefined(operands[0], "if (ternary) requires a condition operand"),
|
|
1222
|
-
thenBranch: assertDefined(operands[1], "if (ternary) requires a then operand"),
|
|
1223
|
-
elseBranch: assertDefined(operands[2], "if (ternary) requires an else operand"),
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
function getConstantBooleanCondition(condition) {
|
|
1227
|
-
if (!isValueOperand(condition)) {
|
|
1228
|
-
return undefined;
|
|
1229
|
-
}
|
|
1230
|
-
if (typeof condition.value !== "boolean") {
|
|
1231
|
-
throw new Error("if (ternary) condition must be a boolean expression");
|
|
1232
|
-
}
|
|
1233
|
-
return condition.value;
|
|
1234
|
-
}
|
|
1235
|
-
function buildBooleanBranchFilter(branch, mapper) {
|
|
1236
|
-
if (!isValueOperand(branch)) {
|
|
1237
|
-
return {
|
|
1238
|
-
kind: "filter",
|
|
1239
|
-
filter: buildPrismaFilterFromCerbosExpression(branch, mapper),
|
|
1240
|
-
};
|
|
1241
|
-
}
|
|
1242
|
-
if (typeof branch.value !== "boolean") {
|
|
1243
|
-
throw new Error("if (ternary) branch in boolean position must be a boolean");
|
|
1244
|
-
}
|
|
1245
|
-
return { kind: "constant", value: branch.value };
|
|
1246
|
-
}
|
|
1247
|
-
/**
|
|
1248
|
-
* "The ternary's condition is definitively FALSE", which is exactly buildNegatedFilter's
|
|
1249
|
-
* contract — three-valued, so a condition that is UNKNOWN (a NULL column, an erroring lambda
|
|
1250
|
-
* body, an absent to-one parent) selects NEITHER branch.
|
|
1251
|
-
*
|
|
1252
|
-
* It delegates rather than spelling a second negation. A private copy is how the ternary
|
|
1253
|
-
* missed the hop requirement #315/#316 added: a bare `NOT` over a chain filter is TRUE when
|
|
1254
|
-
* the to-one parent is absent, so the else-branch was selected for rows CEL denies outright —
|
|
1255
|
-
* the missing path is an evaluation error, not a false condition
|
|
1256
|
-
* (cerbos/query-plan-adapters#334). Delegating also gives the ternary the De Morgan push-down,
|
|
1257
|
-
* which a chained `and`/`or` condition needs for CEL's error absorption to survive.
|
|
1258
|
-
*/
|
|
1259
|
-
function buildFalseConditionFilter(condition, mapper) {
|
|
1260
|
-
if (isValueOperand(condition)) {
|
|
1261
|
-
throw new Error("Constant ternary conditions must be folded before use");
|
|
1262
|
-
}
|
|
1263
|
-
return buildNegatedFilter(condition, mapper);
|
|
1264
|
-
}
|
|
1265
|
-
function buildGuardedTernaryFilter({ condition, thenFilter, elseFilter, mapper, }) {
|
|
1266
|
-
const conditionTrue = buildPrismaFilterFromCerbosExpression(condition, mapper);
|
|
1267
|
-
const conditionFalse = buildFalseConditionFilter(condition, mapper);
|
|
1268
|
-
const guardedBranches = [];
|
|
1269
|
-
if (thenFilter.kind === "filter") {
|
|
1270
|
-
guardedBranches.push({ AND: [conditionTrue, thenFilter.filter] });
|
|
1271
|
-
}
|
|
1272
|
-
else if (thenFilter.value) {
|
|
1273
|
-
guardedBranches.push(conditionTrue);
|
|
1274
|
-
}
|
|
1275
|
-
if (elseFilter.kind === "filter") {
|
|
1276
|
-
guardedBranches.push({ AND: [conditionFalse, elseFilter.filter] });
|
|
1277
|
-
}
|
|
1278
|
-
else if (elseFilter.value) {
|
|
1279
|
-
guardedBranches.push(conditionFalse);
|
|
57
|
+
throw new errors_1.UnsupportedQueryPlanError(`Invalid query plan.`);
|
|
1280
58
|
}
|
|
1281
|
-
// For a known condition this contradiction is false. If the condition is
|
|
1282
|
-
// NULL/error-derived, both sides are SQL UNKNOWN, which keeps the whole
|
|
1283
|
-
// ternary UNKNOWN under an outer NOT instead of authorizing the row.
|
|
1284
|
-
guardedBranches.push({ AND: [conditionTrue, conditionFalse] });
|
|
1285
|
-
return {
|
|
1286
|
-
OR: guardedBranches,
|
|
1287
|
-
};
|
|
1288
|
-
}
|
|
1289
|
-
function finalizeTernaryBranchPredicate(predicate) {
|
|
1290
|
-
if (predicate.kind === "filter") {
|
|
1291
|
-
return predicate.filter;
|
|
1292
|
-
}
|
|
1293
|
-
if (predicate.value) {
|
|
1294
|
-
return buildAlwaysTrueFilter();
|
|
1295
|
-
}
|
|
1296
|
-
// Prisma has no model-agnostic always-false `where` shape: empty logical
|
|
1297
|
-
// arrays are ignored. Real PDP plans fold this case to ALWAYS_DENIED.
|
|
1298
|
-
throw new Error("A constant-false conditional predicate must be folded by the Cerbos planner");
|
|
1299
|
-
}
|
|
1300
|
-
function handleBooleanTernaryOperator(operands, mapper) {
|
|
1301
|
-
const { condition, thenBranch, elseBranch } = getTernaryOperands(operands);
|
|
1302
|
-
const constantCondition = getConstantBooleanCondition(condition);
|
|
1303
|
-
if (constantCondition !== undefined) {
|
|
1304
|
-
return finalizeTernaryBranchPredicate(buildBooleanBranchFilter(constantCondition ? thenBranch : elseBranch, mapper));
|
|
1305
|
-
}
|
|
1306
|
-
return buildGuardedTernaryFilter({
|
|
1307
|
-
condition,
|
|
1308
|
-
thenFilter: buildBooleanBranchFilter(thenBranch, mapper),
|
|
1309
|
-
elseFilter: buildBooleanBranchFilter(elseBranch, mapper),
|
|
1310
|
-
mapper,
|
|
1311
|
-
});
|
|
1312
|
-
}
|
|
1313
|
-
function buildTernaryComparisonBranch({ operator, operands, ternaryIndex, branch, mapper, }) {
|
|
1314
|
-
const substitutedOperands = operands.map((operand, index) => index === ternaryIndex ? branch : operand);
|
|
1315
|
-
assertDefined(substitutedOperands[0], `${operator} requires a left operand`);
|
|
1316
|
-
assertDefined(substitutedOperands[1], `${operator} requires a right operand`);
|
|
1317
|
-
const normalized = normalizeBinaryOperands(operator, substitutedOperands);
|
|
1318
|
-
const normalizedFirst = normalized.operands[0];
|
|
1319
|
-
const normalizedSecond = normalized.operands[1];
|
|
1320
|
-
if (normalized.operands.length === 2 &&
|
|
1321
|
-
normalizedFirst !== undefined &&
|
|
1322
|
-
normalizedSecond !== undefined &&
|
|
1323
|
-
isValueOperand(normalizedFirst) &&
|
|
1324
|
-
isValueOperand(normalizedSecond)) {
|
|
1325
|
-
return {
|
|
1326
|
-
kind: "constant",
|
|
1327
|
-
value: evaluateConstantComparison(normalized.operator, normalizedFirst.value, normalizedSecond.value),
|
|
1328
|
-
};
|
|
1329
|
-
}
|
|
1330
|
-
return {
|
|
1331
|
-
kind: "filter",
|
|
1332
|
-
filter: buildPrismaFilterFromCerbosExpression(normalized, mapper),
|
|
1333
|
-
};
|
|
1334
|
-
}
|
|
1335
|
-
function tryHandleTernaryComparison(operator, operands, mapper) {
|
|
1336
|
-
if (CERBOS_TO_PRISMA_OPERATOR[operator] === undefined) {
|
|
1337
|
-
return null;
|
|
1338
|
-
}
|
|
1339
|
-
const ternaryIndex = operands.findIndex((operand) => isOperatorOperand(operand) && operand.operator === "if");
|
|
1340
|
-
if (ternaryIndex === -1) {
|
|
1341
|
-
return null;
|
|
1342
|
-
}
|
|
1343
|
-
if (operands.length !== 2) {
|
|
1344
|
-
throw new Error(`${operator} with a ternary requires exactly 2 operands, got ${operands.length}`);
|
|
1345
|
-
}
|
|
1346
|
-
const ternary = assertDefined(operands[ternaryIndex], "Ternary comparison operand is missing");
|
|
1347
|
-
if (!isOperatorOperand(ternary)) {
|
|
1348
|
-
throw new Error("Ternary comparison operand must be an expression");
|
|
1349
|
-
}
|
|
1350
|
-
const { condition, thenBranch, elseBranch } = getTernaryOperands(ternary.operands);
|
|
1351
|
-
const constantCondition = getConstantBooleanCondition(condition);
|
|
1352
|
-
if (constantCondition !== undefined) {
|
|
1353
|
-
return finalizeTernaryBranchPredicate(buildTernaryComparisonBranch({
|
|
1354
|
-
operator,
|
|
1355
|
-
operands,
|
|
1356
|
-
ternaryIndex,
|
|
1357
|
-
branch: constantCondition ? thenBranch : elseBranch,
|
|
1358
|
-
mapper,
|
|
1359
|
-
}));
|
|
1360
|
-
}
|
|
1361
|
-
return buildGuardedTernaryFilter({
|
|
1362
|
-
condition,
|
|
1363
|
-
thenFilter: buildTernaryComparisonBranch({
|
|
1364
|
-
operator,
|
|
1365
|
-
operands,
|
|
1366
|
-
ternaryIndex,
|
|
1367
|
-
branch: thenBranch,
|
|
1368
|
-
mapper,
|
|
1369
|
-
}),
|
|
1370
|
-
elseFilter: buildTernaryComparisonBranch({
|
|
1371
|
-
operator,
|
|
1372
|
-
operands,
|
|
1373
|
-
ternaryIndex,
|
|
1374
|
-
branch: elseBranch,
|
|
1375
|
-
mapper,
|
|
1376
|
-
}),
|
|
1377
|
-
mapper,
|
|
1378
|
-
});
|
|
1379
|
-
}
|
|
1380
|
-
function evaluateConstantComparison(operator, left, right) {
|
|
1381
|
-
switch (operator) {
|
|
1382
|
-
case "eq":
|
|
1383
|
-
return areValuesEqual(left, right);
|
|
1384
|
-
case "ne":
|
|
1385
|
-
return !areValuesEqual(left, right);
|
|
1386
|
-
case "lt":
|
|
1387
|
-
case "le":
|
|
1388
|
-
case "gt":
|
|
1389
|
-
case "ge": {
|
|
1390
|
-
if (typeof left === "number" &&
|
|
1391
|
-
typeof right === "number" &&
|
|
1392
|
-
(Number.isNaN(left) || Number.isNaN(right))) {
|
|
1393
|
-
return false;
|
|
1394
|
-
}
|
|
1395
|
-
if (!((typeof left === "number" && typeof right === "number") ||
|
|
1396
|
-
(typeof left === "string" && typeof right === "string"))) {
|
|
1397
|
-
throw new Error(`${operator} constant comparison requires two numbers or two strings`);
|
|
1398
|
-
}
|
|
1399
|
-
switch (operator) {
|
|
1400
|
-
case "lt":
|
|
1401
|
-
return compareConstantValues(left, right) < 0;
|
|
1402
|
-
case "le":
|
|
1403
|
-
return compareConstantValues(left, right) <= 0;
|
|
1404
|
-
case "gt":
|
|
1405
|
-
return compareConstantValues(left, right) > 0;
|
|
1406
|
-
case "ge":
|
|
1407
|
-
return compareConstantValues(left, right) >= 0;
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
throw new Error(`Unsupported constant comparison operator: ${operator}`);
|
|
1412
|
-
}
|
|
1413
|
-
function compareConstantValues(left, right) {
|
|
1414
|
-
if (typeof left === "number" && typeof right === "number") {
|
|
1415
|
-
return left === right ? 0 : left < right ? -1 : 1;
|
|
1416
|
-
}
|
|
1417
|
-
if (typeof left !== "string" || typeof right !== "string") {
|
|
1418
|
-
throw new Error("Cannot order constant values of different types");
|
|
1419
|
-
}
|
|
1420
|
-
const leftCodePoints = Array.from(left, (character) => character.codePointAt(0));
|
|
1421
|
-
const rightCodePoints = Array.from(right, (character) => character.codePointAt(0));
|
|
1422
|
-
const sharedLength = Math.min(leftCodePoints.length, rightCodePoints.length);
|
|
1423
|
-
for (let index = 0; index < sharedLength; index++) {
|
|
1424
|
-
const leftCodePoint = leftCodePoints[index];
|
|
1425
|
-
const rightCodePoint = rightCodePoints[index];
|
|
1426
|
-
if (leftCodePoint !== rightCodePoint) {
|
|
1427
|
-
return leftCodePoint < rightCodePoint ? -1 : 1;
|
|
1428
|
-
}
|
|
1429
|
-
}
|
|
1430
|
-
return leftCodePoints.length === rightCodePoints.length
|
|
1431
|
-
? 0
|
|
1432
|
-
: leftCodePoints.length < rightCodePoints.length
|
|
1433
|
-
? -1
|
|
1434
|
-
: 1;
|
|
1435
|
-
}
|
|
1436
|
-
function areValuesEqual(left, right) {
|
|
1437
|
-
if (Array.isArray(left)) {
|
|
1438
|
-
return (Array.isArray(right) &&
|
|
1439
|
-
left.length === right.length &&
|
|
1440
|
-
left.every((value, index) => areValuesEqual(value, right[index])));
|
|
1441
|
-
}
|
|
1442
|
-
if (Array.isArray(right)) {
|
|
1443
|
-
return false;
|
|
1444
|
-
}
|
|
1445
|
-
if (typeof left === "object" && left !== null) {
|
|
1446
|
-
if (typeof right !== "object" || right === null) {
|
|
1447
|
-
return false;
|
|
1448
|
-
}
|
|
1449
|
-
const leftKeys = Object.keys(left);
|
|
1450
|
-
const rightKeys = Object.keys(right);
|
|
1451
|
-
return (leftKeys.length === rightKeys.length &&
|
|
1452
|
-
leftKeys.every((key) => key in right && areValuesEqual(left[key], right[key])));
|
|
1453
|
-
}
|
|
1454
|
-
return left === right;
|
|
1455
|
-
}
|
|
1456
|
-
function handleSizeComparison(operator, sizeOperand, valueOperand, mapper) {
|
|
1457
|
-
const collectionOperand = sizeOperand.operands[0];
|
|
1458
|
-
if (!collectionOperand || !isNamedOperand(collectionOperand)) {
|
|
1459
|
-
throw new Error("size operator requires a named collection operand");
|
|
1460
|
-
}
|
|
1461
|
-
if (!isValueOperand(valueOperand)) {
|
|
1462
|
-
throw new Error("size comparison requires a numeric value operand");
|
|
1463
|
-
}
|
|
1464
|
-
const count = valueOperand.value;
|
|
1465
|
-
if (typeof count !== "number") {
|
|
1466
|
-
throw new Error("size comparison requires a numeric value");
|
|
1467
|
-
}
|
|
1468
|
-
const isNonEmpty = (operator === "gt" && count === 0) || (operator === "ge" && count === 1);
|
|
1469
|
-
const isEmpty = (operator === "eq" && count === 0) ||
|
|
1470
|
-
(operator === "lt" && count === 1) ||
|
|
1471
|
-
(operator === "le" && count === 0);
|
|
1472
|
-
if (!isNonEmpty && !isEmpty) {
|
|
1473
|
-
throw new Error(`Unsupported size comparison: size(...) ${operator} ${count}`);
|
|
1474
|
-
}
|
|
1475
|
-
const { relations } = resolveFieldReference(collectionOperand.name, mapper);
|
|
1476
|
-
if (!relations || relations.length === 0) {
|
|
1477
|
-
throw new Error("size operator requires a relation mapping");
|
|
1478
|
-
}
|
|
1479
|
-
const deepest = relations[relations.length - 1];
|
|
1480
|
-
if (!deepest) {
|
|
1481
|
-
throw new Error("size operator requires a relation mapping");
|
|
1482
|
-
}
|
|
1483
|
-
const prismaOp = isNonEmpty ? "some" : "none";
|
|
1484
|
-
const leafFilter = relationFilter(deepest, prismaOp, {});
|
|
1485
|
-
if (relations.length === 1) {
|
|
1486
|
-
return leafFilter;
|
|
1487
|
-
}
|
|
1488
|
-
return buildNestedRelationFilter(relations.slice(0, -1), leafFilter);
|
|
1489
|
-
}
|
|
1490
|
-
/**
|
|
1491
|
-
* Helper function to process relational operators (eq, ne, lt, etc.)
|
|
1492
|
-
*/
|
|
1493
|
-
function handleRelationalOperator(operator, operands, mapper) {
|
|
1494
|
-
const ternaryFilter = tryHandleTernaryComparison(operator, operands, mapper);
|
|
1495
|
-
if (ternaryFilter) {
|
|
1496
|
-
return ternaryFilter;
|
|
1497
|
-
}
|
|
1498
|
-
({ operator, operands } = normalizeBinaryOperands(operator, operands));
|
|
1499
|
-
const prismaOperator = CERBOS_TO_PRISMA_OPERATOR[operator];
|
|
1500
|
-
if (!prismaOperator) {
|
|
1501
|
-
throw new Error(`Unsupported operator: ${operator}`);
|
|
1502
|
-
}
|
|
1503
|
-
const leftOperand = operands.find((o) => isNamedOperand(o) || isOperatorOperand(o));
|
|
1504
|
-
if (!leftOperand)
|
|
1505
|
-
throw new Error("No valid left operand found");
|
|
1506
|
-
const rightOperand = operands.find((o) => o !== leftOperand);
|
|
1507
|
-
if (!rightOperand)
|
|
1508
|
-
throw new Error("No valid right operand found");
|
|
1509
|
-
if (isOperatorOperand(leftOperand) && leftOperand.operator === "size") {
|
|
1510
|
-
return handleSizeComparison(operator, leftOperand, rightOperand, mapper);
|
|
1511
|
-
}
|
|
1512
|
-
const arithOperand = [leftOperand, rightOperand].find((o) => isOperatorOperand(o) && ARITHMETIC_OPERATORS.has(o.operator));
|
|
1513
|
-
if (arithOperand) {
|
|
1514
|
-
const otherOperand = arithOperand === leftOperand ? rightOperand : leftOperand;
|
|
1515
|
-
return handleArithmeticComparison(operator, arithOperand, otherOperand, arithOperand === leftOperand, mapper);
|
|
1516
|
-
}
|
|
1517
|
-
const mapOperand = [leftOperand, rightOperand].find((o) => isOperatorOperand(o) && o.operator === "map");
|
|
1518
|
-
if (mapOperand) {
|
|
1519
|
-
throw new Error(`Direct comparison of map(...) to a value is not supported (operator: ${operator}). ` +
|
|
1520
|
-
`Wrap the map() expression in hasIntersection(map(...), [...]) instead.`);
|
|
1521
|
-
}
|
|
1522
|
-
const left = resolveOperand(leftOperand, mapper);
|
|
1523
|
-
const right = resolveOperand(rightOperand, mapper);
|
|
1524
|
-
if (isResolvedFieldReference(left) && isResolvedFieldReference(right)) {
|
|
1525
|
-
return buildFieldToFieldFilter(operator, leftOperand, left, rightOperand, right);
|
|
1526
|
-
}
|
|
1527
|
-
if (isResolvedValue(left) && isResolvedFieldReference(right)) {
|
|
1528
|
-
return buildComparisonFilter(right, MIRRORED_OPERATOR[operator] ?? operator, left.value);
|
|
1529
|
-
}
|
|
1530
|
-
if (isResolvedValue(left) && isResolvedValue(right)) {
|
|
1531
|
-
const matches = evaluateConstantComparison(operator, left.value, right.value);
|
|
1532
|
-
if (matches) {
|
|
1533
|
-
return buildAlwaysTrueFilter();
|
|
1534
|
-
}
|
|
1535
|
-
throw new Error("A constant-false conditional predicate must be folded by the Cerbos planner");
|
|
1536
|
-
}
|
|
1537
|
-
const rightValue = requireResolvedValue(right, "Right operand must be a value");
|
|
1538
|
-
if (isResolvedFieldReference(left)) {
|
|
1539
|
-
return buildComparisonFilter(left, operator, rightValue.value);
|
|
1540
|
-
}
|
|
1541
|
-
return { [prismaOperator]: rightValue.value };
|
|
1542
|
-
}
|
|
1543
|
-
/**
|
|
1544
|
-
* Builds a field-vs-constant comparison. Fractional constants against ordering (and
|
|
1545
|
-
* equality) operators are emitted as a two-clause bracket because Prisma coerces filter
|
|
1546
|
-
* values to the column's type: on an Int column, `gte: 1.5` is silently bound as `gte: 1`,
|
|
1547
|
-
* inverting rows like aNumber == 1. Each bracket pairs the exact constant with its integer
|
|
1548
|
-
* neighbor so the combination is correct BOTH for Float columns (the extra clause is
|
|
1549
|
-
* redundant) and Int columns (whichever way Prisma truncates or floors the fraction).
|
|
1550
|
-
*/
|
|
1551
|
-
function buildComparisonFilter(fieldRef, operator, value) {
|
|
1552
|
-
const prismaOperator = assertDefined(CERBOS_TO_PRISMA_OPERATOR[operator], `Unsupported operator: ${operator}`);
|
|
1553
|
-
if (value === null) {
|
|
1554
|
-
assertNullOperandTranslatable(`\`${operator}\` against a null operand`, fieldRef.nullAttributeRepresentation);
|
|
1555
|
-
}
|
|
1556
|
-
// An attribute the caller sends as an explicit null holds a null VALUE in CEL, so equality
|
|
1557
|
-
// against a non-null operand is a definite FALSE and inequality a definite TRUE. Prisma leans
|
|
1558
|
-
// on SQL's UNKNOWN for both, which drops the row under either polarity, so the presence of the
|
|
1559
|
-
// column has to become part of the predicate. Confined to the equality family: an ordering
|
|
1560
|
-
// comparison against a null receiver is a no-overload error in CEL, which denies exactly as the
|
|
1561
|
-
// dropped row does.
|
|
1562
|
-
if (value !== null && isExplicitNullReference(fieldRef)) {
|
|
1563
|
-
const fieldName = getLeafField(fieldRef.path);
|
|
1564
|
-
if (operator === "eq") {
|
|
1565
|
-
return guardedFieldFilter(fieldRef, { [fieldName]: { equals: value } });
|
|
1566
|
-
}
|
|
1567
|
-
if (operator === "ne") {
|
|
1568
|
-
return {
|
|
1569
|
-
NOT: guardedFieldFilter(fieldRef, { [fieldName]: { equals: value } }),
|
|
1570
|
-
};
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
if (typeof value === "number" && !Number.isInteger(value)) {
|
|
1574
|
-
const fieldName = getLeafField(fieldRef.path);
|
|
1575
|
-
const lower = Math.floor(value);
|
|
1576
|
-
const upper = Math.ceil(value);
|
|
1577
|
-
const equalsBracket = {
|
|
1578
|
-
AND: [
|
|
1579
|
-
{ [fieldName]: { equals: value } },
|
|
1580
|
-
{ [fieldName]: { gt: lower } },
|
|
1581
|
-
{ [fieldName]: { lt: upper } },
|
|
1582
|
-
],
|
|
1583
|
-
};
|
|
1584
|
-
let bracket;
|
|
1585
|
-
switch (operator) {
|
|
1586
|
-
case "gt":
|
|
1587
|
-
bracket = {
|
|
1588
|
-
OR: [{ [fieldName]: { gt: value } }, { [fieldName]: { gte: upper } }],
|
|
1589
|
-
};
|
|
1590
|
-
break;
|
|
1591
|
-
case "ge":
|
|
1592
|
-
bracket = {
|
|
1593
|
-
AND: [{ [fieldName]: { gte: value } }, { [fieldName]: { gt: lower } }],
|
|
1594
|
-
};
|
|
1595
|
-
break;
|
|
1596
|
-
case "lt":
|
|
1597
|
-
bracket = {
|
|
1598
|
-
OR: [{ [fieldName]: { lt: value } }, { [fieldName]: { lte: lower } }],
|
|
1599
|
-
};
|
|
1600
|
-
break;
|
|
1601
|
-
case "le":
|
|
1602
|
-
bracket = {
|
|
1603
|
-
AND: [{ [fieldName]: { lte: value } }, { [fieldName]: { lt: upper } }],
|
|
1604
|
-
};
|
|
1605
|
-
break;
|
|
1606
|
-
case "eq":
|
|
1607
|
-
bracket = equalsBracket;
|
|
1608
|
-
break;
|
|
1609
|
-
case "ne":
|
|
1610
|
-
bracket = { NOT: equalsBracket };
|
|
1611
|
-
break;
|
|
1612
|
-
}
|
|
1613
|
-
if (bracket) {
|
|
1614
|
-
return wrapRelations(fieldRef.relations, bracket);
|
|
1615
|
-
}
|
|
1616
|
-
}
|
|
1617
|
-
return buildFieldFilter(fieldRef, prismaOperator, value);
|
|
1618
|
-
}
|
|
1619
|
-
/**
|
|
1620
|
-
* Builds a column-vs-column comparison as a Prisma field reference. Prisma only supports
|
|
1621
|
-
* references between fields of the SAME model, so the container is the root model for
|
|
1622
|
-
* root-level comparisons and the relation's model inside a lambda; mixed-scope comparisons
|
|
1623
|
-
* (an element column against an outer column) are cross-model and must fail loudly.
|
|
1624
|
-
*/
|
|
1625
|
-
function buildFieldToFieldFilter(operator, leftOperand, left, rightOperand, right) {
|
|
1626
|
-
const prismaOperator = assertDefined(CERBOS_TO_PRISMA_OPERATOR[operator], `Unsupported operator: ${operator}`);
|
|
1627
|
-
if (!isNamedOperand(leftOperand) || !isNamedOperand(rightOperand)) {
|
|
1628
|
-
throw new Error("Field-to-field comparison requires two named operands");
|
|
1629
|
-
}
|
|
1630
|
-
const scope = lambdaScopes[lambdaScopes.length - 1];
|
|
1631
|
-
let container;
|
|
1632
|
-
if (scope) {
|
|
1633
|
-
const prefix = scope.variableName + ".";
|
|
1634
|
-
const leftInScope = leftOperand.name.startsWith(prefix);
|
|
1635
|
-
const rightInScope = rightOperand.name.startsWith(prefix);
|
|
1636
|
-
if (leftInScope !== rightInScope) {
|
|
1637
|
-
throw new Error(`Cannot compare a collection element column with an outer column (${leftOperand.name} vs ${rightOperand.name}): ` +
|
|
1638
|
-
"Prisma field references only work between fields of the same model");
|
|
1639
|
-
}
|
|
1640
|
-
if (leftInScope) {
|
|
1641
|
-
container = scope.relationModel;
|
|
1642
|
-
if (!container) {
|
|
1643
|
-
throw new Error("Field-to-field comparison inside a collection requires `relation.model` in the mapper");
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
}
|
|
1647
|
-
if (container === undefined) {
|
|
1648
|
-
if ((left.relations && left.relations.length > 0) ||
|
|
1649
|
-
(right.relations && right.relations.length > 0)) {
|
|
1650
|
-
throw new Error("Cannot compare columns across relations: Prisma field references only work between fields of the same model");
|
|
1651
|
-
}
|
|
1652
|
-
container = rootModelName;
|
|
1653
|
-
if (!container) {
|
|
1654
|
-
throw new Error("Field-to-field comparison requires the `model` option (the Prisma model name) to build a field reference");
|
|
1655
|
-
}
|
|
1656
|
-
}
|
|
1657
|
-
const leftField = getLeafField(left.path);
|
|
1658
|
-
const rightField = getLeafField(right.path);
|
|
1659
|
-
const fieldReference = { _ref: rightField, _container: container };
|
|
1660
|
-
// Two explicit nulls are EQUAL in CEL, and a null against a value is definitely NOT equal.
|
|
1661
|
-
// A bare field reference gives UNKNOWN for both, which drops the row under either polarity.
|
|
1662
|
-
const leftExplicit = isExplicitNullReference(left);
|
|
1663
|
-
const rightExplicit = isExplicitNullReference(right);
|
|
1664
|
-
// Mixing the two conventions across one comparison has no faithful rendering. The declared side
|
|
1665
|
-
// needs a definite answer for its NULL (CEL holds a null VALUE); the undeclared side needs
|
|
1666
|
-
// UNKNOWN for its NULL (a missing attribute, which CEL denies under both polarities). A definite
|
|
1667
|
-
// predicate returns rows the PDP refuses; a plain one drops rows the PDP allows. Refuse it
|
|
1668
|
-
// rather than pick a direction — declare both attributes, or neither.
|
|
1669
|
-
if (leftExplicit !== rightExplicit && (operator === "eq" || operator === "ne")) {
|
|
1670
|
-
throw new Error(`Cannot translate \`${operator}\` between two columns under mixed null conventions: ` +
|
|
1671
|
-
"cannot compare an attribute declared explicit-null with one on the omitted convention: the omitted side is UNKNOWN for a NULL column while the declared side is definite, and no single predicate is both. Declare nullAttributeRepresentation on both mapper entries, or on neither.");
|
|
1672
|
-
}
|
|
1673
|
-
if (leftExplicit && rightExplicit && (operator === "eq" || operator === "ne")) {
|
|
1674
|
-
const present = [];
|
|
1675
|
-
if (leftExplicit) {
|
|
1676
|
-
present.push({ [leftField]: { not: null } });
|
|
1677
|
-
}
|
|
1678
|
-
if (rightExplicit) {
|
|
1679
|
-
present.push({ [rightField]: { not: null } });
|
|
1680
|
-
}
|
|
1681
|
-
const equality = leftExplicit && rightExplicit
|
|
1682
|
-
? {
|
|
1683
|
-
OR: [
|
|
1684
|
-
{ AND: [{ [leftField]: null }, { [rightField]: null }] },
|
|
1685
|
-
{ AND: [...present, { [leftField]: { equals: fieldReference } }] },
|
|
1686
|
-
],
|
|
1687
|
-
}
|
|
1688
|
-
: { AND: [...present, { [leftField]: { equals: fieldReference } }] };
|
|
1689
|
-
return operator === "eq" ? equality : { NOT: equality };
|
|
1690
|
-
}
|
|
1691
|
-
// `ne` is the one operator whose Prisma spelling cannot carry a field reference: `not` nests a
|
|
1692
|
-
// NestedStringFilter, which has no `_ref` form, so `{ col: { not: { _ref } } }` is rejected by
|
|
1693
|
-
// the client rather than executed. Hoisting the negation to the top-level `NOT` combinator says
|
|
1694
|
-
// the same thing with a shape that does accept one — the same rewrite the explicit-null branch
|
|
1695
|
-
// above already performs. Three-valued logic is unchanged by the hoist: a NULL on either side
|
|
1696
|
-
// makes the inner equality UNKNOWN, and `NOT UNKNOWN` is still UNKNOWN, so the row stays out
|
|
1697
|
-
// under both polarities, which is what a missing attribute does on the check side.
|
|
1698
|
-
if (operator === "ne") {
|
|
1699
|
-
return { NOT: { [leftField]: { equals: fieldReference } } };
|
|
1700
|
-
}
|
|
1701
|
-
return { [leftField]: { [prismaOperator]: fieldReference } };
|
|
1702
|
-
}
|
|
1703
|
-
/**
|
|
1704
|
-
* Helper function to handle "in" operator
|
|
1705
|
-
*/
|
|
1706
|
-
function handleInOperator(operands, mapper) {
|
|
1707
|
-
if (operands.length !== 2) {
|
|
1708
|
-
throw new Error("in requires exactly two operands");
|
|
1709
|
-
}
|
|
1710
|
-
const member = assertDefined(operands[0], "in requires a member operand");
|
|
1711
|
-
const collection = assertDefined(operands[1], "in requires a collection operand");
|
|
1712
|
-
if (isNamedOperand(member) && isValueOperand(collection)) {
|
|
1713
|
-
const fieldRef = resolveFieldReference(member.name, mapper);
|
|
1714
|
-
const values = Array.isArray(collection.value)
|
|
1715
|
-
? collection.value
|
|
1716
|
-
: [collection.value];
|
|
1717
|
-
return buildMembershipFilter(fieldRef, values);
|
|
1718
|
-
}
|
|
1719
|
-
if (isValueOperand(member) && isNamedOperand(collection)) {
|
|
1720
|
-
return buildMembershipFilter(resolveFieldReference(collection.name, mapper), [member.value]);
|
|
1721
|
-
}
|
|
1722
|
-
if (isNamedOperand(member) && isNamedOperand(collection)) {
|
|
1723
|
-
throw new Error("Membership between two database attributes is not supported: Prisma cannot compare a related element column with an outer scalar column");
|
|
1724
|
-
}
|
|
1725
|
-
throw new Error("in requires a field member and literal list, or a literal member and field collection");
|
|
1726
|
-
}
|
|
1727
|
-
// Upper bound on the IN-list produced when enumerating a constant receiver's substrings.
|
|
1728
|
-
const MAX_ENUMERATED_NEEDLES = 1000;
|
|
1729
|
-
/**
|
|
1730
|
-
* Helper function to handle string operators (contains, startsWith, endsWith).
|
|
1731
|
-
*
|
|
1732
|
-
* These operators are receiver-sensitive and the planner preserves policy source order:
|
|
1733
|
-
* operand 0 is the receiver (haystack), operand 1 the needle. Swapping them silently
|
|
1734
|
-
* inverts the match direction, so unlike symmetric comparisons they are never normalized.
|
|
1735
|
-
*/
|
|
1736
|
-
function handleStringOperator(operator, operands, mapper) {
|
|
1737
|
-
if (operands.length !== 2) {
|
|
1738
|
-
throw new Error(`${operator} requires exactly two operands`);
|
|
1739
|
-
}
|
|
1740
|
-
const receiver = resolveOperand(assertDefined(operands[0], `${operator} requires a receiver operand`), mapper);
|
|
1741
|
-
const needle = resolveOperand(assertDefined(operands[1], `${operator} requires a needle operand`), mapper);
|
|
1742
|
-
// Column receiver, constant needle: Prisma's LIKE-based filter.
|
|
1743
|
-
if (isResolvedFieldReference(receiver) && isResolvedValue(needle)) {
|
|
1744
|
-
const { value } = needle;
|
|
1745
|
-
if (typeof value !== "string") {
|
|
1746
|
-
throw new Error(`${operator} operator requires string value`);
|
|
1747
|
-
}
|
|
1748
|
-
// Prisma emits LIKE without an ESCAPE clause and does not escape wildcard characters,
|
|
1749
|
-
// so a needle containing % or _ would match as a pattern instead of literally (e.g.
|
|
1750
|
-
// startsWith("100%") wrongly matches "100xdone"). Fail loudly rather than filter wrong.
|
|
1751
|
-
//
|
|
1752
|
-
// A backslash is the same hazard reached from the other direction, and only an executed
|
|
1753
|
-
// PostgreSQL leg surfaces it (cerbos/query-plan-adapters#320): SQLite's LIKE has no escape
|
|
1754
|
-
// character at all, so `\` is literal there, while PostgreSQL and MySQL treat it as the
|
|
1755
|
-
// DEFAULT escape character even with no ESCAPE clause. `endsWith("\\")` is then a pattern
|
|
1756
|
-
// ending in an escape character — a hard error on PostgreSQL — and a `\x` anywhere inside
|
|
1757
|
-
// silently drops the backslash, so `contains("a\\b")` matches "ab", a row the PDP denies.
|
|
1758
|
-
if (/[%_\\]/.test(value)) {
|
|
1759
|
-
throw new Error(`Cannot translate ${operator} with a needle containing LIKE metacharacters (%, _ or \\): ` +
|
|
1760
|
-
"Prisma does not escape wildcards in string filters, and \\ is the default LIKE " +
|
|
1761
|
-
"escape character on PostgreSQL and MySQL");
|
|
1762
|
-
}
|
|
1763
|
-
const fieldName = getLeafField(receiver.path);
|
|
1764
|
-
return wrapRelations(receiver.relations, {
|
|
1765
|
-
[fieldName]: { [operator]: value },
|
|
1766
|
-
});
|
|
1767
|
-
}
|
|
1768
|
-
// Constant receiver, column needle (e.g. `"a-b-c".contains(R.attr.x)`): enumerate every
|
|
1769
|
-
// candidate needle the constant admits — prefixes for startsWith, suffixes for endsWith,
|
|
1770
|
-
// substrings for contains — into an exact IN filter. No LIKE, so no escaping hazards; a
|
|
1771
|
-
// NULL needle column stays excluded (CEL missing-attribute deny).
|
|
1772
|
-
if (isResolvedValue(receiver) && isResolvedFieldReference(needle)) {
|
|
1773
|
-
if (typeof receiver.value !== "string") {
|
|
1774
|
-
throw new Error(`${operator} operator requires a string receiver`);
|
|
1775
|
-
}
|
|
1776
|
-
const haystack = receiver.value;
|
|
1777
|
-
const candidates = new Set([""]);
|
|
1778
|
-
if (operator === "startsWith") {
|
|
1779
|
-
for (let i = 1; i <= haystack.length; i++) {
|
|
1780
|
-
candidates.add(haystack.slice(0, i));
|
|
1781
|
-
}
|
|
1782
|
-
}
|
|
1783
|
-
else if (operator === "endsWith") {
|
|
1784
|
-
for (let i = 0; i < haystack.length; i++) {
|
|
1785
|
-
candidates.add(haystack.slice(i));
|
|
1786
|
-
}
|
|
1787
|
-
}
|
|
1788
|
-
else {
|
|
1789
|
-
for (let start = 0; start < haystack.length; start++) {
|
|
1790
|
-
for (let end = start + 1; end <= haystack.length; end++) {
|
|
1791
|
-
candidates.add(haystack.slice(start, end));
|
|
1792
|
-
}
|
|
1793
|
-
}
|
|
1794
|
-
}
|
|
1795
|
-
if (candidates.size > MAX_ENUMERATED_NEEDLES) {
|
|
1796
|
-
throw new Error(`Cannot translate ${operator} with a constant receiver of this length: ` +
|
|
1797
|
-
`enumerating its ${candidates.size} candidate needles exceeds the ${MAX_ENUMERATED_NEEDLES}-entry limit`);
|
|
1798
|
-
}
|
|
1799
|
-
const fieldName = getLeafField(needle.path);
|
|
1800
|
-
return wrapRelations(needle.relations, {
|
|
1801
|
-
[fieldName]: { in: [...candidates] },
|
|
1802
|
-
});
|
|
1803
|
-
}
|
|
1804
|
-
if (isResolvedFieldReference(receiver) && isResolvedFieldReference(needle)) {
|
|
1805
|
-
// A column-valued needle would need its LIKE metacharacters escaped per row, which
|
|
1806
|
-
// Prisma's filters cannot do (and Prisma leaks wildcards from field references).
|
|
1807
|
-
throw new Error(`Cannot translate ${operator} between two columns: Prisma cannot escape LIKE wildcards held in a column`);
|
|
1808
|
-
}
|
|
1809
|
-
throw new Error(`${operator} between two constants must be folded by the Cerbos planner`);
|
|
1810
|
-
}
|
|
1811
|
-
/**
|
|
1812
|
-
* Helper function to handle "hasIntersection" operator
|
|
1813
|
-
*/
|
|
1814
|
-
function handleHasIntersectionOperator(operands, mapper) {
|
|
1815
|
-
if (operands.length !== 2) {
|
|
1816
|
-
throw new Error("hasIntersection requires exactly two operands");
|
|
1817
|
-
}
|
|
1818
|
-
// Intersection is symmetric, and the planner preserves policy source order — e.g.
|
|
1819
|
-
// `hasIntersection(["a"], R.attr.tags)` puts the constant list FIRST. Normalize to
|
|
1820
|
-
// field/map-first (see #256).
|
|
1821
|
-
({ operands } = normalizeBinaryOperands("hasIntersection", operands));
|
|
1822
|
-
const leftOperand = assertDefined(operands[0], "hasIntersection requires a left operand");
|
|
1823
|
-
const rightOperand = assertDefined(operands[1], "hasIntersection requires a right operand");
|
|
1824
|
-
// Check if left operand is a map operation
|
|
1825
|
-
if (isOperatorOperand(leftOperand) && leftOperand.operator === "map") {
|
|
1826
|
-
if (!isValueOperand(rightOperand)) {
|
|
1827
|
-
throw new Error("Second operand of hasIntersection must be a value");
|
|
1828
|
-
}
|
|
1829
|
-
const collection = assertDefined(leftOperand.operands[0], "Map expression must include a collection reference");
|
|
1830
|
-
const lambda = assertDefined(leftOperand.operands[1], "Map expression must include a lambda expression");
|
|
1831
|
-
if (!isNamedOperand(collection)) {
|
|
1832
|
-
throw new Error("First operand of map must be a collection reference");
|
|
1833
|
-
}
|
|
1834
|
-
// Get variable name from lambda
|
|
1835
|
-
if (!isOperatorOperand(lambda)) {
|
|
1836
|
-
throw new Error("Lambda expression must have operands");
|
|
1837
|
-
}
|
|
1838
|
-
const variable = assertDefined(lambda.operands[1], "Lambda variable must have a name");
|
|
1839
|
-
if (!isNamedOperand(variable)) {
|
|
1840
|
-
throw new Error("Lambda variable must have a name");
|
|
1841
|
-
}
|
|
1842
|
-
// Create scoped mapper for the collection
|
|
1843
|
-
const scopedMapper = createScopedMapper(collection.name, variable.name, mapper);
|
|
1844
|
-
const { relations } = resolveFieldReference(collection.name, mapper);
|
|
1845
|
-
if (!relations || relations.length === 0) {
|
|
1846
|
-
throw new Error("Map operation requires relations");
|
|
1847
|
-
}
|
|
1848
|
-
const projection = assertDefined(lambda.operands[0], "Invalid map lambda expression structure");
|
|
1849
|
-
if (!isNamedOperand(projection)) {
|
|
1850
|
-
throw new Error("Invalid map lambda expression structure");
|
|
1851
|
-
}
|
|
1852
|
-
// Use scoped mapper for resolving the projection, collecting nullable element columns.
|
|
1853
|
-
const scope = {
|
|
1854
|
-
variableName: variable.name,
|
|
1855
|
-
relationModel: relations[relations.length - 1]?.model,
|
|
1856
|
-
nullableFields: new Set(),
|
|
1857
|
-
unknownFilters: [],
|
|
1858
|
-
};
|
|
1859
|
-
lambdaScopes.push(scope);
|
|
1860
|
-
let resolved;
|
|
1861
|
-
try {
|
|
1862
|
-
resolved = resolveFieldReference(projection.name, scopedMapper);
|
|
1863
|
-
}
|
|
1864
|
-
finally {
|
|
1865
|
-
lambdaScopes.pop();
|
|
1866
|
-
}
|
|
1867
|
-
const fieldName = getLeafField(resolved.path);
|
|
1868
|
-
const base = buildNestedRelationFilter(relations, {
|
|
1869
|
-
[fieldName]: { in: rightOperand.value },
|
|
1870
|
-
});
|
|
1871
|
-
if (scope.nullableFields.size === 0) {
|
|
1872
|
-
return base;
|
|
1873
|
-
}
|
|
1874
|
-
// CEL map() errors if ANY element is missing the projected attribute — even alongside a
|
|
1875
|
-
// matching element — and Cerbos treats that error as deny. Exclude rows holding an
|
|
1876
|
-
// element whose projected (nullable) column is NULL.
|
|
1877
|
-
return {
|
|
1878
|
-
AND: [
|
|
1879
|
-
base,
|
|
1880
|
-
{
|
|
1881
|
-
NOT: buildNestedRelationFilter(relations, buildNullWitnessFilter(scope.nullableFields)),
|
|
1882
|
-
},
|
|
1883
|
-
],
|
|
1884
|
-
};
|
|
1885
|
-
}
|
|
1886
|
-
// Handle regular field reference
|
|
1887
|
-
if (!isNamedOperand(leftOperand)) {
|
|
1888
|
-
throw new Error("First operand of hasIntersection must be a field reference or map expression");
|
|
1889
|
-
}
|
|
1890
|
-
if (!isValueOperand(rightOperand)) {
|
|
1891
|
-
throw new Error("Second operand of hasIntersection must be a value");
|
|
1892
|
-
}
|
|
1893
|
-
const { path, relations } = resolveFieldReference(leftOperand.name, mapper);
|
|
1894
|
-
if (!Array.isArray(rightOperand.value)) {
|
|
1895
|
-
throw new Error("hasIntersection requires an array value");
|
|
1896
|
-
}
|
|
1897
|
-
if (relations && relations.length > 0) {
|
|
1898
|
-
return buildMembershipFilter({ path, relations }, rightOperand.value);
|
|
1899
|
-
}
|
|
1900
|
-
const fieldName = getLeafField(path);
|
|
1901
|
-
return { [fieldName]: { some: rightOperand.value } };
|
|
1902
|
-
}
|
|
1903
|
-
/**
|
|
1904
|
-
* Helper function to handle "lambda" operator
|
|
1905
|
-
*/
|
|
1906
|
-
function handleLambdaOperator(operands) {
|
|
1907
|
-
const condition = assertDefined(operands[0], "Lambda requires a condition operand");
|
|
1908
|
-
const variable = assertDefined(operands[1], "Lambda requires a variable operand");
|
|
1909
|
-
if (!isNamedOperand(variable)) {
|
|
1910
|
-
throw new Error("Lambda variable must have a name");
|
|
1911
|
-
}
|
|
1912
|
-
return buildPrismaFilterFromCerbosExpression(condition, (key) => ({
|
|
1913
|
-
field: key.replace(`${variable.name}.`, ""),
|
|
1914
|
-
}));
|
|
1915
|
-
}
|
|
1916
|
-
function buildCollectionLambdaParts(operator, operands, mapper) {
|
|
1917
|
-
if (operands.length !== 2) {
|
|
1918
|
-
throw new Error(`${operator} requires exactly two operands`);
|
|
1919
|
-
}
|
|
1920
|
-
const collection = assertDefined(operands[0], `${operator} requires a collection operand`);
|
|
1921
|
-
const lambda = assertDefined(operands[1], `${operator} requires a lambda operand`);
|
|
1922
|
-
if (!isNamedOperand(collection)) {
|
|
1923
|
-
throw new Error(`First operand of ${operator} must be a collection reference`);
|
|
1924
|
-
}
|
|
1925
|
-
if (!isOperatorOperand(lambda)) {
|
|
1926
|
-
throw new Error(`Second operand of ${operator} must be a lambda expression`);
|
|
1927
|
-
}
|
|
1928
|
-
// Get variable name from lambda
|
|
1929
|
-
const variable = assertDefined(lambda.operands[1], "Lambda variable must have a name");
|
|
1930
|
-
if (!isNamedOperand(variable)) {
|
|
1931
|
-
throw new Error("Lambda variable must have a name");
|
|
1932
|
-
}
|
|
1933
|
-
// Create scoped mapper for the collection
|
|
1934
|
-
const scopedMapper = createScopedMapper(collection.name, variable.name, mapper);
|
|
1935
|
-
const { relations } = resolveFieldReference(collection.name, mapper);
|
|
1936
|
-
if (!relations || relations.length === 0) {
|
|
1937
|
-
throw new Error(`${operator} operator requires a relation mapping`);
|
|
1938
|
-
}
|
|
1939
|
-
const head = assertDefined(relations[0], `${operator} operator requires a relation mapping`);
|
|
1940
|
-
const restRelations = relations.slice(1);
|
|
1941
|
-
const deepest = assertDefined(relations[relations.length - 1], `${operator} operator requires a relation mapping`);
|
|
1942
|
-
const lambdaConditionOperand = assertDefined(lambda.operands[0], "Lambda expression must provide a condition");
|
|
1943
|
-
const scope = {
|
|
1944
|
-
variableName: variable.name,
|
|
1945
|
-
relationModel: deepest.model,
|
|
1946
|
-
nullableFields: new Set(),
|
|
1947
|
-
unknownFilters: [],
|
|
1948
|
-
};
|
|
1949
|
-
lambdaScopes.push(scope);
|
|
1950
|
-
let lambdaCondition;
|
|
1951
|
-
try {
|
|
1952
|
-
lambdaCondition = buildPrismaFilterFromCerbosExpression(lambdaConditionOperand, // Use the condition part of the lambda
|
|
1953
|
-
scopedMapper);
|
|
1954
|
-
}
|
|
1955
|
-
finally {
|
|
1956
|
-
lambdaScopes.pop();
|
|
1957
|
-
}
|
|
1958
|
-
let filterValue = lambdaCondition;
|
|
1959
|
-
if (restRelations.length > 0) {
|
|
1960
|
-
// Chained collection reference (e.g. R.attr.a.b): the lambda's elements live at the END
|
|
1961
|
-
// of the chain, so the element predicate must join through every intermediate hop.
|
|
1962
|
-
filterValue = buildNestedRelationFilter(restRelations, lambdaCondition);
|
|
1963
|
-
}
|
|
1964
|
-
else if (lambdaCondition["AND"] || lambdaCondition["OR"]) {
|
|
1965
|
-
// If the lambda condition already has a logical structure, use it as-is
|
|
1966
|
-
filterValue = lambdaCondition;
|
|
1967
|
-
}
|
|
1968
|
-
else {
|
|
1969
|
-
const lambdaKeys = Object.keys(lambdaCondition);
|
|
1970
|
-
const defaultKey = lambdaKeys[0];
|
|
1971
|
-
if (!defaultKey) {
|
|
1972
|
-
throw new Error("Lambda condition must have at least one field");
|
|
1973
|
-
}
|
|
1974
|
-
const lambdaFieldValue = lambdaCondition[defaultKey];
|
|
1975
|
-
if (lambdaFieldValue === undefined) {
|
|
1976
|
-
throw new Error("Lambda condition field value cannot be undefined");
|
|
1977
|
-
}
|
|
1978
|
-
const filterField = head.field || defaultKey;
|
|
1979
|
-
filterValue = {
|
|
1980
|
-
[filterField]: lambdaFieldValue,
|
|
1981
|
-
};
|
|
1982
|
-
}
|
|
1983
|
-
return {
|
|
1984
|
-
head,
|
|
1985
|
-
restRelations,
|
|
1986
|
-
filterValue,
|
|
1987
|
-
nullableFields: scope.nullableFields,
|
|
1988
|
-
unknownFilters: scope.unknownFilters,
|
|
1989
|
-
};
|
|
1990
|
-
}
|
|
1991
|
-
/** OR of `field IS NULL` checks for every nullable element column the lambda touched. */
|
|
1992
|
-
function buildNullWitnessFilter(nullableFields) {
|
|
1993
|
-
const checks = [...nullableFields].map((field) => ({ [field]: null }));
|
|
1994
|
-
if (checks.length === 1) {
|
|
1995
|
-
return checks[0];
|
|
1996
|
-
}
|
|
1997
|
-
return { OR: checks };
|
|
1998
|
-
}
|
|
1999
|
-
function buildUnknownElementFilter(parts) {
|
|
2000
|
-
const filters = [...parts.unknownFilters];
|
|
2001
|
-
if (parts.nullableFields.size > 0) {
|
|
2002
|
-
filters.push(buildNullWitnessFilter(parts.nullableFields));
|
|
2003
|
-
}
|
|
2004
|
-
if (filters.length === 0) {
|
|
2005
|
-
return undefined;
|
|
2006
|
-
}
|
|
2007
|
-
if (filters.length === 1) {
|
|
2008
|
-
return filters[0];
|
|
2009
|
-
}
|
|
2010
|
-
return { OR: filters };
|
|
2011
|
-
}
|
|
2012
|
-
function recordNestedCollectionUnknownFilter(filter) {
|
|
2013
|
-
const enclosingScope = lambdaScopes[lambdaScopes.length - 1];
|
|
2014
|
-
enclosingScope?.unknownFilters.push(filter);
|
|
2015
|
-
}
|
|
2016
|
-
/** Wraps an element-level filter through the full relation chain (head + rest). */
|
|
2017
|
-
function wrapCollectionElementFilter(parts, elementFilter) {
|
|
2018
|
-
const inner = parts.restRelations.length > 0
|
|
2019
|
-
? buildNestedRelationFilter(parts.restRelations, elementFilter)
|
|
2020
|
-
: elementFilter;
|
|
2021
|
-
return relationFilter(parts.head, "some", inner);
|
|
2022
|
-
}
|
|
2023
|
-
function throwUnsupportedCollectionOperator(operator) {
|
|
2024
|
-
if (operator === "exists_one") {
|
|
2025
|
-
throw new Error("exists_one requires counting matching elements, which Prisma where-filters cannot express");
|
|
2026
|
-
}
|
|
2027
|
-
throw new Error("The filter() collection operator returns a list, not a boolean. " +
|
|
2028
|
-
"It cannot be used as a standalone condition. " +
|
|
2029
|
-
"Use exists() or combine filter() with size() instead.");
|
|
2030
|
-
}
|
|
2031
|
-
/**
|
|
2032
|
-
* Helper function to handle collection operators (exists, all, except, filter)
|
|
2033
|
-
*/
|
|
2034
|
-
function handleCollectionOperator(operator, operands, mapper) {
|
|
2035
|
-
const knownValueFilter = tryHandleKnownValueCollectionOperator(operator, operands, mapper, false);
|
|
2036
|
-
if (knownValueFilter !== undefined) {
|
|
2037
|
-
return knownValueFilter;
|
|
2038
|
-
}
|
|
2039
|
-
if (operator === "exists_one" || operator === "filter") {
|
|
2040
|
-
throwUnsupportedCollectionOperator(operator);
|
|
2041
|
-
}
|
|
2042
|
-
const parts = buildCollectionLambdaParts(operator, operands, mapper);
|
|
2043
|
-
const { head, filterValue, nullableFields } = parts;
|
|
2044
|
-
switch (operator) {
|
|
2045
|
-
case "exists": {
|
|
2046
|
-
// A NULL element keeps the per-element predicate UNKNOWN, so it can never create a
|
|
2047
|
-
// false positive here; a CEL error (deny) coincides with "no match" — no guard needed.
|
|
2048
|
-
const filter = relationFilter(head, "some", filterValue);
|
|
2049
|
-
const unknownElement = buildUnknownElementFilter(parts);
|
|
2050
|
-
if (unknownElement !== undefined) {
|
|
2051
|
-
recordNestedCollectionUnknownFilter({
|
|
2052
|
-
AND: [
|
|
2053
|
-
{ NOT: filter },
|
|
2054
|
-
wrapCollectionElementFilter(parts, unknownElement),
|
|
2055
|
-
],
|
|
2056
|
-
});
|
|
2057
|
-
}
|
|
2058
|
-
return filter;
|
|
2059
|
-
}
|
|
2060
|
-
case "except":
|
|
2061
|
-
return relationFilter(head, "some", { NOT: filterValue });
|
|
2062
|
-
case "all": {
|
|
2063
|
-
if (parts.restRelations.length > 0) {
|
|
2064
|
-
throw new Error("all() over a multi-hop relation chain is not supported");
|
|
2065
|
-
}
|
|
2066
|
-
const base = relationFilter(head, "every", filterValue);
|
|
2067
|
-
if (nullableFields.size === 0) {
|
|
2068
|
-
return base;
|
|
2069
|
-
}
|
|
2070
|
-
// CEL all() errors when any element evaluation errors without a false witness; SQL
|
|
2071
|
-
// `every` would treat those elements as vacuously passing. Exclude rows holding any
|
|
2072
|
-
// element whose referenced nullable column is NULL. (`every` already rejects rows
|
|
2073
|
-
// with a definitive false witness, matching error absorption.)
|
|
2074
|
-
return {
|
|
2075
|
-
AND: [
|
|
2076
|
-
base,
|
|
2077
|
-
relationFilter(head, "none", buildNullWitnessFilter(nullableFields)),
|
|
2078
|
-
],
|
|
2079
|
-
};
|
|
2080
|
-
}
|
|
2081
|
-
default:
|
|
2082
|
-
throw new Error(`Unexpected operator: ${operator}`);
|
|
2083
|
-
}
|
|
2084
|
-
}
|
|
2085
|
-
/**
|
|
2086
|
-
* Builds the filter for a NEGATED collection operator, encoding CEL's error semantics (see
|
|
2087
|
-
* buildNegatedFilter).
|
|
2088
|
-
*/
|
|
2089
|
-
function buildNegatedCollectionFilter(operator, operands, mapper) {
|
|
2090
|
-
const knownValueFilter = tryHandleKnownValueCollectionOperator(operator, operands, mapper, true);
|
|
2091
|
-
if (knownValueFilter !== undefined) {
|
|
2092
|
-
return knownValueFilter;
|
|
2093
|
-
}
|
|
2094
|
-
if (operator === "exists_one" || operator === "filter") {
|
|
2095
|
-
throwUnsupportedCollectionOperator(operator);
|
|
2096
|
-
}
|
|
2097
|
-
const parts = buildCollectionLambdaParts(operator, operands, mapper);
|
|
2098
|
-
const { head, filterValue, nullableFields } = parts;
|
|
2099
|
-
// An absent to-one parent must stay denied under negation rather than satisfying it
|
|
2100
|
-
// vacuously (#309).
|
|
2101
|
-
const leadingHopsExist = buildLeadingHopsExistFilter(head, parts.restRelations);
|
|
2102
|
-
const requireLeadingHops = (filter) => leadingHopsExist === undefined
|
|
2103
|
-
? filter
|
|
2104
|
-
: { AND: [leadingHopsExist, filter] };
|
|
2105
|
-
switch (operator) {
|
|
2106
|
-
case "exists": {
|
|
2107
|
-
const base = requireLeadingHops({
|
|
2108
|
-
NOT: relationFilter(head, "some", filterValue),
|
|
2109
|
-
});
|
|
2110
|
-
const unknownElement = buildUnknownElementFilter(parts);
|
|
2111
|
-
if (unknownElement === undefined) {
|
|
2112
|
-
return base;
|
|
2113
|
-
}
|
|
2114
|
-
// !exists is TRUE only when every element is definitively false: no P-match AND no
|
|
2115
|
-
// element whose evaluation is UNKNOWN (NULL column = missing attribute = CEL error).
|
|
2116
|
-
return {
|
|
2117
|
-
AND: [
|
|
2118
|
-
base,
|
|
2119
|
-
{
|
|
2120
|
-
NOT: wrapCollectionElementFilter(parts, unknownElement),
|
|
2121
|
-
},
|
|
2122
|
-
],
|
|
2123
|
-
};
|
|
2124
|
-
}
|
|
2125
|
-
case "all":
|
|
2126
|
-
// !all is TRUE only with a definitive false witness, which also absorbs error
|
|
2127
|
-
// elements — exactly `some(NOT P)` in SQL (NULL columns keep NOT P UNKNOWN).
|
|
2128
|
-
return relationFilter(head, "some", { NOT: filterValue });
|
|
2129
|
-
case "except": {
|
|
2130
|
-
// !except(c,P) = every element definitively matches P.
|
|
2131
|
-
const base = requireLeadingHops(relationFilter(head, "none", { NOT: filterValue }));
|
|
2132
|
-
if (nullableFields.size === 0) {
|
|
2133
|
-
return base;
|
|
2134
|
-
}
|
|
2135
|
-
return {
|
|
2136
|
-
AND: [
|
|
2137
|
-
base,
|
|
2138
|
-
relationFilter(head, "none", buildNullWitnessFilter(nullableFields)),
|
|
2139
|
-
],
|
|
2140
|
-
};
|
|
2141
|
-
}
|
|
2142
|
-
default:
|
|
2143
|
-
throw new Error(`Unexpected operator: ${operator}`);
|
|
2144
|
-
}
|
|
2145
|
-
}
|
|
2146
|
-
/**
|
|
2147
|
-
* Helper function to handle "map" operator
|
|
2148
|
-
*/
|
|
2149
|
-
function handleMapOperator(operands, mapper) {
|
|
2150
|
-
if (operands.length !== 2) {
|
|
2151
|
-
throw new Error("map requires exactly two operands");
|
|
2152
|
-
}
|
|
2153
|
-
const collection = assertDefined(operands[0], "map requires a collection operand");
|
|
2154
|
-
const lambda = assertDefined(operands[1], "map requires a lambda operand");
|
|
2155
|
-
if (!isNamedOperand(collection)) {
|
|
2156
|
-
throw new Error("First operand of map must be a collection reference");
|
|
2157
|
-
}
|
|
2158
|
-
if (!isOperatorOperand(lambda) || lambda.operator !== "lambda") {
|
|
2159
|
-
throw new Error("Second operand of map must be a lambda expression");
|
|
2160
|
-
}
|
|
2161
|
-
// Get variable name from lambda
|
|
2162
|
-
const projection = assertDefined(lambda.operands[0], "Map lambda expression must provide a projection");
|
|
2163
|
-
const variable = assertDefined(lambda.operands[1], "Map lambda expression must provide a variable");
|
|
2164
|
-
if (!isNamedOperand(projection) || !isNamedOperand(variable)) {
|
|
2165
|
-
throw new Error("Invalid map lambda expression structure");
|
|
2166
|
-
}
|
|
2167
|
-
// Create scoped mapper for the collection
|
|
2168
|
-
const scopedMapper = createScopedMapper(collection.name, variable.name, mapper);
|
|
2169
|
-
const { relations } = resolveFieldReference(collection.name, mapper);
|
|
2170
|
-
if (!relations || relations.length === 0) {
|
|
2171
|
-
throw new Error("map operator requires a relation mapping");
|
|
2172
|
-
}
|
|
2173
|
-
// Use scoped mapper for resolving the projection
|
|
2174
|
-
const resolved = resolveFieldReference(projection.name, scopedMapper);
|
|
2175
|
-
const fieldName = getLeafField(resolved.path);
|
|
2176
|
-
const lastRelation = assertDefined(relations[relations.length - 1], "Relation mapping must contain at least one relation");
|
|
2177
|
-
return buildNestedRelationFilter(relations, {
|
|
2178
|
-
[getPrismaRelationOperator(lastRelation)]: {
|
|
2179
|
-
select: { [fieldName]: true },
|
|
2180
|
-
},
|
|
2181
|
-
});
|
|
2182
|
-
}
|
|
2183
|
-
function buildImpossibleFilter(fieldRef) {
|
|
2184
|
-
return buildFieldFilter(fieldRef, "in", []);
|
|
2185
|
-
}
|
|
2186
|
-
const ARITHMETIC_OPERATORS = new Set(["add", "sub", "mult", "div"]);
|
|
2187
|
-
/**
|
|
2188
|
-
* Translates `column ⊕ constant CMP value` (and its mirrored forms) by solving for the
|
|
2189
|
-
* column: Prisma where-filters cannot express column arithmetic, but linear arithmetic with
|
|
2190
|
-
* one constant side always rewrites to a plain comparison. Multiplying/dividing by a
|
|
2191
|
-
* negative constant mirrors directional operators. The rewrite happens in IEEE double space,
|
|
2192
|
-
* matching CEL: Cerbos attribute numbers are doubles, so this preserves check-time semantics
|
|
2193
|
-
* (e.g. `n * 0.1 == 0.3` solves to an unrepresentable fraction and matches no integer row,
|
|
2194
|
-
* exactly as CEL evaluates it).
|
|
2195
|
-
*/
|
|
2196
|
-
function handleArithmeticComparison(operator, arithExpr, otherOperand, arithIsLeft, mapper) {
|
|
2197
|
-
const arithOp = arithExpr.operator;
|
|
2198
|
-
const arithLeftOp = assertDefined(arithExpr.operands[0], `${arithOp} operator requires a left operand`);
|
|
2199
|
-
const arithRightOp = assertDefined(arithExpr.operands[1], `${arithOp} operator requires a right operand`);
|
|
2200
|
-
if (isOperatorOperand(otherOperand) &&
|
|
2201
|
-
ARITHMETIC_OPERATORS.has(otherOperand.operator) &&
|
|
2202
|
-
tryFoldValueExpression(otherOperand, mapper) === null) {
|
|
2203
|
-
throw new Error("Arithmetic on both sides of a comparison is not supported: the expression cannot be solved to a plain column filter");
|
|
2204
|
-
}
|
|
2205
|
-
const arithLeft = resolveOperand(arithLeftOp, mapper);
|
|
2206
|
-
const arithRight = resolveOperand(arithRightOp, mapper);
|
|
2207
|
-
const other = resolveOperand(otherOperand, mapper);
|
|
2208
|
-
// Fully constant arithmetic: fold and compare the other side against the result. The
|
|
2209
|
-
// arithmetic side keeps its source position, so when the folded constant was written
|
|
2210
|
-
// FIRST (`1 + 2 < f`), directional operators mirror to keep the field on the left.
|
|
2211
|
-
if (isResolvedValue(arithLeft) && isResolvedValue(arithRight)) {
|
|
2212
|
-
const folded = foldArithmetic(arithOp, arithLeft.value, arithRight.value);
|
|
2213
|
-
if (!isResolvedFieldReference(other)) {
|
|
2214
|
-
throw new Error(`${arithOp} with two values requires a field reference on the other side`);
|
|
2215
|
-
}
|
|
2216
|
-
const effectiveOperator = arithIsLeft
|
|
2217
|
-
? (MIRRORED_OPERATOR[operator] ?? operator)
|
|
2218
|
-
: operator;
|
|
2219
|
-
return buildComparisonFilter(other, effectiveOperator, folded);
|
|
2220
|
-
}
|
|
2221
|
-
if (!isResolvedValue(other)) {
|
|
2222
|
-
throw new Error(`${arithOp} operator with field references requires a value on the other side of the comparison`);
|
|
2223
|
-
}
|
|
2224
|
-
let fieldRef;
|
|
2225
|
-
let constant;
|
|
2226
|
-
let fieldIsLeft;
|
|
2227
|
-
if (isResolvedFieldReference(arithLeft) && isResolvedValue(arithRight)) {
|
|
2228
|
-
fieldRef = arithLeft;
|
|
2229
|
-
constant = arithRight.value;
|
|
2230
|
-
fieldIsLeft = true;
|
|
2231
|
-
}
|
|
2232
|
-
else if (isResolvedValue(arithLeft) &&
|
|
2233
|
-
isResolvedFieldReference(arithRight)) {
|
|
2234
|
-
fieldRef = arithRight;
|
|
2235
|
-
constant = arithLeft.value;
|
|
2236
|
-
fieldIsLeft = false;
|
|
2237
|
-
}
|
|
2238
|
-
else {
|
|
2239
|
-
throw new Error(`${arithOp} operator requires exactly one field reference and one value, or two values`);
|
|
2240
|
-
}
|
|
2241
|
-
// The comparison operator was normalized arithmetic-side-first by the caller; if the
|
|
2242
|
-
// arithmetic was written on the RIGHT of the comparison, direction was already mirrored.
|
|
2243
|
-
let effectiveOperator = arithIsLeft
|
|
2244
|
-
? operator
|
|
2245
|
-
: (MIRRORED_OPERATOR[operator] ?? operator);
|
|
2246
|
-
// String concatenation solving (eq/ne only).
|
|
2247
|
-
if (arithOp === "add" && typeof constant === "string") {
|
|
2248
|
-
if (effectiveOperator !== "eq" && effectiveOperator !== "ne") {
|
|
2249
|
-
throw new Error(`Operator ${effectiveOperator} is not supported with string concatenation`);
|
|
2250
|
-
}
|
|
2251
|
-
const solvedValue = solveAdd(other.value, constant, fieldIsLeft);
|
|
2252
|
-
if (solvedValue === null) {
|
|
2253
|
-
if (effectiveOperator === "eq")
|
|
2254
|
-
return buildImpossibleFilter(fieldRef);
|
|
2255
|
-
return {};
|
|
2256
|
-
}
|
|
2257
|
-
return buildComparisonFilter(fieldRef, effectiveOperator, solvedValue);
|
|
2258
|
-
}
|
|
2259
|
-
if (typeof constant !== "number" || typeof other.value !== "number") {
|
|
2260
|
-
throw new Error(`${arithOp} comparison requires numeric operands`);
|
|
2261
|
-
}
|
|
2262
|
-
if (arithOp === "add" &&
|
|
2263
|
-
(effectiveOperator === "eq" || effectiveOperator === "ne") &&
|
|
2264
|
-
(!Number.isInteger(constant) || !Number.isInteger(other.value))) {
|
|
2265
|
-
throw new Error("Fractional addition equality cannot be translated safely: solving IEEE-754 addition into a plain Prisma column comparison is not reversible");
|
|
2266
|
-
}
|
|
2267
|
-
let solved;
|
|
2268
|
-
switch (arithOp) {
|
|
2269
|
-
case "add":
|
|
2270
|
-
solved = other.value - constant;
|
|
2271
|
-
break;
|
|
2272
|
-
case "sub":
|
|
2273
|
-
if (fieldIsLeft) {
|
|
2274
|
-
// f - c CMP v ⇔ f CMP v + c
|
|
2275
|
-
solved = other.value + constant;
|
|
2276
|
-
}
|
|
2277
|
-
else {
|
|
2278
|
-
// c - f CMP v ⇔ -f CMP v - c ⇔ f mirror(CMP) c - v
|
|
2279
|
-
solved = constant - other.value;
|
|
2280
|
-
effectiveOperator =
|
|
2281
|
-
MIRRORED_OPERATOR[effectiveOperator] ?? effectiveOperator;
|
|
2282
|
-
}
|
|
2283
|
-
break;
|
|
2284
|
-
case "mult":
|
|
2285
|
-
if (constant === 0) {
|
|
2286
|
-
throw new Error("Multiplication by a constant zero must be folded by the Cerbos planner");
|
|
2287
|
-
}
|
|
2288
|
-
solved = other.value / constant;
|
|
2289
|
-
if (constant < 0) {
|
|
2290
|
-
effectiveOperator =
|
|
2291
|
-
MIRRORED_OPERATOR[effectiveOperator] ?? effectiveOperator;
|
|
2292
|
-
}
|
|
2293
|
-
break;
|
|
2294
|
-
case "div":
|
|
2295
|
-
if (!fieldIsLeft) {
|
|
2296
|
-
throw new Error("Division by a column is not supported: the comparison cannot be solved to a plain column filter");
|
|
2297
|
-
}
|
|
2298
|
-
if (constant === 0) {
|
|
2299
|
-
throw new Error("Division by a constant zero is not supported");
|
|
2300
|
-
}
|
|
2301
|
-
solved = other.value * constant;
|
|
2302
|
-
if (constant < 0) {
|
|
2303
|
-
effectiveOperator =
|
|
2304
|
-
MIRRORED_OPERATOR[effectiveOperator] ?? effectiveOperator;
|
|
2305
|
-
}
|
|
2306
|
-
break;
|
|
2307
|
-
default:
|
|
2308
|
-
throw new Error(`Unsupported operator: ${arithOp}`);
|
|
2309
|
-
}
|
|
2310
|
-
return buildComparisonFilter(fieldRef, effectiveOperator, solved);
|
|
2311
|
-
}
|
|
2312
|
-
function foldArithmetic(operator, left, right) {
|
|
2313
|
-
if (operator === "add" &&
|
|
2314
|
-
(typeof left === "string" || typeof right === "string")) {
|
|
2315
|
-
return String(left) + String(right);
|
|
2316
|
-
}
|
|
2317
|
-
if (typeof left !== "number" || typeof right !== "number") {
|
|
2318
|
-
throw new Error(`${operator} operator requires string or number operands`);
|
|
2319
|
-
}
|
|
2320
|
-
switch (operator) {
|
|
2321
|
-
case "add":
|
|
2322
|
-
return left + right;
|
|
2323
|
-
case "sub":
|
|
2324
|
-
return left - right;
|
|
2325
|
-
case "mult":
|
|
2326
|
-
return left * right;
|
|
2327
|
-
case "div":
|
|
2328
|
-
return left / right;
|
|
2329
|
-
default:
|
|
2330
|
-
throw new Error(`Unsupported operator: ${operator}`);
|
|
2331
|
-
}
|
|
2332
|
-
}
|
|
2333
|
-
function solveAdd(comparisonValue, addConstant, fieldIsLeft) {
|
|
2334
|
-
if (typeof comparisonValue === "string" && typeof addConstant === "string") {
|
|
2335
|
-
if (fieldIsLeft) {
|
|
2336
|
-
if (!comparisonValue.endsWith(addConstant))
|
|
2337
|
-
return null;
|
|
2338
|
-
return comparisonValue.slice(0, comparisonValue.length - addConstant.length);
|
|
2339
|
-
}
|
|
2340
|
-
if (!comparisonValue.startsWith(addConstant))
|
|
2341
|
-
return null;
|
|
2342
|
-
return comparisonValue.slice(addConstant.length);
|
|
2343
|
-
}
|
|
2344
|
-
if (typeof comparisonValue === "number" && typeof addConstant === "number") {
|
|
2345
|
-
return comparisonValue - addConstant;
|
|
2346
|
-
}
|
|
2347
|
-
throw new Error("Type mismatch in add comparison");
|
|
2348
|
-
}
|
|
2349
|
-
function resolveHierarchy(expr, mapper) {
|
|
2350
|
-
const operands = expr.operands;
|
|
2351
|
-
if (operands.length === 2) {
|
|
2352
|
-
const strOperand = assertDefined(operands[0], "hierarchy requires operands");
|
|
2353
|
-
const delimOperand = assertDefined(operands[1], "hierarchy requires a delimiter");
|
|
2354
|
-
if (!isValueOperand(delimOperand)) {
|
|
2355
|
-
throw new Error("hierarchy delimiter must be a value");
|
|
2356
|
-
}
|
|
2357
|
-
const delimiter = String(delimOperand.value);
|
|
2358
|
-
if (isValueOperand(strOperand)) {
|
|
2359
|
-
const raw = String(strOperand.value);
|
|
2360
|
-
return { type: "constant", segments: raw.split(delimiter), raw, delimiter };
|
|
2361
|
-
}
|
|
2362
|
-
if (isNamedOperand(strOperand)) {
|
|
2363
|
-
return {
|
|
2364
|
-
type: "field",
|
|
2365
|
-
fieldRef: resolveFieldReference(strOperand.name, mapper),
|
|
2366
|
-
delimiter,
|
|
2367
|
-
};
|
|
2368
|
-
}
|
|
2369
|
-
throw new Error("hierarchy(string, delimiter) requires a value or field operand");
|
|
2370
|
-
}
|
|
2371
|
-
if (operands.length === 1) {
|
|
2372
|
-
const inner = assertDefined(operands[0], "hierarchy requires an operand");
|
|
2373
|
-
if (isValueOperand(inner)) {
|
|
2374
|
-
const raw = String(inner.value);
|
|
2375
|
-
return { type: "constant", segments: raw.split("."), raw, delimiter: "." };
|
|
2376
|
-
}
|
|
2377
|
-
if (isNamedOperand(inner)) {
|
|
2378
|
-
return {
|
|
2379
|
-
type: "field",
|
|
2380
|
-
fieldRef: resolveFieldReference(inner.name, mapper),
|
|
2381
|
-
delimiter: ".",
|
|
2382
|
-
};
|
|
2383
|
-
}
|
|
2384
|
-
if (isOperatorOperand(inner) && inner.operator === "list") {
|
|
2385
|
-
const segments = inner.operands.map((op) => {
|
|
2386
|
-
const resolved = resolveOperand(op, mapper);
|
|
2387
|
-
if (isResolvedValue(resolved)) {
|
|
2388
|
-
return { type: "constant", value: String(resolved.value) };
|
|
2389
|
-
}
|
|
2390
|
-
return { type: "field", fieldRef: resolved };
|
|
2391
|
-
});
|
|
2392
|
-
return { type: "segmented", segments };
|
|
2393
|
-
}
|
|
2394
|
-
throw new Error("hierarchy requires a value, field, or list operand");
|
|
2395
|
-
}
|
|
2396
|
-
throw new Error("hierarchy requires 1 or 2 operands");
|
|
2397
|
-
}
|
|
2398
|
-
function toSegments(resolved) {
|
|
2399
|
-
switch (resolved.type) {
|
|
2400
|
-
case "constant":
|
|
2401
|
-
return resolved.segments.map((s) => ({ type: "constant", value: s }));
|
|
2402
|
-
case "segmented":
|
|
2403
|
-
return resolved.segments;
|
|
2404
|
-
case "field":
|
|
2405
|
-
throw new Error("Cannot get segments from a field-reference hierarchy");
|
|
2406
|
-
}
|
|
2407
|
-
}
|
|
2408
|
-
function normalizeHierarchy(h, defaultDelimiter = ".") {
|
|
2409
|
-
if (h.type !== "segmented")
|
|
2410
|
-
return h;
|
|
2411
|
-
const allConstant = h.segments.every((s) => s.type === "constant");
|
|
2412
|
-
if (!allConstant)
|
|
2413
|
-
return h;
|
|
2414
|
-
const segments = h.segments.map((s) => s.value);
|
|
2415
|
-
return {
|
|
2416
|
-
type: "constant",
|
|
2417
|
-
segments,
|
|
2418
|
-
raw: segments.join(defaultDelimiter),
|
|
2419
|
-
delimiter: defaultDelimiter,
|
|
2420
|
-
};
|
|
2421
|
-
}
|
|
2422
|
-
function checkPrefixConditions(shorter, longer) {
|
|
2423
|
-
if (shorter.length > longer.length)
|
|
2424
|
-
return null;
|
|
2425
|
-
const conditions = [];
|
|
2426
|
-
for (let i = 0; i < shorter.length; i++) {
|
|
2427
|
-
const s = shorter[i];
|
|
2428
|
-
const l = longer[i];
|
|
2429
|
-
if (s.type === "constant" && l.type === "constant") {
|
|
2430
|
-
if (s.value !== l.value)
|
|
2431
|
-
return null;
|
|
2432
|
-
}
|
|
2433
|
-
else if (s.type === "field" && l.type === "constant") {
|
|
2434
|
-
conditions.push(buildFieldFilter(s.fieldRef, "equals", l.value));
|
|
2435
|
-
}
|
|
2436
|
-
else if (s.type === "constant" && l.type === "field") {
|
|
2437
|
-
conditions.push(buildFieldFilter(l.fieldRef, "equals", s.value));
|
|
2438
|
-
}
|
|
2439
|
-
else {
|
|
2440
|
-
throw new Error("Cannot compare two field references in hierarchy overlap");
|
|
2441
|
-
}
|
|
2442
|
-
}
|
|
2443
|
-
if (conditions.length === 0)
|
|
2444
|
-
return {};
|
|
2445
|
-
if (conditions.length === 1)
|
|
2446
|
-
return conditions[0];
|
|
2447
|
-
return { AND: conditions };
|
|
2448
|
-
}
|
|
2449
|
-
function handleOverlapsOperator(operands, mapper) {
|
|
2450
|
-
const [left, right] = extractHierarchyOperands("overlaps", operands, mapper);
|
|
2451
|
-
if (left.type === "field" || right.type === "field") {
|
|
2452
|
-
return handleFieldOverlaps(left, right);
|
|
2453
|
-
}
|
|
2454
|
-
const leftSegs = toSegments(left);
|
|
2455
|
-
const rightSegs = toSegments(right);
|
|
2456
|
-
const leftPrefixOfRight = checkPrefixConditions(leftSegs, rightSegs);
|
|
2457
|
-
const rightPrefixOfLeft = checkPrefixConditions(rightSegs, leftSegs);
|
|
2458
|
-
const validConditions = [leftPrefixOfRight, rightPrefixOfLeft].filter((c) => c !== null);
|
|
2459
|
-
if (validConditions.length === 0) {
|
|
2460
|
-
const allSegs = [...leftSegs, ...rightSegs];
|
|
2461
|
-
const fieldSeg = allSegs.find((s) => s.type === "field");
|
|
2462
|
-
if (fieldSeg)
|
|
2463
|
-
return buildImpossibleFilter(fieldSeg.fieldRef);
|
|
2464
|
-
throw new Error("Cannot determine overlap: no field references found");
|
|
2465
|
-
}
|
|
2466
|
-
if (validConditions.some((c) => Object.keys(c).length === 0))
|
|
2467
|
-
return {};
|
|
2468
|
-
// When both directions are valid (equal-length hierarchies), they produce
|
|
2469
|
-
// identical conditions since the same segment pairs are compared in both.
|
|
2470
|
-
return validConditions[0];
|
|
2471
|
-
}
|
|
2472
|
-
/**
|
|
2473
|
-
* Guards every hierarchy prefix that is about to become a Prisma `startsWith`.
|
|
2474
|
-
*
|
|
2475
|
-
* `startsWith` compiles to `LIKE` with no `ESCAPE` clause, so `%` and `_` in the prefix
|
|
2476
|
-
* match as wildcards instead of literally and widen the filter past what the PDP allows.
|
|
2477
|
-
* `\` is unsafe because PostgreSQL and MySQL treat it as the DEFAULT escape character with no
|
|
2478
|
-
* `ESCAPE` clause present, where SQLite has none at all — so the same prefix means different
|
|
2479
|
-
* things per provider. `[` is unsafe for a third reason: SQL Server opens a character class on
|
|
2480
|
-
* `[` even when an `ESCAPE` clause is declared, so it cannot be made literal at all. Fail loudly
|
|
2481
|
-
* rather than emit a filter that admits denied rows.
|
|
2482
|
-
*/
|
|
2483
|
-
function assertLikeSafePrefix(prefix) {
|
|
2484
|
-
if (/[%_\[\\]/.test(prefix)) {
|
|
2485
|
-
throw new Error("Cannot translate hierarchy prefix matching with LIKE metacharacters (%, _, \\ or [): " +
|
|
2486
|
-
"Prisma emits LIKE without an ESCAPE clause, \\ is the default escape character on " +
|
|
2487
|
-
"PostgreSQL and MySQL, and [ opens a character class on SQL Server even with one");
|
|
2488
|
-
}
|
|
2489
|
-
}
|
|
2490
|
-
function handleFieldOverlaps(left, right) {
|
|
2491
|
-
if (left.type === "field" && right.type === "field") {
|
|
2492
|
-
throw new Error("overlaps: cannot compare two field-reference hierarchies");
|
|
2493
|
-
}
|
|
2494
|
-
const field = (left.type === "field" ? left : right);
|
|
2495
|
-
const other = left.type === "field" ? right : left;
|
|
2496
|
-
if (other.type !== "constant") {
|
|
2497
|
-
throw new Error("overlaps: segmented hierarchies with field hierarchies are not supported");
|
|
2498
|
-
}
|
|
2499
|
-
const delimiter = field.delimiter;
|
|
2500
|
-
const otherRaw = other.segments.join(delimiter);
|
|
2501
|
-
const strictPrefixes = getStrictPrefixes(other.segments, delimiter);
|
|
2502
|
-
const conditions = [];
|
|
2503
|
-
if (strictPrefixes.length > 0) {
|
|
2504
|
-
conditions.push(buildFieldFilter(field.fieldRef, "in", strictPrefixes));
|
|
2505
|
-
}
|
|
2506
|
-
conditions.push(buildFieldFilter(field.fieldRef, "equals", otherRaw));
|
|
2507
|
-
const prefix = otherRaw + delimiter;
|
|
2508
|
-
assertLikeSafePrefix(prefix);
|
|
2509
|
-
conditions.push(buildFieldFilter(field.fieldRef, "startsWith", prefix));
|
|
2510
|
-
if (conditions.length === 1)
|
|
2511
|
-
return conditions[0];
|
|
2512
|
-
return { OR: conditions };
|
|
2513
|
-
}
|
|
2514
|
-
function extractHierarchyOperands(operatorName, operands, mapper) {
|
|
2515
|
-
if (operands.length !== 2) {
|
|
2516
|
-
throw new Error(`${operatorName} requires exactly two operands`);
|
|
2517
|
-
}
|
|
2518
|
-
const leftOp = assertDefined(operands[0], `${operatorName} requires a left operand`);
|
|
2519
|
-
const rightOp = assertDefined(operands[1], `${operatorName} requires a right operand`);
|
|
2520
|
-
if (!isOperatorOperand(leftOp) || leftOp.operator !== "hierarchy" ||
|
|
2521
|
-
!isOperatorOperand(rightOp) || rightOp.operator !== "hierarchy") {
|
|
2522
|
-
throw new Error(`${operatorName} requires two hierarchy operands`);
|
|
2523
|
-
}
|
|
2524
|
-
return [
|
|
2525
|
-
normalizeHierarchy(resolveHierarchy(leftOp, mapper)),
|
|
2526
|
-
normalizeHierarchy(resolveHierarchy(rightOp, mapper)),
|
|
2527
|
-
];
|
|
2528
|
-
}
|
|
2529
|
-
function getStrictPrefixes(segments, delimiter) {
|
|
2530
|
-
if (segments.length <= 1)
|
|
2531
|
-
return [];
|
|
2532
|
-
const prefixes = [];
|
|
2533
|
-
let current = segments[0];
|
|
2534
|
-
prefixes.push(current);
|
|
2535
|
-
for (let i = 1; i < segments.length - 1; i++) {
|
|
2536
|
-
current = current + delimiter + segments[i];
|
|
2537
|
-
prefixes.push(current);
|
|
2538
|
-
}
|
|
2539
|
-
return prefixes;
|
|
2540
|
-
}
|
|
2541
|
-
function handleAncestorDescendantOperator(operands, mapper, direction) {
|
|
2542
|
-
const operatorName = direction === "ancestor" ? "ancestorOf" : "descendentOf";
|
|
2543
|
-
const [left, right] = extractHierarchyOperands(operatorName, operands, mapper);
|
|
2544
|
-
// ancestorOf(A, B) = A is strict prefix of B
|
|
2545
|
-
// descendentOf(A, B) = B is strict prefix of A
|
|
2546
|
-
const ancestor = direction === "ancestor" ? left : right;
|
|
2547
|
-
const descendant = direction === "ancestor" ? right : left;
|
|
2548
|
-
if (ancestor.type === "constant" && descendant.type === "field") {
|
|
2549
|
-
const prefix = ancestor.segments.join(descendant.delimiter) + descendant.delimiter;
|
|
2550
|
-
assertLikeSafePrefix(prefix);
|
|
2551
|
-
return buildFieldFilter(descendant.fieldRef, "startsWith", prefix);
|
|
2552
|
-
}
|
|
2553
|
-
if (ancestor.type === "field" && descendant.type === "constant") {
|
|
2554
|
-
const delimiter = ancestor.delimiter;
|
|
2555
|
-
const prefixes = getStrictPrefixes(descendant.segments, delimiter);
|
|
2556
|
-
if (prefixes.length === 0) {
|
|
2557
|
-
return buildImpossibleFilter(ancestor.fieldRef);
|
|
2558
|
-
}
|
|
2559
|
-
if (prefixes.length === 1) {
|
|
2560
|
-
return buildFieldFilter(ancestor.fieldRef, "equals", prefixes[0]);
|
|
2561
|
-
}
|
|
2562
|
-
return buildFieldFilter(ancestor.fieldRef, "in", prefixes);
|
|
2563
|
-
}
|
|
2564
|
-
if (ancestor.type === "constant" && descendant.type === "constant") {
|
|
2565
|
-
const ancestorSegs = ancestor.segments;
|
|
2566
|
-
const descendantSegs = descendant.segments;
|
|
2567
|
-
if (descendantSegs.length > ancestorSegs.length &&
|
|
2568
|
-
ancestorSegs.every((seg, i) => seg === descendantSegs[i])) {
|
|
2569
|
-
return {};
|
|
2570
|
-
}
|
|
2571
|
-
throw new Error(`${operatorName}: constants do not satisfy ${direction} relationship`);
|
|
2572
|
-
}
|
|
2573
|
-
throw new Error(`${operatorName}: unsupported hierarchy type combination`);
|
|
2574
|
-
}
|
|
2575
|
-
function buildFieldFilter(fieldRef, prismaOp, value) {
|
|
2576
|
-
const fieldName = getLeafField(fieldRef.path);
|
|
2577
|
-
return wrapRelations(fieldRef.relations, {
|
|
2578
|
-
[fieldName]: { [prismaOp]: value },
|
|
2579
|
-
});
|
|
2580
59
|
}
|
|
2581
60
|
//# sourceMappingURL=index.js.map
|