foldkit-entity 0.1.0 → 0.3.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 +256 -7
- package/dist/conformance/index.d.mts +46 -0
- package/dist/conformance/index.d.mts.map +1 -0
- package/dist/conformance/index.mjs +293 -0
- package/dist/conformance/index.mjs.map +1 -0
- package/dist/index.d.mts +344 -21
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +469 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,444 @@
|
|
|
1
1
|
import { Pipeable, Schema } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
|
+
//#region src/expr.ts
|
|
4
|
+
/**
|
|
5
|
+
* `Expr` — a query's scalar computations as typed values.
|
|
6
|
+
*
|
|
7
|
+
* An Entity says what a domain has; an `Expr` says something about one row of
|
|
8
|
+
* it. A field reference, an input placeholder, a literal, and comparisons of
|
|
9
|
+
* those are all immutable data: building one performs no work, reads nothing,
|
|
10
|
+
* and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
|
|
11
|
+
* to SQL, an in-memory evaluator to a predicate over rows.
|
|
12
|
+
*
|
|
13
|
+
* This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
|
|
14
|
+
* operation here is one a real query in this repository needs; the set grows
|
|
15
|
+
* from queries, not from what a database could express.
|
|
16
|
+
*/
|
|
17
|
+
const tagOf = (value) => typeof value === "object" && value !== null ? value._tag : void 0;
|
|
18
|
+
/**
|
|
19
|
+
* An Entity's field and a `FieldExpr` are the same three members under the same
|
|
20
|
+
* tag — the Entity's carries `metadata` besides — so this reads either and is
|
|
21
|
+
* idempotent on its own output. Nothing needs to tell them apart, which is
|
|
22
|
+
* better than telling them apart by which extra member happens to be present.
|
|
23
|
+
*/
|
|
24
|
+
const literal = (value) => ({
|
|
25
|
+
_tag: "Literal",
|
|
26
|
+
value
|
|
27
|
+
});
|
|
28
|
+
const fieldExpr = (field) => ({
|
|
29
|
+
_tag: "Field",
|
|
30
|
+
owner: field.owner,
|
|
31
|
+
key: field.key,
|
|
32
|
+
schema: field.schema
|
|
33
|
+
});
|
|
34
|
+
const predicateTags = /* @__PURE__ */ new Set([
|
|
35
|
+
"Eq",
|
|
36
|
+
"Null",
|
|
37
|
+
"Contains"
|
|
38
|
+
]);
|
|
39
|
+
/** Whether a value is a predicate, and so usable where a boolean is wanted. */
|
|
40
|
+
const isPredicate = (value) => predicateTags.has(tagOf(value));
|
|
41
|
+
/**
|
|
42
|
+
* A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
|
|
43
|
+
* itself, and anything else is the constant it is.
|
|
44
|
+
*/
|
|
45
|
+
const toOperand = (value) => {
|
|
46
|
+
const tag = tagOf(value);
|
|
47
|
+
if (tag === "Field") return fieldExpr(value);
|
|
48
|
+
if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
|
|
49
|
+
return literal(value);
|
|
50
|
+
};
|
|
51
|
+
/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
|
|
52
|
+
const toExpr = (value, step) => {
|
|
53
|
+
const operand = toOperand(value);
|
|
54
|
+
if (isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`);
|
|
55
|
+
return operand;
|
|
56
|
+
};
|
|
57
|
+
const Expr = {
|
|
58
|
+
/** A constant. Comparisons coerce a plain value, so this is rarely written. */
|
|
59
|
+
literal,
|
|
60
|
+
/**
|
|
61
|
+
* A value the query is given when it runs. A definition builds these from its
|
|
62
|
+
* `Input` schema; written by hand only when constructing a body directly.
|
|
63
|
+
*/
|
|
64
|
+
input: (key, schema) => ({
|
|
65
|
+
_tag: "Input",
|
|
66
|
+
key,
|
|
67
|
+
schema
|
|
68
|
+
}),
|
|
69
|
+
/** One field of one Entity, as a scalar. */
|
|
70
|
+
field: (field) => fieldExpr(field),
|
|
71
|
+
/**
|
|
72
|
+
* Two scalars are the same value. A field or a plain value on either side is
|
|
73
|
+
* coerced, so the common form reads as it means:
|
|
74
|
+
*
|
|
75
|
+
* ```ts
|
|
76
|
+
* Expr.eq(Post.fields.slug, input.slug)
|
|
77
|
+
* Expr.eq(Post.fields.status, 'active')
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
eq: (left, right) => ({
|
|
81
|
+
_tag: "Eq",
|
|
82
|
+
left: toOperand(left),
|
|
83
|
+
right: toOperand(right)
|
|
84
|
+
}),
|
|
85
|
+
/**
|
|
86
|
+
* Whether a field holds no value. Its opposite is `isNotNull`; both are the
|
|
87
|
+
* one node, because a query asks which of the two it means and nothing here
|
|
88
|
+
* can negate a predicate.
|
|
89
|
+
*/
|
|
90
|
+
isNull: (operand) => ({
|
|
91
|
+
_tag: "Null",
|
|
92
|
+
operand: toExpr(operand, "isNull"),
|
|
93
|
+
present: false
|
|
94
|
+
}),
|
|
95
|
+
/** Whether a field holds a value. */
|
|
96
|
+
isNotNull: (operand) => ({
|
|
97
|
+
_tag: "Null",
|
|
98
|
+
operand: toExpr(operand, "isNotNull"),
|
|
99
|
+
present: true
|
|
100
|
+
}),
|
|
101
|
+
/**
|
|
102
|
+
* Whether a text value contains `search`, anywhere in it. Containing the
|
|
103
|
+
* empty string is everything, so a search box with nothing typed in it is the
|
|
104
|
+
* same query as one with something — no branch, and no second query.
|
|
105
|
+
*
|
|
106
|
+
* **Case-insensitive**, which is what a search means, and which has to be
|
|
107
|
+
* said rather than left to the interpreter: SQLite's `like` ignores case and
|
|
108
|
+
* Postgres's does not, so a body that left it open would mean two things.
|
|
109
|
+
* Folding is ASCII-only, because that is what `lower` does in SQLite without
|
|
110
|
+
* ICU.
|
|
111
|
+
*
|
|
112
|
+
* **Over a column that can be null this is not the same as no filter.** A
|
|
113
|
+
* null contains nothing, not even the empty string, so its rows drop out. A
|
|
114
|
+
* nullable column that should match everything on an empty search says so:
|
|
115
|
+
* `Expr.or` does not exist yet, so for now such a column needs its own
|
|
116
|
+
* predicate or a native escape hatch.
|
|
117
|
+
*/
|
|
118
|
+
contains: (value, search) => ({
|
|
119
|
+
_tag: "Contains",
|
|
120
|
+
value: toExpr(value, "contains"),
|
|
121
|
+
search: toOperand(search)
|
|
122
|
+
}),
|
|
123
|
+
/** An expression as readable text; see `showExpr` for what it is and is not. */
|
|
124
|
+
show: (node) => showExpr(node)
|
|
125
|
+
};
|
|
126
|
+
const Order = {
|
|
127
|
+
asc: (expr) => ({
|
|
128
|
+
direction: "asc",
|
|
129
|
+
expr: toExpr(expr, "asc")
|
|
130
|
+
}),
|
|
131
|
+
desc: (expr) => ({
|
|
132
|
+
direction: "desc",
|
|
133
|
+
expr: toExpr(expr, "desc")
|
|
134
|
+
})
|
|
135
|
+
};
|
|
136
|
+
const walk = (node, fields, inputs, operations) => {
|
|
137
|
+
switch (node._tag) {
|
|
138
|
+
case "Literal": return;
|
|
139
|
+
case "Field":
|
|
140
|
+
fields.set(`${node.owner.name}.${node.key}`, {
|
|
141
|
+
entity: node.owner.name,
|
|
142
|
+
key: node.key
|
|
143
|
+
});
|
|
144
|
+
return;
|
|
145
|
+
case "Input":
|
|
146
|
+
inputs.add(node.key);
|
|
147
|
+
return;
|
|
148
|
+
case "Eq":
|
|
149
|
+
operations.add("eq");
|
|
150
|
+
walk(node.left, fields, inputs, operations);
|
|
151
|
+
walk(node.right, fields, inputs, operations);
|
|
152
|
+
return;
|
|
153
|
+
case "Null":
|
|
154
|
+
operations.add(node.present ? "isNotNull" : "isNull");
|
|
155
|
+
walk(node.operand, fields, inputs, operations);
|
|
156
|
+
return;
|
|
157
|
+
case "Contains":
|
|
158
|
+
operations.add("contains");
|
|
159
|
+
walk(node.value, fields, inputs, operations);
|
|
160
|
+
walk(node.search, fields, inputs, operations);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* What an expression reads and uses, for the planner and for an interpreter
|
|
166
|
+
* deciding whether it can run this query at all. Distinct entries only, in the
|
|
167
|
+
* order first seen, so the answer is stable enough to assert on.
|
|
168
|
+
*/
|
|
169
|
+
const dependenciesOf = (...nodes) => {
|
|
170
|
+
const fields = /* @__PURE__ */ new Map();
|
|
171
|
+
const inputs = /* @__PURE__ */ new Set();
|
|
172
|
+
const operations = /* @__PURE__ */ new Set();
|
|
173
|
+
for (const node of nodes) walk("direction" in node ? node.expr : node, fields, inputs, operations);
|
|
174
|
+
return {
|
|
175
|
+
fields: [...fields.values()],
|
|
176
|
+
inputs: [...inputs],
|
|
177
|
+
operations: [...operations]
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
/** Every field an expression reads, as the nodes themselves. */
|
|
181
|
+
const fieldsIn = function* (node) {
|
|
182
|
+
switch (node._tag) {
|
|
183
|
+
case "Field":
|
|
184
|
+
yield node;
|
|
185
|
+
return;
|
|
186
|
+
case "Literal":
|
|
187
|
+
case "Input": return;
|
|
188
|
+
case "Eq":
|
|
189
|
+
yield* fieldsIn(node.left);
|
|
190
|
+
yield* fieldsIn(node.right);
|
|
191
|
+
return;
|
|
192
|
+
case "Null":
|
|
193
|
+
yield* fieldsIn(node.operand);
|
|
194
|
+
return;
|
|
195
|
+
case "Contains":
|
|
196
|
+
yield* fieldsIn(node.value);
|
|
197
|
+
yield* fieldsIn(node.search);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* A query reads one Entity, so a predicate or ordering term naming a different
|
|
203
|
+
* one cannot be answered — an interpreter would be asked for a column of a
|
|
204
|
+
* table it was never told to read. Compared by identity, not by name, because
|
|
205
|
+
* two Entities defined with the same name are two Entities.
|
|
206
|
+
*/
|
|
207
|
+
const checkOwnership = (step, what, entity, nodes) => {
|
|
208
|
+
for (const node of nodes) for (const field of fieldsIn("direction" in node ? node.expr : node)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
|
|
209
|
+
};
|
|
210
|
+
const QueryProto = {
|
|
211
|
+
_tag: "Query",
|
|
212
|
+
pipe() {
|
|
213
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
|
|
217
|
+
entity,
|
|
218
|
+
where: Object.freeze(where),
|
|
219
|
+
orderBy: Object.freeze(orderBy)
|
|
220
|
+
}));
|
|
221
|
+
const Query = {
|
|
222
|
+
/** Every row of an Entity: the query each transformation narrows. */
|
|
223
|
+
from: (entity) => query(entity, [], []),
|
|
224
|
+
/**
|
|
225
|
+
* Narrows to the rows the predicate holds for. Two `where`s conjoin — the
|
|
226
|
+
* second never replaces the first — so a fragment can be written once and
|
|
227
|
+
* piped into any query over the same Entity:
|
|
228
|
+
*
|
|
229
|
+
* ```ts
|
|
230
|
+
* const published = Query.where(Expr.eq(Post.fields.published, true))
|
|
231
|
+
* Query.from(Post).pipe(published, Query.where(byTitle))
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
where: (...predicates) => (self) => {
|
|
235
|
+
if (predicates.length === 0) return self;
|
|
236
|
+
checkOwnership("where", "a predicate", self.entity, predicates);
|
|
237
|
+
return query(self.entity, [...self.where, ...predicates], self.orderBy);
|
|
238
|
+
},
|
|
239
|
+
/**
|
|
240
|
+
* Reads the rows in this order. Two `orderBy`s append, so an earlier term
|
|
241
|
+
* stays the more significant one and a later call adds a tie-breaker rather
|
|
242
|
+
* than silently winning.
|
|
243
|
+
*/
|
|
244
|
+
orderBy: (...terms) => (self) => {
|
|
245
|
+
if (terms.length === 0) return self;
|
|
246
|
+
checkOwnership("orderBy", "a term", self.entity, terms);
|
|
247
|
+
return query(self.entity, self.where, [...self.orderBy, ...terms]);
|
|
248
|
+
},
|
|
249
|
+
/**
|
|
250
|
+
* What the whole query reads: the fields and inputs of every predicate and
|
|
251
|
+
* every ordering term, and the operations it uses.
|
|
252
|
+
*/
|
|
253
|
+
dependencies: (self) => dependenciesOf(...self.where, ...self.orderBy),
|
|
254
|
+
/**
|
|
255
|
+
* The operations this query needs that `supported` does not list, in the
|
|
256
|
+
* order the query uses them. Empty means an interpreter declaring
|
|
257
|
+
* `supported` can answer it.
|
|
258
|
+
*
|
|
259
|
+
* An interpreter declares what it runs and refuses the rest, rather than
|
|
260
|
+
* ignoring an operation it does not implement — which would answer a
|
|
261
|
+
* different question and say nothing. The refusal is the interpreter's to
|
|
262
|
+
* raise: this only says what is missing, because what to do about it differs
|
|
263
|
+
* between one that compiles at registration and one that runs a body
|
|
264
|
+
* directly.
|
|
265
|
+
*
|
|
266
|
+
* ```ts
|
|
267
|
+
* const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
|
|
268
|
+
* if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
|
|
269
|
+
* ```
|
|
270
|
+
*/
|
|
271
|
+
unsupported: (self, supported) => {
|
|
272
|
+
const runs = new Set(supported);
|
|
273
|
+
return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
|
|
274
|
+
},
|
|
275
|
+
/**
|
|
276
|
+
* The whole query as readable text, one clause per line:
|
|
277
|
+
*
|
|
278
|
+
* ```text
|
|
279
|
+
* FROM Post
|
|
280
|
+
* WHERE Post.slug = $slug
|
|
281
|
+
* AND Post.published = true
|
|
282
|
+
* ORDER BY Post.updatedAt DESC
|
|
283
|
+
* ```
|
|
284
|
+
*
|
|
285
|
+
* For an explanation or a diagnostic, never for an interpreter — see
|
|
286
|
+
* `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
|
|
287
|
+
* than printing an empty one, so what is shown is what was written.
|
|
288
|
+
*/
|
|
289
|
+
show: (self) => [
|
|
290
|
+
`FROM ${self.entity.name}`,
|
|
291
|
+
...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Expr.show(predicate)}`),
|
|
292
|
+
...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`).join(", ")}`]
|
|
293
|
+
].join("\n")
|
|
294
|
+
};
|
|
295
|
+
/**
|
|
296
|
+
* An expression as readable text, in the IR's own terms.
|
|
297
|
+
*
|
|
298
|
+
* This is for a human — an explanation, a diagnostic, a test that wants to
|
|
299
|
+
* assert on a whole predicate at once — and deliberately **not** for an
|
|
300
|
+
* interpreter. It is close enough to SQL to read at a glance and unlike it
|
|
301
|
+
* everywhere that matters: an input is `$slug` rather than a bound parameter,
|
|
302
|
+
* `contains` is named rather than rendered as somebody's `like`, and no
|
|
303
|
+
* dialect's escaping or collation is implied. What actually ran is whatever
|
|
304
|
+
* that backend compiled, which is not this.
|
|
305
|
+
*
|
|
306
|
+
* A predicate standing where a value is wanted is parenthesised, because
|
|
307
|
+
* `x is not null = $archived` reads as three operands and is two. A predicate
|
|
308
|
+
* that *is* the whole expression is not: nothing encloses it.
|
|
309
|
+
*/
|
|
310
|
+
const showExpr = (node) => {
|
|
311
|
+
switch (node._tag) {
|
|
312
|
+
case "Literal": return JSON.stringify(node.value) ?? String(node.value);
|
|
313
|
+
case "Field": return `${node.owner.name}.${node.key}`;
|
|
314
|
+
case "Input": return `$${node.key}`;
|
|
315
|
+
case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
|
|
316
|
+
case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
|
|
317
|
+
case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
|
|
321
|
+
//#endregion
|
|
322
|
+
//#region src/evaluate.ts
|
|
323
|
+
/**
|
|
324
|
+
* The reference interpreter: a query body run over rows already in memory.
|
|
325
|
+
*
|
|
326
|
+
* `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body
|
|
327
|
+
* directly, which is what makes "source-neutral" a fact rather than a claim —
|
|
328
|
+
* the two are checked against each other over a real database, and a body that
|
|
329
|
+
* means one thing here and another there is a bug in one of them.
|
|
330
|
+
*
|
|
331
|
+
* It is also the interpreter to reach for when there is no database: a test
|
|
332
|
+
* that wants rows, a server assembling a page from values it already holds, or
|
|
333
|
+
* a client judging rows it already has.
|
|
334
|
+
*
|
|
335
|
+
* It lives in `foldkit-entity` because it is the **reference semantics** of the
|
|
336
|
+
* IR this package owns — what §6.0.1 means operationally rather than in prose —
|
|
337
|
+
* and a specification's reference implementation belongs with the
|
|
338
|
+
* specification. The rule that keeps it here: **it may depend on the IR and
|
|
339
|
+
* nothing else.** The moment it wants a Remote concept it has moved to the
|
|
340
|
+
* wrong place and should leave.
|
|
341
|
+
*
|
|
342
|
+
* **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,
|
|
343
|
+
* because SQL is what the other interpreter runs. The important case is null:
|
|
344
|
+
* `null = null` is unknown in SQL and a row is not matched by it, where
|
|
345
|
+
* JavaScript would happily call the two equal.
|
|
346
|
+
*/
|
|
347
|
+
var QueryEvaluateError = class extends Error {
|
|
348
|
+
constructor(message) {
|
|
349
|
+
super(`[foldkit-entity] ${message}`);
|
|
350
|
+
this.name = "QueryEvaluateError";
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
const valueOf = (node, row, input) => {
|
|
354
|
+
switch (node._tag) {
|
|
355
|
+
case "Field": return row[node.key];
|
|
356
|
+
case "Literal": return node.value;
|
|
357
|
+
case "Input": return input[node.key];
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
const isNull = (value) => value === null || value === void 0;
|
|
361
|
+
/** A predicate used as a value is its own truth; anything else is its value. */
|
|
362
|
+
const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
|
|
363
|
+
/**
|
|
364
|
+
* A predicate compared as a value. SQL's unknown is null there too, so an
|
|
365
|
+
* unknown compared to anything stays unknown rather than becoming false.
|
|
366
|
+
*/
|
|
367
|
+
const truthValue = (truth) => truth === "unknown" ? null : truth;
|
|
368
|
+
const holds = (node, row, input) => {
|
|
369
|
+
switch (node._tag) {
|
|
370
|
+
case "Eq": {
|
|
371
|
+
const left = sideOf(node.left, row, input);
|
|
372
|
+
const right = sideOf(node.right, row, input);
|
|
373
|
+
if (isNull(left) || isNull(right)) return "unknown";
|
|
374
|
+
return left === right;
|
|
375
|
+
}
|
|
376
|
+
case "Null": return isNull(valueOf(node.operand, row, input)) !== node.present;
|
|
377
|
+
case "Contains": {
|
|
378
|
+
const value = valueOf(node.value, row, input);
|
|
379
|
+
const search = sideOf(node.search, row, input);
|
|
380
|
+
if (isNull(value) || isNull(search)) return "unknown";
|
|
381
|
+
if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
|
|
382
|
+
return value.toLowerCase().includes(search.toLowerCase());
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
|
|
387
|
+
const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
|
|
388
|
+
const compare = (left, right, query) => {
|
|
389
|
+
if (typeof left === "string" && typeof right === "string") return left < right ? -1 : left > right ? 1 : 0;
|
|
390
|
+
if (typeof left === "number" && typeof right === "number") return left - right;
|
|
391
|
+
if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
|
|
392
|
+
throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${typeof left} and ${typeof right})`);
|
|
393
|
+
};
|
|
394
|
+
const ordered = (rows, terms, query) => {
|
|
395
|
+
if (terms.length === 0) return [...rows];
|
|
396
|
+
return [...rows].sort((left, right) => {
|
|
397
|
+
for (const term of terms) {
|
|
398
|
+
if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
|
|
399
|
+
const a = left[term.expr.key];
|
|
400
|
+
const b = right[term.expr.key];
|
|
401
|
+
if (isNull(a) || isNull(b)) throw new QueryEvaluateError(`query "${query}" orders by "${term.expr.key}", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`);
|
|
402
|
+
const sign = compare(a, b, query);
|
|
403
|
+
if (sign !== 0) return term.direction === "asc" ? sign : -sign;
|
|
404
|
+
}
|
|
405
|
+
return 0;
|
|
406
|
+
});
|
|
407
|
+
};
|
|
408
|
+
/**
|
|
409
|
+
* The operations this interpreter runs. It is the reference, so this is the
|
|
410
|
+
* whole kernel — but it is declared rather than assumed, because an
|
|
411
|
+
* interpreter that gains an operator and forgets to say so is exactly what
|
|
412
|
+
* `Query.unsupported` exists to catch.
|
|
413
|
+
*/
|
|
414
|
+
const supported = [
|
|
415
|
+
"eq",
|
|
416
|
+
"isNull",
|
|
417
|
+
"isNotNull",
|
|
418
|
+
"contains"
|
|
419
|
+
];
|
|
420
|
+
/**
|
|
421
|
+
* Refuses a body needing an operation this interpreter does not run, rather
|
|
422
|
+
* than skipping it and answering a different question. Called by `evaluate`;
|
|
423
|
+
* call it directly to check a body once instead of on every run.
|
|
424
|
+
*/
|
|
425
|
+
const assertSupported = (body) => {
|
|
426
|
+
const missing = Query.unsupported(body, supported);
|
|
427
|
+
if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
|
|
428
|
+
};
|
|
429
|
+
/**
|
|
430
|
+
* The rows the body matches, in the order it asks for. Pure: it reads the rows
|
|
431
|
+
* it is given and nothing else.
|
|
432
|
+
*
|
|
433
|
+
* `input` holds the values this run was given, by the keys the body's
|
|
434
|
+
* placeholders were built with — the same record the query would be called
|
|
435
|
+
* with anywhere else.
|
|
436
|
+
*/
|
|
437
|
+
const evaluate = (body, input, rows) => {
|
|
438
|
+
assertSupported(body);
|
|
439
|
+
return ordered(rows.filter((row) => matches(body, row, input)), body.orderBy, body.entity.name);
|
|
440
|
+
};
|
|
441
|
+
//#endregion
|
|
3
442
|
//#region src/index.ts
|
|
4
443
|
/**
|
|
5
444
|
* `foldkit-entity` — domain structure as typed values.
|
|
@@ -13,6 +452,14 @@ import { Metadata } from "foldkit-metadata";
|
|
|
13
452
|
const EntityTypeId = Symbol.for("foldkit-entity/Entity");
|
|
14
453
|
const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
|
|
15
454
|
const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
|
|
455
|
+
const isText = (ast) => ast._tag === "String" || ast._tag === "TemplateLiteral" || ast._tag === "Literal" && typeof ast.literal === "string" || ast._tag === "Union" && (ast.types ?? []).length > 0 && (ast.types ?? []).every(isText);
|
|
456
|
+
/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
|
|
457
|
+
const idSchemaOf = (entity) => {
|
|
458
|
+
const id = entity.fields.id;
|
|
459
|
+
if (id === void 0 || id._tag !== "Field") return Schema.String;
|
|
460
|
+
const type = Schema.toType(id.schema);
|
|
461
|
+
return isText(type.ast) ? type : Schema.String;
|
|
462
|
+
};
|
|
16
463
|
const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
|
|
17
464
|
const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
|
|
18
465
|
const unmapped = Object.freeze({ _tag: "Unmapped" });
|
|
@@ -146,7 +593,7 @@ const Entity = {
|
|
|
146
593
|
let item;
|
|
147
594
|
if (selected === true) item = Schema.Struct({
|
|
148
595
|
entity: Schema.Literal(target.name),
|
|
149
|
-
id:
|
|
596
|
+
id: idSchemaOf(target)
|
|
150
597
|
});
|
|
151
598
|
else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
|
|
152
599
|
else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
|
|
@@ -161,8 +608,8 @@ const Entity = {
|
|
|
161
608
|
},
|
|
162
609
|
/**
|
|
163
610
|
* A `many` relation read a page at a time, in place of its Selection:
|
|
164
|
-
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a
|
|
165
|
-
* of the Selection's values
|
|
611
|
+
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
|
|
612
|
+
* of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
|
|
166
613
|
*/
|
|
167
614
|
page: (selection, window) => {
|
|
168
615
|
const sides = [window.first, window.last].filter((size) => size !== void 0);
|
|
@@ -222,8 +669,18 @@ const Entity = {
|
|
|
222
669
|
* from a naming convention such as `authorId`.
|
|
223
670
|
*/
|
|
224
671
|
input: (entity, schema, ...mapping) => {
|
|
225
|
-
const
|
|
226
|
-
for (const key of Object.keys(
|
|
672
|
+
const written = mapping[0] ?? {};
|
|
673
|
+
for (const key of Object.keys(written)) if (!(key in schema.fields)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
|
|
674
|
+
const named = (key, name) => {
|
|
675
|
+
const member = entity.members[name];
|
|
676
|
+
if (member?._tag === "Field") return member;
|
|
677
|
+
if (member?._tag === "Relation") return Object.freeze({
|
|
678
|
+
_tag: "RelationInput",
|
|
679
|
+
relation: member
|
|
680
|
+
});
|
|
681
|
+
return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
|
|
682
|
+
};
|
|
683
|
+
const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
|
|
227
684
|
const fields = entity.fields;
|
|
228
685
|
const members = mapValues(schema.fields, (_, key) => {
|
|
229
686
|
const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
|
|
@@ -241,6 +698,12 @@ const Entity = {
|
|
|
241
698
|
/** For an input key that is about the operation rather than the Entity. */
|
|
242
699
|
unmapped,
|
|
243
700
|
/**
|
|
701
|
+
* The schemas of some of an Entity's fields, by key, to spread into an input's
|
|
702
|
+
* struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
|
|
703
|
+
* The input then keeps the field's own rules, and its keys map themselves.
|
|
704
|
+
*/
|
|
705
|
+
fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (entity.fields[key] ?? fail(entity, `"${key}" is not a field`)).schema])),
|
|
706
|
+
/**
|
|
244
707
|
* The Selection of every member an input writes, with each relation as refs:
|
|
245
708
|
* what an edit screen loads before it shows the input's current values.
|
|
246
709
|
*/
|
|
@@ -309,6 +772,6 @@ const Relation = {
|
|
|
309
772
|
};
|
|
310
773
|
const Derived = { make: (schema) => ({ schema }) };
|
|
311
774
|
//#endregion
|
|
312
|
-
export { Derived, Entity, EntityTypeId, Relation, SelectionPageTypeId, SelectionTypeId };
|
|
775
|
+
export { Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, Relation, SelectionPageTypeId, SelectionTypeId, assertSupported, dependenciesOf, evaluate, isPredicate, supported };
|
|
313
776
|
|
|
314
777
|
//# sourceMappingURL=index.mjs.map
|