Remote / foldkit-remote-drizzle

Query connections

Top-level Remote Queries compile to keyset pagination:

ts
import { eq } from 'drizzle-orm'
import { Schema } from 'effect'
import { Query } from 'foldkit-remote'
import { query } from 'foldkit-remote-drizzle'

const ProjectsByOwner = Query.make('ProjectsByOwner', {
  Input: Schema.Struct({ ownerId: Schema.String }),
  Result: Query.connection(Project),
})

const ProjectsByOwnerSource = query(ProjectsByOwner, {
  entity: Project,
  orderBy: [
    { key: projects.createdAt, direction: 'desc' },
    { key: projects.id, direction: 'desc' },
  ],
  where: input => eq(projects.ownerId, input.ownerId),
})

query takes no type arguments. The input is the descriptor's, and a source whose where or orderBy reads nothing of the principal fits any server's. A source that does read it says so on the parameter, where: (input, principal: Principal) => …, and is then a source for a server of that Principal only; a server with another principal refuses it at the type.

A query that carries its own meaning

When the descriptor was declared with Query.define, its body already says which rows and in what order. Register the source and say no more:

ts
import { Expr, Order } from 'foldkit-entity'
import { Query } from 'foldkit-remote'

const PostsBySlug = Query.define('PostsBySlug', { slug: Schema.String }, ({ input }) =>
  Query.from(Post).pipe(
    Query.where(Expr.eq(Post.fields.slug, input.slug)),
    Query.orderBy(Order.asc(Post.fields.id)),
  ),
)

const PostsBySlugSource = query(PostsBySlug, { entity: PostBinding })

The binding is what knows which column holds which field, so nothing in the body names a table and the same body could be compiled by something else. Every field the body reads — in a predicate or in its ordering — is checked when the source is registered, so a server that starts is a server whose queries can be answered, rather than one that fails on whichever request first runs this query.

The body's order is tie-broken by the id. A body says what the rows mean, not how a cursor walks them, so an order that does not already end on the id gets it appended, exactly as a computed orderBy does. A literal orderBy written here is this binding's own and stays as given.

Three things are worth being exact about:

  • A body never widens what a principal may see. The compiled predicates, this server's own where, and the binding's visible rule are conjoined. A body is the application's question; authorization stays where it was.
  • A where given here is added to the body, not put in its place. A binding can narrow a query it did not write.
  • An orderBy given here does replace the body's, because ordering is one decision and a connection pages on exactly one of them.

Query.make is unchanged and still the right declaration when the meaning of a query lives on this side; such a descriptor has no body, and orderBy is then required as before.

The Drizzle query source takes your Remote Query descriptor (input and result entity), applies where and a stable total order, and returns a QueryPage with edges and explicit boundaries.

orderBy must be non-empty and should form a stable total order. Add a unique tie-breaker such as the id.

A body that reads other rows

A body over Entities bound together with bind may read across their one relations, with Expr.path and Expr.exists from foldkit-entity:

ts
import { Expr } from 'foldkit-entity'
import { Query } from 'foldkit-remote'

// Posts whose author the reader follows.
const FollowedPosts = Query.define('FollowedPosts', { me: Schema.String }, ({ input }) =>
  Query.from(Post).pipe(
    Query.where(
      Expr.path(
        Post.relations.author,
        Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, input.me)),
      ),
    ),
  ),
)

Each relation followed compiles to a scalar subquery, and an exists to exists (select 1 …), each under its table's visible rule for the request's principal, resolved once per request. A row the reader may not see is not there: a path to it reads null, and an exists does not find it. A body never reads past what its reader may see, here either.

Checked at registration: each relation on the way is stored on its owner's own table ({ field }), each Entity is bound beside this one, and no table is met twice along one path (that needs SQL aliases, which this compiler does not write yet). An invariant, a write's when and a Read rule take no path yet, and are refused one where they are registered.

Sorting by what the user chose

Put the sort in the query's body, where the client reads it too:

ts
import { Order } from 'foldkit-entity'
import { Sort } from 'foldkit-crud'

const PostSort = Sort.make(['title', 'created'])

const PostsQuery = Query.define('Posts', { sort: PostSort.Schema }, ({ input }) =>
  Query.from(Post).pipe(
    Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title, created: Post.fields.createdAt })),
  ),
)
query(PostsQuery, { entity: Db.Post }) // the body's order, resolved per request

The compiler resolves the chosen field for each request's input and ends the order on the id. An input naming no order the body offers is refused as a query error, the request's mistake. A body that declares its order refuses an orderBy here: two orders would let the server sort one way while the client places rows another.

A Query.make descriptor has no body, so its orderBy may read the query's input, as where does:

ts
import { like } from 'drizzle-orm'

query(PostsSearch, {
  entity: Db.Post,
  where: ({ search }) => (search === '' ? undefined : like(posts.title, `%${search}%`)),
  orderBy: ({ sort }) =>
    sort === 'title'
      ? [{ key: posts.title, direction: 'asc' }]
      : [{ key: posts.id, direction: 'asc' }],
})
  • sortTerms(sort, { title: posts.title, created: posts.createdAt }) turns the state foldkit-crud's Sort makes ({ by, direction }, or null) into order terms: orderBy: ({ sort }) => sortTerms(sort, { ... }). A name the map lacks, or no sort, is no terms, which orders by id.
  • The input should name an order ('title'), never a column. With Order.chosen the body maps each name to a field; with sortTerms the server does.
  • The input is part of a connection's identity, so each order is its own connection with its own cursors. A cursor from one order never pages another.
  • A computed order that leaves the id out is tie-broken by it, ascending, since what a user sorts by is rarely unique. An empty computed order is the id's.
  • A body term's collation is compiled with it, in the ORDER BY and the keyset alike: binary as COLLATE BINARY (SQLite) or COLLATE "C" (Postgres, text columns only; a uuid takes none and orders by bytes), asciiFold as COLLATE NOCASE or lower(x COLLATE "C") (folded under "C", so only ASCII letters fold), and a locale as COLLATE "name" on Postgres; SQLite, which has no locales, refuses one.
  • Where rows without a value go is said on every term and compiled as NULLS FIRST/NULLS LAST, so a nullable column sorts and pages the same on SQLite and Postgres. The default is Postgres's (last ascending, first descending); a body's term says otherwise with Order.asc(field, { nulls: 'first' }), and an orderBy term here with nulls: 'first'. A column the table declares not null has no nulls to place, so its term says nothing: SQLite sorts the last term of an order whose terms place nulls against its own default, even where an index holds the order, so a page ordered …, id would sort its ties. An index that matches the order, its directions included ((owner, created desc, id) for newest first with ties by id), then serves the whole page.

A page's cursor is where it ended: the order's key values at its last row, the id among them (k:[...]). The next page's keyset predicate is built from those values, so "load more" carries on after the last row read was deleted, stopped matching, or moved, from where the page ended. A cursor is client input, and is refused unless it holds exactly one key value (text, a number, a boolean, null, or a tagged date, bigint, or Infinity, -Infinity or NaN, which JSON would write as null) for each term of the order it pages. A cursor from before keys is a row id, still read by re-reading that row's keys; one whose row is gone fails rather than restarting at page one. Such an id may itself begin k:, so a cursor that reads as keyed is first looked up as an id, and a row holding it is the row it names. A page whose keys JSON cannot carry ends on a cursor naming its row's id (k:{"id":...}), never a bare id.

A key cursor carries those values to the client as they are stored. Ordering already tells a reader how rows compare by a field; the cursor tells them the value at each page's end. Do not offer an order (Order.chosen) by a field some reader may not read.

Client-supplied windows are bounded: the default page size is 20, the default maximum is 100, and malformed combinations such as after + before or first + last fail rather than being guessed.

Does an index serve each page?

Every filter and order a client can ask for is declared, so whether the database can serve them is a question a test can ask before production does. queryPlans runs a first page and a later one of each source, for every order a body lets its reader choose, and asks the database how it plans each: served reads the page in order from an index and stops at its end; sorted reads every matching row and sorts them first, on every request.

ts
import { Effect } from 'effect'
import { queryPlans } from 'foldkit-remote-drizzle'

const plans = await Effect.runPromise(
  queryPlans([{ source: PostsBySlugSource, input: { slug: 'hello' }, principal: null }]).pipe(
    Effect.provide(DatabaseLive),
  ),
)
expect(plans.filter(plan => plan.verdict === 'sorted')).toEqual([])

Each plan carries the statement and the database's own lines, which say which index it used. It asks the database rather than reading the indexes, because what serves an order turns on what the dialect knows:

  • The index matches the order's directions, the id tie-break's included: newest first with ties by id is (owner, created desc, id), not (owner, created, id).
  • On Postgres a text key's index column says collate "C", as the compiled order does (it is what lets a client place rows as the server orders them). An index column of the default collation cannot serve it, even on a database whose default is C: Postgres sorts the ties (Incremental Sort). (owner, created desc, id collate "C") serves it.

Run it over a database migrated as production is, and seed a few rows: the rows decide whether there is a later page to plan, and on SQLite which index the planner picks. Only sources made by query are planned.

An operator the application implements

A primitive operator (Expr.operator without definedAs) is a question each interpreter answers its own way, so a binding runs it by two tables: SQL for what the database runs, memory for what the server decides without it (a predicate over the input alone, a write's miss explained, an insert's invariants judged). bind takes both for the whole domain, each its kernel (Text.startsWith) when not given:

ts
import { sql } from 'drizzle-orm'
import { Expr, Operators } from 'foldkit-entity'
import { DrizzleOperators, bind } from 'foldkit-remote-drizzle'

const above = Expr.operator('acme.above', {
  input: [Schema.Number, Schema.Number],
  output: Schema.Boolean,
})

const Db = bind(
  { Project },
  { Project: { table: projects } },
  {
    operators: {
      memory: Operators.merge(
        Operators.kernel,
        Operators.memory(Operators.implement(above, (value, floor) => value > floor)),
      ),
      sql: DrizzleOperators.merge(
        DrizzleOperators.kernel,
        DrizzleOperators.make(
          DrizzleOperators.implement(above, ({ args: [value, floor] }) => sql`(${value} > ${floor})`),
        ),
      ),
    },
  },
)

An implementation is given its arguments compiled and the dialect. An operator that compares text itself (collation: 'required') is given its text arguments folded under the call's collation (asciiFold lowers ASCII letters, binary leaves them), so none comes beside them. It must agree with the memory implementation, nulls included. Text.startsWith, Expr.add and Expr.sub are metakit's own operations, which carry their SQL: DrizzleOperators.kernel holds none, and an implementation of one is refused. The compiler adds what SQL cannot say for itself:

  • On Postgres, a literal or input argument the operator takes as a number or a boolean is cast (cast($1 as integer) while the value fits one, so a function taking one resolves, and bigint past 32 bits, which Schema.Int admits; double precision; boolean): Postgres reads an untyped parameter as text, and refuses $1 + $2. SQLite takes no cast, since its cast(? as integer) would drop a fraction silently, and binds a boolean as 1 or 0, as it stores one.
  • A call whose result is text, compared with a value, is compared under the call's collation.
  • Text holding NUL given to an operator is refused, as SQL text cannot hold it portably.

A binding that cannot run an operator is refused where it would be needed, naming the operator and the table that lacks it: a query where it is registered, an invariant where the writer is built, a write's when where RemoteServer.write registers it. GuardDrizzle.visible(Policy, entities, { operators }) checks Read rules against the SQL table it is given, since it is built before bind. The client runs the same memory table through Remote.make({ operators }).

A body may order by a call whose result orders alike everywhere: a number, or text under binary or asciiFold. The call is compiled as an expression under its collation, selected beside each row, and pages by its value as a column does, so a cursor resumes after the last row read on SQLite and Postgres alike. Nothing indexes it for you: a list that must page fast over many rows wants an index on the expression. An order term is { key, direction, nulls?, collation? }, where key is a column or a Drizzle SQL expression; an expression says its collation in its own SQL, and one given beside it is refused.

The two implementations must agree, and the conformance helper is how to show it: compileCall(call, binding, name) compiles one call of literals as it would in a body, which a runner selects (select <call> as value) and hands to Conformance.operator from foldkit-entity/conformance beside the memory table's, over generated calls with null, NUL, mixed case under each collation and astral text. test/operatorConformance.test.ts runs Text.startsWith and an application's concat that way on SQLite and Postgres.