Entity / Operators

An operator of your own

For custom operations like numeric distance, declare the operator and provide both Operators.memory and DrizzleOperators.make implementations:

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

const distance = Expr.operator('acme.distance', {
  input: [Schema.Int, Schema.Int],
  output: Schema.Int,
  description: 'How far the first number lies from the second.',
})

const memory = Operators.merge(
  Operators.kernel,
  Operators.memory(Operators.implement(distance, (cents, target) => Math.abs(cents - target))),
)
const sqlOperators = DrizzleOperators.merge(
  DrizzleOperators.kernel,
  DrizzleOperators.make(
    DrizzleOperators.implement(distance, ({ args: [cents, target] }) => sql`abs(${cents} - ${target})`),
  ),
)
  • Server wiring: Pass { operators: { memory, sql: sqlOperators } } to bind and { operators } to GuardDrizzle.visible. Missing implementations fail at registration rather than on the first request.
  • Client wiring: Pass { operators: memory } to Remote.make so browser filtering and sorting match the server.
  • Null handling: Arguments are strict by default (any null produces null without calling your function); pass nulls: 'handled' with Operators.implementHandlingNulls to customize null behavior.
  • Text collations: Pass collation: 'operands' on string-returning operators so output inherits input collation.

Ordering by a computed value

Any numeric or collated-text operator works directly in Query.orderBy:

ts
const budget = Expr.input('budget', Schema.Int)
const Nearest = Query.from(Product).pipe(Query.orderBy(Order.asc(distance(fields.cents, budget))))

Both SQL (keyset pagination included) and the browser sort by distance, breaking ties by row ID. Add a SQL expression index if sorting large tables by a computed call.