foldkit-entity 0.11.0 → 0.12.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 +191 -7
- package/dist/conformance/index.d.mts +203 -4
- package/dist/conformance/index.d.mts.map +1 -1
- package/dist/conformance/index.mjs +351 -5
- package/dist/conformance/index.mjs.map +1 -1
- package/dist/{index-BhI_DA2S.d.mts → index-B9fbDo_-.d.mts} +727 -46
- package/dist/index-B9fbDo_-.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{src-DwKdHZDu.mjs → src-CSxcKUv6.mjs} +861 -120
- package/dist/src-CSxcKUv6.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/index-BhI_DA2S.d.mts.map +0 -1
- package/dist/src-DwKdHZDu.mjs.map +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
|
|
1
|
+
import { Array as Array$1, Data, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
|
-
|
|
3
|
+
import { absurd } from "effect/Function";
|
|
4
|
+
// src/collation.ts
|
|
4
5
|
/**
|
|
5
6
|
* How text compares when a query orders by it, declared rather than left to
|
|
6
7
|
* the backend. Left unsaid, SQLite compares bytes, Postgres follows the
|
|
@@ -32,10 +33,106 @@ const Collation = {
|
|
|
32
33
|
/** Member metadata: how a text field orders, wherever a query orders by it. */
|
|
33
34
|
of: (collation) => key$1.of(collation),
|
|
34
35
|
/** The collation a member's metadata declares, if any. */
|
|
35
|
-
declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0])
|
|
36
|
+
declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0]),
|
|
37
|
+
/**
|
|
38
|
+
* Text as `asciiFold` compares it: ASCII letters lowercased, every other
|
|
39
|
+
* character as it is, which is what SQLite's `lower` does without ICU and so
|
|
40
|
+
* what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not
|
|
41
|
+
* there. An operator implementing `asciiFold` folds with this.
|
|
42
|
+
*/
|
|
43
|
+
foldAscii: (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase())
|
|
36
44
|
};
|
|
37
|
-
|
|
38
|
-
|
|
45
|
+
// src/law.ts
|
|
46
|
+
/**
|
|
47
|
+
* Laws an operator declares (expr-operations-DESIGN §10): equations every
|
|
48
|
+
* implementation of it keeps over a domain. A law describes; nothing rewrites a
|
|
49
|
+
* body by one. `Conformance.laws` tests an implementation against them, and
|
|
50
|
+
* what it finds is evidence recorded in that implementation's table.
|
|
51
|
+
*/
|
|
52
|
+
const Laws = Data.taggedEnum();
|
|
53
|
+
const unnarrowed = { domain: Option.none() };
|
|
54
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
55
|
+
const nameOf$1 = (operator) => operator.descriptor.version === 1 ? operator.descriptor.id : `${operator.descriptor.id}@${operator.descriptor.version}`;
|
|
56
|
+
const Law = {
|
|
57
|
+
associative: Laws.Associative(unnarrowed),
|
|
58
|
+
commutative: Laws.Commutative(unnarrowed),
|
|
59
|
+
idempotent: Laws.Idempotent(unnarrowed),
|
|
60
|
+
preservesCollation: Laws.PreservesCollation(unnarrowed),
|
|
61
|
+
/** `value` leaves the other argument as it is, from `side` (both by default). */
|
|
62
|
+
identity: (value, side = "both") => Laws.Identity({
|
|
63
|
+
...unnarrowed,
|
|
64
|
+
value,
|
|
65
|
+
side
|
|
66
|
+
}),
|
|
67
|
+
/** `value` is the answer whatever the other argument, from `side` (both by default). */
|
|
68
|
+
absorbing: (value, side = "both") => Laws.Absorbing({
|
|
69
|
+
...unnarrowed,
|
|
70
|
+
value,
|
|
71
|
+
side
|
|
72
|
+
}),
|
|
73
|
+
/** `other` undoes the operator: `op(a, other(a))` is `identity`. */
|
|
74
|
+
inverse: (other, identity) => Laws.Inverse({
|
|
75
|
+
...unnarrowed,
|
|
76
|
+
other,
|
|
77
|
+
identity
|
|
78
|
+
}),
|
|
79
|
+
/** The operator distributes over `over`, from the left. */
|
|
80
|
+
distributes: (over) => Laws.Distributes({
|
|
81
|
+
...unnarrowed,
|
|
82
|
+
over
|
|
83
|
+
}),
|
|
84
|
+
/** Moving the argument at `position` up moves the result up (or down, decreasing). */
|
|
85
|
+
monotonic: (direction, position) => Laws.Monotonic({
|
|
86
|
+
...unnarrowed,
|
|
87
|
+
direction,
|
|
88
|
+
position
|
|
89
|
+
}),
|
|
90
|
+
/**
|
|
91
|
+
* The law over the values `domain` accepts only: a law that holds of the
|
|
92
|
+
* integers and not of every number, say, narrowed so it is tested where it
|
|
93
|
+
* is claimed.
|
|
94
|
+
*/
|
|
95
|
+
within: (law, domain) => Object.freeze({
|
|
96
|
+
...law,
|
|
97
|
+
domain: Option.some(domain)
|
|
98
|
+
}),
|
|
99
|
+
$match: Laws.$match,
|
|
100
|
+
/** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */
|
|
101
|
+
describe: (law) => {
|
|
102
|
+
const witnesses = Laws.$match(law, {
|
|
103
|
+
Associative: () => ({}),
|
|
104
|
+
Commutative: () => ({}),
|
|
105
|
+
Idempotent: () => ({}),
|
|
106
|
+
PreservesCollation: () => ({}),
|
|
107
|
+
Identity: ({ value, side }) => ({
|
|
108
|
+
value,
|
|
109
|
+
side
|
|
110
|
+
}),
|
|
111
|
+
Absorbing: ({ value, side }) => ({
|
|
112
|
+
value,
|
|
113
|
+
side
|
|
114
|
+
}),
|
|
115
|
+
Inverse: ({ other, identity }) => ({
|
|
116
|
+
other: nameOf$1(other),
|
|
117
|
+
identity
|
|
118
|
+
}),
|
|
119
|
+
Distributes: ({ over }) => ({ over: nameOf$1(over) }),
|
|
120
|
+
Monotonic: ({ direction, position }) => ({
|
|
121
|
+
direction,
|
|
122
|
+
position
|
|
123
|
+
})
|
|
124
|
+
});
|
|
125
|
+
return {
|
|
126
|
+
kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),
|
|
127
|
+
witnesses,
|
|
128
|
+
domain: Option.match(law.domain, {
|
|
129
|
+
onNone: () => null,
|
|
130
|
+
onSome: (domain) => Schema.toJsonSchemaDocument(domain).schema
|
|
131
|
+
})
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
// src/expr.ts
|
|
39
136
|
/**
|
|
40
137
|
* `Expr` — a query's scalar computations as typed values.
|
|
41
138
|
*
|
|
@@ -49,6 +146,8 @@ const Collation = {
|
|
|
49
146
|
* operation here is one a real query in this repository needs; the set grows
|
|
50
147
|
* from queries, not from what a database could express.
|
|
51
148
|
*/
|
|
149
|
+
/** A table implementing nothing: every primitive operator is unsupported by it. */
|
|
150
|
+
const noOperators = Object.freeze({ has: () => false });
|
|
52
151
|
const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
|
|
53
152
|
/**
|
|
54
153
|
* An Entity's field and a `FieldExpr` are the same three members under the same
|
|
@@ -82,7 +181,8 @@ const predicateTags = /* @__PURE__ */ new Set([
|
|
|
82
181
|
"And",
|
|
83
182
|
"Or",
|
|
84
183
|
"Not",
|
|
85
|
-
"Compare"
|
|
184
|
+
"Compare",
|
|
185
|
+
"Test"
|
|
86
186
|
]);
|
|
87
187
|
/** Whether a value is a predicate, and so usable where a boolean is wanted. */
|
|
88
188
|
const isPredicate = (value) => predicateTags.has(tagOf(value));
|
|
@@ -93,7 +193,7 @@ const isPredicate = (value) => predicateTags.has(tagOf(value));
|
|
|
93
193
|
const toOperand = (value) => {
|
|
94
194
|
const tag = tagOf(value);
|
|
95
195
|
if (tag === "Field") return fieldExpr(value);
|
|
96
|
-
if (tag === "Literal" || tag === "Input" || tag === "Next" || predicateTags.has(tag)) return value;
|
|
196
|
+
if (tag === "Literal" || tag === "Input" || tag === "Next" || tag === "Call" || predicateTags.has(tag)) return value;
|
|
97
197
|
return literal(value);
|
|
98
198
|
};
|
|
99
199
|
/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
|
|
@@ -130,7 +230,8 @@ const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
|
|
|
130
230
|
Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
|
|
131
231
|
Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
|
|
132
232
|
Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
|
|
133
|
-
Literal: ({ value }) => literalKind(value)
|
|
233
|
+
Literal: ({ value }) => literalKind(value),
|
|
234
|
+
Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast)
|
|
134
235
|
}));
|
|
135
236
|
/**
|
|
136
237
|
* How a comparison's text compares: the collation given, else the field's
|
|
@@ -144,14 +245,23 @@ const collationFor = (step, left, right, given) => {
|
|
|
144
245
|
const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
|
|
145
246
|
if (kinds.has("none") || kinds.size > 1) throw new Error(`[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`);
|
|
146
247
|
if (!kinds.has("text")) return Option.none();
|
|
147
|
-
const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [
|
|
248
|
+
const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [{
|
|
249
|
+
name: `${field.owner.name}.${field.key}`,
|
|
250
|
+
collation: field.collation
|
|
251
|
+
}]), Match.tag("Next", ({ field }) => [{
|
|
252
|
+
name: `${field.owner.name}.${field.key}`,
|
|
253
|
+
collation: field.collation
|
|
254
|
+
}]), Match.tag("Call", (call) => [{
|
|
255
|
+
name: showExpr(call),
|
|
256
|
+
collation: call.collation
|
|
257
|
+
}]), Match.orElse(() => [])));
|
|
148
258
|
const [first] = fields;
|
|
149
|
-
if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field,
|
|
150
|
-
const named = fields.map((field) =>
|
|
259
|
+
if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, nor a call carrying a collation, to say how it orders`);
|
|
260
|
+
const named = fields.map((field) => field.name).join(" and ");
|
|
151
261
|
const collations = Option.match(given, {
|
|
152
262
|
onSome: (collation) => [collation],
|
|
153
263
|
onNone: () => fields.map((field) => Option.getOrElse(field.collation, () => {
|
|
154
|
-
throw new Error(`[foldkit-entity] Expr.${step}: ${field.
|
|
264
|
+
throw new Error(`[foldkit-entity] Expr.${step}: ${field.name} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`);
|
|
155
265
|
}))
|
|
156
266
|
});
|
|
157
267
|
const [collation] = collations;
|
|
@@ -196,7 +306,304 @@ const connective = (step, kind) => (...given) => {
|
|
|
196
306
|
operands
|
|
197
307
|
});
|
|
198
308
|
};
|
|
309
|
+
const collationTags = /* @__PURE__ */ new Set([
|
|
310
|
+
"Binary",
|
|
311
|
+
"AsciiFold",
|
|
312
|
+
"Locale"
|
|
313
|
+
]);
|
|
314
|
+
/** A call's last value, when it is one past the arguments: its options, checked. */
|
|
315
|
+
const callOptionsOf = (id, value) => {
|
|
316
|
+
const collation = typeof value === "object" && value !== null && Object.hasOwn(value, "collation") ? value.collation : void 0;
|
|
317
|
+
if (!collationTags.has(tagOf(collation))) throw new Error(`[foldkit-entity] ${id}: a value past its arguments is \`{ collation }\`, a Collation`);
|
|
318
|
+
return collation;
|
|
319
|
+
};
|
|
320
|
+
/** A collation a call was given: one its operator compares by, and portable where required. */
|
|
321
|
+
const givenCollation = (id, descriptor, collation) => {
|
|
322
|
+
if (Option.isSome(descriptor.definedAs) || descriptor.collation === "none") throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`);
|
|
323
|
+
if (descriptor.collation === "required" && collation._tag === "Locale") throw new Error(`[foldkit-entity] ${id}: compares by the backend's "${collation.locale}" collation, which only that backend has`);
|
|
324
|
+
return Option.some(collation);
|
|
325
|
+
};
|
|
326
|
+
/** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */
|
|
327
|
+
const operatorId = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
|
|
328
|
+
/**
|
|
329
|
+
* Why `law` cannot be declared of an operator of this shape, if it cannot: an
|
|
330
|
+
* equation over two arguments of a unary operator, a witness that does not
|
|
331
|
+
* decode as the argument it stands in, or a collation law of an operator
|
|
332
|
+
* whose text keeps none.
|
|
333
|
+
*/
|
|
334
|
+
const lawProblem = (law, input, output, collation) => {
|
|
335
|
+
const name = Law.describe(law).kind;
|
|
336
|
+
const binary = () => input.length === 2 ? Option.none() : Option.some(`${name} is a law of an operator of two arguments, and this one takes ${input.length}`);
|
|
337
|
+
const decodes = (value, schema, what) => Schema.is(Schema.toEncoded(schema))(value) ? Option.none() : Option.some(`${name}'s ${what} ${JSON.stringify(value)} does not decode as its schema`);
|
|
338
|
+
const sides = (value, side) => Option.orElse(binary(), () => Option.orElse(side === "right" ? Option.none() : decodes(value, input[0], "left witness"), () => side === "left" ? Option.none() : decodes(value, input[1], "right witness")));
|
|
339
|
+
return Law.$match(law, {
|
|
340
|
+
Associative: binary,
|
|
341
|
+
Commutative: binary,
|
|
342
|
+
Idempotent: binary,
|
|
343
|
+
Identity: ({ value, side }) => sides(value, side),
|
|
344
|
+
Absorbing: ({ value, side }) => sides(value, side),
|
|
345
|
+
Inverse: ({ other, identity }) => Option.orElse(binary(), () => other.descriptor.input.length === 1 ? decodes(identity, output, "identity") : Option.some(`${name}'s other operator takes one argument`)),
|
|
346
|
+
Distributes: ({ over }) => Option.orElse(binary(), () => over.descriptor.input.length === 2 ? Option.none() : Option.some(`${name} is over an operator of two arguments`)),
|
|
347
|
+
Monotonic: ({ position }) => Number.isSafeInteger(position) && position >= 0 && position < input.length ? Option.none() : Option.some(`${name}'s position ${position} is not an argument's`),
|
|
348
|
+
PreservesCollation: () => collation === "operands" ? Option.none() : Option.some(`${name} is a law of an operator declared \`collation: 'operands'\``)
|
|
349
|
+
});
|
|
350
|
+
};
|
|
351
|
+
/** Whether a schema's stored form is a boolean, which makes its operator a predicate. */
|
|
352
|
+
const storedAsBoolean = (schema) => SchemaAST.isBoolean(Schema.toEncoded(schema).ast);
|
|
353
|
+
/** Every field, field after a write, and input an expression reads, as keys to compare. */
|
|
354
|
+
const readKeys = (...nodes) => {
|
|
355
|
+
const read = dependenciesOf(...nodes);
|
|
356
|
+
const named = (prefix, fields) => fields.map((field) => `${prefix}${field.entity}.${field.key}`);
|
|
357
|
+
return /* @__PURE__ */ new Set([
|
|
358
|
+
...named("", read.fields),
|
|
359
|
+
...named("next ", read.next),
|
|
360
|
+
...read.inputs.map((key) => `$${key}`)
|
|
361
|
+
]);
|
|
362
|
+
};
|
|
363
|
+
/** One argument, checked against the schema it is passed for, as a node. */
|
|
364
|
+
const argumentFor = (id, position, schema, value) => {
|
|
365
|
+
const arg = toOperand(value);
|
|
366
|
+
const fail = (what) => {
|
|
367
|
+
throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`);
|
|
368
|
+
};
|
|
369
|
+
if (isPredicate(arg)) {
|
|
370
|
+
if (!storedAsBoolean(schema)) fail("is a predicate, but the operator does not take a boolean");
|
|
371
|
+
return arg;
|
|
372
|
+
}
|
|
373
|
+
if (arg._tag === "Literal") {
|
|
374
|
+
if (!Schema.is(Schema.toEncoded(schema))(arg.value)) fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`);
|
|
375
|
+
return arg;
|
|
376
|
+
}
|
|
377
|
+
const wanted = orderKindOf(Schema.toEncoded(schema).ast);
|
|
378
|
+
const given = sideKind(arg);
|
|
379
|
+
if (wanted !== "none" && (given === "number" || given === "text") && given !== wanted) fail(`is stored as ${given}, but the operator takes ${wanted}`);
|
|
380
|
+
return arg;
|
|
381
|
+
};
|
|
382
|
+
/** A scalar's collation: a field's declared one, or a call's. */
|
|
383
|
+
const collationOf = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
|
|
384
|
+
Field: (field) => field.collation,
|
|
385
|
+
Next: ({ field }) => field.collation,
|
|
386
|
+
Call: (call) => call.collation,
|
|
387
|
+
Literal: () => Option.none(),
|
|
388
|
+
Input: () => Option.none()
|
|
389
|
+
}));
|
|
390
|
+
/**
|
|
391
|
+
* The collation a primitive call compares text under: the one its collated
|
|
392
|
+
* text arguments share. A literal or an input carries none and does not vote.
|
|
393
|
+
* `required` refuses a call with none, or with a backend's locale.
|
|
394
|
+
*/
|
|
395
|
+
const callCollation = (id, rule, args) => {
|
|
396
|
+
if (rule === "none") return Option.none();
|
|
397
|
+
const fail = (what) => {
|
|
398
|
+
throw new Error(`[foldkit-entity] ${id}: ${what}`);
|
|
399
|
+
};
|
|
400
|
+
const voters = args.flatMap((arg) => isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text" ? [] : [{
|
|
401
|
+
name: showExpr(arg),
|
|
402
|
+
collation: collationOf(arg)
|
|
403
|
+
}]);
|
|
404
|
+
const collations = voters.flatMap(({ name, collation }) => Option.match(collation, {
|
|
405
|
+
onSome: (each) => [each],
|
|
406
|
+
onNone: () => rule === "required" ? fail(`${name} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`) : []
|
|
407
|
+
}));
|
|
408
|
+
const [shared] = collations;
|
|
409
|
+
if (shared === void 0) return rule === "required" ? fail("compares text with no field or call holding a collation") : Option.none();
|
|
410
|
+
if (collations.some((each) => each._tag !== shared._tag)) fail(`${voters.map((voter) => voter.name).join(" and ")} declare different collations`);
|
|
411
|
+
if (rule === "required" && shared._tag === "Locale") fail(`compares by the backend's "${shared.locale}" collation, which only that backend has`);
|
|
412
|
+
return Option.some(shared);
|
|
413
|
+
};
|
|
414
|
+
/** Builds an operator: checks what it is given once, then each call. */
|
|
415
|
+
const makeOperator = (id, options) => {
|
|
416
|
+
const fail = (what) => {
|
|
417
|
+
throw new Error(`[foldkit-entity] Expr.operator("${id}"): ${what}`);
|
|
418
|
+
};
|
|
419
|
+
if (!operatorId.test(id)) fail("an id is namespaced lower camel case, as `cms.published`");
|
|
420
|
+
if (id.startsWith("foldkit.")) fail("ids under `foldkit.` are reserved");
|
|
421
|
+
const version = options.version ?? 1;
|
|
422
|
+
if (!Number.isSafeInteger(version) || version < 1) fail("a version is a positive integer");
|
|
423
|
+
if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) fail("`input` is one schema per argument");
|
|
424
|
+
if (!Schema.isSchema(options.output)) fail("`output` is a schema");
|
|
425
|
+
const definedAs = Option.fromUndefinedOr(options.definedAs);
|
|
426
|
+
if (Option.isSome(definedAs) && typeof definedAs.value !== "function") fail("`definedAs` builds what a call means");
|
|
427
|
+
if (Option.isSome(definedAs) && (options.nulls !== void 0 || options.collation !== void 0)) fail("a defined operator means its body, so `nulls` and `collation` are its body's");
|
|
428
|
+
const nulls = options.nulls ?? "strict";
|
|
429
|
+
const collation = options.collation ?? "none";
|
|
430
|
+
if (nulls !== "strict" && nulls !== "handled") fail("`nulls` is 'strict' or 'handled'");
|
|
431
|
+
if (collation !== "none" && collation !== "operands" && collation !== "required") fail("`collation` is 'none', 'operands' or 'required'");
|
|
432
|
+
const input = Object.freeze([...options.input]);
|
|
433
|
+
const predicate = storedAsBoolean(options.output);
|
|
434
|
+
if (collation === "operands" && orderKindOf(Schema.toEncoded(options.output).ast) !== "text") fail("`collation: 'operands'` describes a text result, and this one is not text");
|
|
435
|
+
const laws = Object.freeze([...options.laws ?? []]);
|
|
436
|
+
for (const law of laws) Option.match(lawProblem(law, input, options.output, collation), {
|
|
437
|
+
onNone: () => void 0,
|
|
438
|
+
onSome: fail
|
|
439
|
+
});
|
|
440
|
+
const descriptor = Object.freeze({
|
|
441
|
+
_tag: "Operator",
|
|
442
|
+
id,
|
|
443
|
+
version,
|
|
444
|
+
description: Option.fromUndefinedOr(options.description),
|
|
445
|
+
input,
|
|
446
|
+
output: options.output,
|
|
447
|
+
definedAs,
|
|
448
|
+
nulls,
|
|
449
|
+
collation,
|
|
450
|
+
laws
|
|
451
|
+
});
|
|
452
|
+
/** A defined call's expansion, checked: of its output's kind, reading only its arguments. */
|
|
453
|
+
const expand = (body, args) => {
|
|
454
|
+
const expansion = toOperand(body(...args));
|
|
455
|
+
if (predicate !== isPredicate(expansion)) throw new Error(`[foldkit-entity] ${id}: its output is ${predicate ? "a boolean, so `definedAs` returns a predicate" : "not a boolean, so `definedAs` returns a scalar"}`);
|
|
456
|
+
const allowed = readKeys(...args);
|
|
457
|
+
const hidden = [...readKeys(expansion)].filter((key) => !allowed.has(key));
|
|
458
|
+
if (hidden.length > 0) throw new Error(`[foldkit-entity] ${id}: \`definedAs\` reads ${hidden.join(", ")}, which no argument holds; pass it as one`);
|
|
459
|
+
return expansion;
|
|
460
|
+
};
|
|
461
|
+
const call = (...written) => {
|
|
462
|
+
const explicit = written.length === input.length + 1 ? Option.some(callOptionsOf(id, written[written.length - 1])) : Option.none();
|
|
463
|
+
const given = Option.isSome(explicit) ? written.slice(0, -1) : written;
|
|
464
|
+
if (given.length !== input.length) throw new Error(`[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? "" : "s"}, given ${given.length}`);
|
|
465
|
+
const args = Object.freeze(given.map((value, position) => argumentFor(id, position, input[position], value)));
|
|
466
|
+
const expansion = Option.map(descriptor.definedAs, (body) => expand(body, args));
|
|
467
|
+
const carried = Option.match(explicit, {
|
|
468
|
+
onSome: (each) => givenCollation(id, descriptor, each),
|
|
469
|
+
onNone: () => Option.match(expansion, {
|
|
470
|
+
onSome: (body) => isPredicate(body) ? Option.none() : collationOf(body),
|
|
471
|
+
onNone: () => callCollation(id, collation, args)
|
|
472
|
+
})
|
|
473
|
+
});
|
|
474
|
+
return predicate ? node({
|
|
475
|
+
_tag: "Test",
|
|
476
|
+
operator: descriptor,
|
|
477
|
+
args,
|
|
478
|
+
expansion,
|
|
479
|
+
collation: carried
|
|
480
|
+
}) : node({
|
|
481
|
+
_tag: "Call",
|
|
482
|
+
operator: descriptor,
|
|
483
|
+
args,
|
|
484
|
+
expansion,
|
|
485
|
+
collation: carried
|
|
486
|
+
});
|
|
487
|
+
};
|
|
488
|
+
return Object.freeze(Object.assign(call, { descriptor }));
|
|
489
|
+
};
|
|
490
|
+
/** Each defined call replaced by its expansion, deeply; built once per node. */
|
|
491
|
+
const expandedCache = /* @__PURE__ */ new WeakMap();
|
|
492
|
+
const expandedScalar = (scalar) => {
|
|
493
|
+
const known = expandedCache.get(scalar);
|
|
494
|
+
if (known !== void 0) return known;
|
|
495
|
+
const result = scalar._tag === "Call" ? Option.match(scalar.expansion, {
|
|
496
|
+
onSome: expandedScalar,
|
|
497
|
+
onNone: () => node({
|
|
498
|
+
...scalar,
|
|
499
|
+
args: scalar.args.map(expandedSide)
|
|
500
|
+
})
|
|
501
|
+
}) : scalar;
|
|
502
|
+
expandedCache.set(scalar, result);
|
|
503
|
+
return result;
|
|
504
|
+
};
|
|
505
|
+
const expandedSide = (side) => isPredicate(side) ? expandedPredicate(side) : expandedScalar(side);
|
|
506
|
+
const expandedPredicate = (predicate) => {
|
|
507
|
+
const known = expandedCache.get(predicate);
|
|
508
|
+
if (known !== void 0) return known;
|
|
509
|
+
const result = Match.value(predicate).pipe(Match.tagsExhaustive({
|
|
510
|
+
Eq: (eq) => node({
|
|
511
|
+
...eq,
|
|
512
|
+
left: expandedSide(eq.left),
|
|
513
|
+
right: expandedSide(eq.right)
|
|
514
|
+
}),
|
|
515
|
+
Null: (nul) => node({
|
|
516
|
+
...nul,
|
|
517
|
+
operand: expandedScalar(nul.operand)
|
|
518
|
+
}),
|
|
519
|
+
Contains: (contains) => node({
|
|
520
|
+
...contains,
|
|
521
|
+
value: expandedScalar(contains.value),
|
|
522
|
+
search: expandedSide(contains.search)
|
|
523
|
+
}),
|
|
524
|
+
In: (inPredicate) => node({
|
|
525
|
+
...inPredicate,
|
|
526
|
+
value: expandedScalar(inPredicate.value),
|
|
527
|
+
among: expandedScalar(inPredicate.among)
|
|
528
|
+
}),
|
|
529
|
+
And: (and) => node({
|
|
530
|
+
...and,
|
|
531
|
+
operands: Array$1.map(and.operands, expandedPredicate)
|
|
532
|
+
}),
|
|
533
|
+
Or: (or) => node({
|
|
534
|
+
...or,
|
|
535
|
+
operands: Array$1.map(or.operands, expandedPredicate)
|
|
536
|
+
}),
|
|
537
|
+
Not: (not) => node({
|
|
538
|
+
...not,
|
|
539
|
+
operand: expandedPredicate(not.operand)
|
|
540
|
+
}),
|
|
541
|
+
Compare: (compare) => node({
|
|
542
|
+
...compare,
|
|
543
|
+
left: expandedScalar(compare.left),
|
|
544
|
+
right: expandedScalar(compare.right)
|
|
545
|
+
}),
|
|
546
|
+
Test: (test) => Option.match(test.expansion, {
|
|
547
|
+
onSome: expandedPredicate,
|
|
548
|
+
onNone: () => node({
|
|
549
|
+
...test,
|
|
550
|
+
args: test.args.map(expandedSide)
|
|
551
|
+
})
|
|
552
|
+
})
|
|
553
|
+
}));
|
|
554
|
+
expandedCache.set(predicate, result);
|
|
555
|
+
return result;
|
|
556
|
+
};
|
|
199
557
|
const Expr = {
|
|
558
|
+
/**
|
|
559
|
+
* An operator, defined by what a call of it means: `definedAs` builds that
|
|
560
|
+
* expression from the call's arguments, once per call, and every interpreter
|
|
561
|
+
* runs it, so the operator needs no implementation anywhere. What it adds is
|
|
562
|
+
* a name: a query, a guard and an invariant that mean the same thing say so,
|
|
563
|
+
* and print it.
|
|
564
|
+
*
|
|
565
|
+
* ```ts
|
|
566
|
+
* const published = Expr.operator('cms.published', {
|
|
567
|
+
* input: [Schema.Unknown],
|
|
568
|
+
* output: Schema.Boolean,
|
|
569
|
+
* definedAs: publishedAt => Expr.isNotNull(publishedAt),
|
|
570
|
+
* })
|
|
571
|
+
* Query.where(published(Post.fields.publishedAt))
|
|
572
|
+
* ```
|
|
573
|
+
*
|
|
574
|
+
* Arguments are checked by their stored form: a field, scalar or plain value
|
|
575
|
+
* of the input's stored type, or a predicate where it takes a boolean. A
|
|
576
|
+
* boolean output makes a call a predicate. `definedAs` may read only what its
|
|
577
|
+
* arguments hold: a field or input it closes over instead is refused when
|
|
578
|
+
* called, since nothing asking what the call reads would see it. The id is
|
|
579
|
+
* namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
|
|
580
|
+
* changes when what it means does.
|
|
581
|
+
*
|
|
582
|
+
* **Without `definedAs` it is primitive**: each interpreter implements it
|
|
583
|
+
* (`Operators.implement` in memory), and one without an implementation
|
|
584
|
+
* refuses the body by the operator's id. `nulls` (default `strict`: a null
|
|
585
|
+
* argument gives null, the implementation never sees one) and `collation`
|
|
586
|
+
* (`operands`: a text result carries its text arguments' shared collation;
|
|
587
|
+
* `required`: it compares text itself and needs one) are a primitive
|
|
588
|
+
* operator's; a defined one means its body for both.
|
|
589
|
+
*/
|
|
590
|
+
operator: (id, options) => makeOperator(id, options),
|
|
591
|
+
/**
|
|
592
|
+
* The predicate or scalar (an order term's, say) with every call of a
|
|
593
|
+
* defined operator replaced by what it means, deeply. An interpreter that
|
|
594
|
+
* compiles a body expands it first, and compiles exactly what was written
|
|
595
|
+
* out. A call with no definition stays, for the interpreter to run or refuse
|
|
596
|
+
* by name.
|
|
597
|
+
*/
|
|
598
|
+
expanded: (node) => isPredicate(node) ? expandedPredicate(node) : expandedScalar(node),
|
|
599
|
+
/**
|
|
600
|
+
* What these expressions need that an interpreter lacks, as `Query.unsupported`
|
|
601
|
+
* says it for a query: each kernel operation `supported` does not list, then
|
|
602
|
+
* each primitive operator `operators` does not implement, by name (`id`, or
|
|
603
|
+
* `id@version` past the first). For anything holding expressions that is not a
|
|
604
|
+
* query: a guard's rule, an invariant, a write's `when`.
|
|
605
|
+
*/
|
|
606
|
+
unsupported: (nodes, interpreter) => unsupportedIn(nodes, interpreter.operations, interpreter.operators),
|
|
200
607
|
/** A constant. Comparisons coerce a plain value, so this is rarely written. */
|
|
201
608
|
literal,
|
|
202
609
|
/**
|
|
@@ -365,7 +772,16 @@ const Expr = {
|
|
|
365
772
|
*/
|
|
366
773
|
substituteNext: (predicate, values) => substituted(predicate, (operand) => Match.value(operand).pipe(Match.tag("Next", ({ field }) => Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand), Match.orElse(() => operand)))
|
|
367
774
|
};
|
|
368
|
-
const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) :
|
|
775
|
+
const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite);
|
|
776
|
+
/**
|
|
777
|
+
* A scalar rewritten: a call's arguments and expansion each, so a field read
|
|
778
|
+
* under it is rewritten as one read directly is; anything else by `rewrite`.
|
|
779
|
+
*/
|
|
780
|
+
const substitutedScalar = (scalar, rewrite) => scalar._tag === "Call" ? node({
|
|
781
|
+
...scalar,
|
|
782
|
+
args: Object.freeze(scalar.args.map((arg) => substitutedSide(arg, rewrite))),
|
|
783
|
+
expansion: Option.map(scalar.expansion, (expansion) => substitutedScalar(expansion, rewrite))
|
|
784
|
+
}) : rewrite(scalar);
|
|
369
785
|
const substituted = (predicate, rewrite) => {
|
|
370
786
|
switch (predicate._tag) {
|
|
371
787
|
case "Eq": return node({
|
|
@@ -375,17 +791,17 @@ const substituted = (predicate, rewrite) => {
|
|
|
375
791
|
});
|
|
376
792
|
case "Null": return node({
|
|
377
793
|
...predicate,
|
|
378
|
-
operand:
|
|
794
|
+
operand: substitutedScalar(predicate.operand, rewrite)
|
|
379
795
|
});
|
|
380
796
|
case "Contains": return node({
|
|
381
797
|
...predicate,
|
|
382
|
-
value:
|
|
798
|
+
value: substitutedScalar(predicate.value, rewrite),
|
|
383
799
|
search: substitutedSide(predicate.search, rewrite)
|
|
384
800
|
});
|
|
385
801
|
case "In": return node({
|
|
386
802
|
...predicate,
|
|
387
|
-
value:
|
|
388
|
-
among:
|
|
803
|
+
value: substitutedScalar(predicate.value, rewrite),
|
|
804
|
+
among: substitutedScalar(predicate.among, rewrite)
|
|
389
805
|
});
|
|
390
806
|
case "And":
|
|
391
807
|
case "Or": return node({
|
|
@@ -398,19 +814,48 @@ const substituted = (predicate, rewrite) => {
|
|
|
398
814
|
});
|
|
399
815
|
case "Compare": return node({
|
|
400
816
|
...predicate,
|
|
401
|
-
left:
|
|
402
|
-
right:
|
|
817
|
+
left: substitutedScalar(predicate.left, rewrite),
|
|
818
|
+
right: substitutedScalar(predicate.right, rewrite)
|
|
819
|
+
});
|
|
820
|
+
case "Test": return node({
|
|
821
|
+
...predicate,
|
|
822
|
+
args: Object.freeze(predicate.args.map((arg) => substitutedSide(arg, rewrite))),
|
|
823
|
+
expansion: Option.map(predicate.expansion, (expansion) => substituted(expansion, rewrite))
|
|
403
824
|
});
|
|
404
825
|
}
|
|
405
826
|
};
|
|
406
827
|
/** A term, its nulls placed by `options` or by the direction's default. */
|
|
407
|
-
const term = (direction, expr, options = {}) =>
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
828
|
+
const term = (direction, expr, options = {}) => {
|
|
829
|
+
const collation = Option.orElse(Option.fromUndefinedOr(options.collation), () => Match.value(expr).pipe(Match.tag("Field", (field) => field.collation), Match.tag("Call", (call) => call.collation), Match.orElse(() => Option.none())));
|
|
830
|
+
if (expr._tag === "Call") orderableCall(expr, collation);
|
|
831
|
+
return node({
|
|
832
|
+
_tag: "Term",
|
|
833
|
+
direction,
|
|
834
|
+
expr,
|
|
835
|
+
nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
|
|
836
|
+
collation
|
|
837
|
+
});
|
|
838
|
+
};
|
|
839
|
+
/**
|
|
840
|
+
* Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):
|
|
841
|
+
* its result must be a number, or text under a collation every interpreter
|
|
842
|
+
* shares. A field's text may be left to the backend; a call's has no backend
|
|
843
|
+
* column to fall back on.
|
|
844
|
+
*/
|
|
845
|
+
const orderableCall = (call, collation) => {
|
|
846
|
+
const fail = (why) => {
|
|
847
|
+
throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`);
|
|
848
|
+
};
|
|
849
|
+
const kind = sideKind(call);
|
|
850
|
+
if (kind === "number") return;
|
|
851
|
+
if (kind !== "text") fail("is neither a number nor text, so it orders nowhere alike");
|
|
852
|
+
Option.match(collation, {
|
|
853
|
+
onNone: () => fail("is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold"),
|
|
854
|
+
onSome: (each) => {
|
|
855
|
+
if (each._tag === "Locale") fail(`is ordered by the backend's "${each.locale}" collation, which a call cannot carry`);
|
|
856
|
+
}
|
|
857
|
+
});
|
|
858
|
+
};
|
|
414
859
|
const Order = {
|
|
415
860
|
/** Smallest first; rows without a value last, unless `nulls` says first. */
|
|
416
861
|
asc: (expr, options) => term("asc", toExpr(expr, "asc"), options),
|
|
@@ -418,8 +863,8 @@ const Order = {
|
|
|
418
863
|
desc: (expr, options) => term("desc", toExpr(expr, "desc"), options),
|
|
419
864
|
/**
|
|
420
865
|
* The order the input names, among `choices`: every name the sort can hold
|
|
421
|
-
* maps to a field, so a name left out is a type error
|
|
422
|
-
* silently orders by nothing. A `null` sort chooses none, and the terms after
|
|
866
|
+
* maps to a field or a call that orders, so a name left out is a type error
|
|
867
|
+
* here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
|
|
423
868
|
* it decide.
|
|
424
869
|
*
|
|
425
870
|
* ```ts
|
|
@@ -430,7 +875,8 @@ const Order = {
|
|
|
430
875
|
const fields = Object.create(null);
|
|
431
876
|
for (const [name, choice] of Object.entries(choices)) {
|
|
432
877
|
const expr = toExpr(choice, "chosen");
|
|
433
|
-
if (expr._tag !== "Field") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is
|
|
878
|
+
if (expr._tag !== "Field" && expr._tag !== "Call") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is neither a field nor a call`);
|
|
879
|
+
if (expr._tag === "Call") orderableCall(expr, expr.collation);
|
|
434
880
|
fields[name] = expr;
|
|
435
881
|
}
|
|
436
882
|
return node({
|
|
@@ -451,15 +897,18 @@ const notPlaceable = (reason) => Object.freeze({
|
|
|
451
897
|
* every order term.
|
|
452
898
|
*/
|
|
453
899
|
const ordersIntrinsically = (ast) => SchemaAST.isNumber(ast) || SchemaAST.isBoolean(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal !== "string" || SchemaAST.isUnion(ast) && ast.types.every((member) => SchemaAST.isNull(member) || ordersIntrinsically(member));
|
|
454
|
-
/** Why a term cannot be placed by a client
|
|
455
|
-
const unplaceable = (orderTerm) => Match.value(orderTerm.expr).pipe(Match.tag("
|
|
900
|
+
/** Why a term cannot be placed by a client running `operators`, if it cannot. */
|
|
901
|
+
const unplaceable = (orderTerm, operators) => Match.value(orderTerm.expr).pipe(Match.tag("Call", (call) => {
|
|
902
|
+
const missing = missingFrom(dependenciesOf(call).operators, operators);
|
|
903
|
+
return missing.length === 0 ? Option.none() : Option.some(`it orders by ${showExpr(call)}, and this client does not run ${missing.join(", ")}`);
|
|
904
|
+
}), Match.tag("Field", (field) => Option.match(orderTerm.collation, {
|
|
456
905
|
onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
|
|
457
906
|
onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
|
|
458
907
|
Binary: () => Option.none(),
|
|
459
908
|
AsciiFold: () => Option.none(),
|
|
460
909
|
Locale: ({ locale }) => Option.some(`it orders ${field.owner.name}.${field.key} by the backend's "${locale}" collation`)
|
|
461
910
|
}))
|
|
462
|
-
})), Match.orElse(() => Option.some("it orders by something that is
|
|
911
|
+
})), Match.orElse(() => Option.some("it orders by something that is neither a field nor a call")));
|
|
463
912
|
/** Each Entity's id tie-break, made once, so a resolved order reuses one term. */
|
|
464
913
|
const idTerms = /* @__PURE__ */ new WeakMap();
|
|
465
914
|
const idTermOf = (entity) => {
|
|
@@ -565,6 +1014,15 @@ const walk = (expr, found) => {
|
|
|
565
1014
|
walk(expr.sort, found);
|
|
566
1015
|
for (const choice of Object.values(expr.choices)) walk(choice, found);
|
|
567
1016
|
return;
|
|
1017
|
+
case "Call":
|
|
1018
|
+
case "Test":
|
|
1019
|
+
found.operators.add(expr.operator);
|
|
1020
|
+
Option.match(expansionOf(expr), {
|
|
1021
|
+
onSome: (expansion) => walk(expansion, found),
|
|
1022
|
+
onNone: () => expr.args.forEach((arg) => walk(arg, found))
|
|
1023
|
+
});
|
|
1024
|
+
return;
|
|
1025
|
+
default: return absurd(expr);
|
|
568
1026
|
}
|
|
569
1027
|
};
|
|
570
1028
|
/**
|
|
@@ -580,14 +1038,16 @@ const dependenciesOf = (...nodes) => {
|
|
|
580
1038
|
inputs: /* @__PURE__ */ new Set(),
|
|
581
1039
|
next: /* @__PURE__ */ new Map(),
|
|
582
1040
|
nextOrder: [],
|
|
583
|
-
operations: /* @__PURE__ */ new Set()
|
|
1041
|
+
operations: /* @__PURE__ */ new Set(),
|
|
1042
|
+
operators: /* @__PURE__ */ new Set()
|
|
584
1043
|
};
|
|
585
1044
|
for (const term of nodes) walk(term, found);
|
|
586
1045
|
return {
|
|
587
1046
|
fields: found.order,
|
|
588
1047
|
next: found.nextOrder,
|
|
589
1048
|
inputs: [...found.inputs],
|
|
590
|
-
operations: [...found.operations]
|
|
1049
|
+
operations: [...found.operations],
|
|
1050
|
+
operators: [...found.operators]
|
|
591
1051
|
};
|
|
592
1052
|
};
|
|
593
1053
|
/** Every field an expression reads, as the nodes themselves, each node visited once. */
|
|
@@ -635,6 +1095,11 @@ const fieldsIn = function* (expr, seen) {
|
|
|
635
1095
|
case "Chosen":
|
|
636
1096
|
for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen);
|
|
637
1097
|
return;
|
|
1098
|
+
case "Call":
|
|
1099
|
+
case "Test":
|
|
1100
|
+
for (const arg of expr.args) yield* fieldsIn(arg, seen);
|
|
1101
|
+
return;
|
|
1102
|
+
default: return absurd(expr);
|
|
638
1103
|
}
|
|
639
1104
|
};
|
|
640
1105
|
/**
|
|
@@ -669,6 +1134,11 @@ const childrenOf = (expr) => {
|
|
|
669
1134
|
case "Or": return expr.operands;
|
|
670
1135
|
case "Not": return [expr.operand];
|
|
671
1136
|
case "Compare": return [expr.left, expr.right];
|
|
1137
|
+
case "Call":
|
|
1138
|
+
case "Test": return Option.match(expansionOf(expr), {
|
|
1139
|
+
onSome: (expansion) => [expansion],
|
|
1140
|
+
onNone: () => expr.args
|
|
1141
|
+
});
|
|
672
1142
|
}
|
|
673
1143
|
};
|
|
674
1144
|
/** A node's size as a tree, each distinct node sized once. */
|
|
@@ -739,13 +1209,15 @@ const Query = {
|
|
|
739
1209
|
/**
|
|
740
1210
|
* Whether a client can order this query's rows exactly as the server does,
|
|
741
1211
|
* for one input: every term over a number or a boolean (a row may lack it), or over text with a
|
|
742
|
-
* portable collation (`binary`, `asciiFold`)
|
|
743
|
-
*
|
|
1212
|
+
* portable collation (`binary`, `asciiFold`), or a call whose primitive
|
|
1213
|
+
* operators the client's table (`operators`; none when not given) runs. A
|
|
1214
|
+
* body that names no order leaves it to the server, and is never placeable.
|
|
744
1215
|
*/
|
|
745
|
-
placement: (self, input) => {
|
|
1216
|
+
placement: (self, input, options = {}) => {
|
|
746
1217
|
if (self.orderBy.length === 0) return notPlaceable("its order is the server's: the body names none");
|
|
1218
|
+
const operators = options.operators ?? noOperators;
|
|
747
1219
|
for (const orderTerm of Query.orderFor(self, input)) {
|
|
748
|
-
const reason = unplaceable(orderTerm);
|
|
1220
|
+
const reason = unplaceable(orderTerm, operators);
|
|
749
1221
|
if (Option.isSome(reason)) return notPlaceable(reason.value);
|
|
750
1222
|
}
|
|
751
1223
|
return placeable;
|
|
@@ -762,8 +1234,10 @@ const Query = {
|
|
|
762
1234
|
}),
|
|
763
1235
|
/**
|
|
764
1236
|
* The operations this query needs that `supported` does not list, in the
|
|
765
|
-
* order the query uses them
|
|
766
|
-
* `
|
|
1237
|
+
* order the query uses them, then each primitive operator `operators` does
|
|
1238
|
+
* not implement, by name. Without `operators`, every primitive operator is
|
|
1239
|
+
* named: a list of operations implements none. Empty means an interpreter
|
|
1240
|
+
* declaring both can answer it.
|
|
767
1241
|
*
|
|
768
1242
|
* An interpreter declares what it runs and refuses the rest, rather than
|
|
769
1243
|
* ignoring an operation it does not implement — which would answer a
|
|
@@ -777,10 +1251,7 @@ const Query = {
|
|
|
777
1251
|
* if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
|
|
778
1252
|
* ```
|
|
779
1253
|
*/
|
|
780
|
-
unsupported: (self, supported) =>
|
|
781
|
-
const runs = new Set(supported);
|
|
782
|
-
return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
|
|
783
|
-
},
|
|
1254
|
+
unsupported: (self, supported, operators = noOperators) => unsupportedIn([...self.where, ...self.orderBy], supported, operators),
|
|
784
1255
|
/**
|
|
785
1256
|
* The whole query as readable text, one clause per line:
|
|
786
1257
|
*
|
|
@@ -833,8 +1304,29 @@ const showExpr = (node) => {
|
|
|
833
1304
|
case "Or": return node.operands.map(showConnected).join(" or ");
|
|
834
1305
|
case "Not": return `not (${showExpr(node.operand)})`;
|
|
835
1306
|
case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
|
|
1307
|
+
case "Call":
|
|
1308
|
+
case "Test": return `${operatorName$1(node.operator)}(${node.args.map(showOperand).join(", ")})`;
|
|
836
1309
|
}
|
|
837
1310
|
};
|
|
1311
|
+
/** A call's expansion, scalar or predicate alike. */
|
|
1312
|
+
const expansionOf = (call) => call.expansion;
|
|
1313
|
+
/**
|
|
1314
|
+
* What `nodes` need that an interpreter lacks: each kernel operation it does
|
|
1315
|
+
* not list, then each primitive operator its table does not implement, by
|
|
1316
|
+
* name. A defined operator needs nothing: what it means is walked instead.
|
|
1317
|
+
*/
|
|
1318
|
+
const unsupportedIn = (nodes, supported, operators) => {
|
|
1319
|
+
const read = dependenciesOf(...nodes);
|
|
1320
|
+
const runs = new Set(supported);
|
|
1321
|
+
return [...read.operations.filter((operation) => !runs.has(operation)), ...missingFrom(read.operators, operators)];
|
|
1322
|
+
};
|
|
1323
|
+
/**
|
|
1324
|
+
* The primitive operators among `read` that `operators` does not implement, by
|
|
1325
|
+
* name. A defined one needs nothing: what it means was walked into `read`.
|
|
1326
|
+
*/
|
|
1327
|
+
const missingFrom = (read, operators) => read.filter((operator) => Option.isNone(operator.definedAs) && !operators.has(operator)).map(operatorName$1);
|
|
1328
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
1329
|
+
const operatorName$1 = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
838
1330
|
const symbols = {
|
|
839
1331
|
lt: "<",
|
|
840
1332
|
lte: "<=",
|
|
@@ -847,8 +1339,146 @@ const showConnected = (node) => Match.value(node).pipe(Match.tags({
|
|
|
847
1339
|
Or: () => `(${showExpr(node)})`
|
|
848
1340
|
}), Match.orElse(() => showExpr(node)));
|
|
849
1341
|
const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
|
|
850
|
-
|
|
851
|
-
|
|
1342
|
+
// src/text.ts
|
|
1343
|
+
/**
|
|
1344
|
+
* The kernel's text operators: primitive, so each interpreter implements them,
|
|
1345
|
+
* and each states what it means here, where data-query §6.0.1 holds the rest.
|
|
1346
|
+
*/
|
|
1347
|
+
const Text = {
|
|
1348
|
+
/**
|
|
1349
|
+
* Whether the first text begins with the second, under the first's collation.
|
|
1350
|
+
*
|
|
1351
|
+
* | Case | Answer |
|
|
1352
|
+
* | --- | --- |
|
|
1353
|
+
* | either is null | unknown |
|
|
1354
|
+
* | the prefix is `''` | true |
|
|
1355
|
+
* | otherwise | whether it begins so, compared under the collation |
|
|
1356
|
+
*
|
|
1357
|
+
* The collation is the text's: a field's declared one, or a call's. `binary`
|
|
1358
|
+
* compares exactly; `asciiFold` folds ASCII letters on both sides. Text with
|
|
1359
|
+
* none, or with a backend's locale, is refused where the call is written.
|
|
1360
|
+
* Prefixes are by character, so non-ASCII and astral text begin as they read.
|
|
1361
|
+
*
|
|
1362
|
+
* ```ts
|
|
1363
|
+
* Query.where(Text.startsWith(Product.fields.upc, input.search))
|
|
1364
|
+
* ```
|
|
1365
|
+
*/
|
|
1366
|
+
startsWith: Expr.operator("text.startsWith", {
|
|
1367
|
+
input: [Schema.NullOr(Schema.String), Schema.NullOr(Schema.String)],
|
|
1368
|
+
output: Schema.Boolean,
|
|
1369
|
+
collation: "required",
|
|
1370
|
+
description: "Whether the first text begins with the second, under the first's collation."
|
|
1371
|
+
}) };
|
|
1372
|
+
// src/operators.ts
|
|
1373
|
+
/**
|
|
1374
|
+
* How the in-memory interpreter runs primitive operators: a table of
|
|
1375
|
+
* implementations, passed to `evaluate` and every judge as a value. A table is
|
|
1376
|
+
* immutable and implements each operator once; nothing registers anything
|
|
1377
|
+
* globally. See `docs/design/expr-operations-DESIGN.md` §5.4.
|
|
1378
|
+
*/
|
|
1379
|
+
const Evidence = Data.taggedEnum();
|
|
1380
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
1381
|
+
const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
1382
|
+
const fail$3 = (what) => {
|
|
1383
|
+
throw new Error(`[foldkit-entity] Operators: ${what}`);
|
|
1384
|
+
};
|
|
1385
|
+
const table = (implementations, checked, evidence) => {
|
|
1386
|
+
const byOperator = /* @__PURE__ */ new Map();
|
|
1387
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1388
|
+
for (const { operator, run } of implementations) {
|
|
1389
|
+
if (byOperator.has(operator)) fail$3(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
|
|
1390
|
+
const named = byName.get(nameOf(operator));
|
|
1391
|
+
if (named !== void 0 && named !== operator) fail$3(`two operators are named ${nameOf(operator)}; give one another id or version`);
|
|
1392
|
+
byName.set(nameOf(operator), operator);
|
|
1393
|
+
byOperator.set(operator, run);
|
|
1394
|
+
}
|
|
1395
|
+
return Object.freeze({
|
|
1396
|
+
_tag: "MemoryOperators",
|
|
1397
|
+
has: (operator) => byOperator.has(operator),
|
|
1398
|
+
get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
|
|
1399
|
+
checked,
|
|
1400
|
+
implementations: Object.freeze([...implementations]),
|
|
1401
|
+
evidence: Object.freeze([...evidence])
|
|
1402
|
+
});
|
|
1403
|
+
};
|
|
1404
|
+
/** Whether two laws, as JSON, are the same law. */
|
|
1405
|
+
const sameLaw = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
1406
|
+
/** An implementation, its operator's null rule checked against the function chosen for it. */
|
|
1407
|
+
const implementation = (operator, nulls, run) => {
|
|
1408
|
+
if (operator.nulls !== nulls) fail$3(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
|
|
1409
|
+
return Object.freeze({
|
|
1410
|
+
operator,
|
|
1411
|
+
run: (args, context) => run(...args, context)
|
|
1412
|
+
});
|
|
1413
|
+
};
|
|
1414
|
+
const Operators = {
|
|
1415
|
+
/**
|
|
1416
|
+
* An implementation of a strict operator: a pure function of its arguments'
|
|
1417
|
+
* stored values, never given a null (the kernel answers null, or unknown, for
|
|
1418
|
+
* one first), and told the call's collation last.
|
|
1419
|
+
*
|
|
1420
|
+
* ```ts
|
|
1421
|
+
* Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))
|
|
1422
|
+
* ```
|
|
1423
|
+
*/
|
|
1424
|
+
implement: (operator, run) => implementation(operator.descriptor, "strict", run),
|
|
1425
|
+
/**
|
|
1426
|
+
* An implementation of an operator declared `nulls: 'handled'`: given nulls
|
|
1427
|
+
* as they are, it answers for them; a predicate answers `null` for unknown.
|
|
1428
|
+
*/
|
|
1429
|
+
implementHandlingNulls: (operator, run) => implementation(operator.descriptor, "handled", run),
|
|
1430
|
+
/** A table of implementations. One operator implemented twice, or two under one name, is refused. */
|
|
1431
|
+
memory: (...implementations) => table(implementations, false, []),
|
|
1432
|
+
/** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */
|
|
1433
|
+
merge: (left, right) => {
|
|
1434
|
+
const both = right.implementations.filter(({ operator }) => left.has(operator));
|
|
1435
|
+
if (both.length > 0) fail$3(`both tables implement ${both.map(({ operator }) => nameOf(operator)).join(", ")}; replace with Operators.override`);
|
|
1436
|
+
return table([...left.implementations, ...right.implementations], left.checked || right.checked, [...left.evidence, ...right.evidence]);
|
|
1437
|
+
},
|
|
1438
|
+
/**
|
|
1439
|
+
* The table with these implementations in place of its own for the same
|
|
1440
|
+
* operators. Evidence of a replaced implementation goes with it: it was
|
|
1441
|
+
* that implementation's.
|
|
1442
|
+
*/
|
|
1443
|
+
override: (base, ...implementations) => {
|
|
1444
|
+
const replaced = new Set(implementations.map(({ operator }) => operator));
|
|
1445
|
+
const names = new Set([...replaced].map(nameOf));
|
|
1446
|
+
return table([...base.implementations.filter(({ operator }) => !replaced.has(operator)), ...implementations], base.checked, base.evidence.filter(({ operator }) => !names.has(operator)));
|
|
1447
|
+
},
|
|
1448
|
+
/**
|
|
1449
|
+
* The table with what is known of its implementations' laws recorded: each
|
|
1450
|
+
* record of an operator it implements and a law that operator declares.
|
|
1451
|
+
* `Conformance.laws` gives `Tested` records; `Evidence.Proven` says a proof
|
|
1452
|
+
* elsewhere covers one.
|
|
1453
|
+
*/
|
|
1454
|
+
withEvidence: (base, evidence) => {
|
|
1455
|
+
const declared = new Map(base.implementations.map(({ operator }) => [nameOf(operator), operator.laws.map(Law.describe)]));
|
|
1456
|
+
for (const record of evidence) if (!(declared.get(record.operator) ?? fail$3(`evidence names ${record.operator}, which this table does not implement`)).some((law) => sameLaw(law, record.law))) fail$3(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`);
|
|
1457
|
+
return table(base.implementations, base.checked, [...base.evidence, ...evidence]);
|
|
1458
|
+
},
|
|
1459
|
+
/**
|
|
1460
|
+
* Each operator the table implements, by name, with the laws it declares and
|
|
1461
|
+
* the evidence the table records of them: what a server can publish of how
|
|
1462
|
+
* it runs a body. JSON as it is.
|
|
1463
|
+
*/
|
|
1464
|
+
describeTable: (base) => base.implementations.map(({ operator }) => ({
|
|
1465
|
+
operator: nameOf(operator),
|
|
1466
|
+
laws: operator.laws.map(Law.describe),
|
|
1467
|
+
evidence: base.evidence.filter((record) => record.operator === nameOf(operator))
|
|
1468
|
+
})),
|
|
1469
|
+
/**
|
|
1470
|
+
* The table, checking every answer against its operator's output schema, so
|
|
1471
|
+
* an implementation that answers the wrong kind fails where it answered. For
|
|
1472
|
+
* tests: it costs a decode per call.
|
|
1473
|
+
*/
|
|
1474
|
+
checked: (base) => table(base.implementations, true, base.evidence),
|
|
1475
|
+
/** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
|
|
1476
|
+
kernel: table([implementation(Text.startsWith.descriptor, "strict", (...given) => {
|
|
1477
|
+
const [text, prefix, { collation }] = given;
|
|
1478
|
+
return Option.exists(collation, (each) => each._tag === "AsciiFold") ? Collation.foldAscii(text).startsWith(Collation.foldAscii(prefix)) : text.startsWith(prefix);
|
|
1479
|
+
})], false, [])
|
|
1480
|
+
};
|
|
1481
|
+
// src/evaluate.ts
|
|
852
1482
|
/**
|
|
853
1483
|
* The reference interpreter: a query body run over rows already in memory.
|
|
854
1484
|
*
|
|
@@ -879,21 +1509,80 @@ var QueryEvaluateError = class extends Error {
|
|
|
879
1509
|
this.name = "QueryEvaluateError";
|
|
880
1510
|
}
|
|
881
1511
|
};
|
|
1512
|
+
/**
|
|
1513
|
+
* A call of a primitive operator the table does not implement. Its own class,
|
|
1514
|
+
* because a form judging an invariant reads it as a judgement it cannot make
|
|
1515
|
+
* (`Undecided`), not as a failure.
|
|
1516
|
+
*/
|
|
1517
|
+
var OperatorMissingError = class extends QueryEvaluateError {
|
|
1518
|
+
operator;
|
|
1519
|
+
/** The operator by its id, and its version past the first. */
|
|
1520
|
+
named;
|
|
1521
|
+
constructor(operator) {
|
|
1522
|
+
super(`this interpreter does not run the operator "${operatorName(operator)}"`);
|
|
1523
|
+
this.name = "OperatorMissingError";
|
|
1524
|
+
this.operator = operator;
|
|
1525
|
+
this.named = operatorName(operator);
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
1529
|
+
const operatorName = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
882
1530
|
const valueOf = (node, scope) => {
|
|
883
1531
|
switch (node._tag) {
|
|
884
1532
|
case "Field": return scope.row[node.key];
|
|
885
1533
|
case "Next": return scope.next[node.field.key];
|
|
886
1534
|
case "Literal": return node.value;
|
|
887
1535
|
case "Input": return scope.input[node.key];
|
|
1536
|
+
case "Call": return called(node, scope);
|
|
1537
|
+
default: return absurd(node);
|
|
888
1538
|
}
|
|
889
1539
|
};
|
|
890
|
-
const isNull = (value) => value === null || value === void 0;
|
|
891
1540
|
/**
|
|
892
|
-
*
|
|
893
|
-
*
|
|
894
|
-
*
|
|
1541
|
+
* What a call comes to, as a value (a predicate's truth as SQL's, unknown as
|
|
1542
|
+
* null). The table's implementation when it has one; else, for a defined
|
|
1543
|
+
* operator, what it means; else it is refused by name.
|
|
1544
|
+
*/
|
|
1545
|
+
const called = (call, scope) => {
|
|
1546
|
+
const expansion = call.expansion;
|
|
1547
|
+
return Option.match(scope.operators.get(call.operator), {
|
|
1548
|
+
onSome: (run) => ran(call, run, scope),
|
|
1549
|
+
onNone: () => Option.match(expansion, {
|
|
1550
|
+
onSome: (body) => sideOf(body, scope),
|
|
1551
|
+
onNone: () => {
|
|
1552
|
+
throw new OperatorMissingError(call.operator);
|
|
1553
|
+
}
|
|
1554
|
+
})
|
|
1555
|
+
});
|
|
1556
|
+
};
|
|
1557
|
+
/**
|
|
1558
|
+
* A primitive operator run: strict about null and NUL before it is asked, a
|
|
1559
|
+
* throw it makes named as its own, and, in a checked table, its answer held to
|
|
1560
|
+
* its output schema.
|
|
895
1561
|
*/
|
|
896
|
-
const
|
|
1562
|
+
const ran = (call, run, scope) => {
|
|
1563
|
+
const { operator } = call;
|
|
1564
|
+
const values = call.args.map((arg) => sideOf(arg, scope));
|
|
1565
|
+
if (values.some(holdsNul)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" was given text holding a NUL character, which SQL text cannot hold portably`);
|
|
1566
|
+
if (operator.nulls === "strict" && values.some(isNull)) return null;
|
|
1567
|
+
let answer;
|
|
1568
|
+
try {
|
|
1569
|
+
answer = run(values, { collation: call.collation });
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
if (error instanceof QueryEvaluateError) throw error;
|
|
1572
|
+
throw new QueryEvaluateError(`the operator "${operatorName(operator)}" failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1573
|
+
}
|
|
1574
|
+
const unknownTruth = call._tag === "Test" && answer === null;
|
|
1575
|
+
if (scope.operators.checked && !unknownTruth && !Schema.is(Schema.toEncoded(operator.output))(answer)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" answered ${JSON.stringify(answer)}, which its output schema does not admit`);
|
|
1576
|
+
return answer;
|
|
1577
|
+
};
|
|
1578
|
+
/** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */
|
|
1579
|
+
const truthOf = (call, answer) => {
|
|
1580
|
+
if (answer === null || answer === void 0) return "unknown";
|
|
1581
|
+
if (typeof answer !== "boolean") throw new QueryEvaluateError(`the operator "${operatorName(call.operator)}" answered ${JSON.stringify(answer)}, which is not a truth`);
|
|
1582
|
+
return answer;
|
|
1583
|
+
};
|
|
1584
|
+
const isNull = (value) => value === null || value === void 0;
|
|
1585
|
+
const { foldAscii } = Collation;
|
|
897
1586
|
const NUL = String.fromCharCode(0);
|
|
898
1587
|
/**
|
|
899
1588
|
* Whether `value` is text holding a NUL, which Postgres text cannot hold and
|
|
@@ -903,12 +1592,26 @@ const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
|
|
|
903
1592
|
/** A predicate used as a value is its own truth; anything else is its value. */
|
|
904
1593
|
const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
|
|
905
1594
|
/**
|
|
1595
|
+
* What an operand comes to over no row: a call of literals and inputs, run by
|
|
1596
|
+
* `operators` (the kernel's when not given), a predicate as its truth with
|
|
1597
|
+
* unknown as null. How a conformance check asks an implementation one
|
|
1598
|
+
* question; refuses what `evaluate` refuses (an operator the table lacks,
|
|
1599
|
+
* text holding NUL).
|
|
1600
|
+
*/
|
|
1601
|
+
const valueOfOperand = (node, options = {}) => sideOf(node, {
|
|
1602
|
+
row: {},
|
|
1603
|
+
input: options.input ?? {},
|
|
1604
|
+
next: {},
|
|
1605
|
+
operators: options.operators ?? Operators.kernel
|
|
1606
|
+
});
|
|
1607
|
+
/**
|
|
906
1608
|
* A predicate compared as a value. SQL's unknown is null there too, so an
|
|
907
1609
|
* unknown compared to anything stays unknown rather than becoming false.
|
|
908
1610
|
*/
|
|
909
1611
|
const truthValue = (truth) => truth === "unknown" ? null : truth;
|
|
910
1612
|
const holds = (node, scope) => {
|
|
911
1613
|
switch (node._tag) {
|
|
1614
|
+
case "Test": return truthOf(node, called(node, scope));
|
|
912
1615
|
case "Eq": {
|
|
913
1616
|
const left = sideOf(node.left, scope);
|
|
914
1617
|
const right = sideOf(node.right, scope);
|
|
@@ -969,7 +1672,7 @@ const readsAField = /* @__PURE__ */ new WeakMap();
|
|
|
969
1672
|
* before it builds anything: `isNull($status)` is known before any row is.
|
|
970
1673
|
* Refuses what `evaluate` refuses (text holding a NUL).
|
|
971
1674
|
*/
|
|
972
|
-
const decided = (node, input) => {
|
|
1675
|
+
const decided = (node, input, operators = Operators.kernel) => {
|
|
973
1676
|
let reads = readsAField.get(node);
|
|
974
1677
|
if (reads === void 0) {
|
|
975
1678
|
const read = dependenciesOf(node);
|
|
@@ -979,20 +1682,23 @@ const decided = (node, input) => {
|
|
|
979
1682
|
return reads ? Option.none() : Option.some(holds(node, {
|
|
980
1683
|
row: {},
|
|
981
1684
|
input,
|
|
982
|
-
next: {}
|
|
1685
|
+
next: {},
|
|
1686
|
+
operators
|
|
983
1687
|
}));
|
|
984
1688
|
};
|
|
985
1689
|
/** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
|
|
986
|
-
const truthOver = (node, row, input = {}, next = {}) => holds(node, {
|
|
1690
|
+
const truthOver = (node, row, input = {}, next = {}, operators = Operators.kernel) => holds(node, {
|
|
987
1691
|
row,
|
|
988
1692
|
input,
|
|
989
|
-
next
|
|
1693
|
+
next,
|
|
1694
|
+
operators
|
|
990
1695
|
});
|
|
991
1696
|
/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
|
|
992
|
-
const matches = (body, row, input) => body.where.every((node) => holds(node, {
|
|
1697
|
+
const matches = (body, row, input, operators) => body.where.every((node) => holds(node, {
|
|
993
1698
|
row,
|
|
994
1699
|
input,
|
|
995
|
-
next: {}
|
|
1700
|
+
next: {},
|
|
1701
|
+
operators
|
|
996
1702
|
}) === true);
|
|
997
1703
|
/** The kinds of value this interpreter orders by; every key of one term must share one. */
|
|
998
1704
|
const comparable = /* @__PURE__ */ new Set([
|
|
@@ -1024,58 +1730,72 @@ const compare = (left, right, collation) => {
|
|
|
1024
1730
|
if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
|
|
1025
1731
|
return left - right;
|
|
1026
1732
|
};
|
|
1733
|
+
/** Each term's key for one row: a field's value, or what a call comes to over the row. */
|
|
1734
|
+
const keysOf = (row, terms, scope) => terms.map((term) => valueOf(term.expr, {
|
|
1735
|
+
row,
|
|
1736
|
+
input: scope.input,
|
|
1737
|
+
next: {},
|
|
1738
|
+
operators: scope.operators
|
|
1739
|
+
}));
|
|
1027
1740
|
/**
|
|
1028
1741
|
* Refuses an ordering this interpreter will not answer for, before sorting, so
|
|
1029
1742
|
* the refusal names the first offending row in row order rather than whichever
|
|
1030
1743
|
* pair the engine's sort happened to compare first. Every term is checked over
|
|
1031
|
-
* every row: a key whose kind differs from the first present one's. A
|
|
1032
|
-
* is not refused; the term says where it goes.
|
|
1744
|
+
* every row's keys: a key whose kind differs from the first present one's. A
|
|
1745
|
+
* null key is not refused; the term says where it goes.
|
|
1033
1746
|
*/
|
|
1034
|
-
const checkOrder = (
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
first ??= kind;
|
|
1045
|
-
if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
|
|
1046
|
-
}
|
|
1747
|
+
const checkOrder = (keys, terms, query) => terms.forEach((term, index) => {
|
|
1748
|
+
if (term.expr._tag !== "Field" && term.expr._tag !== "Call") throw new QueryEvaluateError(`query "${query}" orders by something that is neither a field nor a call`);
|
|
1749
|
+
if (Option.exists(term.collation, (declared) => declared._tag === "Locale")) throw new QueryEvaluateError(`query "${query}" orders ${Expr.show(term.expr)} by a backend's locale collation, which only that backend has`);
|
|
1750
|
+
let first;
|
|
1751
|
+
for (const row of keys) {
|
|
1752
|
+
const value = row[index];
|
|
1753
|
+
if (isNull(value)) continue;
|
|
1754
|
+
const kind = typeof value;
|
|
1755
|
+
first ??= kind;
|
|
1756
|
+
if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
|
|
1047
1757
|
}
|
|
1048
|
-
};
|
|
1049
|
-
/** Two rows by checked terms: negative when `left` sorts first. */
|
|
1758
|
+
});
|
|
1759
|
+
/** Two rows' keys by checked terms: negative when `left` sorts first. */
|
|
1050
1760
|
const byTerms = (terms, left, right) => {
|
|
1051
|
-
for (const term of terms) {
|
|
1052
|
-
const
|
|
1053
|
-
const
|
|
1054
|
-
const absentRight = isNull(right[key]);
|
|
1761
|
+
for (const [index, term] of terms.entries()) {
|
|
1762
|
+
const absentLeft = isNull(left[index]);
|
|
1763
|
+
const absentRight = isNull(right[index]);
|
|
1055
1764
|
if (absentLeft || absentRight) {
|
|
1056
1765
|
if (absentLeft && absentRight) continue;
|
|
1057
1766
|
return absentLeft === (term.nulls === "first") ? -1 : 1;
|
|
1058
1767
|
}
|
|
1059
|
-
const sign = compare(left[
|
|
1768
|
+
const sign = compare(left[index], right[index], term.collation);
|
|
1060
1769
|
if (sign !== 0) return term.direction === "asc" ? sign : -sign;
|
|
1061
1770
|
}
|
|
1062
1771
|
return 0;
|
|
1063
1772
|
};
|
|
1064
|
-
const ordered = (rows, terms, query) => {
|
|
1773
|
+
const ordered = (rows, terms, query, scope) => {
|
|
1065
1774
|
if (terms.length === 0 || rows.length < 2) return [...rows];
|
|
1066
|
-
|
|
1067
|
-
|
|
1775
|
+
const keyed = rows.map((row) => ({
|
|
1776
|
+
row,
|
|
1777
|
+
keys: keysOf(row, terms, scope)
|
|
1778
|
+
}));
|
|
1779
|
+
checkOrder(keyed.map(({ keys }) => keys), terms, query);
|
|
1780
|
+
return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row);
|
|
1068
1781
|
};
|
|
1069
1782
|
/**
|
|
1070
1783
|
* Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
|
|
1071
|
-
* as `evaluate` sorts: negative when it comes first.
|
|
1072
|
-
*
|
|
1073
|
-
*
|
|
1784
|
+
* as `evaluate` sorts: negative when it comes first. A call among them runs
|
|
1785
|
+
* over each row with `input` and `operators` (the kernel's when not given).
|
|
1786
|
+
* Refuses what `evaluate` refuses, for these two rows: a term over neither a
|
|
1787
|
+
* field nor a call, a locale collation, keys of different kinds, or an
|
|
1788
|
+
* operator the table lacks. For a client placing one row among others it
|
|
1074
1789
|
* holds.
|
|
1075
1790
|
*/
|
|
1076
|
-
const compareRows = (terms, left, right, query) => {
|
|
1077
|
-
|
|
1078
|
-
|
|
1791
|
+
const compareRows = (terms, left, right, query, options = {}) => {
|
|
1792
|
+
const scope = {
|
|
1793
|
+
input: options.input ?? {},
|
|
1794
|
+
operators: options.operators ?? Operators.kernel
|
|
1795
|
+
};
|
|
1796
|
+
const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
|
|
1797
|
+
checkOrder(keys, terms, query);
|
|
1798
|
+
return byTerms(terms, keys[0], keys[1]);
|
|
1079
1799
|
};
|
|
1080
1800
|
/**
|
|
1081
1801
|
* The operations this interpreter runs. It is the reference, so this is the
|
|
@@ -1099,8 +1819,8 @@ const supported = [
|
|
|
1099
1819
|
* than skipping it and answering a different question. Called by `evaluate`;
|
|
1100
1820
|
* call it directly to check a body once instead of on every run.
|
|
1101
1821
|
*/
|
|
1102
|
-
const assertSupported = (body) => {
|
|
1103
|
-
const missing = Query.unsupported(body, supported);
|
|
1822
|
+
const assertSupported = (body, operators = Operators.kernel) => {
|
|
1823
|
+
const missing = Query.unsupported(body, supported, operators);
|
|
1104
1824
|
if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
|
|
1105
1825
|
};
|
|
1106
1826
|
/**
|
|
@@ -1111,12 +1831,15 @@ const assertSupported = (body) => {
|
|
|
1111
1831
|
* placeholders were built with — the same record the query would be called
|
|
1112
1832
|
* with anywhere else.
|
|
1113
1833
|
*/
|
|
1114
|
-
const evaluate = (body, input, rows) => {
|
|
1115
|
-
|
|
1116
|
-
|
|
1834
|
+
const evaluate = (body, input, rows, options = {}) => {
|
|
1835
|
+
const operators = options.operators ?? Operators.kernel;
|
|
1836
|
+
assertSupported(body, operators);
|
|
1837
|
+
return ordered(rows.filter((row) => matches(body, row, input, operators)), Query.orderFor(body, input), body.entity.name, {
|
|
1838
|
+
input,
|
|
1839
|
+
operators
|
|
1840
|
+
});
|
|
1117
1841
|
};
|
|
1118
|
-
|
|
1119
|
-
//#region src/invariant.ts
|
|
1842
|
+
// src/invariant.ts
|
|
1120
1843
|
/**
|
|
1121
1844
|
* Invariants: what every stored row of an Entity must hold, and what every
|
|
1122
1845
|
* change of one must, declared once on the Entity through its metadata and read
|
|
@@ -1172,23 +1895,30 @@ const invariant = (id, build, options) => Object.assign((entity) => {
|
|
|
1172
1895
|
}, { id });
|
|
1173
1896
|
const invariantsOf = (entity) => Invariants.get(entity.metadata);
|
|
1174
1897
|
/** `judge` with the invariants given, as a binding that keeps them holds them. */
|
|
1175
|
-
const judgeAgainst = (invariants, change) => {
|
|
1898
|
+
const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
|
|
1176
1899
|
const missing = /* @__PURE__ */ new Set();
|
|
1900
|
+
const unrun = /* @__PURE__ */ new Set();
|
|
1177
1901
|
const failures = [];
|
|
1178
1902
|
const { after, before } = change;
|
|
1179
1903
|
for (const held of invariants) {
|
|
1180
1904
|
if (readsBefore(held) && before === void 0) continue;
|
|
1181
1905
|
const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
|
|
1182
1906
|
if (absent.length > 0) absent.forEach((key) => missing.add(key));
|
|
1183
|
-
else
|
|
1907
|
+
else try {
|
|
1908
|
+
if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) failures.push(held);
|
|
1909
|
+
} catch (error) {
|
|
1910
|
+
if (!(error instanceof OperatorMissingError)) throw error;
|
|
1911
|
+
unrun.add(error.named);
|
|
1912
|
+
}
|
|
1184
1913
|
}
|
|
1185
1914
|
if (failures.length > 0) return {
|
|
1186
1915
|
_tag: "Invalid",
|
|
1187
1916
|
failures
|
|
1188
1917
|
};
|
|
1189
|
-
if (missing.size > 0) return {
|
|
1918
|
+
if (missing.size > 0 || unrun.size > 0) return {
|
|
1190
1919
|
_tag: "Undecided",
|
|
1191
|
-
fields: [...missing]
|
|
1920
|
+
fields: [...missing],
|
|
1921
|
+
operators: [...unrun]
|
|
1192
1922
|
};
|
|
1193
1923
|
return { _tag: "Valid" };
|
|
1194
1924
|
};
|
|
@@ -1199,7 +1929,7 @@ const judgeAgainst = (invariants, change) => {
|
|
|
1199
1929
|
* undecided, never valid. Without `before` (a create), transition invariants
|
|
1200
1930
|
* are not judged.
|
|
1201
1931
|
*/
|
|
1202
|
-
const judge = (entity, change) => judgeAgainst(invariantsOf(entity), change);
|
|
1932
|
+
const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
|
|
1203
1933
|
/**
|
|
1204
1934
|
* The row an input's value describes, judged under its Entity's state
|
|
1205
1935
|
* invariants: each key mapped to a field, encoded as the store holds it. An
|
|
@@ -1207,7 +1937,7 @@ const judge = (entity, change) => judgeAgainst(invariantsOf(entity), change);
|
|
|
1207
1937
|
* key left out) is undecided, so a partial input is never called valid on its
|
|
1208
1938
|
* account. It has no row before, so it judges no transition.
|
|
1209
1939
|
*/
|
|
1210
|
-
const judgeInput = (input, value) => {
|
|
1940
|
+
const judgeInput = (input, value, operators = Operators.kernel) => {
|
|
1211
1941
|
const invariants = invariantsOf(input.entity);
|
|
1212
1942
|
if (invariants.length === 0) return { _tag: "Valid" };
|
|
1213
1943
|
const members = input.members;
|
|
@@ -1222,14 +1952,14 @@ const judgeInput = (input, value) => {
|
|
|
1222
1952
|
row[member.key] = encoded;
|
|
1223
1953
|
});
|
|
1224
1954
|
}
|
|
1225
|
-
return judgeAgainst(invariants, { after: row });
|
|
1955
|
+
return judgeAgainst(invariants, { after: row }, operators);
|
|
1226
1956
|
};
|
|
1227
1957
|
/**
|
|
1228
1958
|
* The Entity's state invariants as an Effect Schema check over its row type:
|
|
1229
1959
|
* each failure at its path, with its message. The value is encoded first,
|
|
1230
1960
|
* field by field, so it is judged as the store would hold it.
|
|
1231
1961
|
*/
|
|
1232
|
-
const check = (entity) => Schema.makeFilter((value) => {
|
|
1962
|
+
const check = (entity, options = {}) => Schema.makeFilter((value) => {
|
|
1233
1963
|
const fields = entity.fields;
|
|
1234
1964
|
const decoded = value;
|
|
1235
1965
|
const row = {};
|
|
@@ -1237,17 +1967,21 @@ const check = (entity) => Schema.makeFilter((value) => {
|
|
|
1237
1967
|
if (!Object.hasOwn(decoded, key)) continue;
|
|
1238
1968
|
row[key] = Schema.encodeUnknownSync(field.schema)(decoded[key]);
|
|
1239
1969
|
}
|
|
1240
|
-
const judged = judge(entity, { after: row });
|
|
1970
|
+
const judged = judge(entity, { after: row }, options.operators);
|
|
1241
1971
|
if (judged._tag !== "Invalid") return void 0;
|
|
1242
1972
|
return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
|
|
1243
1973
|
path: [key],
|
|
1244
1974
|
issue: failure.message
|
|
1245
1975
|
})));
|
|
1246
1976
|
});
|
|
1247
|
-
|
|
1248
|
-
//#region src/shape.ts
|
|
1977
|
+
// src/shape.ts
|
|
1249
1978
|
const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
|
|
1250
1979
|
const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
|
|
1980
|
+
/** Whether any of these checks is `Schema.isInt`, alone or inside a group (`isInt32`). */
|
|
1981
|
+
const checksInteger = (checks) => checks.some((check) => Match.value(check).pipe(Match.tagsExhaustive({
|
|
1982
|
+
Filter: (filter) => filter.annotations?.representation?.id === "effect/schema/isInt",
|
|
1983
|
+
FilterGroup: (group) => checksInteger(group.checks)
|
|
1984
|
+
})));
|
|
1251
1985
|
/** What a schema's AST holds, read through Effect's own guards. */
|
|
1252
1986
|
const SchemaShape = {
|
|
1253
1987
|
/** True for the `null` and `undefined` members that make a schema optional. */
|
|
@@ -1258,10 +1992,15 @@ const SchemaShape = {
|
|
|
1258
1992
|
*/
|
|
1259
1993
|
present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
|
|
1260
1994
|
/** True when every value the schema admits is a string. */
|
|
1261
|
-
isText
|
|
1995
|
+
isText,
|
|
1996
|
+
/**
|
|
1997
|
+
* True when the AST is checked to hold integers (`Schema.isInt`, alone or in
|
|
1998
|
+
* a group such as `isInt32`). Read it from a schema's encoded side to ask
|
|
1999
|
+
* what the store holds.
|
|
2000
|
+
*/
|
|
2001
|
+
holdsIntegers: (ast) => checksInteger(ast.checks ?? [])
|
|
1262
2002
|
};
|
|
1263
|
-
|
|
1264
|
-
//#region src/readFilter.ts
|
|
2003
|
+
// src/readFilter.ts
|
|
1265
2004
|
/**
|
|
1266
2005
|
* The members a server filters an Entity's rows by under a rule the client
|
|
1267
2006
|
* does not run, such as an authorization rule. A client that places rows in
|
|
@@ -1280,8 +2019,7 @@ const ReadFilter = {
|
|
|
1280
2019
|
/** The members an Entity's metadata names, every attachment's together. */
|
|
1281
2020
|
members: (metadata) => key.get(metadata)[0] ?? []
|
|
1282
2021
|
};
|
|
1283
|
-
|
|
1284
|
-
//#region src/words.ts
|
|
2022
|
+
// src/words.ts
|
|
1285
2023
|
const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
|
|
1286
2024
|
const Words = {
|
|
1287
2025
|
/**
|
|
@@ -1299,8 +2037,7 @@ of: (schema) => {
|
|
|
1299
2037
|
description: Option.orElse(text(resolved.description), () => text(own["description"]))
|
|
1300
2038
|
};
|
|
1301
2039
|
} };
|
|
1302
|
-
|
|
1303
|
-
//#region src/write.ts
|
|
2040
|
+
// src/write.ts
|
|
1304
2041
|
/**
|
|
1305
2042
|
* A write as a value: what an operation changes, declared over the input it
|
|
1306
2043
|
* takes, so the changes can be known before it runs and its interpreters can
|
|
@@ -1406,9 +2143,12 @@ const declared = (kind, input, options) => {
|
|
|
1406
2143
|
};
|
|
1407
2144
|
/** Whether a value's stored form is a plain number. */
|
|
1408
2145
|
const storedAsNumber = (schema) => SchemaAST.isNumber(Schema.toEncoded(schema).ast);
|
|
2146
|
+
/** Whether a value's stored form is checked to be an integer. */
|
|
2147
|
+
const storedAsInteger = (schema) => SchemaShape.holdsIntegers(Schema.toEncoded(schema).ast);
|
|
1409
2148
|
/**
|
|
1410
2149
|
* One increment, checked: a field of the Entity stored as a number, written
|
|
1411
|
-
* by nothing else, moved by an unmapped input key whose value is a number
|
|
2150
|
+
* by nothing else, moved by an unmapped input key whose value is a number, and
|
|
2151
|
+
* an integer when the field is one.
|
|
1412
2152
|
*/
|
|
1413
2153
|
const incrementOf = (input, fieldKey, key, declared) => {
|
|
1414
2154
|
const fields = input.entity.fields;
|
|
@@ -1423,9 +2163,12 @@ const incrementOf = (input, fieldKey, key, declared) => {
|
|
|
1423
2163
|
if (member._tag !== "Unmapped") return fail$1(input, `"${key}" is an amount, so it must be unmapped, not written as a member`);
|
|
1424
2164
|
const amount = input.schema.fields[key];
|
|
1425
2165
|
if (!storedAsNumber(amount)) return fail$1(input, `"${key}" is an amount, but not a number`);
|
|
2166
|
+
const integer = storedAsInteger(amount);
|
|
2167
|
+
if (storedAsInteger(field.schema) && !integer) return fail$1(input, `"${key}" may not be an integer, but "${fieldKey}" is one; give the amount Schema.Int`);
|
|
1426
2168
|
return Object.freeze({
|
|
1427
2169
|
key,
|
|
1428
|
-
field
|
|
2170
|
+
field,
|
|
2171
|
+
integer
|
|
1429
2172
|
});
|
|
1430
2173
|
};
|
|
1431
2174
|
/** An update or an insert that would write nothing is refused where it is declared. */
|
|
@@ -1537,8 +2280,7 @@ const Write = {
|
|
|
1537
2280
|
};
|
|
1538
2281
|
}
|
|
1539
2282
|
};
|
|
1540
|
-
|
|
1541
|
-
//#region src/index.ts
|
|
2283
|
+
// src/index.ts
|
|
1542
2284
|
/**
|
|
1543
2285
|
* `foldkit-entity` — domain structure as typed values.
|
|
1544
2286
|
*
|
|
@@ -1906,7 +2648,6 @@ const Relation = {
|
|
|
1906
2648
|
})
|
|
1907
2649
|
};
|
|
1908
2650
|
const Derived = { make: (schema) => ({ schema }) };
|
|
1909
|
-
|
|
1910
|
-
export { maxQueryNodes as C, isPredicate as S, truthOver as _, SelectionPageTypeId as a, Query as b, Words as c, QueryEvaluateError as d, assertSupported as f, supported as g, evaluate as h, Relation as i, ReadFilter as l, decided as m, Entity as n, SelectionTypeId as o, compareRows as p, EntityTypeId as r, Write as s, Derived as t, SchemaShape as u, Expr as v, Collation as w, dependenciesOf as x, Order as y };
|
|
2651
|
+
export { Law as A, Expr as C, isPredicate as D, dependenciesOf as E, maxQueryNodes as O, Text as S, Query as T, supported as _, SelectionPageTypeId as a, Evidence as b, Words as c, OperatorMissingError as d, QueryEvaluateError as f, evaluate as g, decided as h, Relation as i, Collation as j, noOperators as k, ReadFilter as l, compareRows as m, Entity as n, SelectionTypeId as o, assertSupported as p, EntityTypeId as r, Write as s, Derived as t, SchemaShape as u, truthOver as v, Order as w, Operators as x, valueOfOperand as y };
|
|
1911
2652
|
|
|
1912
|
-
//# sourceMappingURL=src-
|
|
2653
|
+
//# sourceMappingURL=src-CSxcKUv6.mjs.map
|