foldkit-entity 0.8.1 → 0.10.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.
@@ -1,4 +1,4 @@
1
- import { Match, Option, Pipeable, Schema, SchemaAST } from "effect";
1
+ import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
2
  import { Metadata } from "foldkit-metadata";
3
3
  //#region src/shape.ts
4
4
  const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
@@ -94,7 +94,11 @@ const predicateTags = /* @__PURE__ */ new Set([
94
94
  "Eq",
95
95
  "Null",
96
96
  "Contains",
97
- "In"
97
+ "In",
98
+ "And",
99
+ "Or",
100
+ "Not",
101
+ "Compare"
98
102
  ]);
99
103
  /** Whether a value is a predicate, and so usable where a boolean is wanted. */
100
104
  const isPredicate = (value) => predicateTags.has(tagOf(value));
@@ -114,6 +118,99 @@ const toExpr = (value, step) => {
114
118
  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`);
115
119
  return operand;
116
120
  };
121
+ /** How values encoded by `ast` order: as numbers, as text, or not at all. */
122
+ const orderKindOf = (ast) => {
123
+ if (SchemaAST.isNumber(ast)) return "number";
124
+ if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return "text";
125
+ if (SchemaAST.isLiteral(ast)) {
126
+ if (typeof ast.literal === "number") return "number";
127
+ if (typeof ast.literal === "string") return "text";
128
+ return "none";
129
+ }
130
+ if (SchemaAST.isUnion(ast)) {
131
+ const kinds = new Set(ast.types.filter((member) => !SchemaAST.isNull(member)).map(orderKindOf));
132
+ const [only] = kinds;
133
+ return kinds.size === 1 && only !== void 0 ? only : "none";
134
+ }
135
+ return "none";
136
+ };
137
+ /** How a literal orders; a null orders as anything, since comparing it is unknown. */
138
+ const literalKind = (value) => {
139
+ if (value === null) return "null";
140
+ if (typeof value === "number") return "number";
141
+ if (typeof value === "string") return "text";
142
+ return "none";
143
+ };
144
+ /** How a side orders, read from its encoded form. */
145
+ const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
146
+ Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
147
+ Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
148
+ Literal: ({ value }) => literalKind(value)
149
+ }));
150
+ /**
151
+ * How a comparison's text compares: the collation given, else the field's
152
+ * declared one. Text orders differently by backend (SQLite's `BINARY`, the
153
+ * Postgres database's locale, JavaScript's UTF-16 units), so it is compared
154
+ * only under `binary` or `asciiFold`, which every interpreter here agrees on,
155
+ * and only against a field, whose collation it is. Values that order
156
+ * intrinsically, numbers, need none.
157
+ */
158
+ const collationFor = (step, left, right, given) => {
159
+ const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
160
+ 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`);
161
+ if (!kinds.has("text")) return Option.none();
162
+ const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [field]), Match.orElse(() => [])));
163
+ const [first] = fields;
164
+ if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, whose collation would say how it orders`);
165
+ const named = fields.map((field) => `${field.owner.name}.${field.key}`).join(" and ");
166
+ const collations = Option.match(given, {
167
+ onSome: (collation) => [collation],
168
+ onNone: () => fields.map((field) => Option.getOrElse(field.collation, () => {
169
+ throw new Error(`[foldkit-entity] Expr.${step}: ${field.owner.name}.${field.key} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`);
170
+ }))
171
+ });
172
+ const [collation] = collations;
173
+ if (collation === void 0 || collations.some((each) => each._tag !== collation._tag)) throw new Error(`[foldkit-entity] Expr.${step}: ${named} declare different collations; pass one to compare them by`);
174
+ return Match.value(collation).pipe(Match.tagsExhaustive({
175
+ Binary: () => Option.some(collation),
176
+ AsciiFold: () => Option.some(collation),
177
+ Locale: ({ locale }) => {
178
+ throw new Error(`[foldkit-entity] Expr.${step}: ${named} compares by the backend's "${locale}" collation, which only that backend has`);
179
+ }
180
+ }));
181
+ };
182
+ /** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */
183
+ const comparison = (operator) => (left, right, options = {}) => {
184
+ const leftSide = toExpr(left, operator);
185
+ const rightSide = toExpr(right, operator);
186
+ return node({
187
+ _tag: "Compare",
188
+ operator,
189
+ left: leftSide,
190
+ right: rightSide,
191
+ collation: collationFor(operator, leftSide, rightSide, Option.fromUndefinedOr(options.collation))
192
+ });
193
+ };
194
+ /** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */
195
+ const connected = (step, kind, given) => {
196
+ const operands = given.flatMap((operand) => {
197
+ if (!isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: every operand is a predicate; compare a value with Expr.eq first`);
198
+ return Match.value(operand).pipe(Match.tags({
199
+ And: (and) => kind === "And" ? and.operands : [and],
200
+ Or: (or) => kind === "Or" ? or.operands : [or]
201
+ }), Match.orElse(() => [operand]));
202
+ });
203
+ if (operands.length > 1e3) throw new Error(`[foldkit-entity] Expr.${step}: more than ${maxQueryNodes} operands, the most a query's predicates may hold`);
204
+ if (!Array$1.isReadonlyArrayNonEmpty(operands)) throw new Error(`[foldkit-entity] Expr.${step}: no operands, which would match ${step === "and" ? "every row" : "no row"}; check a list is non-empty before spreading it`);
205
+ return operands;
206
+ };
207
+ const connective = (step, kind) => (...given) => {
208
+ const operands = connected(step, kind, given);
209
+ return operands.length === 1 ? operands[0] : node({
210
+ _tag: kind,
211
+ operands
212
+ });
213
+ };
117
214
  const Expr = {
118
215
  /** A constant. Comparisons coerce a plain value, so this is rarely written. */
119
216
  literal,
@@ -129,7 +226,8 @@ const Expr = {
129
226
  /** One field of one Entity, as a scalar. */
130
227
  field: (field) => fieldExpr(field),
131
228
  /**
132
- * Two scalars are the same value. A field or a plain value on either side is
229
+ * Two scalars are the same value: a field (or an expression) on the left,
230
+ * and the value on the right, typed from it. Fields and plain values are
133
231
  * coerced, so the common form reads as it means:
134
232
  *
135
233
  * ```ts
@@ -144,8 +242,8 @@ const Expr = {
144
242
  }),
145
243
  /**
146
244
  * Whether a field holds no value. Its opposite is `isNotNull`; both are the
147
- * one node, because a query asks which of the two it means and nothing here
148
- * can negate a predicate.
245
+ * one node, since a query asks which of the two it means, and `is not null`
246
+ * has no unknown for a `not` to keep.
149
247
  */
150
248
  isNull: (operand) => node({
151
249
  _tag: "Null",
@@ -172,8 +270,7 @@ const Expr = {
172
270
  * **Over a column that can be null this is not the same as no filter.** A
173
271
  * null contains nothing, not even the empty string, so its rows drop out. A
174
272
  * nullable column that should match everything on an empty search says so:
175
- * `Expr.or` does not exist yet, so for now such a column needs its own
176
- * predicate or a native escape hatch.
273
+ * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
177
274
  */
178
275
  contains: (value, search) => node({
179
276
  _tag: "Contains",
@@ -198,6 +295,73 @@ const Expr = {
198
295
  value: toExpr(value, "in"),
199
296
  among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
200
297
  }),
298
+ /**
299
+ * `left` orders before `right`. Numbers compare as numbers; text compares
300
+ * under a collation, the one given or the field's declared one, which must be
301
+ * `binary` or `asciiFold` (so every backend agrees), and text needs a field on
302
+ * one side. A date compares by its encoded form: as text when it is stored as
303
+ * an ISO string, so its field declares `Collation.binary`. A null on either
304
+ * side is unknown, so the row is matched by neither this nor its `not`.
305
+ *
306
+ * ```ts
307
+ * Expr.lt(fields.cents, 1000)
308
+ * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))
309
+ * ```
310
+ */
311
+ lt: comparison("lt"),
312
+ /** `left` orders before `right`, or with it; see `Expr.lt`. */
313
+ lte: comparison("lte"),
314
+ /** `left` orders after `right`; see `Expr.lt`. */
315
+ gt: comparison("gt"),
316
+ /** `left` orders after `right`, or with it; see `Expr.lt`. */
317
+ gte: comparison("gte"),
318
+ /**
319
+ * Every operand holds, as one predicate to place inside another: `where`'s
320
+ * list is already a conjunction, so this is for `or(and(a, b), c)`.
321
+ * Unknown as SQL's `and` is: false wins over unknown, which wins over true.
322
+ * Needs an operand; a list built at run time is checked non-empty first
323
+ * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.
324
+ */
325
+ and: connective("and", "And"),
326
+ /**
327
+ * At least one operand holds:
328
+ *
329
+ * ```ts
330
+ * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))
331
+ * ```
332
+ *
333
+ * Unknown as SQL's `or` is: true wins over unknown, which wins over false.
334
+ * Needs an operand, since an empty `or` would match no row.
335
+ */
336
+ or: connective("or", "Or"),
337
+ /**
338
+ * The operand does not hold. **A null is matched by neither side**:
339
+ * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since
340
+ * `null = 'draft'` is unknown and so is its `not`, as in SQL. "Everything
341
+ * but drafts" over a nullable column is
342
+ * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.
343
+ */
344
+ not: (operand) => {
345
+ if (!isPredicate(operand)) throw new Error("[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first");
346
+ return node({
347
+ _tag: "Not",
348
+ operand
349
+ });
350
+ },
351
+ /**
352
+ * A filter that applies only when its input is given: `or(isNull($x), …)`,
353
+ * with the predicate built from the input as never null.
354
+ *
355
+ * ```ts
356
+ * // Every product, or those of the chosen status.
357
+ * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))
358
+ * ```
359
+ *
360
+ * An interpreter that runs per request, as the Drizzle compiler does, decides
361
+ * `isNull($x)` before writing SQL, so this compiles to `true`, which filters
362
+ * nothing, or to the predicate alone.
363
+ */
364
+ whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
201
365
  /** An expression as readable text; see `showExpr` for what it is and is not. */
202
366
  show: (node) => showExpr(node)
203
367
  };
@@ -323,6 +487,23 @@ const walk = (expr, found) => {
323
487
  walk(expr.value, found);
324
488
  walk(expr.among, found);
325
489
  return;
490
+ case "And":
491
+ found.operations.add("and");
492
+ for (const operand of expr.operands) walk(operand, found);
493
+ return;
494
+ case "Or":
495
+ found.operations.add("or");
496
+ for (const operand of expr.operands) walk(operand, found);
497
+ return;
498
+ case "Not":
499
+ found.operations.add("not");
500
+ walk(expr.operand, found);
501
+ return;
502
+ case "Compare":
503
+ found.operations.add("compare");
504
+ walk(expr.left, found);
505
+ walk(expr.right, found);
506
+ return;
326
507
  case "Term":
327
508
  walk(expr.expr, found);
328
509
  return;
@@ -377,6 +558,17 @@ const fieldsIn = function* (expr, seen) {
377
558
  yield* fieldsIn(expr.value, seen);
378
559
  yield* fieldsIn(expr.among, seen);
379
560
  return;
561
+ case "And":
562
+ case "Or":
563
+ for (const operand of expr.operands) yield* fieldsIn(operand, seen);
564
+ return;
565
+ case "Not":
566
+ yield* fieldsIn(expr.operand, seen);
567
+ return;
568
+ case "Compare":
569
+ yield* fieldsIn(expr.left, seen);
570
+ yield* fieldsIn(expr.right, seen);
571
+ return;
380
572
  case "Term":
381
573
  yield* fieldsIn(expr.expr, seen);
382
574
  return;
@@ -412,6 +604,10 @@ const childrenOf = (expr) => {
412
604
  case "Null": return [expr.operand];
413
605
  case "Contains": return [expr.value, expr.search];
414
606
  case "In": return [expr.value, expr.among];
607
+ case "And":
608
+ case "Or": return expr.operands;
609
+ case "Not": return [expr.operand];
610
+ case "Compare": return [expr.left, expr.right];
415
611
  }
416
612
  };
417
613
  /** A node's size as a tree, each distinct node sized once. */
@@ -540,7 +736,7 @@ const Query = {
540
736
  */
541
737
  show: (self) => [
542
738
  `FROM ${self.entity.name}`,
543
- ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Expr.show(predicate)}`),
739
+ ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Match.value(predicate).pipe(Match.tag("Or", (or) => self.where.length > 1 ? `(${Expr.show(or)})` : Expr.show(or)), Match.orElse((each) => Expr.show(each)))}`),
544
740
  ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
545
741
  Term: (term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,
546
742
  Chosen: (chosen) => `$${chosen.sort.key} among (${Object.entries(chosen.choices).map(([name, field]) => `${name}: ${Expr.show(field)}`).join(", ")})`
@@ -571,8 +767,23 @@ const showExpr = (node) => {
571
767
  case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
572
768
  case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
573
769
  case "In": return `${showOperand(node.value)} in ${showOperand(node.among)}`;
770
+ case "And": return node.operands.map(showConnected).join(" and ");
771
+ case "Or": return node.operands.map(showConnected).join(" or ");
772
+ case "Not": return `not (${showExpr(node.operand)})`;
773
+ case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
574
774
  }
575
775
  };
776
+ const symbols = {
777
+ lt: "<",
778
+ lte: "<=",
779
+ gt: ">",
780
+ gte: ">="
781
+ };
782
+ /** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */
783
+ const showConnected = (node) => Match.value(node).pipe(Match.tags({
784
+ And: () => `(${showExpr(node)})`,
785
+ Or: () => `(${showExpr(node)})`
786
+ }), Match.orElse(() => showExpr(node)));
576
787
  const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
577
788
  //#endregion
578
789
  //#region src/readFilter.ts
@@ -700,7 +911,47 @@ const holds = (node, row, input) => {
700
911
  if (among.some((each) => each === value)) return true;
701
912
  return among.some(isNull) ? "unknown" : false;
702
913
  }
914
+ case "And": {
915
+ const truths = node.operands.map((operand) => holds(operand, row, input));
916
+ if (truths.includes(false)) return false;
917
+ return truths.includes("unknown") ? "unknown" : true;
918
+ }
919
+ case "Or": {
920
+ const truths = node.operands.map((operand) => holds(operand, row, input));
921
+ if (truths.includes(true)) return true;
922
+ return truths.includes("unknown") ? "unknown" : false;
923
+ }
924
+ case "Not": {
925
+ const truth = holds(node.operand, row, input);
926
+ return truth === "unknown" ? "unknown" : !truth;
927
+ }
928
+ case "Compare": {
929
+ const left = valueOf(node.left, row, input);
930
+ const right = valueOf(node.right, row, input);
931
+ if (isNull(left) || isNull(right)) return "unknown";
932
+ if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("a comparison was given text holding a NUL character, which SQL text cannot hold portably");
933
+ const kind = typeof left;
934
+ if (kind !== typeof right || kind !== "number" && kind !== "string") throw new QueryEvaluateError("a comparison was given values that do not order together");
935
+ const order = compare(left, right, node.collation);
936
+ return Match.value(node.operator).pipe(Match.when("lt", () => order < 0), Match.when("lte", () => order <= 0), Match.when("gt", () => order > 0), Match.when("gte", () => order >= 0), Match.exhaustive);
937
+ }
938
+ }
939
+ };
940
+ /** Whether a predicate reads a field, asked once per node: nodes are frozen. */
941
+ const readsAField = /* @__PURE__ */ new WeakMap();
942
+ /**
943
+ * A predicate's truth from the input alone, when it reads no field; none when
944
+ * it reads one. An interpreter that runs per request decides such a predicate
945
+ * before it builds anything: `isNull($status)` is known before any row is.
946
+ * Refuses what `evaluate` refuses (text holding a NUL).
947
+ */
948
+ const decided = (node, input) => {
949
+ let reads = readsAField.get(node);
950
+ if (reads === void 0) {
951
+ reads = dependenciesOf(node).fields.length > 0;
952
+ readsAField.set(node, reads);
703
953
  }
954
+ return reads ? Option.none() : Option.some(holds(node, {}, input));
704
955
  };
705
956
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
706
957
  const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
@@ -798,7 +1049,11 @@ const supported = [
798
1049
  "isNull",
799
1050
  "isNotNull",
800
1051
  "contains",
801
- "in"
1052
+ "in",
1053
+ "and",
1054
+ "or",
1055
+ "not",
1056
+ "compare"
802
1057
  ];
803
1058
  /**
804
1059
  * Refuses a body needing an operation this interpreter does not run, rather
@@ -1334,6 +1589,6 @@ const Relation = {
1334
1589
  };
1335
1590
  const Derived = { make: (schema) => ({ schema }) };
1336
1591
  //#endregion
1337
- export { SchemaShape as S, Query as _, SelectionPageTypeId as a, maxQueryNodes as b, QueryEvaluateError as c, evaluate as d, supported as f, Order as g, Expr as h, Relation as i, assertSupported as l, ReadFilter as m, Entity as n, SelectionTypeId as o, Words as p, EntityTypeId as r, Write as s, Derived as t, compareRows as u, dependenciesOf as v, Collation as x, isPredicate as y };
1592
+ export { SchemaShape as C, Collation as S, Order as _, SelectionPageTypeId as a, isPredicate as b, QueryEvaluateError as c, decided as d, evaluate as f, Expr as g, ReadFilter as h, Relation as i, assertSupported as l, Words as m, Entity as n, SelectionTypeId as o, supported as p, EntityTypeId as r, Write as s, Derived as t, compareRows as u, Query as v, maxQueryNodes as x, dependenciesOf as y };
1338
1593
 
1339
- //# sourceMappingURL=src-BAA6oWw-.mjs.map
1594
+ //# sourceMappingURL=src-Iz7806gm.mjs.map