foldkit-entity 0.8.1 → 0.9.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,
@@ -144,8 +241,8 @@ const Expr = {
144
241
  }),
145
242
  /**
146
243
  * 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.
244
+ * one node, since a query asks which of the two it means, and `is not null`
245
+ * has no unknown for a `not` to keep.
149
246
  */
150
247
  isNull: (operand) => node({
151
248
  _tag: "Null",
@@ -172,8 +269,7 @@ const Expr = {
172
269
  * **Over a column that can be null this is not the same as no filter.** A
173
270
  * null contains nothing, not even the empty string, so its rows drop out. A
174
271
  * 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.
272
+ * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
177
273
  */
178
274
  contains: (value, search) => node({
179
275
  _tag: "Contains",
@@ -198,6 +294,73 @@ const Expr = {
198
294
  value: toExpr(value, "in"),
199
295
  among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
200
296
  }),
297
+ /**
298
+ * `left` orders before `right`. Numbers compare as numbers; text compares
299
+ * under a collation, the one given or the field's declared one, which must be
300
+ * `binary` or `asciiFold` (so every backend agrees), and text needs a field on
301
+ * one side. A date compares by its encoded form: as text when it is stored as
302
+ * an ISO string, so its field declares `Collation.binary`. A null on either
303
+ * side is unknown, so the row is matched by neither this nor its `not`.
304
+ *
305
+ * ```ts
306
+ * Expr.lt(fields.cents, 1000)
307
+ * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))
308
+ * ```
309
+ */
310
+ lt: comparison("lt"),
311
+ /** `left` orders before `right`, or with it; see `Expr.lt`. */
312
+ lte: comparison("lte"),
313
+ /** `left` orders after `right`; see `Expr.lt`. */
314
+ gt: comparison("gt"),
315
+ /** `left` orders after `right`, or with it; see `Expr.lt`. */
316
+ gte: comparison("gte"),
317
+ /**
318
+ * Every operand holds, as one predicate to place inside another: `where`'s
319
+ * list is already a conjunction, so this is for `or(and(a, b), c)`.
320
+ * Unknown as SQL's `and` is: false wins over unknown, which wins over true.
321
+ * Needs an operand; a list built at run time is checked non-empty first
322
+ * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.
323
+ */
324
+ and: connective("and", "And"),
325
+ /**
326
+ * At least one operand holds:
327
+ *
328
+ * ```ts
329
+ * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))
330
+ * ```
331
+ *
332
+ * Unknown as SQL's `or` is: true wins over unknown, which wins over false.
333
+ * Needs an operand, since an empty `or` would match no row.
334
+ */
335
+ or: connective("or", "Or"),
336
+ /**
337
+ * The operand does not hold. **A null is matched by neither side**:
338
+ * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since
339
+ * `null = 'draft'` is unknown and so is its `not`, as in SQL. "Everything
340
+ * but drafts" over a nullable column is
341
+ * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.
342
+ */
343
+ not: (operand) => {
344
+ if (!isPredicate(operand)) throw new Error("[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first");
345
+ return node({
346
+ _tag: "Not",
347
+ operand
348
+ });
349
+ },
350
+ /**
351
+ * A filter that applies only when its input is given: `or(isNull($x), …)`,
352
+ * with the predicate built from the input as never null.
353
+ *
354
+ * ```ts
355
+ * // Every product, or those of the chosen status.
356
+ * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))
357
+ * ```
358
+ *
359
+ * An interpreter that runs per request, as the Drizzle compiler does, decides
360
+ * `isNull($x)` before writing SQL, so this compiles to `true`, which filters
361
+ * nothing, or to the predicate alone.
362
+ */
363
+ whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
201
364
  /** An expression as readable text; see `showExpr` for what it is and is not. */
202
365
  show: (node) => showExpr(node)
203
366
  };
@@ -323,6 +486,23 @@ const walk = (expr, found) => {
323
486
  walk(expr.value, found);
324
487
  walk(expr.among, found);
325
488
  return;
489
+ case "And":
490
+ found.operations.add("and");
491
+ for (const operand of expr.operands) walk(operand, found);
492
+ return;
493
+ case "Or":
494
+ found.operations.add("or");
495
+ for (const operand of expr.operands) walk(operand, found);
496
+ return;
497
+ case "Not":
498
+ found.operations.add("not");
499
+ walk(expr.operand, found);
500
+ return;
501
+ case "Compare":
502
+ found.operations.add("compare");
503
+ walk(expr.left, found);
504
+ walk(expr.right, found);
505
+ return;
326
506
  case "Term":
327
507
  walk(expr.expr, found);
328
508
  return;
@@ -377,6 +557,17 @@ const fieldsIn = function* (expr, seen) {
377
557
  yield* fieldsIn(expr.value, seen);
378
558
  yield* fieldsIn(expr.among, seen);
379
559
  return;
560
+ case "And":
561
+ case "Or":
562
+ for (const operand of expr.operands) yield* fieldsIn(operand, seen);
563
+ return;
564
+ case "Not":
565
+ yield* fieldsIn(expr.operand, seen);
566
+ return;
567
+ case "Compare":
568
+ yield* fieldsIn(expr.left, seen);
569
+ yield* fieldsIn(expr.right, seen);
570
+ return;
380
571
  case "Term":
381
572
  yield* fieldsIn(expr.expr, seen);
382
573
  return;
@@ -412,6 +603,10 @@ const childrenOf = (expr) => {
412
603
  case "Null": return [expr.operand];
413
604
  case "Contains": return [expr.value, expr.search];
414
605
  case "In": return [expr.value, expr.among];
606
+ case "And":
607
+ case "Or": return expr.operands;
608
+ case "Not": return [expr.operand];
609
+ case "Compare": return [expr.left, expr.right];
415
610
  }
416
611
  };
417
612
  /** A node's size as a tree, each distinct node sized once. */
@@ -540,7 +735,7 @@ const Query = {
540
735
  */
541
736
  show: (self) => [
542
737
  `FROM ${self.entity.name}`,
543
- ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Expr.show(predicate)}`),
738
+ ...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
739
  ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
545
740
  Term: (term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,
546
741
  Chosen: (chosen) => `$${chosen.sort.key} among (${Object.entries(chosen.choices).map(([name, field]) => `${name}: ${Expr.show(field)}`).join(", ")})`
@@ -571,8 +766,23 @@ const showExpr = (node) => {
571
766
  case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
572
767
  case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
573
768
  case "In": return `${showOperand(node.value)} in ${showOperand(node.among)}`;
769
+ case "And": return node.operands.map(showConnected).join(" and ");
770
+ case "Or": return node.operands.map(showConnected).join(" or ");
771
+ case "Not": return `not (${showExpr(node.operand)})`;
772
+ case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
574
773
  }
575
774
  };
775
+ const symbols = {
776
+ lt: "<",
777
+ lte: "<=",
778
+ gt: ">",
779
+ gte: ">="
780
+ };
781
+ /** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */
782
+ const showConnected = (node) => Match.value(node).pipe(Match.tags({
783
+ And: () => `(${showExpr(node)})`,
784
+ Or: () => `(${showExpr(node)})`
785
+ }), Match.orElse(() => showExpr(node)));
576
786
  const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
577
787
  //#endregion
578
788
  //#region src/readFilter.ts
@@ -700,7 +910,47 @@ const holds = (node, row, input) => {
700
910
  if (among.some((each) => each === value)) return true;
701
911
  return among.some(isNull) ? "unknown" : false;
702
912
  }
913
+ case "And": {
914
+ const truths = node.operands.map((operand) => holds(operand, row, input));
915
+ if (truths.includes(false)) return false;
916
+ return truths.includes("unknown") ? "unknown" : true;
917
+ }
918
+ case "Or": {
919
+ const truths = node.operands.map((operand) => holds(operand, row, input));
920
+ if (truths.includes(true)) return true;
921
+ return truths.includes("unknown") ? "unknown" : false;
922
+ }
923
+ case "Not": {
924
+ const truth = holds(node.operand, row, input);
925
+ return truth === "unknown" ? "unknown" : !truth;
926
+ }
927
+ case "Compare": {
928
+ const left = valueOf(node.left, row, input);
929
+ const right = valueOf(node.right, row, input);
930
+ if (isNull(left) || isNull(right)) return "unknown";
931
+ if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("a comparison was given text holding a NUL character, which SQL text cannot hold portably");
932
+ const kind = typeof left;
933
+ if (kind !== typeof right || kind !== "number" && kind !== "string") throw new QueryEvaluateError("a comparison was given values that do not order together");
934
+ const order = compare(left, right, node.collation);
935
+ 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);
936
+ }
937
+ }
938
+ };
939
+ /** Whether a predicate reads a field, asked once per node: nodes are frozen. */
940
+ const readsAField = /* @__PURE__ */ new WeakMap();
941
+ /**
942
+ * A predicate's truth from the input alone, when it reads no field; none when
943
+ * it reads one. An interpreter that runs per request decides such a predicate
944
+ * before it builds anything: `isNull($status)` is known before any row is.
945
+ * Refuses what `evaluate` refuses (text holding a NUL).
946
+ */
947
+ const decided = (node, input) => {
948
+ let reads = readsAField.get(node);
949
+ if (reads === void 0) {
950
+ reads = dependenciesOf(node).fields.length > 0;
951
+ readsAField.set(node, reads);
703
952
  }
953
+ return reads ? Option.none() : Option.some(holds(node, {}, input));
704
954
  };
705
955
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
706
956
  const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
@@ -798,7 +1048,11 @@ const supported = [
798
1048
  "isNull",
799
1049
  "isNotNull",
800
1050
  "contains",
801
- "in"
1051
+ "in",
1052
+ "and",
1053
+ "or",
1054
+ "not",
1055
+ "compare"
802
1056
  ];
803
1057
  /**
804
1058
  * Refuses a body needing an operation this interpreter does not run, rather
@@ -1334,6 +1588,6 @@ const Relation = {
1334
1588
  };
1335
1589
  const Derived = { make: (schema) => ({ schema }) };
1336
1590
  //#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 };
1591
+ 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
1592
 
1339
- //# sourceMappingURL=src-BAA6oWw-.mjs.map
1593
+ //# sourceMappingURL=src-5avJ3IkP.mjs.map