Entity / foldkit-entity
Saying something about a row: Expr
An Entity says what a domain has. An Expr says something about one row of it,
as a value. This section is the reference; the
Expressions guide teaches the language in order,
with one body answered by SQL, by evaluate and by Judge.
import { Schema } from 'effect'
import { Expr, Order } from 'foldkit-entity'
const byTitle = Expr.eq(Blog.Post.fields.title, Expr.input('title', Schema.String))
const isPublished = Expr.eq(Blog.Post.fields.published, true)
const newestTerms = [Order.desc(Blog.Post.fields.title), Order.asc(Blog.Post.fields.id)]Building one produces pure data; an interpreter runs it
(foldkit-remote-drizzle compiles it to SQL, evaluate judges rows in memory),
so one query means the same thing on client and server.
Why
evaluatelives here. It is the reference semantics of the language: what each operation means over rows already in hand. It may depend on the language and nothing else (no database, no transport, no Remote concept), and a page importing onlyEntitydoes not carry it.
A comparison coerces what it is given, so the common forms read as they mean: a
field becomes a reference, a plain value becomes a literal, and an Expr is
already one. What it will not do is compare a field to the wrong kind of value —
Expr.eq(Blog.Post.fields.title, 42) is an error where it is written, rather
than a row that never matches. The value's type comes from the left, so eq takes
the field on the left; Expr.eq('Hello', Blog.Post.fields.title) is refused with
that sentence. The comparisons (lt, gte, …) also take a field second,
wrapped in Expr.field(…).
dependenciesOf(...) says which fields and inputs an expression reads and which
operations it uses, so a planner knows what it needs and an interpreter can
refuse a query it cannot run. Each field names its owner, the Entity's
identity, as well as the Entity's name, so two Entities defined with the same
name are two entries.
Every node is frozen as it is built, so a query is the value it was when
Query.where checked it: nothing can swap a field or a literal in afterwards.
A node can be shared (Expr.eq(n, n)), and the analysis visits each one once.
An interpreter does not: evaluate reads a predicate as a tree on every row,
and the SQL compiler writes a shared operand out wherever it appears. So a
query whose predicates and order terms expand past maxQueryNodes (1,000)
nodes, counting a shared node on each path that reaches it, is refused where
it is built.
Data-last: step with Effect's pipe and flow
Every comparison (eq, lt, lte, gt, gte, contains, in) and every
operator has a step member: the call without its subject. It builds exactly the
node the data-first call builds, so it is a spelling, not a second meaning.
import { Schema, flow, pipe } from 'effect'
import { Collation, Entity, Expr, Text } from 'foldkit-entity'
const Post = Entity.define(
'Post',
Schema.Struct({ id: Schema.String, status: Schema.Literals(['draft', 'live']), upc: Schema.String }),
).pipe(Entity.annotateMembers({ upc: Collation.of(Collation.binary) }))
const isDraft = pipe(Post.fields.status, Expr.eq.step('draft'))
// the same node as Expr.eq(Post.fields.status, 'draft')
const startsWithA = pipe(Post.fields.upc, Text.startsWith.step('A'))
const draftOrLive = flow(Expr.in.step(['draft', 'live']))
const anyStatus = draftOrLive(Post.fields.status)stephas one signature, so reads stay exact throughpipeandflow(isDraftreads'Post', andQuery.wherestill refuses a predicate over another Entity). An overloaded callable would lose them, which is why it is a member and not the function's own data-last form.- A wrong value is refused at the step:
pipe(Post.fields.status, Expr.eq.step(42))is an error where it is written.Expr.eq(Post.fields.status)is still an arity error. - The
stepoflt,lte,gtandgtetakes the options its builder takes (Expr.lt.step('m', { collation })); an operator's takes none, so a call that needs a collation is written data-first. A step takes the arguments past the first, then the first: an operator of one argument has astep()that takes nothing, andText.startsWith.step(prefix)takes one. - Data-first stays the form to learn first; a step earns its place in a chain.
Asking a question that depends on an input, without branching on it
Since an input is a placeholder, a query cannot choose between two shapes based on what it was given. It does not need to: a question that looks like a branch is usually a comparison waiting to be written.
const Entry = Entity.define(
'Entry',
Schema.Struct({ id: Schema.String, label: Schema.String, archivedAt: Schema.NullOr(Schema.String) }),
)
const input = {
archived: Expr.input('archived', Schema.Boolean),
search: Expr.input('search', Schema.String),
}
// A list that shows archived entries or unarchived ones, as the reader asks:
Expr.eq(Expr.isNotNull(Entry.fields.archivedAt), input.archived)
// A search box that filters when something is typed and not when nothing is:
Expr.contains(Entry.fields.label, input.search)The first is "is-archived equals what you asked for". The second relies on
everything containing the empty string. Both are one static body, and both ask
exactly what archived ? … : … and search === '' ? … : … asked.
isNull and isNotNull are the same node with the answer absence gives
flipped, so nothing has to negate a predicate to get the other.
contains is case-insensitive, which is what a search means — and which
has to be said, not left to the interpreter: SQLite's like ignores case and
Postgres's does not, so a body that left it open would mean two things. Folding
is ASCII-only, since that is what lower does in SQLite without ICU: É does
not match é, though each matches itself. Text holding a NUL character is
refused by every interpreter here, in contains, eq and in alike, since
Postgres text cannot hold one and SQLite compares only up to it.
in asks whether a value is one of a list, written out
(Expr.in(Post.fields.status, ['draft', 'live'])) or given as an input of a
list. Each element is
compared as eq compares, and it reads as SQL's in: a null value is
unknown, so is no match against a list holding a null, and an empty list
matches no row (on Postgres too, which refuses in (); the compiler says
false instead).
contains searches text, and its operand is constrained to text. Over a
number it would compile to lower(rank) like …, which SQLite coerces into an
answer and Postgres rejects at runtime, so a non-text operand is a compile
error where it is written. Nullable text is allowed, and there an empty search
is not the same as no filter: a null contains nothing, not even the empty
string, so its rows drop out.
Who asks, and when: the context
A write's context is part of the language. Expr.viewer(User) is whoever
asks, as a User's id, and null for a visitor or a viewer of another Entity, so
a comparison with it holds of no row. Expr.now is the time, in milliseconds.
Neither is a field or an input: each interpreter reads them from the context
it is given.
import { Option, Schema } from 'effect'
import { Entity, Expr, Query, evaluate } from 'foldkit-entity'
const User = Entity.define('User', Schema.Struct({ id: Schema.String }))
const Note = Entity.define('Note', Schema.Struct({ id: Schema.String, ownerId: Schema.String }))
const MyNotes = Query.from(Note).pipe(
Query.where(Expr.eq(Note.fields.ownerId, Expr.viewer(User))),
)
const ada = { entity: 'User', id: 'ada' }
evaluate(MyNotes, {}, [{ id: 'n1', ownerId: 'ada' }, { id: 'n2', ownerId: 'bo' }], {
context: { viewer: Option.some(ada), now: Option.none() },
})
// [{ id: 'n1', ownerId: 'ada' }]The viewer is a ref (EntityRef), so a viewer of another Entity reads null.
A server gives them from RemoteServer.make({ viewer }) and its clock; a
client from Remote.make({ viewer }), with no reading of the time a server
judges a list at, so a list over Expr.now is the server's to say. A run
given no context, or no reading of a time it reads, refuses the body
(ContextMissingError) rather than reading a visitor or a null. A write's
computed assignment may not read them; a member whose value they give is
declared with Entity.sets.
Which rows: Query
A Query is an Entity to read, the predicates every row must hold, and the
order to read them in — composed with pipe, one immutable value per step:
import { Query } from 'foldkit-entity'
const published = Query.where(Expr.eq(Blog.Post.fields.published, true))
const newest = Query.orderBy(Order.desc(Blog.Post.fields.title))
const recent = Query.from(Blog.Post).pipe(published, newest)
const oneOf = Query.from(Blog.Post).pipe(published, Query.where(byTitle))published and newest are fragments: written once, piped into any query over
the same Entity. Composing builds an immutable query value; an interpreter runs
it when asked. A fragment over another Entity is refused where it is
piped: a predicate's type names the Entities its fields belong to, so
Query.from(Blog.Post).pipe(Query.where(Expr.eq(Blog.Comment.fields.body, 'x')))
reads a predicate reads Comment, but the query is from Post, and an ordering
term over another Entity is refused by Query.orderBy the same way. The same check
runs again when the query is built, for what a type cannot see: a predicate
typed plainly as Predicate, or two Entities that share a name.
Two wheres conjoin and two orderBys append. Neither replaces what came
before, so piping a fragment can only ever narrow a query, never silently undo
part of it. An earlier ordering term stays the more significant one, which is
what makes a later Query.orderBy(Order.asc(id)) a tie-breaker.
A sort the reader picks is part of the body too. Order.chosen maps each
name the input's sort can hold to a field, so the server and the client read one
declaration of what title means, and the client can tell which edits may move
a row:
import { type InputExpr } from 'foldkit-entity'
const PostSort = Schema.NullOr(
Schema.Struct({ by: Schema.Literals(['title', 'id']), direction: Schema.Literals(['asc', 'desc']) }),
)
const sorted = (sort: InputExpr<typeof PostSort.Type>) =>
Query.from(Blog.Post).pipe(
Query.orderBy(Order.chosen(sort, { title: Blog.Post.fields.title, id: Blog.Post.fields.id })),
)Every name the sort can hold needs a field, or it does not compile. A null
sort chooses none, and the terms after it decide. foldkit-crud's
Sort.make(['title', 'id']).Schema is such a sort. Query.orderFor(query, input)
is the fixed terms for one input, which is what every interpreter sorts by.
Every order is total. orderFor ends it on the Entity's id, ascending,
unless the terms already read the id, so rows with equal keys come out in one
order on every interpreter rather than each breaking ties its own way.
How text orders is declared, or left to the server. Left unsaid, SQLite
compares bytes, Postgres follows the database's locale and a plain JavaScript
sort follows UTF-16 code units. A field declares its collation, which SQL
compiles, and Query.placement says whether a client can order the same way.
evaluate refuses an order over text with no declared collation, with the
reason Query.placement gives, so a page and the reference agree on whether
the question can be answered; a database orders such text by its own default,
which differs between SQLite and Postgres. evaluateEach, which only judges
membership, does not refuse, and its matched list is then in code point
order:
const Tagged = Entity.define('Tagged', Schema.Struct({ id: Schema.String, name: Schema.String })).pipe(
Entity.annotateMembers({ name: Collation.of(Collation.asciiFold) }),
)
const byName = Query.from(Tagged).pipe(Query.orderBy(Order.asc(Tagged.fields.name)))
Query.placement(byName, {}) // { _tag: 'Placeable' }Collation.binaryis code point order: SQLiteBINARY, PostgresCOLLATE "C". An id isbinaryunless it says otherwise.Collation.asciiFoldfolds ASCII letters, then compares by code point: SQLiteNOCASE, Postgreslower(x COLLATE "C").Collation.locale('en-US')is the backend's own, ordered on the server and never by a client.
A term overrides its field's: Order.asc(field, { collation }).
Query.placement(query, input, { operators }) says whether a client can order the rows exactly
as the server does: every term over a number or a boolean (a row may lack it), over text with a
portable collation, or a call whose primitive operators the client's table runs. A body with no
order, text with none declared, a locale, or an operator the table lacks is NotPlaceable, with
the reason.
The list of predicates is the conjunction: a query wanting three
conditions writes three wheres. Expr.and is for a conjunction inside
something else, and Expr.or and Expr.not are the other two connectives:
const Product = Entity.define(
'Product',
Schema.Struct({
id: Schema.String,
description: Schema.String,
upc: Schema.String,
status: Schema.String,
cents: Schema.Number,
}),
)
const filters = {
search: Expr.input('search', Schema.String),
status: Expr.input('status', Schema.NullOr(Schema.String)),
}
// A search over two fields: a product whose description or UPC holds the text.
Expr.or(
Expr.contains(Product.fields.description, filters.search),
Expr.contains(Product.fields.upc, filters.search),
)
// A filter that applies only when its input is given (`filters.status` may be null).
Expr.whenGiven(filters.status, status => Expr.eq(Product.fields.status, status))They mean what SQL's do, three-valued: a comparison of a null is unknown, a row
is kept only when its predicate is true, or takes true over unknown and and
takes false over it, and not of an unknown is unknown. So
Expr.not(Expr.eq(field, 'draft')) leaves out a row whose field is null;
"everything but drafts", nulls included, is
Expr.or(Expr.isNull(field), Expr.not(Expr.eq(field, 'draft'))). and and
or need an operand (an empty one would match every row, or none), a nested
one of the same kind is flattened into its parent, and one operand is that
operand. An interpreter that runs per request decides an operand that reads no
field before it writes anything: whenGiven compiles to true, which filters
nothing, when its input is null, and to the predicate alone when it is given.
Expr.implies(a, b) is Expr.or(Expr.not(a), b), the same nodes: b binds
only the rows a holds of (Expr.implies(Expr.eq(Product.fields.status,
'active'), Expr.gt(Product.fields.cents, 0))).
Comparisons order two values: Expr.lt, lte, gt and gte.
Expr.lt(Product.fields.cents, 1000)
// A range of dates, stored as ISO strings, which order by time under binary:
const Shipment = Entity.define('Shipment', Schema.Struct({ id: Schema.String, shippedAt: Schema.String }))
const range = { from: Expr.input('from', Schema.String), until: Expr.input('until', Schema.String) }
Expr.and(
Expr.gte(Shipment.fields.shippedAt, range.from, { collation: Collation.binary }),
Expr.lt(Shipment.fields.shippedAt, range.until, { collation: Collation.binary }),
)Numbers compare as numbers, and nothing compares across kinds or for a value
stored as neither a number nor text. Text orders by a collation, and the
defaults disagree (above), so text is compared only under Collation.binary
or Collation.asciiFold, passed or declared on a side that carries one (a
field, a path to one, an operator call with a collation): anything else
throws where the comparison is built. A value is
compared in its encoded form, which is why a date stored as an ISO string is
text here. A null on either side is unknown, as in SQL. There is no between;
it is the and above.
Sums and differences are numbers too: Expr.add(a, b) and Expr.sub(a, b),
over number fields, inputs, literals and each other, on either side.
const price = { discount: Expr.input('discount', Schema.Number) }
Expr.gte(Expr.sub(Product.fields.cents, price.discount), 100)
Expr.show(Expr.sub(Product.fields.cents, price.discount)) // '(Product.cents - $discount)'They are the kernel's primitive operators number.add and number.subtract,
which every memory table runs and every binding's SQL kernel holds: + and -
in memory, in SQLite and in Postgres, and conformance cases hold the three to
one answer. A null on either side gives null; a text operand is a type error
where it is passed. A comparison, an order term, an invariant, a write's when
and its compute read one as any number, and a sum of integers computes an
integer field. An integer sum past 2^53 - 1, where a double no longer holds
every integer, is refused in memory (a QueryEvaluateError); the SQL both
databases run gives NULL there, since SQL has no refusal.
Reading across relations: Expr.path and Expr.exists
A predicate may read the row a one relation points at, and ask whether any
row points at this one. Both start on the query's own row, so they belong in
its where:
const { Post, User, Follow } = Entity.relate(
{ Post: PostFields, User: UserFields, Follow: FollowFields },
{ Post: { author: Relation.one(UserFields) }, Follow: { followee: Relation.one(UserFields) } },
)
// Posts by a handle: a field of the row `author` points at.
const ByHandle = Query.from(Post).pipe(
Query.where(
Expr.eq(Expr.path(Post.relations.author, User.fields.handle), Expr.input('handle', Schema.String)),
),
Query.orderBy(Order.asc(Post.fields.id)),
)
// Posts whose author the reader follows: some Follow points at the author, and is theirs.
Expr.path(
Post.relations.author,
Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, Expr.input('me', Schema.String))),
)(packages/entity/test/readmePaths.test.ts runs these, with the three Entities
it declares.)
Expr.path(relation, end)follows aonerelation, then readsendthere: a field, a further path, or an exists. A null link, or a row the reader may not see, reaches no row, and the field reads null, as SQL's scalar subquery does. At most four relations.Expr.exists(relation, where?)names the pointing edge, aonerelation of another Entity (Follow.followee), asDerived.countdoes. Only rows the reader may see count.wherereads the pointing row's own fields, the input and the context (Expr.viewer,Expr.now); another Entity's field or a further path or exists is refused where it is written.- A list does not order by a path.
A one relation is itself an operand: the id it points at, typed as the
target's id, and null where an optional one points nowhere. So a rule compares
the link, and no field over the same column has to repeat it:
// Posts by whoever asks: where `author` points.
const Mine = Query.from(Post).pipe(Query.where(Expr.eq(Post.relations.author, Expr.viewer(User))))A row given to an interpreter holds the relation under its key as that id, as
Held.rows takes it; SQL reads the column the relation is stored on. A list
does not order by a link: a client holds it as a ref, not as the id it would
order by.
foldkit-remote-drizzle compiles both to subqueries under each reached
table's visible rule. evaluate, given one table's rows, cannot follow them: it
refuses such a body, as it refuses any operation it does not run. Judge,
below, reads them from what a holder has.
Judging what you hold: Judge
evaluate reads a missing key as null, which is right for a server holding
every row and wrong for a client holding some: "this field is null" and "I was
never sent it" are different answers. Judge reads a row as a holder has it
(HeldRow) and keeps the two apart:
import { Option } from 'effect'
import { Held, Judge } from 'foldkit-entity'
const holder = Held.rows([
{ entity: Post, rows: [{ id: 'p1', body: 'hi', author: 'u1' }, { id: 'p2', body: 'yo', author: 'u2' }] },
// Ada is held; u2 is not, and this holder may lack users.
{ entity: User, rows: [{ id: 'u1', handle: 'ada' }], complete: false },
])
Judge.query(ByHandle, { handle: 'ada' }, Option.getOrThrow(holder.row(Post, 'p1')))
// { _tag: 'True', evidence: none }
Judge.query(ByHandle, { handle: 'ada' }, Option.getOrThrow(holder.row(Post, 'p2')))
// { _tag: 'Unknown', reason: 'User u2 is not held', obligation: none }A verdict is metakit's Verdict (read it with Verdict.match from @doeixd/metakit):
True, False or Unknown. A predicate SQL leaves null is False (a row is
not kept on it; Judge.predicate gives the witness 'null'); Unknown means the answer
rests on a field or row the holder lacks or may not see, or on an operator only
the server runs. What can decide anyway does: a null beside an unheld value,
and's false, or's true, an exists' held witness. An exists is false only
where the holder's pointing says it misses no row: it is given what the
filter fixes (Pinned, each eq of a field and a literal, an input or the
viewer), so a holder that holds every row with those values (a client's list
of whom the viewer follows) can say so without holding every pointing row.
Judge.pins(predicates, { input, context }) works out what a conjunction
fixes, and whether that is all it says. Judge.query(…, {
serverOnly }) names a filter the server adds that the holder does not run. The
law, checked against SQL by foldkit-entity/conformance's relationalCases:
where Judge knows, it is what the server answers.
Saying what an interpreter can run
An Expr is only portable if the thing running it says what it runs.
Query.unsupported(query, supported) names the operations a query needs that
an interpreter does not have:
const missing = Query.unsupported(ByHandle, ['eq', 'isNull', 'isNotNull'])
// ['path']: ByHandle reads a path, which this interpreter does not list
if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)The refusal belongs to the interpreter, not here: one that compiles at
registration and one that runs a body directly fail at different moments. What
matters is that it refuses rather than skipping the operation — an interpreter
that quietly drops a contains it cannot compile answers a different question
in full confidence, and every test it does support still passes.
Reading one back
Query.show(query) renders a body as text, one clause per line. A list of
published posts by slug, newest first, reads:
FROM Post
WHERE Post.slug = $slug
AND Post.published = true
ORDER BY Post.updatedAt DESCIt is for a person (an explanation, a diagnostic, a test asserting on a whole
predicate at once), never for an interpreter: an input is $slug rather than
a bound parameter, contains is named rather than rendered as somebody's
like, and no dialect's escaping or collation is implied. Expr.show(node)
does the same for one expression.
A Query specifies which rows to match and how to order them. Which fields to
return belongs to a Selection, while page sizes, missing-row handling, and live
updates belong to the consumer running the query.