Entity / Expressions

A first query and its answer

This example declares a Post entity with binary text ordering, builds a Short query expression, prints it, evaluates it in memory, and inspects its field dependencies:

ts
import { Schema } from 'effect'
import { Collation, Entity, Expr, Order, Query, evaluate } from 'foldkit-entity'

const Post = Entity.define(
  'Post',
  Schema.Struct({
    id: Schema.String,
    title: Schema.String,
    words: Schema.Number,
    publishedAt: Schema.NullOr(Schema.Number),
  }),
).pipe(Entity.annotateMembers({ title: Collation.of(Collation.binary) }))

const Short = Query.from(Post).pipe(
  Query.where(Expr.lt(Post.fields.words, 1000)),
  Query.orderBy(Order.asc(Post.fields.title)),
)

const rows = [
  { id: 'p1', title: 'Notes on the Engine', words: 900, publishedAt: 100 },
  { id: 'p2', title: 'Compilers', words: 2400, publishedAt: null },
  { id: 'p3', title: 'compost', words: 300, publishedAt: 300 },
]

Query.show(Short)
// FROM Post
// WHERE Post.words < 1000
// ORDER BY Post.title ASC

evaluate(Short, {}, rows).map(row => row.id)
// ['p1', 'p3']

Query.dependencies(Short).predicate.map(field => field.key) // ['words']
Query.dependencies(Short).order.map(field => field.key) // ['title']

What each call does:

  • Expr.lt(Post.fields.words, 1000) constructs a typed comparison node. Because the right-hand literal inherits the field's type, Expr.lt(Post.fields.words, 'long') fails at compile time.
  • Query.from(...).pipe(Query.where, Query.orderBy) describes the Entity, filter predicate, and sort order without binding a table or window size (which Selections and queries add separately).
  • Query.show formats a human-readable summary for debugging.
  • evaluate runs the pure reference interpreter over in-memory rows, returning the same IDs in the same order as foldkit-remote-drizzle's SQL compiler.
  • Query.dependencies lists which fields affect filtering (words) vs. ordering (title), letting the client tell which edits can move a row in or out of a cached list.
  • Collation.of(Collation.binary) specifies code-point ordering for title so SQLite, Postgres, and JavaScript agree ('Notes on the Engine' before 'compost').

In an application, wrap the body in Query.define('Short', { under: Schema.Number }, ({ input }) => ...) from foldkit-remote, register query(Short, { entity }) on the server, and fetch it on the client with Data.query(Short, { under: 1000 }, { select }).