@inixiative/json-rules 3.22.0 → 3.23.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 CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  A serializable rules engine for TypeScript. You write a rule once, as JSON, and the same rule AST runs in three places:
6
6
 
7
- - `check()` evaluates it against in-memory data and returns `true` or the rule's own error message.
7
+ - `check()` evaluates it against in-memory data and returns `true` or a failure message: the rule's `error` when it sets one, otherwise a generated one (`age must be greater than or equal to 18`).
8
8
  - `toPrisma()` compiles it into a Prisma query plan.
9
9
  - `toSql()` compiles it into a PostgreSQL `WHERE` clause. `toWhereSql()` and `toLensWhereSql()` write inline predicates for PostgreSQL or MySQL.
10
10
 
@@ -96,7 +96,7 @@ Used in `aggregate.mode`:
96
96
  - `sum`
97
97
  - `avg`
98
98
 
99
- Supported comparison operators for aggregate rules: `equals`, `notEquals`, `lessThan`, `lessThanEquals`, `greaterThan`, `greaterThanEquals`, `between`, `notBetween`.
99
+ Supported comparison operators for aggregate rules: `equals`, `notEquals`, `lessThan`, `lessThanEquals`, `greaterThan`, `greaterThanEquals`, `between`, `notBetween`, `exists`, `notExists`.
100
100
 
101
101
  ### Date Operators
102
102
 
@@ -210,12 +210,13 @@ Computes `sum` or `avg` of an array and compares the result to a value.
210
210
  Empty-array semantics: `sum([]) = 0`, and `avg([])` is NULL, as SQL's `AVG` is: nothing has no
211
211
  average. An average over no values is compared as a NULL column is — a positive operator
212
212
  (`lessThan`, `equals`, `between`, …) doesn't hold, a negated one (`notEquals`, `notBetween`) does —
213
- and `negate()` adds the "no values" arm, the aggregate's own `notExists`, as it adds `notExists`
213
+ and the compilers' internal complement adds the "no values" arm, the aggregate's own `notExists`, as it adds `notExists`
214
214
  to a field's. Ask for it directly with `operator: 'exists'` / `'notExists'` (or, as on a field,
215
215
  `equals` / `notEquals` `null`); a sum always exists. An aggregate rule's `coerceType` (a numeric
216
216
  kind) parses each item before it is added (`'3'` → 3), as `coerceType` does on a field; without
217
217
  it the items must be numbers. To count no values as
218
- low, say so: `any: [count == 0, avg < 3]`. A NULL or absent array is empty, and NULL items are
218
+ low, say so: `any: [{ field, arrayOperator: 'empty' }, { field, aggregate: { mode: 'avg' }, operator: 'lessThan', value: 3 }]`
219
+ (or `operator: 'notExists'` on the aggregate for the first arm). A NULL or absent array is empty, and NULL items are
219
220
  skipped, as SQL's `SUM` / `AVG` skip them.
220
221
 
221
222
  ### Value Expressions
@@ -278,6 +279,7 @@ evaluateValue(asksLast90Days, advocate, { now }); // 2
278
279
  const lastAskAt = {
279
280
  field: 'brandReferenceRequestFanUsers',
280
281
  aggregate: { mode: 'max', field: 'activatedAt' },
282
+ coerceType: 'DateTime', // ISO strings: without it `max` throws on non-numbers
281
283
  filter: { field: 'activatedAt', operator: Operator.exists },
282
284
  };
283
285
 
@@ -374,11 +376,13 @@ toSql(rule, { now });
374
376
  | Option | Default | Governs |
375
377
  | --- | --- | --- |
376
378
  | `now` | none (required when a relative/period expression is present) | the anchor instant |
377
- | `timeZone` | `'UTC'` | how `now` and period boundaries localize: a zone name, or a `{ bind }` read from the bindings |
379
+ | `timeZone` | `'UTC'` | how `now` and period boundaries localize: a zone name; `check()` and `evaluateValue` also take a `{ bind }` read from the bindings (the compilers need a zone name: bind first) |
378
380
  | `weekStart` | `'monday'` (ISO / isoWeek) | start of `week` for `this`/`last`/`next` |
379
381
 
380
- Compilers resolve expressions to concrete `Date` bounds at compile time, so
381
- `check()`, `toPrisma()`, and `toSql()` all compare the same instant.
382
+ Compilers resolve literal and bound expressions at compile time (a `Date` in the Prisma
383
+ plan, an ISO-string parameter in `toSql()`), so `check()`, `toPrisma()`, and `toSql()` all
384
+ compare the same instant. An amount read from the row (`{ days: { path } }`) compiles in
385
+ `toSql()` to interval arithmetic on the column.
382
386
 
383
387
  ### Windowing: first/last with `orderBy` / `take` / `skip`
384
388
 
@@ -399,7 +403,7 @@ predicate. Pipeline: filter → order → skip → take. Direction comes from `o
399
403
  ```
400
404
 
401
405
  `filter` is a condition each element must pass to enter the window (`narrowRule` puts a lens
402
- clamp there under `all`). `orderBy` is a non-empty array of `{ field, dir: 'asc' | 'desc' }` (multi-key);
406
+ clamp there under `all`). `orderBy` is an array of `{ field, dir: 'asc' | 'desc' }` (multi-key; an empty one orders nothing);
403
407
  `take`/`skip` are non-negative integers. **Empty-window semantics are author-driven**:
404
408
  `all` is vacuously true on an empty window, `atLeast: 1` (or `any`) is false. To require
405
409
  "the windowed element matches **and** one exists," combine `all` with `notEmpty` / `atLeast: 1`.
@@ -412,7 +416,7 @@ clamp there under `all`). `orderBy` is a non-empty array of `{ field, dir: 'asc'
412
416
  > { some: {} } }, { fanMissions: { none: { completedAt: { gte: <now-30d> } } } }] }] }`. A `filter`
413
417
  > alone (no `orderBy` / `take` / `skip`) folds into the rule: `all` through the exact complement
414
418
  > of its condition, the rest as `filter AND condition`. Any other windowed rule (`take > 1`,
415
- > `skip`, multi-key `orderBy`, a different/non-monotonic condition, a misaligned direction, or a
419
+ > a non-zero `skip`, multi-key `orderBy`, a different/non-monotonic condition, a misaligned direction, or a
416
420
  > `filter` beside an ordered window) throws a clear "unsupported" error. `toSql()` does not
417
421
  > compile windowing at all (no relation subqueries in a `WHERE` fragment). Evaluate the
418
422
  > unsupported cases in memory with `check()`.
@@ -716,9 +720,12 @@ optional peer dependency), so there is nothing to configure; set `prismaOptions.
716
720
  use a different client's. Without `@prisma/client`, a Json null check throws.
717
721
 
718
722
  Prisma filters follow the column kind the map
719
- declares: on Json, `contains` / `startsWith` / `endsWith` become `string_contains` / … and `in`
720
- becomes one `equals` per value; on a scalar list, `contains` becomes `has` and emptiness
721
- `isEmpty`; `caseInsensitive` adds `mode: 'insensitive'` on text only.
723
+ declares: on Json, `contains` becomes an OR of `string_contains` and `array_contains`,
724
+ `startsWith` / `endsWith` become `string_starts_with` / `string_ends_with`, and `in`
725
+ becomes one `equals` per value (`notContains`, `notStartsWith`, `notEndsWith` and a case-insensitive `contains` throw on Json; `notEquals` and `notIn` compile, keeping the null rows); on a scalar list, `contains` becomes `has` and emptiness
726
+ `isEmpty`; `caseInsensitive` adds `mode: 'insensitive'` when a string meets a text, Json or
727
+ undeclared field, on a provider that takes it (PostgreSQL, CockroachDB, MongoDB; MySQL and
728
+ SQLite are case-insensitive by collation).
722
729
 
723
730
  ### A value the row doesn't carry
724
731
 
@@ -748,7 +755,7 @@ null`.
748
755
  | `clock.finestUnit` | `'second'` | The finest unit a date rule may name: one of `CLOCK_UNITS`, or its plural (`'hours'` reads as `'hour'`); anything else throws when a date rule is evaluated. Every unit a date rule names counts, in its value (a relative date, either end of a range) and in its offset, whatever it compares against: a relative date, an absolute one or another column. A finer one fails: `check`, `toPrisma` and `toSql` throw and `validateRule` reports `clock_unit_below_floor`. The rule decides as written, so an amount read from the row or a binding (`{ minutes: { path } }`, a null one too) fails the same, and a bound whole expression is held to it once bound. Under `'hour'`, `{ ago: { minutes: 30 } }`, `{ this: 'minute' }`, and any compare offset by `{ ago: { minutes: 5 } }` fail. A caller whose finest tick is an hour sets it once at boot. |
749
756
 
750
757
  ```ts
751
- import { engineGlobals } from '@inixiative/json-rules';
758
+ import { check, engineGlobals, SqlDialect } from '@inixiative/json-rules';
752
759
 
753
760
  engineGlobals.set('string.caseInsensitive', true);
754
761
  engineGlobals.get('string.caseInsensitive'); // true
@@ -836,7 +843,9 @@ toSql(rule, { map: lens, mapName: 'prisma', model: 'Post' });
836
843
  Two small helpers write a condition, or a lens's row filters, as a SQL predicate for a caller
837
844
  that names its own columns and writes its own joins (an Omni topic, for one). They write the
838
845
  engine's `sql.dialect` (`SqlDialect.postgres` by default, `SqlDialect.mysql` the other) and
839
- are not a second `toSql`: `toSql` and `toPrisma` are unchanged.
846
+ are not a second `toSql`.
847
+
848
+ ### `toWhereSql`: a condition as a predicate
840
849
 
841
850
  ```ts
842
851
  import { ArrayOperator, engineGlobals, Operator, SqlDialect, toLensWhereSql, toWhereSql } from '@inixiative/json-rules';
@@ -891,8 +900,8 @@ toLensWhereSql(lens, { columns, tables });
891
900
  relation of the related rows nests (`tables['<relation>.<relation>']`). A relation behind
892
901
  another one (`profile.affiliations`), a relation missing from `tables`, `atLeast` / `atMost` /
893
902
  `exactly`, a window (`filter` / `orderBy` / `take` / `skip`) and a fieldless array rule throw.
894
- - **Map:** `map` / `mapName` / `model` are required. A value is checked against its column's
895
- kind (`leafFitViolations`, as `validateNarrowing` checks it) and an undeclared path is refused, because
903
+ - **Map:** `map` and `model` are required, and `mapName` too when `map` is a `FieldMapSet`. A value is checked against its column's
904
+ kind (as `validateNarrowing` checks it) and an undeclared path is refused, because
896
905
  MySQL casts a mistyped literal instead of erroring, so `score = TRUE` would match 1 where
897
906
  `check()` matches nothing. The map also finds a to-one relation's key for its `exists`
898
907
  (`columns['<relation>.<key>']`: the related row's key, NULL when there is none), and says which
@@ -910,6 +919,8 @@ toLensWhereSql(lens, { columns, tables });
910
919
  exactly, so a `_ci` column (MySQL's default) also matches `'Advocate'` for `'advocate'`; compare a
911
920
  binary-collated column where that matters.
912
921
 
922
+ ### `toLensWhereSql`: a lens's row filters
923
+
913
924
  `toLensWhereSql(lens, { columns, tables?, toMany? })` mirrors the lens: the root path's `where`s under `root` (null
914
925
  when it has none), each relation path's own under `relations`, keyed by the path, and each model
915
926
  default's (`mapDefaults[map].models[model].where`) under `mapDefaults`, keyed the same way: one
@@ -936,7 +947,9 @@ the lens hides throws, and its condition's fields are checked from the relation,
936
947
  model it sits on. A model default compiles to one predicate for every path that reaches its
937
948
  model, so it throws when a to-many relation it reads carries different clamps on two of them.
938
949
 
939
- **Join mode: `toMany: 'join'`.** For a caller that can't run a correlated subquery (an Omni
950
+ ### Join mode: `toMany: 'join'`
951
+
952
+ For a caller that can't run a correlated subquery (an Omni
940
953
  topic rebuilds one as its own query and loses the correlation), the root's `where` reads a to-many
941
954
  relation on the row the caller's join brings instead. Nothing about the join is a new option: the
942
955
  caller LEFT JOINs each to-many relation the root's `where` reads (a relation the lens declares),
@@ -1041,7 +1054,7 @@ and `in [null, …]` carry the same hop arms: a user with no profile has a NULL
1041
1054
  an `equals: null` on a NOT NULL column is a Prisma validation error. Nullability
1042
1055
  comes from the field map: `FieldMapEntry.isRequired: false` (prisma-map emits it).
1043
1056
  Without `{ map, model }`, or on an entry that doesn't declare it, the bare
1044
- `not` / `notIn` is emitted and NULL rows fall out, as they always did.
1057
+ `not` / `notIn` is emitted and NULL rows fall out.
1045
1058
 
1046
1059
  Date rules follow the same split. The positive operators answer non-match on both
1047
1060
  rails: a bare boundary is not something a NULL column satisfies, so `check()`
@@ -1058,17 +1071,18 @@ positive operator, ask for them:
1058
1071
  | `notAfter X` / `notBefore X` | matches | `(col <= $1 OR col IS NULL)` / `(col >= $1 OR col IS NULL)` | `{ OR: [{ col: { lte } }, { col: { equals: null } }] }` (nullable column) |
1059
1072
  | `notWithin { ago: { days: 30 } }` | matches | `(col NOT BETWEEN $1 AND $2 OR col IS NULL)` | `{ OR: [{ NOT: { col: { gte, lte } } }, { col: { equals: null } }] }` (nullable column) |
1060
1073
  | `notBetween` | matches | `(col NOT BETWEEN $1 AND $2 OR col IS NULL)` | `{ OR: [{ NOT: { col: … } }, { col: { equals: null } }] }` (nullable column, same field-map licensing as above) |
1061
- | `dayNotIn` | matches | `(EXTRACT(DOW FROM col) <> ALL($1) OR col IS NULL)` | none (no Prisma output) |
1074
+ | `dayNotIn` | matches | `(EXTRACT(DOW FROM (… col AT TIME ZONE $1)) <> ALL($2) OR col IS NULL)` (`$1` the zone, `$2` the days) | none (no Prisma output) |
1062
1075
  | `notExists` OR `before` | matches via the first arm | `(col IS NULL OR col < $1)` | `{ OR: [{ col: { equals: null } }, { col: { lt: … } }] }` |
1063
1076
 
1064
- `0` is an instant (1970-01-01) and compares; `''` is malformed data and raises
1065
- `"is not a valid date"`.
1077
+ `0` is an instant (1970-01-01) and compares, on every rail; `''` is malformed: as row data it
1078
+ raises `"is not a valid date"` in `check()`, and as a rule value it throws on every rail
1079
+ (`"Invalid comparison date"` in `check()`, `"Invalid date value"` in the compilers).
1066
1080
 
1067
1081
  ### Prisma Limitations
1068
1082
 
1069
1083
  - `matches` and `notMatches` are not supported by Prisma output
1070
1084
  - `dayIn` and `dayNotIn` are not supported by Prisma output
1071
- - `path: '$.field'` column-to-column comparisons are not supported by Prisma `WHERE`; no scope ref (`$$.` path, prefixed `field`) compiles
1085
+ - `path: '$.field'` column-to-column comparisons compile only between columns of the same model and visit, with `{ map, model }`; a `$$.` scope ref, or a read of the root from inside a relation filter, doesn't compile
1072
1086
  - count-based and aggregate relation operators require `{ map, model }`
1073
1087
  - aggregate rules on JSON/native stored arrays are not supported by Prisma; use `toSql()` or `check()` for those
1074
1088
  - an aggregate rule compared against a column (`path`) is refused: Prisma computes the aggregate in a `groupBy`, whose `having` can't read the parent row
@@ -1078,7 +1092,8 @@ positive operator, ask for them:
1078
1092
 
1079
1093
  ### SQL Limitations
1080
1094
 
1081
- - complex array element operators are not supported in SQL output:
1095
+ - complex array element operators are not supported in `toSql()` output (`toWhereSql()`
1096
+ compiles `any` / `all` / `none` over a to-many relation as `EXISTS` / `NOT EXISTS`):
1082
1097
  - `all`
1083
1098
  - `any`
1084
1099
  - `none`
@@ -1239,6 +1254,11 @@ readScopeRef('$$$.x', [rootRow, order]);
1239
1254
  `readScopeRef` returns the scope a ref names and the path left to read in it. It never throws:
1240
1255
  a ref deeper than the stack comes back as `{ outOfBounds }` with the message.
1241
1256
 
1257
+ `pathSegments(path)` is the list of keys a path reads, as `check()` reads it: dotted names,
1258
+ bracket indices and quoted keys (`messages[0].authorId` and `["messages"][0]["authorId"]` are
1259
+ both `['messages', '0', 'authorId']`). Use it, never `split('.')`, to walk a path of your own:
1260
+ a dotted split misses every bracket spelling `check()` accepts.
1261
+
1242
1262
  ## Error Handling
1243
1263
 
1244
1264
  The library throws when a rule is structurally invalid, for example:
@@ -1283,6 +1303,10 @@ try {
1283
1303
  }
1284
1304
  ```
1285
1305
 
1306
+ A rule that reaches past the lens is neither: `toPrisma` / `toSql` under `{ lens }` throw a
1307
+ plain `Error` (`"<rail>: the rule leaves the lens — …"`), which `validateRuleInLens` reports
1308
+ first.
1309
+
1286
1310
  ## Root-Array Rules in `check()`
1287
1311
 
1288
1312
  When `data` is an array, the rule must be a tree of `all` / `any` whose leaves are **fieldless** `ArrayRule`s (no `field`, `arrayOperator` operates on the array itself).
@@ -1342,7 +1366,7 @@ and visibility model.
1342
1366
 
1343
1367
  ### How it's built
1344
1368
 
1345
- The `Lens` primitive is a schema-aware view layer over one or more `FieldMap`s. It enables rule authoring against multi-source data (e.g. Prisma + an external CRM), with declarative cross-source `Bridge`s and recursive `Narrowing`s for both schema (picks/omits/enumPicks/enumOmits) and data (`where`).
1369
+ The `Lens` primitive is a schema-aware view layer over one or more `FieldMap`s. It enables rule authoring against multi-source data (e.g. Prisma + an external CRM), with declarative cross-source `Bridge`s and recursive `LensNarrowing`s for both schema (picks/omits/enumPicks/enumOmits) and data (`where`).
1346
1370
 
1347
1371
  ### FieldMap & FieldMapSet
1348
1372
 
@@ -1372,7 +1396,7 @@ const set = stitchFieldMaps({
1372
1396
  });
1373
1397
  ```
1374
1398
 
1375
- `stitchFieldMaps()` injects bridge entries as `kind: 'bridge'` fields on each endpoint model, addressable in rules via `<fieldMap>:<Model>` notation (e.g. `salesforce:Contact.industry`). Each endpoint's `on` is the symmetric join field used at eval time for hydration. Bridge cardinality controls list-vs-single on each side.
1399
+ `stitchFieldMaps()` injects bridge entries as `kind: 'bridge'` fields on each endpoint model, addressable in rules via `<fieldMap>:<Model>` notation (e.g. `salesforce:Contact.industry`). Each endpoint's `on` is the symmetric join field; `indexBridges` and `toSourceQueries` read it to join the two sides (`check()` never does: it reads the rows it is given). Bridge cardinality controls list-vs-single on each side.
1376
1400
 
1377
1401
  ### Lens
1378
1402
 
@@ -1402,7 +1426,7 @@ const narrowing: LensNarrowing = {
1402
1426
  parent: lens,
1403
1427
  root: { relations: { org: { relations: { parent: {} } } } }, // along the path
1404
1428
  mapDefaults: {
1405
- prisma: { models: { Org: { relations: { users: {} } } } }, // wherever Org is visited
1429
+ prisma: { models: { Org: { relations: { users: {} } } } }, // wherever Org is visited, unless User is already on the path
1406
1430
  },
1407
1431
  };
1408
1432
  validateRuleInLens({ field: 'org.parent.name', operator: Operator.equals, value: 'Acme' }, narrowing); // ok
@@ -1427,11 +1451,11 @@ validateRuleInLens({ field: 'posts', arrayOperator: ArrayOperator.any, condition
1427
1451
  turn-ons are followed breadth-first, each model once, at its nearest reach (ties: the earlier
1428
1452
  parent, then the relation declared first). Anything else is reached by spelling it under
1429
1453
  `root.relations`; a spelled node grows its own tree. Every posture walks the same tree, so they
1430
- agree and stay small. `lensVisit(lens, 'org.users')` resolves one visit on demand, as
1454
+ agree and stay small. `lensVisit(lens, 'org.parent')` resolves one visit on demand, as
1431
1455
  `projectLens` would give it, or `null`.
1432
1456
  - **Clamps.** The first narrowing's `where`s (and source eligibility `where`s) may read any
1433
1457
  relation on the schema; a later layer's may read only what its parent shows, so a delegate can't
1434
- probe a relation it can't see (`validateNarrowing` reports it; every posture throws). A bare
1458
+ probe a relation it can't see (`validateNarrowing` reports it; the gate refuses it and every other posture throws). A bare
1435
1459
  value `path` reads the root row, so only `root.where` may hold one. `toLensSelect` fetches exactly the columns clamps read, and
1436
1460
  `projectRows({ keepClampColumns: true })` keeps them for a re-check.
1437
1461
 
@@ -1464,7 +1488,7 @@ Composition across chained narrowings is pure intersection: relations are turned
1464
1488
 
1465
1489
  | Function | Purpose |
1466
1490
  | --- | --- |
1467
- | `validateNarrowing(narrowing)` | Returns `{ ok, errors: { path, message, code }[] }` for structural or chain problems, one code each: `not_in_lens`, `not_visible` (an item an ancestor hid, or a relation the parent doesn't show), `conflicting_selection` (picks beside an omitted column), `wrong_kind` (a relation named in `picks`, among others), `value_not_allowed`, `invalid_source` (a source label / axis crossing a relation that is off, among others), `invalid_binding`, plus the lens gate's codes for a `where`. `assertValidNarrowing` throws instead. Call at narrowing construction. |
1491
+ | `validateNarrowing(narrowing)` | Returns `{ ok, errors: { path, message, code }[] }` for structural or chain problems, one code each: `not_in_lens`, `not_visible` (an item an ancestor hid, or a relation the parent doesn't show), `conflicting_selection` (picks beside an omitted column), `wrong_kind` (a relation named in `picks`, among others), `value_not_allowed`, `invalid_source` (a source label / axis crossing a relation that is off, among others), `invalid_binding`, `invalid_value_source`, `scope_out_of_bounds`, the codes of the `LensRefusal`s it folds in (`unsupported_clamp`, among others), plus the lens gate's codes for a `where`. `assertValidNarrowing` throws instead. Call at narrowing construction. |
1468
1492
  | `assertValidFieldMaps(set)` | Throws when a field name in any map holds `.` or `:` (a path step and a bridge marker). `validateFieldMaps(set)` returns `{ ok, errors }` with code `invalid_field_name`. To check a single map, wrap it: `assertValidFieldMaps({ maps: { prisma: map } })`. |
1469
1493
  | `projectLens(lens)` | Returns `Record<dottedPath, ProjectedVisit>`: each path the relations turned on reach keys its own resolved narrowing (path picks/omits/enums chain-intersected ∩ `mapDefaults` for the target model); a relation field appears only where it is on. Sibling paths to the same model stay independent. Use for SDK-contract / OpenAPI emission, search-field enumeration, validation whitelists. See [docs/LENS.md §10](./docs/LENS.md). |
1470
1494
  | `describeRuleSources(rule, lens)` | The values a rule names at each source the lens declares, keyed like `projectLens` (`path` + `field`, with the source's `mapName` / `model`). Resolved through the lens like `walkLensPath`, so `mapDefaults` sources answer wherever a relation turned on reaches their model. `dynamic: true` when the set can't be enumerated: a `path` / `bind` leaf, an offset or a read amount that moves the value, a substring / pattern / range / window operator, or an operator the catalog doesn't know; callers fail closed on it. The reverse question for a reference registry ("which rows does this rule name"): join `model` + `values`. |
@@ -1564,7 +1588,7 @@ const projection = projectLens(narrowing, { sourceValues: [values] });
1564
1588
  | Function | Purpose |
1565
1589
  | --- | --- |
1566
1590
  | `toSourceQueries(lensOrNarrowing, options?)` | `SourceQuery[]`, one per sourced field: `{ path, mapName, model, field, label?, groupBy?, composedWhere, prisma, sql, recheck? }`. `options` is the clock (`now`, `timeZone`, `weekStart`) a relative date in the where compiles with: required for one, a plain usage error without it; bind a lens's binds with `bindLens` first. `prisma.steps` is present when the where needs `executePrismaPlan` (a count step, or a column reference to resolve): query with the where it returns. `sql.sql` is `null` with an `error` when SQL can't express the where. A source that reads across a bridge gets an over-fetching query and a `recheck`: its rows are candidates, not options (see "Sources across a bridge"). `distinct` is the value and a sibling label column; a grouped source or a dotted label drops it, so every label comes back and the least one is picked. |
1567
- | `materializeSourceQuery(query, rows, { rowShape?, lens?, now?, … })` | One query's fetched rows as `SourceValues`. `rowShape` is `'prisma'` (default: a dotted `label` and each `groupBy` axis come nested) or `'sql'` (they come flat as `__label` / `__group_i`). Options are deduplicated and sorted. A query with `recheck` needs `lens` and rows holding the far side: it re-checks each candidate (`check`, with the clock and bindings given) and reads a bridged label or axis from the far side; a missing far side is a `UsageError`. |
1591
+ | `materializeSourceQuery(query, rows, { rowShape?, lens?, now?, … })` | One query's fetched rows as `SourceValues`. `rowShape` is `'prisma'` (default: a dotted `label` and each `groupBy` axis come nested) or `'sql'` (they come flat as `__label` / `__group_i`). Options are deduplicated and ordered by value, or in the query's own order with `order: SourceOptionOrder.query`. A query with `recheck` needs `lens` and rows holding the far side: it re-checks each candidate (`check`, with the clock and bindings given) and reads a bridged label or axis from the far side; a missing far side is a `UsageError`. |
1568
1592
  | `materializeSources(lensOrNarrowing, rows, options?)` | `SourceValues[]` for every sourced field, from the rows the lens fetches: `toLensSelect`'s rows as fetched, or as `projectRows(…, { keepClampColumns: true })` keeps them. A viewer's projection drops what sources read: a row lacking any key a read walks (through each relation and list element to the column) that a source or a clamp on its path reads throws a `UsageError` (a fetch returns every key it selects, NULL as `null`). The path is walked down the rows (the tree is its link), each level's clamps met, and each row it reaches must meet, through `check()` with `options`, its visit's clamps, its source `where` narrowed as a rule is, the guards of the relations its label and axes cross and the values the lens allows, so it offers what `toSourceQueries` does. A scalar-list field gives one option per element; a value takes its least label. A `from: 'mapDefaults'` source throws (see below). |
1569
1593
 
1570
1594
  Options never offer a value the lens disallows: `projectLens` drops fetched values outside a
@@ -1576,7 +1600,7 @@ couldn't carry there (one narrowRule can't re-root, a to-many relation read flat
1576
1600
  it is for a rule; so is a source whose query has a window toPrisma can't compile (by its shape,
1577
1601
  before anything compiles; `materializeSources` refuses it too, so the two never disagree).
1578
1602
 
1579
- #### Two kinds of source
1603
+ ### Two kinds of source
1580
1604
 
1581
1605
  A source declared down a relation path offers the rows **reachable** from there: the path is
1582
1606
  carried down through each relation's inverse (where the map declares one), and every clamp above
@@ -1627,7 +1651,7 @@ over-fetches and re-checks (see "Sources across a bridge"). A clamp a path can't
1627
1651
  map declares no inverse) is a `LensRefusal`, never an empty list. `materializeSources` refuses a pointer, because a fetched collection can't hold unlinked
1628
1652
  rows; query it with `toSourceQueries` and `materializeSourceQuery`.
1629
1653
 
1630
- #### Sources across a bridge
1654
+ ### Sources across a bridge
1631
1655
 
1632
1656
  A source whose path, `where`, `label` or an axis reads across a bridge can't be decided by one
1633
1657
  database: each holds one side. `toSourceQueries` still returns a real query for the side it can