foldkit-entity 0.9.0 → 0.11.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
@@ -355,6 +355,129 @@ optional relation set to nothing), and each interpreter carries it its own way,
355
355
  a ref key in a store, a foreign key in a table. A `many` relation or a nested
356
356
  key is refused where the write is declared.
357
357
 
358
+ An update or a delete may also say when it makes sense: `when` is what the row
359
+ must hold for it to land, written as a query body is: `() =>
360
+ Expr.eq(Post.fields.title, 'Draft')`, or with the input, `({ input }) =>
361
+ Expr.eq(Post.fields.title, input.from)`. It reads the row as it is before the write and the input,
362
+ never who is asking (that is a guard's), and only its own Entity: a field of
363
+ another is a type error, and refused where the write is declared. It is held as
364
+ a query body (`write.when`), so an interpreter checks it in the statement that
365
+ writes, and a row it does not hold of is refused as unmet. A write declared with
366
+ one is a `ConditionedWrite`, which is how `Mutation.write` knows it may be
367
+ refused so.
368
+
369
+ An update may move a number field by an amount the input holds, rather than set
370
+ it: `increment: { stock: 'quantity' }` adds the input's `quantity` (an unmapped
371
+ key, a number; negative takes away) to the stored `stock`, in the statement that
372
+ writes, so no concurrent change is lost. A retry must not add twice, so either it
373
+ expects a revision (a retry of a write that landed is then a conflict), or its
374
+ writer keeps a ledger, which answers the retry from its record and lets two
375
+ concurrent increments both land. `RemoteServer.write` refuses one with neither. The field must
376
+ be stored as a number, and may not be the id, the revision, or set by another
377
+ key. `Write.bind` gives the amounts apart from the values (`increments`), so a
378
+ client can add them to the value it holds as it reads it (Remote does), never
379
+ fixing a sum over a row that may since have moved. `Write.reads(write)` is what a write
380
+ reads from its row: what its `when` reads, each field it increments, and the
381
+ revision. How a declaration, its guard, its writer and the client fit together is
382
+ the [declared writes guide](../../docs/declared-writes.md).
383
+
384
+ ## What every row and change must hold: invariants
385
+
386
+ A Schema judges a value, and a write's `when` the row before it. Neither judges
387
+ the row a write leaves: with `quantity = 10, reserved = 5`, an update setting
388
+ `quantity = 3` decodes, and leaves a row that holds more reserved than there is.
389
+ An **invariant** is what every stored row must hold, read over the row after a
390
+ write (`after`):
391
+
392
+ ```ts
393
+ import { Schema } from 'effect'
394
+ import { Entity, Expr } from 'foldkit-entity'
395
+
396
+ const InventoryFields = Entity.define(
397
+ 'Inventory',
398
+ Schema.Struct({ id: Schema.String, quantity: Schema.Number, reserved: Schema.Number }),
399
+ )
400
+ const Inventory = InventoryFields.pipe(
401
+ Entity.invariant(
402
+ 'reservedWithinQuantity',
403
+ ({ after }) => Expr.lte(after.reserved, after.quantity),
404
+ { message: 'Reserved stock cannot exceed the quantity', path: ['reserved'] },
405
+ ),
406
+ )
407
+
408
+ Entity.judge(Inventory, { after: { id: 'i1', quantity: 3, reserved: 5 } })
409
+ // { _tag: 'Invalid', failures: [{ id: 'reservedWithinQuantity', … }] }
410
+ ```
411
+
412
+ One that reads the row before too (`before`) relates the two, each of which may
413
+ be valid on its own: an order that shipped stays shipped.
414
+
415
+ ```ts
416
+ const OrderFields = Entity.define(
417
+ 'Order',
418
+ Schema.Struct({ id: Schema.String, status: Schema.Literals(['placed', 'shipped']) }),
419
+ )
420
+ const Order = OrderFields.pipe(
421
+ Entity.invariant(
422
+ 'shippedStaysShipped',
423
+ ({ before, after }) =>
424
+ Expr.or(Expr.not(Expr.eq(before.status, 'shipped')), Expr.eq(after.status, 'shipped')),
425
+ { message: 'A shipped order stays shipped', path: ['status'] },
426
+ ),
427
+ )
428
+
429
+ const shipped = { id: 'o1', status: 'shipped' }
430
+ Entity.judge(Order, { before: shipped, after: { ...shipped, status: 'placed' } })
431
+ // { _tag: 'Invalid', failures: [{ id: 'shippedStaysShipped', … }] }
432
+ ```
433
+
434
+ What an invariant reads decides when it is judged; nothing else is declared:
435
+
436
+ ```text
437
+ reads after only -> state invariant: every create and update; a CHECK constraint
438
+ reads before too -> transition invariant: every update, the only write with a row before
439
+ ```
440
+
441
+ `Entity.readsBefore(invariant)` says which one is.
442
+
443
+ `Entity.invariant` returns the step that attaches it, carrying its `id`. Hoist
444
+ it to export it, naming the Entity's type (what it reads is checked against
445
+ it), and match a refusal against it rather than spelling the id again:
446
+
447
+ ```ts
448
+ export const reservedWithinQuantity = Entity.invariant<typeof InventoryFields>(
449
+ 'reservedWithinQuantity',
450
+ ({ after }) => Expr.lte(after.reserved, after.quantity),
451
+ { message: 'Reserved stock cannot exceed the quantity', path: ['reserved'] },
452
+ )
453
+ export const Inventory = InventoryFields.pipe(reservedWithinQuantity)
454
+
455
+ // Where a write's refusal is read (foldkit-remote):
456
+ Refusal.isInvalidBy(refusal, reservedWithinQuantity)
457
+ ```
458
+
459
+ - `before` is each field as the row before holds it (`Expr.field`), and `after`
460
+ each as the row after holds it (`Expr.next`), both typed as the field.
461
+ - It is declared once, on the Entity's metadata, and attaching more adds to it;
462
+ the Entity stays the same (`Entity.same`). Its interpreters read it from there.
463
+ - It reads stored rows only: one over another Entity, or reading an input, is
464
+ refused where it is declared, as is an id declared twice or a `path` naming no
465
+ field. So is one reading nothing of `after`: which rows a write may start from
466
+ is its `when`. Who may write is a guard's; whether a write applies now is its `when`'s.
467
+ - `Entity.judge(entity, { after, before? })` judges rows as the store holds them
468
+ (encoded) and is pure. Without `before` (a create) it skips transition
469
+ invariants. A row holds one only when it is true: a null fails it, as SQL's
470
+ unknown drops a row from a `WHERE`. A row without a field it reads is
471
+ `Undecided`, never `Valid`.
472
+ - `Entity.check(entity)` is the state invariants as a Schema check over the row
473
+ type (`entity.schema.check(Entity.check(entity))`): it encodes the value, and
474
+ reports each failure at its `path` with its `message`.
475
+
476
+ Text compares only under a declared collation, here too: a date stored as text
477
+ needs `{ collation: Collation.binary }` on its comparison. An interpreter that
478
+ judges stored rows alone refuses `after`'s nodes as the operation `next`;
479
+ `Expr.substituteNext` reads the ones a write sets as their values.
480
+
358
481
  ## Attaching metadata
359
482
 
360
483
  An interpreter declares a [`foldkit-metadata`](../metadata/README.md) key and
@@ -437,7 +560,10 @@ A comparison coerces what it is given, so the common forms read as they mean: a
437
560
  field becomes a reference, a plain value becomes a literal, and an `Expr` is
438
561
  already one. What it will not do is compare a field to the wrong kind of value —
439
562
  `Expr.eq(Blog.Post.fields.title, 42)` is an error where it is written, rather
440
- than a row that never matches.
563
+ than a row that never matches. The value's type comes from the left, so `eq` takes
564
+ the field on the left; `Expr.eq('Hello', Blog.Post.fields.title)` is refused with
565
+ that sentence. The comparisons (`lt`, `gte`, …) also take a field second,
566
+ wrapped in `Expr.field(…)`.
441
567
 
442
568
  **An input is a placeholder, not a value.** A query's body is built once, so
443
569
  `Expr.input('title', …)` stands for whatever the query is given when it runs —
@@ -525,7 +651,13 @@ const oneOf = Query.from(Blog.Post).pipe(published, Query.where(byTitle))
525
651
 
526
652
  `published` and `newest` are fragments: written once, piped into any query over
527
653
  the same Entity. Composing performs no work — no table is named, no connection
528
- opened, nothing read.
654
+ opened, nothing read. A fragment over another Entity is refused where it is
655
+ piped: a predicate's type names the Entities its fields belong to, so
656
+ `Query.from(Blog.Post).pipe(Query.where(Expr.eq(Blog.Comment.fields.body, 'x')))`
657
+ reads `a predicate reads Comment, but the query is from Post`, and an ordering
658
+ term over another Entity is refused by `Query.orderBy` the same way. The same check
659
+ runs again when the query is built, for what a type cannot see: a predicate
660
+ typed plainly as `Predicate`, or two Entities that share a name.
529
661
 
530
662
  **Two `where`s conjoin and two `orderBy`s append.** Neither replaces what came
531
663
  before, so piping a fragment can only ever narrow a query, never silently undo
@@ -689,7 +821,8 @@ from queries, not from what a database could express.
689
821
  | `Entity.select(entity, { key: true or Selection })` | A Selection: what was selected (`members`) and the `schema` of the result. |
690
822
  | `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a page: `items`, `hasNext`, `hasPrevious`. |
691
823
  | `Entity.fields(entity, ...keys)` | The schemas of those fields, by key, to spread into an input's struct. |
692
- | `Write.update(input, { id, expect? })` | A declared update of one row: every key the input maps to a field, but the id and the expected revision. |
824
+ | `Write.update(input, { id, expect?, when?, increment? })` | A declared update of one row: every key the input maps to a field, but the id and the expected revision; `when`, what the row must hold for it to land; `increment`, the number fields it moves by an input amount. |
825
+ | `Write.reads(write)` | The fields a write reads from its row: its `when`'s, each it increments, the revision. |
693
826
  | `Write.writes(write)` / `Write.bind(write, value, keys?)` | The fields it may change; the row and values one input writes, encoded as the store holds them. |
694
827
  | `Entity.input(entity, struct, mapping?)` | Experimental. Which member each key of an operation's input writes. |
695
828
  | `Relation.nested(relation, input)` | In an input mapping: the key holds the target itself, written through `input`. |
@@ -702,7 +835,7 @@ from queries, not from what a database could express.
702
835
  | `Selected<typeof selection>` | Type: the value a Selection reads (its `schema`'s `Type`). |
703
836
  | `Words.of(schema)` | A schema's `title` and `description`, each an `Option`, including a title given before a check. |
704
837
  | `Entity.is(value)` | Whether a value is an Entity descriptor. |
705
- | `Expr.eq(left, right)` | Two values are the same; a field or a plain value on either side is coerced, and a predicate may stand where a boolean is wanted. |
838
+ | `Expr.eq(left, right)` | Two values are the same: a field (or an expression) on the left, and the value on the right, which is typed from it; a predicate may stand where a boolean is wanted. A plain value on the left is a compile error that says so. |
706
839
  | `Expr.isNull(field)` / `Expr.isNotNull(field)` | Whether a value is absent; one node, with the answer absence gives flipped. |
707
840
  | `Expr.contains(field, search)` | Whether text contains text, over a text or nullable-text operand only. Containing the empty string is everything, but a null contains nothing. |
708
841
  | `Expr.in(field, among)` | Whether a value is one of a list (written out, or an input), each compared as `eq` compares; SQL's `in`, an empty list matching nothing. |
@@ -1,4 +1,4 @@
1
- import { rt as AnyQuery, s as Entity } from "../index-BzdK89FC.mjs";
1
+ import { ft as AnyQuery, s as Entity } from "../index-BhI_DA2S.mjs";
2
2
  import { Schema } from "effect";
3
3
  //#region src/conformance/index.d.ts
4
4
  /** The one Entity every case reads, with a column of each kind that matters. */
@@ -1,4 +1,4 @@
1
- import { S as Collation, _ as Order, g as Expr, n as Entity, v as Query } from "../src-5avJ3IkP.mjs";
1
+ import { b as Query, n as Entity, v as Expr, w as Collation, y as Order } from "../src-DwKdHZDu.mjs";
2
2
  import { Schema, SchemaGetter } from "effect";
3
3
  //#region src/conformance/index.ts
4
4
  /**