foldkit-entity 0.13.0 → 0.15.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 +962 -512
- package/dist/collation.d.ts +33 -0
- package/dist/collation.d.ts.map +1 -0
- package/dist/collation.js +46 -0
- package/dist/collation.js.map +1 -0
- package/dist/conformance/index.d.ts +66 -0
- package/dist/conformance/index.d.ts.map +1 -0
- package/dist/conformance/{index.mjs → index.js} +22 -360
- package/dist/conformance/index.js.map +1 -0
- package/dist/conformance/operator.d.ts +115 -0
- package/dist/conformance/operator.d.ts.map +1 -0
- package/dist/conformance/operator.js +354 -0
- package/dist/conformance/operator.js.map +1 -0
- package/dist/conformance/relational.d.ts +240 -0
- package/dist/conformance/relational.d.ts.map +1 -0
- package/dist/conformance/relational.js +425 -0
- package/dist/conformance/relational.js.map +1 -0
- package/dist/conformance/tuples.d.ts +8 -0
- package/dist/conformance/tuples.d.ts.map +1 -0
- package/dist/conformance/tuples.js +43 -0
- package/dist/conformance/tuples.js.map +1 -0
- package/dist/conformance/variants.d.ts +47 -0
- package/dist/conformance/variants.d.ts.map +1 -0
- package/dist/conformance/variants.js +126 -0
- package/dist/conformance/variants.js.map +1 -0
- package/dist/context.d.ts +60 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +36 -0
- package/dist/context.js.map +1 -0
- package/dist/descriptor.d.ts +33 -0
- package/dist/descriptor.d.ts.map +1 -0
- package/dist/descriptor.js +137 -0
- package/dist/descriptor.js.map +1 -0
- package/dist/entity.d.ts +231 -0
- package/dist/entity.d.ts.map +1 -0
- package/dist/entity.js +435 -0
- package/dist/entity.js.map +1 -0
- package/dist/evaluate.d.ts +204 -0
- package/dist/evaluate.d.ts.map +1 -0
- package/dist/evaluate.js +765 -0
- package/dist/evaluate.js.map +1 -0
- package/dist/expr.d.ts +915 -0
- package/dist/expr.d.ts.map +1 -0
- package/dist/expr.js +1630 -0
- package/dist/expr.js.map +1 -0
- package/dist/held.d.ts +112 -0
- package/dist/held.d.ts.map +1 -0
- package/dist/held.js +155 -0
- package/dist/held.js.map +1 -0
- package/dist/ids.d.ts +8 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +8 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +380 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +110 -0
- package/dist/index.js.map +1 -0
- package/dist/invariant.d.ts +123 -0
- package/dist/invariant.d.ts.map +1 -0
- package/dist/invariant.js +236 -0
- package/dist/invariant.js.map +1 -0
- package/dist/jsonSchema.d.ts +3 -0
- package/dist/jsonSchema.d.ts.map +1 -0
- package/dist/jsonSchema.js +17 -0
- package/dist/jsonSchema.js.map +1 -0
- package/dist/law.d.ts +264 -0
- package/dist/law.d.ts.map +1 -0
- package/dist/law.js +111 -0
- package/dist/law.js.map +1 -0
- package/dist/operators.d.ts +170 -0
- package/dist/operators.d.ts.map +1 -0
- package/dist/operators.js +207 -0
- package/dist/operators.js.map +1 -0
- package/dist/readFilter.d.ts +8 -0
- package/dist/readFilter.d.ts.map +1 -0
- package/dist/readFilter.js +23 -0
- package/dist/readFilter.js.map +1 -0
- package/dist/record.d.ts +11 -0
- package/dist/record.d.ts.map +1 -0
- package/dist/record.js +21 -0
- package/dist/record.js.map +1 -0
- package/dist/sets.d.ts +18 -0
- package/dist/sets.d.ts.map +1 -0
- package/dist/sets.js +57 -0
- package/dist/sets.js.map +1 -0
- package/dist/shape.d.ts +23 -0
- package/dist/shape.d.ts.map +1 -0
- package/dist/shape.js +30 -0
- package/dist/shape.js.map +1 -0
- package/dist/tested.d.ts +8 -0
- package/dist/tested.d.ts.map +1 -0
- package/dist/tested.js +25 -0
- package/dist/tested.js.map +1 -0
- package/dist/text.d.ts +27 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +39 -0
- package/dist/text.js.map +1 -0
- package/dist/variants.d.ts +72 -0
- package/dist/variants.d.ts.map +1 -0
- package/dist/variants.js +76 -0
- package/dist/variants.js.map +1 -0
- package/dist/words.d.ts +17 -0
- package/dist/words.d.ts.map +1 -0
- package/dist/words.js +22 -0
- package/dist/words.js.map +1 -0
- package/dist/write.d.ts +312 -0
- package/dist/write.d.ts.map +1 -0
- package/dist/write.js +520 -0
- package/dist/write.js.map +1 -0
- package/package.json +8 -8
- package/dist/conformance/index.d.mts +0 -274
- package/dist/conformance/index.d.mts.map +0 -1
- package/dist/conformance/index.mjs.map +0 -1
- package/dist/index-hu8IYlNc.d.mts +0 -2228
- package/dist/index-hu8IYlNc.d.mts.map +0 -1
- package/dist/index.d.mts +0 -2
- package/dist/index.mjs +0 -1
- package/dist/src-DBAilaDV.mjs +0 -3061
- package/dist/src-DBAilaDV.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
# foldkit-entity
|
|
2
2
|
|
|
3
|
-
A domain
|
|
4
|
-
relations to other entities, and the derived values consumers may read
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
>
|
|
12
|
-
> [
|
|
3
|
+
A domain declared once as typed values: each entity's intrinsic fields, its
|
|
4
|
+
relations to other entities, and the derived values consumers may read; and,
|
|
5
|
+
over that, a small language for saying which rows (`Expr`, `Query`), what a
|
|
6
|
+
write does to one (`Write`), and what every stored row must hold
|
|
7
|
+
(invariants). Other packages interpret these declarations; this one only
|
|
8
|
+
describes, and gives the reference meaning of the language over rows already
|
|
9
|
+
in hand.
|
|
10
|
+
|
|
11
|
+
> **Who reads it.** `foldkit-remote`
|
|
12
|
+
> [registers Entities and reads Selections and query bodies](../remote/README.md#entities-declared-with-foldkit-entity),
|
|
13
|
+
> and judges the rows it holds by them. `foldkit-remote-drizzle` binds a related
|
|
14
|
+
> set to tables with
|
|
15
|
+
> [`bind`](../remote-drizzle/README.md#binding-a-foldkit-entity-domain) and
|
|
16
|
+
> compiles bodies, writes and invariants to SQL. [`foldkit-form`](../form/README.md)
|
|
17
|
+
> builds a form from `Entity.input`, [`foldkit-crud`](../crud/README.md) joins
|
|
18
|
+
> one to a Remote operation, and `foldkit-guard` writes its rules as `Expr`.
|
|
13
19
|
|
|
14
20
|
For the whole path in one runnable trace, domain to client to SQL, see
|
|
15
21
|
[`examples/entity`](../../examples/entity).
|
|
@@ -17,15 +23,23 @@ For the whole path in one runnable trace, domain to client to SQL, see
|
|
|
17
23
|
## What it owns
|
|
18
24
|
|
|
19
25
|
`foldkit-entity` owns **domain structure**: which members an entity has, what
|
|
20
|
-
kind each is, and which entity a relation points to.
|
|
26
|
+
kind each is, and which entity a relation points to. It also owns the
|
|
27
|
+
**meaning** of the declarations made over it: what a query body, a declared
|
|
28
|
+
write and an invariant say, as values every interpreter reads the same way.
|
|
21
29
|
|
|
22
30
|
It does not own:
|
|
23
31
|
|
|
24
|
-
- **
|
|
25
|
-
stays the only
|
|
32
|
+
- **Validity of one value.** `entity.schema` is an ordinary Effect
|
|
33
|
+
`Schema.Struct` and stays the rule for a value. An invariant adds only what a
|
|
34
|
+
Schema cannot judge: a rule across fields, or between a row before and after
|
|
35
|
+
a write.
|
|
26
36
|
- **Storage or fetching.** A relation says "one Author", not "a foreign key" or
|
|
27
|
-
"a join table".
|
|
28
|
-
|
|
37
|
+
"a join table". A query body fetches nothing; `foldkit-remote-drizzle`
|
|
38
|
+
compiles it, and `foldkit-remote` judges the rows it holds by it.
|
|
39
|
+
- **Operations.** An Entity implies no create, update, or delete. A `Write`
|
|
40
|
+
is declared by an operation, and an Entity having a field grants no one the
|
|
41
|
+
right to set it.
|
|
42
|
+
- **Who may.** Authorization is `foldkit-guard`'s, written in the same `Expr`.
|
|
29
43
|
- **Application state.** Nothing here touches a Model or dispatches a Message.
|
|
30
44
|
|
|
31
45
|
## Mental model
|
|
@@ -34,16 +48,40 @@ It does not own:
|
|
|
34
48
|
Entity
|
|
35
49
|
├── fields intrinsic values: the properties of entity.schema
|
|
36
50
|
├── relations navigation edges: one / many of another Entity (Entity.relate)
|
|
37
|
-
├── derived readable values an interpreter supplies
|
|
38
|
-
|
|
51
|
+
├── derived readable values an interpreter supplies, counts or finds
|
|
52
|
+
├── members all three under one namespace; keys never collide
|
|
53
|
+
├── sets members the write's context fills (who asks, when)
|
|
54
|
+
└── invariants what every stored row must hold (kept in its metadata)
|
|
55
|
+
|
|
56
|
+
over it, as data:
|
|
57
|
+
Selection which members a consumer reads Entity.select
|
|
58
|
+
Query which rows, in which order Query.from · Expr
|
|
59
|
+
Write what one operation does to one row Write.update / insert / delete
|
|
39
60
|
|
|
40
61
|
interpreter ──(foldkit-metadata)──► Entity / member attaches what it needs
|
|
41
|
-
interpreter ◄── reads
|
|
62
|
+
interpreter ◄── reads all of the above, and runs it (SQL, the client's store)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
An Entity has **one set of members**. `Entity.relate`, `Entity.derived` and
|
|
66
|
+
`Entity.sets` add to it, and every descriptor of the Entity reads it: the one
|
|
67
|
+
declared before `relate`, the one a relation's `target()` returns, the one a
|
|
68
|
+
query captured. Metadata is the exception: `Entity.annotate`,
|
|
69
|
+
`Entity.annotateMembers` and `Entity.invariant` return a new descriptor that
|
|
70
|
+
carries its own, so one reader's view (a form's labels) stays its own. Compare
|
|
71
|
+
descriptors with `Entity.same(a, b)`, not `a === b`.
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
identity ── relations, derived, sets one per Entity; relate / derived / sets add
|
|
75
|
+
├── descriptor fields, metadata define, relate, derived, sets return it
|
|
76
|
+
└── descriptor fields, metadata' annotate / annotateMembers / invariant make one
|
|
42
77
|
```
|
|
43
78
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
79
|
+
A descriptor's *type* still shows only the steps it came through: read typed
|
|
80
|
+
members from the descriptor `relate` returned, or a later one.
|
|
81
|
+
|
|
82
|
+
Everything here is checked where it is declared: a type error where the types
|
|
83
|
+
can see it, and a throw for what they cannot. An interpreter that cannot run
|
|
84
|
+
something refuses it by name rather than skipping it.
|
|
47
85
|
|
|
48
86
|
## Install
|
|
49
87
|
|
|
@@ -97,7 +135,7 @@ const Blog = Entity.relate(
|
|
|
97
135
|
editor: Relation.one(Author, { optional: true }),
|
|
98
136
|
comments: Relation.many(Comment),
|
|
99
137
|
},
|
|
100
|
-
Comment: { post: Relation.one(Post) },
|
|
138
|
+
Comment: { post: Relation.one(Post), author: Relation.one(Author) },
|
|
101
139
|
},
|
|
102
140
|
)
|
|
103
141
|
|
|
@@ -107,21 +145,64 @@ Blog.Post.relations.editor.optional // true
|
|
|
107
145
|
Blog.Post.derived.commentCount.schema // Schema.Number
|
|
108
146
|
Blog.Post.relations.comments.target() // Blog.Comment
|
|
109
147
|
Blog.Post.relations.comments.target().relations.post.target() // Blog.Post, fully typed
|
|
110
|
-
Object.keys(Blog.Post.members) // id, title, published,
|
|
148
|
+
Object.keys(Blog.Post.members) // id, title, published, author, editor, comments, commentCount
|
|
111
149
|
```
|
|
112
150
|
|
|
113
151
|
- `Entity.define` generates one `Field` per schema property and creates the
|
|
114
152
|
identity. Calling it twice with the same name makes two different entities.
|
|
115
153
|
- `Derived.make` states a readable value's schema and nothing about how it is
|
|
116
154
|
produced. `Entity.derived` is a pipe step because it concerns one entity.
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
155
|
+
It may also say what a client can foresee of it
|
|
156
|
+
([below](#what-a-client-foresees-of-a-supplied-member)).
|
|
157
|
+
- `Derived.count(relation)` says what it is: how many rows point at this one
|
|
158
|
+
through `relation`, a `one` relation of the counted Entity. It names another
|
|
159
|
+
Entity's relation, so it is added after `Entity.relate`:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
const Post = Blog.Post.pipe(
|
|
163
|
+
Entity.derived({ commentTotal: Derived.count(Blog.Comment.relations.post) }),
|
|
164
|
+
)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
A count of a `many` relation, or of rows pointing at another Entity, is
|
|
168
|
+
refused where it is declared. `remote-drizzle` compiles it with no binding
|
|
169
|
+
entry, and Remote predicts it while a write that adds, removes or moves a
|
|
170
|
+
counted row is pending.
|
|
171
|
+
- `Derived.exists(relation, { viewer })` says whether a row points here
|
|
172
|
+
through `relation` and at whoever reads it through `viewer`, another `one`
|
|
173
|
+
relation of the same Entity: "did I comment on this post?"
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
const Post = Blog.Post.pipe(
|
|
177
|
+
Entity.derived({
|
|
178
|
+
myComment: Derived.exists(Blog.Comment.relations.post, {
|
|
179
|
+
viewer: Blog.Comment.relations.author,
|
|
180
|
+
}),
|
|
181
|
+
}),
|
|
182
|
+
)
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Its value is that row's id, or none (`Option<string>`), so the reader can
|
|
186
|
+
take it back by deleting the row. It depends on who reads it. Each derived
|
|
187
|
+
member's `derives` says which kind it is (`Supplied`, `Count`, `Exists`).
|
|
188
|
+
- `Entity.relate` takes the entities and every relation between them, adds
|
|
189
|
+
the relations to them, and returns them typed with their relations. Use the
|
|
190
|
+
returned ones (`Blog.Post`) for their types; the `Post` you passed in has the
|
|
191
|
+
same relations at runtime.
|
|
120
192
|
- `Relation.one` / `Relation.many` state what the owner sees. `Post.author: one`
|
|
121
193
|
and `Author.posts: many` together are the familiar one-to-many; neither side
|
|
122
194
|
names it.
|
|
123
195
|
- `target()` returns the related entity, so relations can be followed from
|
|
124
196
|
there, around a cycle too.
|
|
197
|
+
- `Relation.one(Post, { onDelete: 'cascade' })` says a row goes when the row
|
|
198
|
+
it points at is deleted: a comment with its post, a reply with the post it
|
|
199
|
+
answers. It is declared on the link the row holds, as its foreign key is,
|
|
200
|
+
and a `many` declares nothing. `Entity.cascading(Post)` lists every relation
|
|
201
|
+
that takes rows with a deleted post (`{ relation, owner }`), so Remote
|
|
202
|
+
removes those it holds while the delete is pending, counts and lists with
|
|
203
|
+
them, and `remote-drizzle`'s writer removes them where it deletes, on a store
|
|
204
|
+
without foreign keys too. `cascade` is the one action; `setNull` and
|
|
205
|
+
`restrict` are not declared yet (#348).
|
|
125
206
|
|
|
126
207
|
`Entity.relate` throws, and the types reject, a relation key that is already a
|
|
127
208
|
member, an owner that is not in the first argument, and a target that is not
|
|
@@ -235,582 +316,952 @@ An unknown member, a nested Selection on a field, a page of a `one` relation,
|
|
|
235
316
|
and a Selection of the wrong
|
|
236
317
|
Entity are type errors, and `Entity.select` throws for untyped callers.
|
|
237
318
|
|
|
238
|
-
##
|
|
239
|
-
|
|
240
|
-
> Experimental: the smallest mapping that several operation shapes and
|
|
241
|
-
> [`foldkit-form`](../form/README.md) needed.
|
|
319
|
+
## Attaching metadata
|
|
242
320
|
|
|
243
|
-
An
|
|
244
|
-
|
|
245
|
-
and says what each key means in terms of the Entity, so a consumer can find the
|
|
246
|
-
field's metadata for a label, or the relation's target for a picker.
|
|
321
|
+
An interpreter declares a [`foldkit-metadata`](../metadata/README.md) key and
|
|
322
|
+
attaches entries to the entity or to members. Entity core never reads them.
|
|
247
323
|
|
|
248
324
|
```ts
|
|
249
|
-
|
|
250
|
-
title: Schema.String,
|
|
251
|
-
authorId: Schema.String,
|
|
252
|
-
notify: Schema.Boolean,
|
|
253
|
-
})
|
|
325
|
+
import { Metadata } from 'foldkit-metadata'
|
|
254
326
|
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
327
|
+
const Labels = Metadata.key<string>('my-admin/labels', {
|
|
328
|
+
merge: labels => [...new Set(labels)],
|
|
329
|
+
summarize: label => label,
|
|
258
330
|
})
|
|
259
331
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
332
|
+
const CmsPost = Blog.Post.pipe(
|
|
333
|
+
Entity.annotate(Labels.of('Post')),
|
|
334
|
+
Entity.annotateMembers({ title: Labels.of('Title'), author: Labels.of('Byline') }),
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
Labels.get(CmsPost.fields.title.metadata) // ['Title']
|
|
338
|
+
Entity.same(CmsPost, Blog.Post) // true: the metadata changed, the entity did not
|
|
263
339
|
```
|
|
264
340
|
|
|
265
|
-
|
|
266
|
-
present value has to fit: a key may be optional (a partial update), admit
|
|
267
|
-
`null` (clearing it), or hold an `Option` (an id absent for something new),
|
|
268
|
-
which is the input schema's rule to make.
|
|
269
|
-
A declared write (`Write.update`, `Write.insert`) writes what an `Option`
|
|
270
|
-
holds and nothing for one holding nothing or a key left out; its id may not
|
|
271
|
-
be absent, since it names the row it writes.
|
|
272
|
-
- Every other key needs an entry: a Field under another name, a relation's ids
|
|
273
|
-
with `Relation.input(relation)`, or `Entity.unmapped`. Nothing is inferred
|
|
274
|
-
from a name like `authorId`.
|
|
275
|
-
- An entry may name the member by its key: `{ headline: 'title', authorId: 'author' }`
|
|
276
|
-
is the `title` Field and `Relation.input` of `author`. It is the same reading,
|
|
277
|
-
checked the same way; a name that is no field or relation is a type error.
|
|
278
|
-
- `Entity.fields(Post, 'id', 'title')` is those fields' schemas, to spread into
|
|
279
|
-
the input's struct, so the input keeps the field's rules without repeating
|
|
280
|
-
`Post.fields.title.schema` per key.
|
|
281
|
-
- `Relation.input` expects one id for a `one`, `id | null` for an optional
|
|
282
|
-
`one`, and an array of ids for a `many`.
|
|
283
|
-
- A derived member cannot be written, and a member of another Entity cannot be
|
|
284
|
-
mapped. Both are type errors and throw.
|
|
341
|
+
Annotating again combines with what is there, using the key's own `merge`.
|
|
285
342
|
|
|
286
|
-
###
|
|
343
|
+
### A schema's own words
|
|
287
344
|
|
|
288
|
-
A
|
|
289
|
-
|
|
345
|
+
A label or a help text written on a schema (`annotate({ title, description })`)
|
|
346
|
+
is read with `Words.of(schema)`, which gives each as an `Option`. Under Effect 4 a
|
|
347
|
+
schema with checks resolves to its **last check's** annotations, which say what
|
|
348
|
+
the check expects and carry no title, so
|
|
349
|
+
`Schema.String.annotate({ title: 'Name' }).check(Schema.isMinLength(1))` resolved
|
|
350
|
+
directly has no title. `Words.of` falls back to the schema's own annotations. A
|
|
351
|
+
form's labels, Crud's columns and the page Builder's inspector read words
|
|
352
|
+
through it.
|
|
290
353
|
|
|
291
354
|
```ts
|
|
292
|
-
|
|
355
|
+
import { Schema } from 'effect'
|
|
356
|
+
import { Words } from 'foldkit-entity'
|
|
293
357
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
Schema.Struct({ title: Schema.String, author: NewAuthor.schema }),
|
|
297
|
-
{ author: Relation.nested(Blog.Post.relations.author, NewAuthor) },
|
|
298
|
-
)
|
|
358
|
+
Words.of(Schema.String.annotate({ title: 'Name' }).check(Schema.isMinLength(1))).title
|
|
359
|
+
// Option.some('Name')
|
|
299
360
|
```
|
|
300
361
|
|
|
301
|
-
|
|
302
|
-
input must be of the relation's target, and both are checked by type and at
|
|
303
|
-
runtime. `Entity.selectFor` then loads what the nested input writes of the
|
|
304
|
-
target, and `Entity.valuesFor` turns the loaded target back into nested values.
|
|
305
|
-
What a nested write *does* (insert, update, replace the list) is the
|
|
306
|
-
operation's handler to decide.
|
|
362
|
+
## Saying something about a row: `Expr`
|
|
307
363
|
|
|
308
|
-
|
|
364
|
+
An Entity says what a domain has. An `Expr` says something about one row of it,
|
|
365
|
+
as a value:
|
|
309
366
|
|
|
310
|
-
|
|
311
|
-
|
|
367
|
+
> **Why query semantics live in this package.** They describe and interpret
|
|
368
|
+
> nothing, which is the line this package already draws: an `Expr` says which
|
|
369
|
+
> rows and fetches none of them, and the interpreters that *fetch* live
|
|
370
|
+
> elsewhere — `foldkit-remote-drizzle` compiles a body to SQL against a
|
|
371
|
+
> database.
|
|
372
|
+
>
|
|
373
|
+
> `evaluate` is here rather than there because it is the **reference
|
|
374
|
+
> semantics** of the IR: what the operator definitions mean, operationally, over
|
|
375
|
+
> rows already in hand. A specification's reference implementation belongs with
|
|
376
|
+
> the specification, and it reaches nothing — no database, no transport, no
|
|
377
|
+
> Remote concept. The rule that keeps it honest is that **it may depend on the
|
|
378
|
+
> IR and nothing else**; the moment it wants one of those it has moved to the
|
|
379
|
+
> wrong place. Nothing that imports only
|
|
380
|
+
> `Entity` pays for them: they are ordinary consts in a `sideEffects: false`
|
|
381
|
+
> package, so a bundler drops them, and a package like `foldkit-form` imports
|
|
382
|
+
> only types from here in any case.
|
|
312
383
|
|
|
313
384
|
```ts
|
|
314
|
-
|
|
315
|
-
// a Selection of `title` and `author`, the members the input writes; `author` as a ref
|
|
385
|
+
import { Expr, Order } from 'foldkit-entity'
|
|
316
386
|
|
|
317
|
-
|
|
318
|
-
|
|
387
|
+
const byTitle = Expr.eq(Blog.Post.fields.title, Expr.input('title', Schema.String))
|
|
388
|
+
const published = Expr.eq(Blog.Post.fields.published, true)
|
|
389
|
+
const newest = [Order.desc(Blog.Post.fields.title), Order.asc(Blog.Post.fields.id)]
|
|
319
390
|
```
|
|
320
391
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
unmapped key appears in neither, since the Entity knows nothing about it.
|
|
392
|
+
Building one performs no work: it reads nothing, names no database, and runs no
|
|
393
|
+
query. An interpreter compiles it — `foldkit-remote-drizzle` to SQL, an
|
|
394
|
+
in-memory evaluator to a predicate over rows — which is what lets one query mean
|
|
395
|
+
the same thing in more than one place.
|
|
326
396
|
|
|
327
|
-
|
|
328
|
-
value
|
|
329
|
-
|
|
397
|
+
A comparison coerces what it is given, so the common forms read as they mean: a
|
|
398
|
+
field becomes a reference, a plain value becomes a literal, and an `Expr` is
|
|
399
|
+
already one. What it will not do is compare a field to the wrong kind of value —
|
|
400
|
+
`Expr.eq(Blog.Post.fields.title, 42)` is an error where it is written, rather
|
|
401
|
+
than a row that never matches. The value's type comes from the left, so `eq` takes
|
|
402
|
+
the field on the left; `Expr.eq('Hello', Blog.Post.fields.title)` is refused with
|
|
403
|
+
that sentence. The comparisons (`lt`, `gte`, …) also take a field second,
|
|
404
|
+
wrapped in `Expr.field(…)`.
|
|
330
405
|
|
|
331
|
-
|
|
406
|
+
**An input is a placeholder, not a value.** A query's body is built once, so
|
|
407
|
+
`Expr.input('title', …)` stands for whatever the query is given when it runs —
|
|
408
|
+
there is nothing there yet to branch on. An `InputExpr` is an object, so a
|
|
409
|
+
`condition ? a : b` over one is always truthy and decides itself once, forever.
|
|
410
|
+
A query that depends on what it was passed says so with a comparison over the
|
|
411
|
+
placeholder instead of a branch around it.
|
|
332
412
|
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
a
|
|
336
|
-
|
|
413
|
+
`dependenciesOf(...)` says which fields and inputs an expression reads and which
|
|
414
|
+
operations it uses, so a planner knows what it needs and an interpreter can
|
|
415
|
+
refuse a query it cannot run. Each field names its `owner`, the Entity's
|
|
416
|
+
identity, as well as the Entity's name, so two Entities defined with the same
|
|
417
|
+
name are two entries.
|
|
337
418
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const Edit = Write.update(EditPost, { id: 'id' })
|
|
419
|
+
Every node is frozen as it is built, so a query is the value it was when
|
|
420
|
+
`Query.where` checked it: nothing can swap a field or a literal in afterwards.
|
|
341
421
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
422
|
+
A node can be shared (`Expr.eq(n, n)`), and the analysis visits each one once.
|
|
423
|
+
An interpreter does not: `evaluate` reads a predicate as a tree on every row,
|
|
424
|
+
and the SQL compiler writes a shared operand out wherever it appears. So a
|
|
425
|
+
query whose predicates and order terms expand past `maxQueryNodes` (1,000)
|
|
426
|
+
nodes, counting a shared node on each path that reaches it, is refused where
|
|
427
|
+
it is built.
|
|
346
428
|
|
|
347
|
-
|
|
348
|
-
an Entity having a field grants no one the right to set it. `bind` encodes each
|
|
349
|
-
value through its field's schema, so the patch is in the store's shape, and
|
|
350
|
-
takes the keys to write when an author changed only some. `expect` names a key
|
|
351
|
-
holding the revision the row was read at, for an interpreter to write only a row
|
|
352
|
-
still at it. An unmapped key is not written. A key mapped to a `one` relation
|
|
353
|
-
points the row elsewhere: `bind` gives it as a ref in `links` (none for an
|
|
354
|
-
optional relation set to nothing), and each interpreter carries it its own way,
|
|
355
|
-
a ref key in a store, a foreign key in a table. A `many` relation or a nested
|
|
356
|
-
key is refused where the write is declared.
|
|
429
|
+
### Asking a question that depends on an input, without branching on it
|
|
357
430
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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.
|
|
431
|
+
Since an input is a placeholder, a query cannot choose between two shapes based
|
|
432
|
+
on what it was given. It does not need to: a question that looks like a branch
|
|
433
|
+
is usually a comparison waiting to be written.
|
|
368
434
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
The field must be stored as a number, and may not be the id, the revision, or
|
|
379
|
-
set by another key. `Write.bind` gives the amounts apart from the values (`increments`), so a
|
|
380
|
-
client can add them to the value it holds as it reads it (Remote does), never
|
|
381
|
-
fixing a sum over a row that may since have moved. `Write.reads(write)` is what a write
|
|
382
|
-
reads from its row: what its `when` reads, each field it increments, what its
|
|
383
|
-
assignments read, and the revision. How a declaration, its guard, its writer and
|
|
384
|
-
the client fit together is the [declared writes guide](../../docs/declared-writes.md).
|
|
435
|
+
```ts
|
|
436
|
+
const Entry = Entity.define(
|
|
437
|
+
'Entry',
|
|
438
|
+
Schema.Struct({ id: Schema.String, label: Schema.String, archivedAt: Schema.NullOr(Schema.String) }),
|
|
439
|
+
)
|
|
440
|
+
const input = {
|
|
441
|
+
archived: Expr.input('archived', Schema.Boolean),
|
|
442
|
+
search: Expr.input('search', Schema.String),
|
|
443
|
+
}
|
|
385
444
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
operator such as the `concat` [below](#operators-each-interpreter-implements). It
|
|
389
|
-
reads neither the row after the write nor another Entity, so assignments never
|
|
390
|
-
depend on each other, and is refused where it is declared for a field another
|
|
391
|
-
key writes or a value of a kind the field does not store. A defined operator in
|
|
392
|
-
it is expanded there, so `Write.bind` carries it as data (`assignments`, each a
|
|
393
|
-
`Computation`: fields by key, values encoded, operators by name), which a writer
|
|
394
|
-
compiles into the statement and a client predicts by its own table. A
|
|
395
|
-
computation does not repeat without effect, so a retry of one is held to it as
|
|
396
|
-
an increment's is; without a revision it lands only under a ledger, and there
|
|
397
|
-
only where the writer pins the row it read (a guarded writer with a `revision`)
|
|
398
|
-
or by an operator whose commutativity and associativity are tested over every
|
|
399
|
-
value for each implementation the writer runs (`Conformance.laws` in memory,
|
|
400
|
-
`Conformance.lawsBy` in SQL).
|
|
445
|
+
// A list that shows archived entries or unarchived ones, as the reader asks:
|
|
446
|
+
Expr.eq(Expr.isNotNull(Entry.fields.archivedAt), input.archived)
|
|
401
447
|
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
it, a writer explains a miss by it, a client predicts it. `unknown` names each
|
|
406
|
-
field it could not work out (one the row lacks, or an operator the table lacks),
|
|
407
|
-
which keeps what the row holds.
|
|
448
|
+
// A search box that filters when something is typed and not when nothing is:
|
|
449
|
+
Expr.contains(Entry.fields.label, input.search)
|
|
450
|
+
```
|
|
408
451
|
|
|
409
|
-
|
|
452
|
+
The first is "is-archived equals what you asked for". The second relies on
|
|
453
|
+
everything containing the empty string. Both are one static body, and both ask
|
|
454
|
+
exactly what `archived ? … : …` and `search === '' ? … : …` asked.
|
|
410
455
|
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
`quantity = 3` decodes, and leaves a row that holds more reserved than there is.
|
|
414
|
-
An **invariant** is what every stored row must hold, read over the row after a
|
|
415
|
-
write (`after`):
|
|
456
|
+
`isNull` and `isNotNull` are the same node with the answer absence gives
|
|
457
|
+
flipped, so nothing has to negate a predicate to get the other.
|
|
416
458
|
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
459
|
+
**`contains` is case-insensitive**, which is what a search means — and which
|
|
460
|
+
has to be said, not left to the interpreter: SQLite's `like` ignores case and
|
|
461
|
+
Postgres's does not, so a body that left it open would mean two things. Folding
|
|
462
|
+
is ASCII-only, since that is what `lower` does in SQLite without ICU: `É` does
|
|
463
|
+
not match `é`, though each matches itself. Text holding a NUL character is
|
|
464
|
+
refused by every interpreter here, in `contains`, `eq` and `in` alike, since
|
|
465
|
+
Postgres text cannot hold one and SQLite compares only up to it.
|
|
420
466
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
467
|
+
**`in` asks whether a value is one of a list**, written out or given as an
|
|
468
|
+
input: `Expr.in(Todo.fields.projectId, input.projectIds)`. Each element is
|
|
469
|
+
compared as `eq` compares, and it reads as SQL's `in`: a null value is
|
|
470
|
+
unknown, so is no match against a list holding a null, and an empty list
|
|
471
|
+
matches no row (on Postgres too, which refuses `in ()`; the compiler says
|
|
472
|
+
`false` instead).
|
|
473
|
+
|
|
474
|
+
**It searches text, and the operand is constrained to text.** `contains` over a
|
|
475
|
+
number would compile to `lower(rank) like …`, which SQLite coerces into an
|
|
476
|
+
answer and Postgres rejects at runtime — so a non-text operand is a compile
|
|
477
|
+
error where it is written rather than a surprise where it runs. Nullable text is
|
|
478
|
+
allowed, because it is a real case with a real meaning:
|
|
479
|
+
|
|
480
|
+
**Over a column that can be null it is not the same as no filter.** A null
|
|
481
|
+
contains nothing, not even the empty string, so its rows drop out. The column
|
|
482
|
+
the CMS searches is declared not-null, which is what makes an empty search
|
|
483
|
+
exactly everything there.
|
|
484
|
+
|
|
485
|
+
### Who asks, and when: the context
|
|
486
|
+
|
|
487
|
+
A write's context is part of the language. `Expr.viewer(User)` is whoever
|
|
488
|
+
asks, as a User's id, and null for a visitor or a viewer of another Entity, so
|
|
489
|
+
a comparison with it holds of no row. `Expr.now` is the time, in milliseconds.
|
|
490
|
+
Neither is a field or an input: each interpreter reads them from the context
|
|
491
|
+
it is given.
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
const User = Entity.define('User', Schema.Struct({ id: Schema.String }))
|
|
495
|
+
const Note = Entity.define('Note', Schema.Struct({ id: Schema.String, ownerId: Schema.String }))
|
|
496
|
+
|
|
497
|
+
const Mine = Query.from(Note).pipe(
|
|
498
|
+
Query.where(Expr.eq(Note.fields.ownerId, Expr.viewer(User))),
|
|
424
499
|
)
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
500
|
+
const ada = { entity: 'User', id: 'ada' }
|
|
501
|
+
evaluate(Mine, {}, [{ id: 'n1', ownerId: 'ada' }, { id: 'n2', ownerId: 'bo' }], {
|
|
502
|
+
context: { viewer: Option.some(ada), now: Option.none() },
|
|
503
|
+
})
|
|
504
|
+
// [{ id: 'n1', ownerId: 'ada' }]
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
The viewer is a ref (`EntityRef`), so a viewer of another Entity reads null.
|
|
508
|
+
|
|
509
|
+
A server gives them from `RemoteServer.make({ viewer })` and its clock; a
|
|
510
|
+
client from `Remote.make({ viewer })`, with no reading of the time a server
|
|
511
|
+
judges a list at, so a list over `Expr.now` is the server's to say. A run
|
|
512
|
+
given no context, or no reading of a time it reads, refuses the body
|
|
513
|
+
(`ContextMissingError`) rather than reading a visitor or a null. A write's
|
|
514
|
+
computed assignment may not read them; a member whose value they give is
|
|
515
|
+
declared with `Entity.sets`.
|
|
516
|
+
|
|
517
|
+
### Which rows: `Query`
|
|
518
|
+
|
|
519
|
+
A `Query` is an Entity to read, the predicates every row must hold, and the
|
|
520
|
+
order to read them in — composed with `pipe`, one immutable value per step:
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
const published = Query.where(Expr.eq(Blog.Post.fields.published, true))
|
|
524
|
+
const newest = Query.orderBy(Order.desc(Blog.Post.fields.title))
|
|
525
|
+
|
|
526
|
+
const recent = Query.from(Blog.Post).pipe(published, newest)
|
|
527
|
+
const oneOf = Query.from(Blog.Post).pipe(published, Query.where(byTitle))
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
`published` and `newest` are fragments: written once, piped into any query over
|
|
531
|
+
the same Entity. Composing performs no work — no table is named, no connection
|
|
532
|
+
opened, nothing read. A fragment over another Entity is refused where it is
|
|
533
|
+
piped: a predicate's type names the Entities its fields belong to, so
|
|
534
|
+
`Query.from(Blog.Post).pipe(Query.where(Expr.eq(Blog.Comment.fields.body, 'x')))`
|
|
535
|
+
reads `a predicate reads Comment, but the query is from Post`, and an ordering
|
|
536
|
+
term over another Entity is refused by `Query.orderBy` the same way. The same check
|
|
537
|
+
runs again when the query is built, for what a type cannot see: a predicate
|
|
538
|
+
typed plainly as `Predicate`, or two Entities that share a name.
|
|
539
|
+
|
|
540
|
+
**Two `where`s conjoin and two `orderBy`s append.** Neither replaces what came
|
|
541
|
+
before, so piping a fragment can only ever narrow a query, never silently undo
|
|
542
|
+
part of it. An earlier ordering term stays the more significant one, which is
|
|
543
|
+
what makes a later `Query.orderBy(Order.asc(id))` a tie-breaker.
|
|
544
|
+
|
|
545
|
+
**A sort the reader picks is part of the body too.** `Order.chosen` maps each
|
|
546
|
+
name the input's sort can hold to a field, so the server and the client read one
|
|
547
|
+
declaration of what `title` means, and the client can tell which edits may move
|
|
548
|
+
a row:
|
|
549
|
+
|
|
550
|
+
```ts
|
|
551
|
+
const PostSort = Schema.NullOr(
|
|
552
|
+
Schema.Struct({ by: Schema.Literals(['title', 'id']), direction: Schema.Literals(['asc', 'desc']) }),
|
|
431
553
|
)
|
|
554
|
+
const sorted = (sort: InputExpr<typeof PostSort.Type>) =>
|
|
555
|
+
Query.from(Blog.Post).pipe(
|
|
556
|
+
Query.orderBy(Order.chosen(sort, { title: Blog.Post.fields.title, id: Blog.Post.fields.id })),
|
|
557
|
+
)
|
|
558
|
+
```
|
|
432
559
|
|
|
433
|
-
|
|
434
|
-
|
|
560
|
+
Every name the sort can hold needs a field, or it does not compile. A `null`
|
|
561
|
+
sort chooses none, and the terms after it decide. `foldkit-crud`'s
|
|
562
|
+
`Sort.make(['title', 'id']).Schema` is such a sort. `Query.orderFor(query, input)`
|
|
563
|
+
is the fixed terms for one input, which is what every interpreter sorts by.
|
|
564
|
+
|
|
565
|
+
**Every order is total.** `orderFor` ends it on the Entity's id, ascending,
|
|
566
|
+
unless the terms already read the id, so rows with equal keys come out in one
|
|
567
|
+
order on every interpreter rather than each breaking ties its own way.
|
|
568
|
+
|
|
569
|
+
**How text orders is declared, or left to the server.** Left unsaid, SQLite
|
|
570
|
+
compares bytes, Postgres follows the database's locale and a JavaScript sort
|
|
571
|
+
follows UTF-16 code units. A field declares its collation, and every
|
|
572
|
+
interpreter that can honour it orders the same; one that cannot refuses:
|
|
573
|
+
|
|
574
|
+
```ts
|
|
575
|
+
const Tagged = Entity.define('Tagged', Schema.Struct({ id: Schema.String, name: Schema.String })).pipe(
|
|
576
|
+
Entity.annotateMembers({ name: Collation.of(Collation.asciiFold) }),
|
|
577
|
+
)
|
|
578
|
+
const byName = Query.from(Tagged).pipe(Query.orderBy(Order.asc(Tagged.fields.name)))
|
|
579
|
+
Query.placement(byName, {}) // { _tag: 'Placeable' }
|
|
435
580
|
```
|
|
436
581
|
|
|
437
|
-
|
|
438
|
-
|
|
582
|
+
- `Collation.binary` is code point order: SQLite `BINARY`, Postgres
|
|
583
|
+
`COLLATE "C"`. An id is `binary` unless it says otherwise.
|
|
584
|
+
- `Collation.asciiFold` folds ASCII letters, then compares by code point:
|
|
585
|
+
SQLite `NOCASE`, Postgres `lower(x COLLATE "C")`.
|
|
586
|
+
- `Collation.locale('en-US')` is the backend's own, ordered on the server and
|
|
587
|
+
never by a client.
|
|
588
|
+
|
|
589
|
+
A term overrides its field's: `Order.asc(field, { collation })`.
|
|
590
|
+
`Query.placement(query, input, { operators })` says whether a client can order the rows exactly
|
|
591
|
+
as the server does: every term over a number or a boolean (a row may lack it), over text with a
|
|
592
|
+
portable collation, or a call whose primitive operators the client's table runs. A body with no
|
|
593
|
+
order, text with none declared, a locale, or an operator the table lacks is `NotPlaceable`, with
|
|
594
|
+
the reason.
|
|
595
|
+
|
|
596
|
+
The list of predicates **is** the conjunction: a query wanting three
|
|
597
|
+
conditions writes three `where`s. `Expr.and` is for a conjunction inside
|
|
598
|
+
something else, and `Expr.or` and `Expr.not` are the other two connectives:
|
|
439
599
|
|
|
440
600
|
```ts
|
|
441
|
-
const
|
|
442
|
-
'
|
|
443
|
-
Schema.Struct({
|
|
601
|
+
const Product = Entity.define(
|
|
602
|
+
'Product',
|
|
603
|
+
Schema.Struct({
|
|
604
|
+
id: Schema.String,
|
|
605
|
+
description: Schema.String,
|
|
606
|
+
upc: Schema.String,
|
|
607
|
+
status: Schema.String,
|
|
608
|
+
cents: Schema.Number,
|
|
609
|
+
}),
|
|
444
610
|
)
|
|
445
|
-
const
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
611
|
+
const filters = {
|
|
612
|
+
search: Expr.input('search', Schema.String),
|
|
613
|
+
status: Expr.input('status', Schema.NullOr(Schema.String)),
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// A search over two fields: a product whose description or UPC holds the text.
|
|
617
|
+
Expr.or(
|
|
618
|
+
Expr.contains(Product.fields.description, filters.search),
|
|
619
|
+
Expr.contains(Product.fields.upc, filters.search),
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
// A filter that applies only when its input is given (`filters.status` may be null).
|
|
623
|
+
Expr.whenGiven(filters.status, status => Expr.eq(Product.fields.status, status))
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
They mean what SQL's do, three-valued: a comparison of a null is unknown, a row
|
|
627
|
+
is kept only when its predicate is true, `or` takes true over unknown and `and`
|
|
628
|
+
takes false over it, and **`not` of an unknown is unknown**. So
|
|
629
|
+
`Expr.not(Expr.eq(field, 'draft'))` leaves out a row whose `field` is null;
|
|
630
|
+
"everything but drafts", nulls included, is
|
|
631
|
+
`Expr.or(Expr.isNull(field), Expr.not(Expr.eq(field, 'draft')))`. `and` and
|
|
632
|
+
`or` need an operand (an empty one would match every row, or none), a nested
|
|
633
|
+
one of the same kind is flattened into its parent, and one operand is that
|
|
634
|
+
operand. An interpreter that runs per request decides an operand that reads no
|
|
635
|
+
field before it writes anything: `whenGiven` compiles to `true`, which filters
|
|
636
|
+
nothing, when its input is null, and to the predicate alone when it is given.
|
|
637
|
+
|
|
638
|
+
**Comparisons** order two values: `Expr.lt`, `lte`, `gt` and `gte`.
|
|
639
|
+
|
|
640
|
+
```ts
|
|
641
|
+
Expr.lt(Product.fields.cents, 1000)
|
|
642
|
+
|
|
643
|
+
// A range of dates, stored as ISO strings, which order by time under binary:
|
|
644
|
+
const Shipment = Entity.define('Shipment', Schema.Struct({ id: Schema.String, shippedAt: Schema.String }))
|
|
645
|
+
const range = { from: Expr.input('from', Schema.String), until: Expr.input('until', Schema.String) }
|
|
646
|
+
Expr.and(
|
|
647
|
+
Expr.gte(Shipment.fields.shippedAt, range.from, { collation: Collation.binary }),
|
|
648
|
+
Expr.lt(Shipment.fields.shippedAt, range.until, { collation: Collation.binary }),
|
|
649
|
+
)
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
Numbers compare as numbers, and nothing compares across kinds or for a value
|
|
653
|
+
stored as neither a number nor text. Text orders by a collation, and backends disagree
|
|
654
|
+
about the default one (SQLite's `BINARY`, the Postgres database's locale,
|
|
655
|
+
JavaScript's UTF-16 units), so text is compared only under `Collation.binary`
|
|
656
|
+
or `Collation.asciiFold`, declared on the field or passed, and only against a
|
|
657
|
+
field: anything else is refused where the comparison is written. A value is
|
|
658
|
+
compared in its encoded form, which is why a date stored as an ISO string is
|
|
659
|
+
text here. A null on either side is unknown, as in SQL. There is no `between`;
|
|
660
|
+
it is the `and` above.
|
|
661
|
+
|
|
662
|
+
### Reading across relations: `Expr.path` and `Expr.exists`
|
|
663
|
+
|
|
664
|
+
A predicate may read the row a `one` relation points at, and ask whether any
|
|
665
|
+
row points at this one. Both start on the query's own row, so they belong in
|
|
666
|
+
its `where`:
|
|
667
|
+
|
|
668
|
+
```ts
|
|
669
|
+
const { Post, User, Follow } = Entity.relate(
|
|
670
|
+
{ Post: PostFields, User: UserFields, Follow: FollowFields },
|
|
671
|
+
{ Post: { author: Relation.one(UserFields) }, Follow: { followee: Relation.one(UserFields) } },
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
// Posts by a handle: a field of the row `author` points at.
|
|
675
|
+
const ByHandle = Query.from(Post).pipe(
|
|
676
|
+
Query.where(
|
|
677
|
+
Expr.eq(Expr.path(Post.relations.author, User.fields.handle), Expr.input('handle', Schema.String)),
|
|
451
678
|
),
|
|
679
|
+
Query.orderBy(Order.asc(Post.fields.id)),
|
|
452
680
|
)
|
|
453
681
|
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
682
|
+
// Posts whose author the reader follows: some Follow points at the author, and is theirs.
|
|
683
|
+
Expr.path(
|
|
684
|
+
Post.relations.author,
|
|
685
|
+
Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, Expr.input('me', Schema.String))),
|
|
686
|
+
)
|
|
457
687
|
```
|
|
458
688
|
|
|
459
|
-
|
|
689
|
+
(`packages/entity/test/readmePaths.test.ts` runs these, with the three Entities
|
|
690
|
+
it declares.)
|
|
691
|
+
|
|
692
|
+
- `Expr.path(relation, end)` follows a `one` relation, then reads `end` there:
|
|
693
|
+
a field, a further path, or an exists. A null link, or a row the reader may
|
|
694
|
+
not see, reaches no row, and the field reads null, as SQL's scalar subquery
|
|
695
|
+
does. At most four relations.
|
|
696
|
+
- `Expr.exists(relation, where?)` names the pointing edge, a `one` relation of
|
|
697
|
+
another Entity (`Follow.followee`), as `Derived.count` does. Only rows the
|
|
698
|
+
reader may see count. `where` reads the pointing row's own fields and the
|
|
699
|
+
input; anything past them is refused where it is written.
|
|
700
|
+
- A list does not order by a path.
|
|
701
|
+
|
|
702
|
+
A `one` relation is itself an operand: the id it points at, typed as the
|
|
703
|
+
target's id, and null where an optional one points nowhere. So a rule compares
|
|
704
|
+
the link, and no field over the same column has to repeat it:
|
|
705
|
+
|
|
706
|
+
```ts
|
|
707
|
+
// Posts by whoever asks: where `author` points.
|
|
708
|
+
const Mine = Query.from(Post).pipe(Query.where(Expr.eq(Post.relations.author, Expr.viewer(User))))
|
|
709
|
+
```
|
|
710
|
+
|
|
711
|
+
A row given to an interpreter holds the relation under its key as that id, as
|
|
712
|
+
`Held.rows` takes it; SQL reads the column the relation is stored on. A list
|
|
713
|
+
does not order by a link: a client holds it as a ref, not as the id it would
|
|
714
|
+
order by.
|
|
715
|
+
|
|
716
|
+
`foldkit-remote-drizzle` compiles both to subqueries under each reached
|
|
717
|
+
table's `visible` rule. `evaluate`, given one row, cannot follow them: it
|
|
718
|
+
refuses such a body, as it refuses any operation it does not run. `Judge`,
|
|
719
|
+
below, reads them from what a holder has.
|
|
720
|
+
|
|
721
|
+
### Judging what you hold: `Judge`
|
|
722
|
+
|
|
723
|
+
`evaluate` reads a missing key as null, which is right for a server holding
|
|
724
|
+
every row and wrong for a client holding some: "this field is null" and "I was
|
|
725
|
+
never sent it" are different answers. `Judge` reads a row as a holder has it
|
|
726
|
+
(`HeldRow`) and keeps the two apart:
|
|
727
|
+
|
|
728
|
+
```ts
|
|
729
|
+
const holder = Held.rows([
|
|
730
|
+
{ entity: Post, rows: [{ id: 'p1', body: 'hi', author: 'u1' }, { id: 'p2', body: 'yo', author: 'u2' }] },
|
|
731
|
+
// Ada is held; u2 is not, and this holder may lack users.
|
|
732
|
+
{ entity: User, rows: [{ id: 'u1', handle: 'ada' }], complete: false },
|
|
733
|
+
])
|
|
734
|
+
Judge.query(ByHandle, { handle: 'ada' }, Option.getOrThrow(holder.row(Post, 'p1')))
|
|
735
|
+
// { _tag: 'Known', truth: true }
|
|
736
|
+
Judge.query(ByHandle, { handle: 'ada' }, Option.getOrThrow(holder.row(Post, 'p2')))
|
|
737
|
+
// { _tag: 'Unknown', reason: 'User u2 is not held' }
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
A verdict is `Known` or `Unknown`. A known predicate's truth is SQL's three
|
|
741
|
+
values, its null decided (a row is not kept on it); unknown means the answer
|
|
742
|
+
rests on a field or row the holder lacks or may not see, or on an operator only
|
|
743
|
+
the server runs. What can decide anyway does: a null beside an unheld value,
|
|
744
|
+
`and`'s false, `or`'s true, an exists' held witness. An exists is false only
|
|
745
|
+
where the holder's `pointing` says it misses no row: it is given what the
|
|
746
|
+
filter fixes (`Pinned`, each `eq` of a field and a literal, an input or the
|
|
747
|
+
viewer), so a holder that holds every row with those values (a client's list
|
|
748
|
+
of whom the viewer follows) can say so without holding every pointing row.
|
|
749
|
+
`Judge.pins(predicates, { input, context })` works out what a conjunction
|
|
750
|
+
fixes, and whether that is all it says. `Judge.query(…, {
|
|
751
|
+
serverOnly })` names a filter the server adds that the holder does not run. The
|
|
752
|
+
law, checked against SQL by `foldkit-entity/conformance`'s `relationalCases`:
|
|
753
|
+
where `Judge` knows, it is what the server answers.
|
|
754
|
+
|
|
755
|
+
### Saying what an interpreter can run
|
|
756
|
+
|
|
757
|
+
An `Expr` is only portable if the thing running it says what it runs.
|
|
758
|
+
`Query.unsupported(query, supported)` names the operations a query needs that
|
|
759
|
+
an interpreter does not have:
|
|
760
|
+
|
|
761
|
+
```ts
|
|
762
|
+
const missing = Query.unsupported(ByHandle, ['eq', 'isNull', 'isNotNull'])
|
|
763
|
+
if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
|
|
764
|
+
```
|
|
765
|
+
|
|
766
|
+
The refusal belongs to the interpreter, not here: one that compiles at
|
|
767
|
+
registration and one that runs a body directly fail at different moments. What
|
|
768
|
+
matters is that it refuses rather than skipping the operation — an interpreter
|
|
769
|
+
that quietly drops a `contains` it cannot compile answers a different question
|
|
770
|
+
in full confidence, and every test it does support still passes.
|
|
771
|
+
|
|
772
|
+
### Reading one back
|
|
773
|
+
|
|
774
|
+
`Query.show(query)` renders a body as text, one clause per line. A list of
|
|
775
|
+
published posts by slug, newest first, reads:
|
|
460
776
|
|
|
461
777
|
```text
|
|
462
|
-
|
|
463
|
-
|
|
778
|
+
FROM Post
|
|
779
|
+
WHERE Post.slug = $slug
|
|
780
|
+
AND Post.published = true
|
|
781
|
+
ORDER BY Post.updatedAt DESC
|
|
464
782
|
```
|
|
465
783
|
|
|
466
|
-
|
|
784
|
+
For a person — an explanation, a diagnostic, a test asserting on a whole
|
|
785
|
+
predicate at once — and never for an interpreter. It is close enough to SQL to
|
|
786
|
+
read at a glance and unlike it everywhere that matters: an input is `$slug`
|
|
787
|
+
rather than a bound parameter, `contains` is named rather than rendered as
|
|
788
|
+
somebody's `like`, and no dialect's escaping or collation is implied. What
|
|
789
|
+
actually ran is whatever that backend compiled, which is not this.
|
|
790
|
+
`Expr.show(node)` does the same for one expression.
|
|
791
|
+
|
|
792
|
+
A `Query` says which rows. It does not say which fields — that is a Selection —
|
|
793
|
+
and it does not say how many, whether absence is an error, or whether to watch
|
|
794
|
+
for changes: those belong to the consumer doing the reading, not to the
|
|
795
|
+
relation.
|
|
796
|
+
|
|
797
|
+
Only the operations a real query in this repository needs exist. The set grows
|
|
798
|
+
from queries, not from what a database could express.
|
|
799
|
+
|
|
800
|
+
## Rows of several shapes: variants
|
|
467
801
|
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
802
|
+
> Experimental (#357): the Entity, its Selections and `Expr`. Remote's
|
|
803
|
+
> store, forms and guards read the stored row for now.
|
|
804
|
+
|
|
805
|
+
A domain search answers `Available`, with a price and a term, or
|
|
806
|
+
`Unconfirmed`, with neither. `Entity.defineVariants` declares that as one
|
|
807
|
+
Entity whose row is one of its cases, each case's fields by its tag, the shape
|
|
808
|
+
`Schema.TaggedUnion` takes:
|
|
471
809
|
|
|
472
810
|
```ts
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
811
|
+
const DomainName = { id: Schema.String, name: Schema.String }
|
|
812
|
+
const Domain = Entity.defineVariants('Domain', {
|
|
813
|
+
Available: { ...DomainName, price: Schema.Finite, years: Schema.Int },
|
|
814
|
+
Unconfirmed: DomainName,
|
|
815
|
+
})
|
|
816
|
+
|
|
817
|
+
// The row: Effect's tagged union of the cases, with its own `match`.
|
|
818
|
+
const priceOf = (row: typeof Domain.variants.Type) =>
|
|
819
|
+
Domain.variants.match(row, { Available: ({ price }) => price, Unconfirmed: () => 0 })
|
|
820
|
+
```
|
|
821
|
+
|
|
822
|
+
One Entity has two views of one row:
|
|
823
|
+
|
|
824
|
+
```text
|
|
825
|
+
row Domain.variants { _tag: 'Available', id, name, price, years }
|
|
826
|
+
| { _tag: 'Unconfirmed', id, name }
|
|
827
|
+
stored row Domain.fields { _tag, id, name, price | null, years | null }
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
- **The stored row** is what `fields` and `schema` describe: `_tag`, every
|
|
831
|
+
field all cases have as declared, and every other field nullable, since a
|
|
832
|
+
row of another case holds null there (a field whose stored form holds null
|
|
833
|
+
already, `Schema.OptionFromNullOr`, stays as it is). It is what every
|
|
834
|
+
interpreter reads, so a table, a Remote read and a form work as they do for
|
|
835
|
+
any Entity.
|
|
836
|
+
- **The row** is `Domain.variants`, branched on with its `match`, never by
|
|
837
|
+
reading which fields are null. `Entity.variantsOf(Domain)` holds the codec
|
|
838
|
+
between the two (`stored`): a stored row, encoded, decodes to its case, and
|
|
839
|
+
one holding another case's field is refused.
|
|
840
|
+
- **Each case says what it holds.** A case with fields of its own gets an
|
|
841
|
+
invariant (`variant_Available`: an Available holds `price` and `years`;
|
|
842
|
+
`variant_Unconfirmed`: an Unconfirmed holds none of them), so `Entity.judge`
|
|
843
|
+
and a form refuse a row that mixes cases, and `foldkit-remote-drizzle`
|
|
844
|
+
writes each as a CHECK.
|
|
845
|
+
|
|
846
|
+
A key in several cases is one stored field, so it is declared once and spread
|
|
847
|
+
into each, as `DomainName` is. Refused where declared: fewer than two cases, a
|
|
848
|
+
case declaring `_tag`, an optional key, and a key with two different schemas.
|
|
849
|
+
|
|
850
|
+
`Expr.is` narrows a predicate to a case. Given a function, it hands it the
|
|
851
|
+
case's fields typed as the case holds them, never null:
|
|
852
|
+
|
|
853
|
+
```ts
|
|
854
|
+
const CheapDomains = Query.from(Domain).pipe(
|
|
855
|
+
Query.where(Expr.is(Domain, 'Available', ({ price }) => Expr.lt(price, 20))),
|
|
477
856
|
)
|
|
478
|
-
|
|
857
|
+
```
|
|
479
858
|
|
|
480
|
-
|
|
481
|
-
|
|
859
|
+
It is `_tag = 'Available'` and the predicate, so it is false, not unknown, on
|
|
860
|
+
an Unconfirmed: `Expr.not` of it keeps every Unconfirmed, where
|
|
861
|
+
`Expr.not(Expr.lt(Domain.fields.price, 20))` drops them, since their stored
|
|
862
|
+
`price` is null. Given a `one` relation to a variant Entity, it reads the
|
|
863
|
+
case of the row the relation reaches, each field as a path (`Expr.is(
|
|
864
|
+
Cart.relations.domain, 'Available', …)`). Several cases at once are
|
|
865
|
+
`Expr.in(Domain.fields._tag, ['Available', 'Unconfirmed'])`.
|
|
866
|
+
|
|
867
|
+
A Selection that selects `_tag` reads the row as its case: its schema is a
|
|
868
|
+
tagged union whose cases hold the selected fields they have, typed as the
|
|
869
|
+
case holds them, and every selected relation and derived member.
|
|
870
|
+
|
|
871
|
+
```ts
|
|
872
|
+
const Quote = Entity.select(Domain, { _tag: true, name: true, price: true })
|
|
873
|
+
type Quote = Selected<typeof Quote>
|
|
874
|
+
// { _tag: 'Available', name: string, price: number } | { _tag: 'Unconfirmed', name: string }
|
|
875
|
+
const shown = (quote: Quote) =>
|
|
876
|
+
Quote.schema.match(quote, { Available: ({ price }) => `$${price}`, Unconfirmed: () => 'taken?' })
|
|
482
877
|
```
|
|
483
878
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
the Entity stays the same (`Entity.same`). Its interpreters read it from there.
|
|
488
|
-
- It reads stored rows only: one over another Entity, or reading an input, is
|
|
489
|
-
refused where it is declared, as is an id declared twice or a `path` naming no
|
|
490
|
-
field. So is one reading nothing of `after`: which rows a write may start from
|
|
491
|
-
is its `when`. Who may write is a guard's; whether a write applies now is its `when`'s.
|
|
492
|
-
- `Entity.judge(entity, { after, before? })` judges rows as the store holds them
|
|
493
|
-
(encoded) and is pure. Without `before` (a create) it skips transition
|
|
494
|
-
invariants. A row holds one only when it is true: a null fails it, as SQL's
|
|
495
|
-
unknown drops a row from a `WHERE`. A row without a field it reads is
|
|
496
|
-
`Undecided`, never `Valid`.
|
|
497
|
-
- `Entity.check(entity)` is the state invariants as a Schema check over the row
|
|
498
|
-
type (`entity.schema.check(Entity.check(entity))`): it encodes the value, and
|
|
499
|
-
reports each failure at its `path` with its `message`.
|
|
879
|
+
Without `_tag` a Selection is the stored row's Struct, and a field only some
|
|
880
|
+
cases have is refused there, at the type and where it is written: nothing
|
|
881
|
+
would say which case a row is.
|
|
500
882
|
|
|
501
|
-
|
|
502
|
-
needs `{ collation: Collation.binary }` on its comparison. An interpreter that
|
|
503
|
-
judges stored rows alone refuses `after`'s nodes as the operation `next`;
|
|
504
|
-
`Expr.substituteNext` reads the ones a write sets as their values.
|
|
883
|
+
## Reading an operation's input
|
|
505
884
|
|
|
506
|
-
|
|
885
|
+
> Experimental: the smallest mapping that several operation shapes and
|
|
886
|
+
> [`foldkit-form`](../form/README.md) needed.
|
|
507
887
|
|
|
508
|
-
An
|
|
509
|
-
|
|
888
|
+
An Entity does not decide what may be written; an operation does (a Remote
|
|
889
|
+
mutation, an RPC, a form). `Entity.input` takes that operation's input schema
|
|
890
|
+
and says what each key means in terms of the Entity, so a consumer can find the
|
|
891
|
+
field's metadata for a label, or the relation's target for a picker.
|
|
510
892
|
|
|
511
893
|
```ts
|
|
512
|
-
|
|
894
|
+
const CreatePostInput = Schema.Struct({
|
|
895
|
+
title: Schema.String,
|
|
896
|
+
authorId: Schema.String,
|
|
897
|
+
notify: Schema.Boolean,
|
|
898
|
+
})
|
|
513
899
|
|
|
514
|
-
const
|
|
515
|
-
|
|
516
|
-
|
|
900
|
+
const CreatePost = Entity.input(Blog.Post, CreatePostInput, {
|
|
901
|
+
authorId: Relation.input(Blog.Post.relations.author),
|
|
902
|
+
notify: Entity.unmapped,
|
|
517
903
|
})
|
|
518
904
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
905
|
+
CreatePost.members.title // Blog.Post.fields.title: it names a field, so it maps itself
|
|
906
|
+
CreatePost.members.authorId.relation.target() // Blog.Author: what a picker chooses from
|
|
907
|
+
CreatePost.members.notify // Entity.unmapped: about the operation, not the Post
|
|
908
|
+
```
|
|
523
909
|
|
|
524
|
-
|
|
525
|
-
|
|
910
|
+
- A key that names a field, with a value that fits it, maps itself. Only the
|
|
911
|
+
present value has to fit: a key may be optional (a partial update), admit
|
|
912
|
+
`null` (clearing it), or hold an `Option` (an id absent for something new),
|
|
913
|
+
which is the input schema's rule to make.
|
|
914
|
+
A declared write (`Write.update`, `Write.insert`) writes what an `Option`
|
|
915
|
+
holds and nothing for one holding nothing or a key left out; its id may not
|
|
916
|
+
be absent, since it names the row it writes.
|
|
917
|
+
- Every other key needs an entry: a Field under another name, a relation's ids
|
|
918
|
+
with `Relation.input(relation)`, or `Entity.unmapped`. Nothing is inferred
|
|
919
|
+
from a name like `authorId`.
|
|
920
|
+
- An entry may name the member by its key: `{ headline: 'title', authorId: 'author' }`
|
|
921
|
+
is the `title` Field and `Relation.input` of `author`. It is the same reading,
|
|
922
|
+
checked the same way; a name that is no field or relation is a type error.
|
|
923
|
+
- `Entity.fields(Post, 'id', 'title')` is those fields' schemas, to spread into
|
|
924
|
+
the input's struct, so the input keeps the field's rules without repeating
|
|
925
|
+
`Post.fields.title.schema` per key.
|
|
926
|
+
- `Relation.input` expects one id for a `one`, `id | null` for an optional
|
|
927
|
+
`one`, and an array of ids for a `many`.
|
|
928
|
+
- A derived member cannot be written, and a member of another Entity cannot be
|
|
929
|
+
mapped. Both are type errors and throw.
|
|
930
|
+
|
|
931
|
+
### An input that holds the target itself
|
|
932
|
+
|
|
933
|
+
A post created together with a new author carries the author, not an id.
|
|
934
|
+
`Relation.nested` maps the key to the relation and to an input of its target:
|
|
935
|
+
|
|
936
|
+
```ts
|
|
937
|
+
const NewAuthor = Entity.input(Blog.Author, Schema.Struct({ name: Schema.String }))
|
|
938
|
+
|
|
939
|
+
const CreatePost = Entity.input(
|
|
940
|
+
Blog.Post,
|
|
941
|
+
Schema.Struct({ title: Schema.String, author: NewAuthor.schema }),
|
|
942
|
+
{ author: Relation.nested(Blog.Post.relations.author, NewAuthor) },
|
|
943
|
+
)
|
|
526
944
|
```
|
|
527
945
|
|
|
528
|
-
|
|
946
|
+
A `one` holds the nested input's value, a `many` a list of them; the nested
|
|
947
|
+
input must be of the relation's target, and both are checked by type and at
|
|
948
|
+
runtime. `Entity.selectFor` then loads what the nested input writes of the
|
|
949
|
+
target, and `Entity.valuesFor` turns the loaded target back into nested values.
|
|
950
|
+
What a nested write *does* (insert, update, replace the list) is the
|
|
951
|
+
operation's handler to decide.
|
|
529
952
|
|
|
530
|
-
###
|
|
953
|
+
### Showing what is there
|
|
531
954
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
schema with checks resolves to its **last check's** annotations, which say what
|
|
535
|
-
the check expects and carry no title, so
|
|
536
|
-
`Schema.String.annotate({ title: 'Name' }).check(Schema.isMinLength(1))` resolved
|
|
537
|
-
directly has no title. `Words.of` falls back to the schema's own annotations. A
|
|
538
|
-
form's labels, Crud's columns and the page Builder's inspector read words
|
|
539
|
-
through it.
|
|
955
|
+
An edit screen has to load the current values and turn them into input values.
|
|
956
|
+
Both follow from the reading, so neither is written by hand:
|
|
540
957
|
|
|
541
958
|
```ts
|
|
542
|
-
|
|
543
|
-
|
|
959
|
+
const PostForEdit = Entity.selectFor(CreatePost)
|
|
960
|
+
// a Selection of `title` and `author`, the members the input writes; `author` as a ref
|
|
544
961
|
|
|
545
|
-
|
|
546
|
-
//
|
|
962
|
+
Entity.valuesFor(CreatePost, { title: 'Hello', author: { entity: 'Author', id: 'a1' } })
|
|
963
|
+
// { title: 'Hello', authorId: 'a1' }
|
|
547
964
|
```
|
|
548
965
|
|
|
549
|
-
|
|
966
|
+
`selectFor` selects every member the input writes, by the member's key, with
|
|
967
|
+
each relation as refs. `valuesFor` reads such a value back under the input's
|
|
968
|
+
keys: a field as it is, a relation as the id or ids of what it holds. A relation
|
|
969
|
+
read without its ids (a nested Selection that left `id` out) fills nothing. An
|
|
970
|
+
unmapped key appears in neither, since the Entity knows nothing about it.
|
|
550
971
|
|
|
551
|
-
|
|
552
|
-
|
|
972
|
+
The schema is an ordinary `Schema.Struct`, so declare it once and give the same
|
|
973
|
+
value to the operation, for example `Mutation.make('CreatePost', { Input:
|
|
974
|
+
CreatePostInput, … })` in `foldkit-remote`.
|
|
553
975
|
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
> `evaluate` is here rather than there because it is the **reference
|
|
561
|
-
> semantics** of the IR: what the operator definitions mean, operationally, over
|
|
562
|
-
> rows already in hand. A specification's reference implementation belongs with
|
|
563
|
-
> the specification, and it reaches nothing — no database, no transport, no
|
|
564
|
-
> Remote concept. The rule that keeps it honest is that **it may depend on the
|
|
565
|
-
> IR and nothing else**; the moment it wants one of those it has moved to the
|
|
566
|
-
> wrong place. Nothing that imports only
|
|
567
|
-
> `Entity` pays for them: they are ordinary consts in a `sideEffects: false`
|
|
568
|
-
> package, so a bundler drops them, and a package like `foldkit-form` imports
|
|
569
|
-
> only types from here in any case.
|
|
976
|
+
## Declaring what an input writes
|
|
977
|
+
|
|
978
|
+
An input says what each key *is*; a `Write` says what an operation *does* with
|
|
979
|
+
them: `Write.update` one row, named by a key, setting every other key mapped to
|
|
980
|
+
a field; `Write.insert` a row under an id the client chose; or `Write.delete`
|
|
981
|
+
one, which sets nothing.
|
|
570
982
|
|
|
571
983
|
```ts
|
|
572
|
-
import {
|
|
984
|
+
import { Write } from 'foldkit-entity'
|
|
573
985
|
|
|
574
|
-
const
|
|
575
|
-
const
|
|
576
|
-
const
|
|
986
|
+
const EditPostInput = Schema.Struct({ id: Schema.String, title: Schema.String })
|
|
987
|
+
const EditPost = Entity.input(Blog.Post, EditPostInput)
|
|
988
|
+
const Edit = Write.update(EditPost, { id: 'id' })
|
|
989
|
+
|
|
990
|
+
Write.writes(Edit) // the fields and `one` relations any invocation may change
|
|
991
|
+
Write.bind(Edit, { id: 'p1', title: 'Compilers' })
|
|
992
|
+
// { entity: 'Post', id: 'p1', values: { title: 'Compilers' }, links: {}, increments: {}, assignments: {} }
|
|
577
993
|
```
|
|
578
994
|
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
the
|
|
995
|
+
It is declared data, like a query body: nothing is written by building one, and
|
|
996
|
+
an Entity having a field grants no one the right to set it. `bind` encodes each
|
|
997
|
+
value through its field's schema, so the patch is in the store's shape, and
|
|
998
|
+
takes the keys to write when an author changed only some. `expect` names a key
|
|
999
|
+
holding the revision the row was read at, for an interpreter to write only a row
|
|
1000
|
+
still at it. An unmapped key is not written. A key mapped to a `one` relation
|
|
1001
|
+
points the row elsewhere: `bind` gives it as a ref in `links` (none for an
|
|
1002
|
+
optional relation set to nothing), and each interpreter carries it its own way,
|
|
1003
|
+
a ref key in a store, a foreign key in a table. A `many` relation or a nested
|
|
1004
|
+
key is refused where the write is declared.
|
|
583
1005
|
|
|
584
|
-
|
|
585
|
-
field becomes a reference, a plain value becomes a literal, and an `Expr` is
|
|
586
|
-
already one. What it will not do is compare a field to the wrong kind of value —
|
|
587
|
-
`Expr.eq(Blog.Post.fields.title, 42)` is an error where it is written, rather
|
|
588
|
-
than a row that never matches. The value's type comes from the left, so `eq` takes
|
|
589
|
-
the field on the left; `Expr.eq('Hello', Blog.Post.fields.title)` is refused with
|
|
590
|
-
that sentence. The comparisons (`lt`, `gte`, …) also take a field second,
|
|
591
|
-
wrapped in `Expr.field(…)`.
|
|
1006
|
+
### Values no client chooses: `Entity.sets`
|
|
592
1007
|
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
`
|
|
597
|
-
A query that depends on what it was passed says so with a comparison over the
|
|
598
|
-
placeholder instead of a branch around it.
|
|
1008
|
+
Some values no client should choose: who wrote a row, and when. The Entity
|
|
1009
|
+
says so once, with `Entity.sets`, after `Entity.relate` when it names a
|
|
1010
|
+
relation. A value is a term of the write's context, `Expr.viewer` or
|
|
1011
|
+
`Expr.now`, and `on` says which writes set it:
|
|
599
1012
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
identity, as well as the Entity's name, so two Entities defined with the same
|
|
604
|
-
name are two entries.
|
|
1013
|
+
```ts
|
|
1014
|
+
const AuthoredPost = Blog.Post.pipe(Entity.sets({ author: Expr.viewer(Author) }, { on: 'create' }))
|
|
1015
|
+
```
|
|
605
1016
|
|
|
606
|
-
|
|
607
|
-
|
|
1017
|
+
`Expr.viewer(Author)` is whoever asks: a `one` relation to an Author pointed
|
|
1018
|
+
at them, or a field stored as text holding their id. `Expr.now` is the time,
|
|
1019
|
+
for a field stored as a number. A path from the viewer is what their row, or
|
|
1020
|
+
a row reached from it, holds: `Expr.path(Expr.viewer(Member),
|
|
1021
|
+
Expr.path(Member.relations.team, Team.fields.orgId))` sets a note's `orgId` to
|
|
1022
|
+
its writer's team's, for a field that holds what the path's end holds. A
|
|
1023
|
+
server reads it through its own sources as the asker may see them; a client
|
|
1024
|
+
reads it from the rows it holds, and predicts nothing where it lacks one. A
|
|
1025
|
+
query body or a guard rule compares with one as with any value
|
|
1026
|
+
(`Expr.eq(Note.fields.orgId, orgOfViewer)`): SQL reads it in subqueries under
|
|
1027
|
+
each reached table's `visible` rule, and `Judge` from the rows its holder has
|
|
1028
|
+
(`rows`), unknown where it lacks the viewer's row.
|
|
1029
|
+
|
|
1030
|
+
`on: 'create'` sets the member on every insert; `on: 'write'` on every insert
|
|
1031
|
+
and every update (an `editedAt`). A delete sets nothing. Every write of the
|
|
1032
|
+
Entity follows from this one declaration (`write.context`), and a write whose
|
|
1033
|
+
input sets, links, moves or computes such a member is refused where it is
|
|
1034
|
+
declared. `Write.contextValues(write, { viewer, now }, read)` works out what
|
|
1035
|
+
they come to, `read` giving one member of one row at a time for a path. Each interpreter fills them from what
|
|
1036
|
+
it has: a server from its principal and its clock, a client as a prediction. A
|
|
1037
|
+
value that comes to null where the member holds none (a visitor) is named
|
|
1038
|
+
`unfilled`: a server refuses the write, a client predicts nothing for it.
|
|
1039
|
+
Nothing else about what a write does is declared anywhere: what it moves is
|
|
1040
|
+
read from the Entities' derived members and the queries' bodies.
|
|
1041
|
+
|
|
1042
|
+
### When a write applies: `when`
|
|
608
1043
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
1044
|
+
An update or a delete may also say when it makes sense: `when` is what the row
|
|
1045
|
+
must hold for it to land, written as a query body is: `() =>
|
|
1046
|
+
Expr.eq(Post.fields.title, 'Draft')`, or with the input, `({ input }) =>
|
|
1047
|
+
Expr.eq(Post.fields.title, input.from)`. It reads the row as it is before the write and the input,
|
|
1048
|
+
never who is asking (that is a guard's), and only its own Entity: a field of
|
|
1049
|
+
another is a type error, and refused where the write is declared. It is held as
|
|
1050
|
+
a query body (`write.when`), so an interpreter checks it in the statement that
|
|
1051
|
+
writes, and a row it does not hold of is refused as unmet. A write declared with
|
|
1052
|
+
one is a `ConditionedWrite`, which is how `Mutation.write` knows it may be
|
|
1053
|
+
refused so.
|
|
616
1054
|
|
|
617
|
-
###
|
|
1055
|
+
### Moving a number: `increment`
|
|
618
1056
|
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
1057
|
+
An update may move a number field by an amount the input holds, rather than set
|
|
1058
|
+
it: `increment: { stock: 'quantity' }` adds the input's `quantity` (an unmapped
|
|
1059
|
+
key, a number; negative takes away) to the stored `stock`, in the statement that
|
|
1060
|
+
writes, so no concurrent change is lost. A retry must not add twice, so either it
|
|
1061
|
+
expects a revision (a retry of a write that landed is then a conflict), or its
|
|
1062
|
+
writer keeps a ledger, which answers the retry from its record and lets two
|
|
1063
|
+
concurrent increments both land. `RemoteServer.write` refuses one with neither,
|
|
1064
|
+
and one of a real number with no revision even under a ledger: floating-point
|
|
1065
|
+
addition does not associate, so two concurrent sums could land as two results.
|
|
1066
|
+
The field must be stored as a number, and may not be the id, the revision, or
|
|
1067
|
+
set by another key. `Write.bind` gives the amounts apart from the values (`increments`), so a
|
|
1068
|
+
client can add them to the value it holds as it reads it (Remote does), never
|
|
1069
|
+
fixing a sum over a row that may since have moved. `Write.reads(write)` is what a write
|
|
1070
|
+
reads from its row: what its `when` reads, each field it increments, what its
|
|
1071
|
+
assignments read, and the revision. How a declaration, its guard, its writer and
|
|
1072
|
+
the client fit together is the [declared writes guide](../../docs/declared-writes.md).
|
|
622
1073
|
|
|
623
|
-
|
|
624
|
-
// A list that shows archived entries or unarchived ones, as the reader asks:
|
|
625
|
-
Expr.eq(Expr.isNotNull(Entry.fields.archivedAt), input.archived)
|
|
1074
|
+
### Computing a field: `compute`
|
|
626
1075
|
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
1076
|
+
An update may also compute a field from the row before it and the input:
|
|
1077
|
+
`compute: { label: ({ row, input }) => concat(input.prefix, row.name) }`, with an
|
|
1078
|
+
operator such as the `concat` [below](#operators-each-interpreter-implements). It
|
|
1079
|
+
reads neither the row after the write nor another Entity, so assignments never
|
|
1080
|
+
depend on each other, and is refused where it is declared for a field another
|
|
1081
|
+
key writes or a value of a kind the field does not store. A defined operator in
|
|
1082
|
+
it is expanded there, so `Write.bind` carries it as data (`assignments`, each a
|
|
1083
|
+
`Computation`: fields by key, values encoded, operators by name), which a writer
|
|
1084
|
+
compiles into the statement and a client predicts by its own table. A
|
|
1085
|
+
computation does not repeat without effect, so a retry of one is held to it as
|
|
1086
|
+
an increment's is; without a revision it lands only under a ledger, and there
|
|
1087
|
+
only where the writer pins the row it read (a guarded writer with a `revision`)
|
|
1088
|
+
or by an operator whose commutativity and associativity are tested over every
|
|
1089
|
+
value for each implementation the writer runs (`Conformance.laws` in memory,
|
|
1090
|
+
`Conformance.lawsBy` in SQL).
|
|
630
1091
|
|
|
631
|
-
The
|
|
632
|
-
everything containing the empty string. Both are one static body, and both ask
|
|
633
|
-
exactly what `archived ? … : …` and `search === '' ? … : …` asked.
|
|
1092
|
+
### The row a write leaves: `Write.apply`
|
|
634
1093
|
|
|
635
|
-
`
|
|
636
|
-
|
|
1094
|
+
`Write.apply(row, bound, { operators })` is the row a bound write leaves over
|
|
1095
|
+
the row before it: values set, amounts added (a null stays null, as in SQL),
|
|
1096
|
+
assignments computed. It is the one computation of that row: a guard judges
|
|
1097
|
+
it, a writer explains a miss by it, a client predicts it. `unknown` names each
|
|
1098
|
+
field it could not work out (one the row lacks, or an operator the table lacks),
|
|
1099
|
+
which keeps what the row holds.
|
|
637
1100
|
|
|
638
|
-
|
|
639
|
-
has to be said, not left to the interpreter: SQLite's `like` ignores case and
|
|
640
|
-
Postgres's does not, so a body that left it open would mean two things. Folding
|
|
641
|
-
is ASCII-only, since that is what `lower` does in SQLite without ICU: `É` does
|
|
642
|
-
not match `é`, though each matches itself. Text holding a NUL character is
|
|
643
|
-
refused by every interpreter here, in `contains`, `eq` and `in` alike, since
|
|
644
|
-
Postgres text cannot hold one and SQLite compares only up to it.
|
|
1101
|
+
### What a client foresees of a supplied member
|
|
645
1102
|
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
unknown, so is no match against a list holding a null, and an empty list
|
|
650
|
-
matches no row (on Postgres too, which refuses `in ()`; the compiler says
|
|
651
|
-
`false` instead).
|
|
1103
|
+
A count or an exists says what it is, so a client predicts it for a row it
|
|
1104
|
+
writes. A `Derived.make` member says nothing, so a client waits for the server,
|
|
1105
|
+
unless it says how to foresee it:
|
|
652
1106
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
1107
|
+
- `Derived.make(schema, { predict })`: `predict({ entity, row, rows, context })`
|
|
1108
|
+
reads the row the write leaves as the holder has it (a `HeldRow`, with the
|
|
1109
|
+
holder's other `rows` and the write's `context`) and returns the value,
|
|
1110
|
+
encoded, or none where it cannot know.
|
|
1111
|
+
- `Derived.make(schema, { forbids })`: `forbids(value, surface)` says which
|
|
1112
|
+
write to a row the value refuses. `surface` is a `WriteSurface` (`kind`
|
|
1113
|
+
`Update` or `Delete`, the `members` it writes, the `relations` it points as
|
|
1114
|
+
`Link` or `Unlink`), and the answer is `Option<{ reason }>`, only for a
|
|
1115
|
+
definite refusal. A client holding the value refuses that write where it is
|
|
1116
|
+
made, showing and sending nothing.
|
|
658
1117
|
|
|
659
|
-
|
|
660
|
-
contains nothing, not even the empty string, so its rows drop out. The column
|
|
661
|
-
the CMS searches is declared not-null, which is what makes an empty search
|
|
662
|
-
exactly everything there.
|
|
1118
|
+
`foldkit-guard`'s `may` declares both.
|
|
663
1119
|
|
|
664
|
-
|
|
1120
|
+
## What every row and change must hold: invariants
|
|
665
1121
|
|
|
666
|
-
A
|
|
667
|
-
|
|
1122
|
+
A Schema judges a value, and a write's `when` the row before it. Neither judges
|
|
1123
|
+
the row a write leaves: with `quantity = 10, reserved = 5`, an update setting
|
|
1124
|
+
`quantity = 3` decodes, and leaves a row that holds more reserved than there is.
|
|
1125
|
+
An **invariant** is what every stored row must hold, read over the row after a
|
|
1126
|
+
write (`after`):
|
|
668
1127
|
|
|
669
1128
|
```ts
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
const recent = Query.from(Blog.Post).pipe(published, newest)
|
|
674
|
-
const oneOf = Query.from(Blog.Post).pipe(published, Query.where(byTitle))
|
|
675
|
-
```
|
|
1129
|
+
import { Schema } from 'effect'
|
|
1130
|
+
import { Entity, Expr } from 'foldkit-entity'
|
|
676
1131
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
1132
|
+
const InventoryFields = Entity.define(
|
|
1133
|
+
'Inventory',
|
|
1134
|
+
Schema.Struct({ id: Schema.String, quantity: Schema.Number, reserved: Schema.Number }),
|
|
1135
|
+
)
|
|
1136
|
+
const Inventory = InventoryFields.pipe(
|
|
1137
|
+
Entity.invariant(
|
|
1138
|
+
'reservedWithinQuantity',
|
|
1139
|
+
({ after }) => Expr.lte(after.reserved, after.quantity),
|
|
1140
|
+
{ message: 'Reserved stock cannot exceed the quantity', path: ['reserved'] },
|
|
1141
|
+
),
|
|
1142
|
+
)
|
|
686
1143
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
what makes a later `Query.orderBy(Order.asc(id))` a tie-breaker. Neither ever replaces what a fragment added.
|
|
1144
|
+
Entity.judge(Inventory, { after: { id: 'i1', quantity: 3, reserved: 5 } })
|
|
1145
|
+
// { _tag: 'Invalid', failures: [{ id: 'reservedWithinQuantity', … }] }
|
|
1146
|
+
```
|
|
691
1147
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
declaration of what `title` means, and the client can tell which edits may move
|
|
695
|
-
a row:
|
|
1148
|
+
One that reads the row before too (`before`) relates the two, each of which may
|
|
1149
|
+
be valid on its own: an order that shipped stays shipped.
|
|
696
1150
|
|
|
697
1151
|
```ts
|
|
698
|
-
const
|
|
699
|
-
|
|
1152
|
+
const OrderFields = Entity.define(
|
|
1153
|
+
'Order',
|
|
1154
|
+
Schema.Struct({ id: Schema.String, status: Schema.Literals(['placed', 'shipped']) }),
|
|
1155
|
+
)
|
|
1156
|
+
const Order = OrderFields.pipe(
|
|
1157
|
+
Entity.invariant(
|
|
1158
|
+
'shippedStaysShipped',
|
|
1159
|
+
({ before, after }) =>
|
|
1160
|
+
Expr.or(Expr.not(Expr.eq(before.status, 'shipped')), Expr.eq(after.status, 'shipped')),
|
|
1161
|
+
{ message: 'A shipped order stays shipped', path: ['status'] },
|
|
1162
|
+
),
|
|
700
1163
|
)
|
|
701
|
-
const sorted = (sort: InputExpr<typeof PostSort.Type>) =>
|
|
702
|
-
Query.from(Blog.Post).pipe(
|
|
703
|
-
Query.orderBy(Order.chosen(sort, { title: Blog.Post.fields.title, id: Blog.Post.fields.id })),
|
|
704
|
-
)
|
|
705
|
-
```
|
|
706
|
-
|
|
707
|
-
Every name the sort can hold needs a field, or it does not compile. A `null`
|
|
708
|
-
sort chooses none, and the terms after it decide. `Query.orderFor(query, input)`
|
|
709
|
-
is the fixed terms for one input, which is what every interpreter sorts by.
|
|
710
1164
|
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
1165
|
+
const shipped = { id: 'o1', status: 'shipped' }
|
|
1166
|
+
Entity.judge(Order, { before: shipped, after: { ...shipped, status: 'placed' } })
|
|
1167
|
+
// { _tag: 'Invalid', failures: [{ id: 'shippedStaysShipped', … }] }
|
|
1168
|
+
```
|
|
714
1169
|
|
|
715
|
-
|
|
716
|
-
compares bytes, Postgres follows the database's locale and a JavaScript sort
|
|
717
|
-
follows UTF-16 code units. A field declares its collation, and every
|
|
718
|
-
interpreter that can honour it orders the same; one that cannot refuses:
|
|
1170
|
+
What an invariant reads decides when it is judged; nothing else is declared:
|
|
719
1171
|
|
|
720
|
-
```
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
)
|
|
724
|
-
const byName = Query.from(Tagged).pipe(Query.orderBy(Order.asc(Tagged.fields.name)))
|
|
725
|
-
Query.placement(byName, {}) // { _tag: 'Placeable' }
|
|
1172
|
+
```text
|
|
1173
|
+
reads after only -> state invariant: every create and update; a CHECK constraint
|
|
1174
|
+
reads before too -> transition invariant: every update, the only write with a row before
|
|
726
1175
|
```
|
|
727
1176
|
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
- `Collation.asciiFold` folds ASCII letters, then compares by code point:
|
|
731
|
-
SQLite `NOCASE`, Postgres `lower(x COLLATE "C")`.
|
|
732
|
-
- `Collation.locale('en-US')` is the backend's own, ordered on the server and
|
|
733
|
-
never by a client.
|
|
1177
|
+
`Entity.readsBefore(invariant)` says which one is, for each of
|
|
1178
|
+
`Entity.invariants(entity)`.
|
|
734
1179
|
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
order, text with none declared, a locale, or an operator the table lacks is `NotPlaceable`, with
|
|
740
|
-
the reason.
|
|
741
|
-
`foldkit-crud`'s `Sort.make(['title', 'id']).Schema` is such a sort.
|
|
1180
|
+
`before` and `after` hold each field as the store does, encoded, and are typed
|
|
1181
|
+
so: a date stored as ISO text is compared with ISO text
|
|
1182
|
+
(`Expr.eq(after.at, '2026-01-01T00:00:00.000Z')`), since a `Date` would never
|
|
1183
|
+
equal it.
|
|
742
1184
|
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
1185
|
+
A `one` relation is there too, as the id it points at, as it is in a query
|
|
1186
|
+
or a guard: a rule over where a row points stays on the Entity, judged with
|
|
1187
|
+
the rest, and compiles to a CHECK over the columns the relations are stored
|
|
1188
|
+
on. Pipe it onto the Entity `Entity.relate` returned, which has them:
|
|
1189
|
+
|
|
1190
|
+
<!-- docs-check
|
|
1191
|
+
import { Relation } from 'foldkit-entity'
|
|
1192
|
+
-->
|
|
746
1193
|
|
|
747
1194
|
```ts
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
1195
|
+
const PersonFields = Entity.define('Person', Schema.Struct({ id: Schema.String }))
|
|
1196
|
+
const Social = Entity.relate(
|
|
1197
|
+
{ Person: PersonFields, Follow: Entity.define('Follow', Schema.Struct({ id: Schema.String })) },
|
|
1198
|
+
{ Follow: { follower: Relation.one(PersonFields), followee: Relation.one(PersonFields) } },
|
|
1199
|
+
)
|
|
1200
|
+
const Follow = Social.Follow.pipe(
|
|
1201
|
+
Entity.invariant('notSelf', ({ after }) => Expr.not(Expr.eq(after.follower, after.followee)), {
|
|
1202
|
+
message: 'You cannot follow yourself',
|
|
1203
|
+
path: ['followee'],
|
|
1204
|
+
}),
|
|
752
1205
|
)
|
|
753
1206
|
|
|
754
|
-
|
|
755
|
-
|
|
1207
|
+
Entity.judge(Follow, { after: { id: 'f1', follower: 'ada', followee: 'ada' } })
|
|
1208
|
+
// { _tag: 'Invalid', failures: [{ id: 'notSelf', … }] }
|
|
756
1209
|
```
|
|
757
1210
|
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
`Expr.not(Expr.eq(field, 'draft'))` leaves out a row whose `field` is null;
|
|
762
|
-
"everything but drafts", nulls included, is
|
|
763
|
-
`Expr.or(Expr.isNull(field), Expr.not(Expr.eq(field, 'draft')))`. `and` and
|
|
764
|
-
`or` need an operand (an empty one would match every row, or none), a nested
|
|
765
|
-
one of the same kind is flattened into its parent, and one operand is that
|
|
766
|
-
operand. An interpreter that runs per request decides an operand that reads no
|
|
767
|
-
field before it writes anything: `whenGiven` compiles to `true`, which filters
|
|
768
|
-
nothing, when its input is null, and to the predicate alone when it is given.
|
|
1211
|
+
A row judged holds each relation it reads as that id (null where an optional
|
|
1212
|
+
one points nowhere); `Entity.judgeInput` reads an input key mapped to the
|
|
1213
|
+
relation as it. A `many` relation holds no one value, so it is not there.
|
|
769
1214
|
|
|
770
|
-
|
|
1215
|
+
`Entity.invariant` returns the step that attaches it, carrying its `id` and,
|
|
1216
|
+
once attached, its Entity's name as `entity`: an id is unique only within an
|
|
1217
|
+
Entity, so a refusal names both. A declaration attaches to one Entity; reading
|
|
1218
|
+
`entity` before it is attached throws. Hoist it to export it, naming the
|
|
1219
|
+
Entity's type (what it reads is checked against it), and match a refusal
|
|
1220
|
+
against it rather than spelling the id again:
|
|
771
1221
|
|
|
772
1222
|
```ts
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
Expr.
|
|
776
|
-
|
|
777
|
-
Expr.lt(Shipment.fields.shippedAt, input.until, { collation: Collation.binary }),
|
|
1223
|
+
export const reservedWithinQuantity = Entity.invariant<typeof InventoryFields>(
|
|
1224
|
+
'reservedWithinQuantity',
|
|
1225
|
+
({ after }) => Expr.lte(after.reserved, after.quantity),
|
|
1226
|
+
{ message: 'Reserved stock cannot exceed the quantity', path: ['reserved'] },
|
|
778
1227
|
)
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
Numbers compare as numbers, and nothing compares across kinds or for a value
|
|
782
|
-
stored as neither a number nor text. Text orders by a collation, and backends disagree
|
|
783
|
-
about the default one (SQLite's `BINARY`, the Postgres database's locale,
|
|
784
|
-
JavaScript's UTF-16 units), so text is compared only under `Collation.binary`
|
|
785
|
-
or `Collation.asciiFold`, declared on the field or passed, and only against a
|
|
786
|
-
field: anything else is refused where the comparison is written. A value is
|
|
787
|
-
compared in its encoded form, which is why a date stored as an ISO string is
|
|
788
|
-
text here. A null on either side is unknown, as in SQL. There is no `between`;
|
|
789
|
-
it is the `and` above.
|
|
790
|
-
|
|
791
|
-
A query reads one Entity, so a predicate or ordering term naming a different
|
|
792
|
-
one is refused where it is piped: an interpreter would otherwise be asked for a
|
|
793
|
-
column of a table it was never told to read. Entities are compared by identity,
|
|
794
|
-
so two declared with the same name are two Entities here as everywhere else.
|
|
1228
|
+
export const Inventory = InventoryFields.pipe(reservedWithinQuantity)
|
|
795
1229
|
|
|
796
|
-
|
|
1230
|
+
// Where a write's refusal is read (foldkit-remote):
|
|
1231
|
+
Refusal.isInvalidBy(refusal, reservedWithinQuantity)
|
|
1232
|
+
```
|
|
797
1233
|
|
|
798
|
-
|
|
799
|
-
`
|
|
800
|
-
an
|
|
1234
|
+
- `before` is each field as the row before holds it (`Expr.field`), and `after`
|
|
1235
|
+
each as the row after holds it (`Expr.next`), both typed as the field. Each
|
|
1236
|
+
is an expression already, so it goes on either side as it is; `Expr.field`
|
|
1237
|
+
wraps an Entity's own field, and refuses one of these:
|
|
801
1238
|
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
1239
|
+
| Write | Not |
|
|
1240
|
+
| --- | --- |
|
|
1241
|
+
| `Expr.gte(after.quantity, before.quantity)` | `Expr.gte(after.quantity, Expr.field(before.quantity))` |
|
|
1242
|
+
- It is declared once, on the Entity's metadata, and attaching more adds to it;
|
|
1243
|
+
the Entity stays the same (`Entity.same`). Its interpreters read it from there.
|
|
1244
|
+
- It reads stored rows only: one over another Entity, or reading an input, is
|
|
1245
|
+
refused where it is declared, as is an id declared twice or a `path` naming
|
|
1246
|
+
neither a field nor a `one` relation. So is one reading nothing of `after`: which rows a write may start from
|
|
1247
|
+
is its `when`. Who may write is a guard's; whether a write applies now is its `when`'s.
|
|
1248
|
+
- `Entity.judge(entity, { after, before? })` judges rows as the store holds them
|
|
1249
|
+
(encoded) and is pure. Without `before` (a create) it skips transition
|
|
1250
|
+
invariants. A row holds one only when it is true: a null fails it, as SQL's
|
|
1251
|
+
unknown drops a row from a `WHERE`. A row without a field it reads is
|
|
1252
|
+
`Undecided`, never `Valid`.
|
|
1253
|
+
- `Entity.check(entity)` is the state invariants as a Schema check over the row
|
|
1254
|
+
type (`entity.schema.check(Entity.check(entity))`): it encodes the value, and
|
|
1255
|
+
reports each failure at its `path` with its `message`. It throws where it is
|
|
1256
|
+
made when an invariant calls an operator its table does not run, since it
|
|
1257
|
+
could judge no value by that invariant and would pass them all.
|
|
806
1258
|
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
in full confidence, and every test it does support still passes.
|
|
1259
|
+
Text compares only under a declared collation, here too: a date stored as text
|
|
1260
|
+
needs `{ collation: Collation.binary }` on its comparison. An interpreter that
|
|
1261
|
+
judges stored rows alone refuses `after`'s nodes as the operation `next`;
|
|
1262
|
+
`Expr.substituteNext` reads the ones a write sets as their values.
|
|
812
1263
|
|
|
813
|
-
|
|
1264
|
+
## Naming a question: operators
|
|
814
1265
|
|
|
815
1266
|
What operators make possible, end to end (a rule named once, search and order
|
|
816
1267
|
the kernel lacks, writes that compute, one meaning checked across
|
|
@@ -977,17 +1428,20 @@ Operators.describeTable(recorded) // [{ name: 'acme.concat', …, laws, evidence
|
|
|
977
1428
|
over the non-negative numbers only). Strict null makes both sides null, so no
|
|
978
1429
|
law needs a null case.
|
|
979
1430
|
- **Testing is sampling, seeded.** Cases come from a fixed sample of each kind
|
|
980
|
-
(the empty string, mixed case, non-ASCII and astral text
|
|
1431
|
+
(the empty string, mixed case, non-ASCII and astral text, `%`, `_` and `\`; zero, negatives, a
|
|
981
1432
|
fraction), kept where the schemas decode them, up to `cases` (200) a law
|
|
982
1433
|
chosen by `seed` (0), under each of `binary` and `asciiFold` where the
|
|
983
1434
|
operator or a witness its law calls compares text (so a record of such a law
|
|
984
1435
|
counts twice the cases). The verdict is `Holds` with one `Tested` record a law, or the
|
|
985
1436
|
first `Counterexample` with both sides and its collation: declaring `concat` commutative
|
|
986
|
-
finds `"a"` and `"A"`, which give `"aA"` and `"Aa"`.
|
|
1437
|
+
finds `"a"` and `"A"`, which give `"aA"` and `"Aa"`. Two sides that both refuse agree,
|
|
1438
|
+
but are no case: a record counts only cases whose sides both answered, and a law with
|
|
1439
|
+
none is `Unanswered`, with the first refusal's reason, and records nothing.
|
|
987
1440
|
- **Evidence is an implementation's.** `Operators.withEvidence` refuses a record
|
|
988
1441
|
of an operator the table lacks or a law it does not declare, and a `Tested`
|
|
989
1442
|
record `Conformance.laws` did not make of this table's own implementation
|
|
990
|
-
(`Operators.testedOn(record)` names the one it did)
|
|
1443
|
+
(`Operators.testedOn(record)` names the one it did), or tested beside another
|
|
1444
|
+
implementation of a witness its law calls; `override` drops a
|
|
991
1445
|
replaced implementation's records, and those of a law that called it as a
|
|
992
1446
|
witness (`inverse`, `distributes`); `merge` keeps both tables'. An SQL table
|
|
993
1447
|
(`DrizzleOperators.withEvidence`) takes only records `Conformance.lawsBy`
|
|
@@ -1006,7 +1460,8 @@ every implementation given and reports where they disagree, a refusal included:
|
|
|
1006
1460
|
generated from each argument's samples, null where its schema admits one, and
|
|
1007
1461
|
text holding NUL, under `binary` and `asciiFold` where the operator compares
|
|
1008
1462
|
text. `Conformance.memory(table)` is the reference interpreter's runner; a
|
|
1009
|
-
defined operator's expansion runs beside the others
|
|
1463
|
+
defined operator's expansion runs beside the others as `expansion`, a name an
|
|
1464
|
+
implementation of it may not take. `foldkit-remote-drizzle`
|
|
1010
1465
|
runs the kernel's operators and an application's through it on SQLite and
|
|
1011
1466
|
Postgres.
|
|
1012
1467
|
|
|
@@ -1053,56 +1508,37 @@ holding `acme.slug` does not answer a body calling `acme.slug@2`, and the
|
|
|
1053
1508
|
refusal names both (`acme.slug@2 (this table has acme.slug)`), so a client and a
|
|
1054
1509
|
server on different deploys see which side is behind.
|
|
1055
1510
|
|
|
1056
|
-
### Reading one back
|
|
1057
|
-
|
|
1058
|
-
`Query.show(query)` renders a body as text, one clause per line:
|
|
1059
|
-
|
|
1060
|
-
```ts
|
|
1061
|
-
Query.show(body)
|
|
1062
|
-
// FROM Post
|
|
1063
|
-
// WHERE Post.slug = $slug
|
|
1064
|
-
// AND Post.published = true
|
|
1065
|
-
// ORDER BY Post.updatedAt DESC
|
|
1066
|
-
```
|
|
1067
|
-
|
|
1068
|
-
For a person — an explanation, a diagnostic, a test asserting on a whole
|
|
1069
|
-
predicate at once — and never for an interpreter. It is close enough to SQL to
|
|
1070
|
-
read at a glance and unlike it everywhere that matters: an input is `$slug`
|
|
1071
|
-
rather than a bound parameter, `contains` is named rather than rendered as
|
|
1072
|
-
somebody's `like`, and no dialect's escaping or collation is implied. What
|
|
1073
|
-
actually ran is whatever that backend compiled, which is not this.
|
|
1074
|
-
`Expr.show(node)` does the same for one expression.
|
|
1075
|
-
|
|
1076
|
-
A `Query` says which rows. It does not say which fields — that is a Selection —
|
|
1077
|
-
and it does not say how many, whether absence is an error, or whether to watch
|
|
1078
|
-
for changes: those belong to the consumer doing the reading, not to the
|
|
1079
|
-
relation.
|
|
1080
|
-
|
|
1081
|
-
Only the operations a real query in this repository needs exist. The set grows
|
|
1082
|
-
from queries, not from what a database could express.
|
|
1083
|
-
|
|
1084
1511
|
## API
|
|
1085
1512
|
|
|
1086
1513
|
| Call | Meaning |
|
|
1087
1514
|
| --- | --- |
|
|
1088
1515
|
| `Entity.define(name, struct)` | A new Entity with a Field per property. |
|
|
1516
|
+
| `Entity.defineVariants(name, { Case: fields, … })` | Experimental. An Entity whose row is one of its cases: `variants` is their tagged union, `fields` the stored row (`_tag`, shared fields, the rest nullable), with an invariant per case. |
|
|
1517
|
+
| `Entity.selectionSchema(entity, schemas)` | The schema a Selection of those members reads, given each one's schema: a Struct, or a variant Entity's union when `_tag` is among them. What an interpreter reading members its own way (Remote's refs) builds a Selection's value with. |
|
|
1518
|
+
| `Entity.variantsOf(entity)` | An Entity's variants for an interpreter (the union, each case's fields, the codec from a stored row to its case), or none. |
|
|
1089
1519
|
| `Entity.relate(entities, { Owner: { key: Relation.one(Target) } })` | The entities with their relations declared; targets resolve to the returned entities. |
|
|
1090
|
-
| `Entity.select(entity, { key: true or Selection })` | A Selection: what was selected (`members`) and the `schema` of the result. |
|
|
1520
|
+
| `Entity.select(entity, { key: true or Selection })` | A Selection: what was selected (`members`) and the `schema` of the result; a tagged union of cases for a variant Entity whose `_tag` is selected. |
|
|
1091
1521
|
| `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a page: `items`, `hasNext`, `hasPrevious`. |
|
|
1092
1522
|
| `Entity.fields(entity, ...keys)` | The schemas of those fields, by key, to spread into an input's struct. |
|
|
1093
1523
|
| `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. |
|
|
1524
|
+
| `Write.insert(input, { id })` / `Write.delete(input, { id, expect?, when? })` | A declared insert under an id the client chose; a declared delete of one row, which sets nothing. |
|
|
1094
1525
|
| `Write.reads(write)` | The fields a write reads from its row: its `when`'s, each it increments, its assignments', the revision. |
|
|
1095
1526
|
| `Write.update(input, { …, compute })` / `Computation` | A field computed from the row before the write and the input, carried as data. |
|
|
1096
1527
|
| `Write.apply(row, bound, { operators })` / `Write.boundReads(bound)` | The row a bound write leaves, and what of the row before it that needs. |
|
|
1097
1528
|
| `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. |
|
|
1098
1529
|
| `Entity.input(entity, struct, mapping?)` | Experimental. Which member each key of an operation's input writes. |
|
|
1099
1530
|
| `Relation.nested(relation, input)` | In an input mapping: the key holds the target itself, written through `input`. |
|
|
1100
|
-
| `Entity.selectFor(input)` | The Selection of the members an input writes: what an edit screen loads. |
|
|
1531
|
+
| `Entity.selectFor(input, { also? })` | The Selection of the members an input writes, and `also` beside them: what an edit screen loads. |
|
|
1101
1532
|
| `Entity.valuesFor(input, value)` | The input values that reproduce a loaded value: fields as they are, refs as ids. |
|
|
1102
|
-
| `Entity.derived({ key: Derived.make(schema) })` | Pipe step adding readable, externally supplied members. |
|
|
1533
|
+
| `Entity.derived({ key: Derived.make(schema, { predict?, forbids? }) })` | Pipe step adding readable, externally supplied members; `predict` and `forbids` say what a client foresees of one. |
|
|
1534
|
+
| `Derived.count(Other.relations.pointer)` | A derived member counting the rows whose `one` relation points at this one. |
|
|
1535
|
+
| `Derived.exists(Other.relations.pointer, { viewer: Other.relations.by })` | The id of a row pointing at this one and at whoever reads it, or none. |
|
|
1536
|
+
| `Entity.invariant(id, ({ before, after }) => predicate, { message, path })` | Pipe step: what every stored row must hold, judged over the row a write leaves. |
|
|
1537
|
+
| `Entity.judge(entity, { after, before? })` / `Entity.check(entity)` | Judge rows against the invariants (`Valid`, `Invalid`, `Undecided`); the state invariants as a Schema check. |
|
|
1538
|
+
| `Entity.invariants(entity)` / `Entity.readsBefore(invariant)` | The invariants an Entity holds; whether one reads the row before (a transition invariant). |
|
|
1103
1539
|
| `Entity.annotate(metadata)` | Pipe step attaching metadata to the Entity. |
|
|
1104
1540
|
| `Entity.annotateMembers({ key: metadata })` | Pipe step attaching metadata to members by key. |
|
|
1105
|
-
| `Entity.same(a, b)` | Whether two descriptors are
|
|
1541
|
+
| `Entity.same(a, b)` | Whether two descriptors are of one Entity. |
|
|
1106
1542
|
| `Selected<typeof selection>` | Type: the value a Selection reads (its `schema`'s `Type`). |
|
|
1107
1543
|
| `Words.of(schema)` | A schema's `title` and `description`, each an `Option`, including a title given before a check. |
|
|
1108
1544
|
| `Entity.is(value)` | Whether a value is an Entity descriptor. |
|
|
@@ -1113,6 +1549,16 @@ from queries, not from what a database could express.
|
|
|
1113
1549
|
| `Expr.and(a, b, …)` / `Expr.or(a, b, …)` | Every operand holds / at least one does, as SQL's three-valued `and` and `or`. At least one operand; a nested one of the same kind is flattened in. |
|
|
1114
1550
|
| `Expr.not(predicate)` | The predicate does not hold; an unknown stays unknown, so a null matches neither side. |
|
|
1115
1551
|
| `Expr.lt` / `lte` / `gt` / `gte(left, right, { collation? })` | One value orders before or after the other. Numbers as numbers; text only under `binary` or `asciiFold` (the field's declared collation, or the one given), and only against a field. |
|
|
1552
|
+
| `Expr.is(entity or relation, tag, fields => predicate?)` | The row, or the row a `one` relation reaches, is of a case of a variant Entity, and holds what is asked of that case's fields, typed as the case holds them. False on another case. |
|
|
1553
|
+
| `Expr.path(relation, end)` | What the row a `one` relation points at holds: a field, a further path, or an exists; null where no row is reached. At most `maxPathLength` (4) relations. |
|
|
1554
|
+
| `Entity.sets({ member: Expr.viewer(E) or Expr.now }, { on })` | Pipe step: members whose value the write's context gives, on every insert (`'create'`) or every insert and update (`'write'`); no input sets them. A value may also be a path from the viewer (`Expr.path(Expr.viewer(E), end)`). `Write.contextValues(write, context, read)` is what they come to. |
|
|
1555
|
+
| `Expr.eq(Post.relations.author, …)` | A `one` relation as an operand: the id it points at, null for none. |
|
|
1556
|
+
| `Expr.exists(relation, where?)` | Some row of another Entity points here through its `one` relation and holds `where`, a predicate over its own fields and the input. |
|
|
1557
|
+
| `Judge.predicate(p, row, options)` / `Judge.query(body, input, row, options)` | The reference semantics over a `HeldRow`: a `Verdict`, `Known` (SQL's answer) or `Unknown` with why. `Judge.match` reads one. |
|
|
1558
|
+
| `Held.fromRefs(query, row)` | A row holding each `one` relation as its ref key (`'User:ada'`), as a Source answers it and a Remote store keeps it, with each link the query reads given as the id it points at. |
|
|
1559
|
+
| `Judge.pins(predicates, { input, context })` | What a conjunction fixes by field (each `eq` of a field and a literal, an input or the viewer), and whether that is all it says (`whole`). What an exists passes `HeldRow.pointing`, so a holder holding every row with those values can say it misses none. |
|
|
1560
|
+
| `Held.isLink(identity, key)` | Whether `key` is a `one` relation of the Entity `identity` names: how a ref-keyed holder reads a row it knows only by identity, as a row `HeldRow.pointing` returns is. |
|
|
1561
|
+
| `Held.rows(tables)` | A holder over plain records, each table complete or not, with keys hidden; `row(entity, id)` and `rows(entity)` give `HeldRow`s. |
|
|
1116
1562
|
| `Expr.whenGiven(input, given => predicate)` | A filter applying only when a nullable input is given: `or(isNull(input), predicate)`, the predicate seeing the input as never null. |
|
|
1117
1563
|
| `Expr.operator(id, { input, output, definedAs?, version?, description?, nulls?, collation?, laws? })` | An operator: defined by what a call means (`definedAs`, whose expansion every interpreter runs) or primitive (each interpreter's table implements it). Calling it builds a `Test` predicate (a boolean output) or a `Call` scalar. |
|
|
1118
1564
|
| `Expr.unsupported(nodes, { operations, operators })` | What these expressions need that an interpreter lacks: operations, then primitive operators by name. |
|
|
@@ -1147,10 +1593,14 @@ from queries, not from what a database could express.
|
|
|
1147
1593
|
because Remote keys its store by `id`.
|
|
1148
1594
|
- A Selection has no filtering or ordering, and a page has no total; those
|
|
1149
1595
|
belong to the interpreter that fetches.
|
|
1150
|
-
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1596
|
+
- A relation reaches only the entities of its own `Entity.relate` call; relate
|
|
1597
|
+
them again to add relations between them.
|
|
1598
|
+
- `target()` returns the entity as `relate` returned it: every member added
|
|
1599
|
+
since is on it (`likeCount`), but metadata annotated afterwards (`CmsPost`
|
|
1600
|
+
above) is on that new descriptor only, so annotate before relating when a
|
|
1601
|
+
target should carry it. Its type shows the members as related; read a later
|
|
1602
|
+
one as an `AnyEntity`.
|
|
1603
|
+
- A member is added once per Entity: two pipe chains from one descriptor that
|
|
1604
|
+
each add `score` are refused, as one chain adding it twice is. Adding the very
|
|
1605
|
+
spec again (`Guards.may` on a second view) is the member it added.
|
|
1156
1606
|
- No registry: nothing checks that two different entities share a name.
|