Filters: compiler and database adapters
The portable compiler
Section titled “The portable compiler”Adapters call the core compiler for you, but you can use it directly to write a new adapter:
import { compileFilters, compileFilterNode } from "@xtandard/lib/filters";
const { where } = compileFilters({ spec: { status: "enum", amount: "number" }, // field → kind allow-list filters, resolveDate, // required iff a `date` preset is present});// where: CompiledWhere | null — an and/or/not tree of normalized leaf conditionsLowering rules (uniform across every adapter):
- A field not in
spec, or whose filterkindmismatches the spec, is dropped. datepreset →gte+lt(resolvedDates).between→gte AND lte;notBetween→lt OR gt. No adapter emits SQLBETWEEN.- Text-match ops (
contains/ilike/…) stay semantic in the AST so each adapter renders them natively (SQLILIKE, Mongo$regex, Prismacontains-mode).
How one ColumnFilter is lowered:
flowchart TD
CF["ColumnFilter { field, filter }"] --> ALLOW{"spec[field] === filter.kind?"}
ALLOW -->|no| DROP["dropped"]
ALLOW -->|yes| OP{"kind / operator"}
OP -->|"number: between"| BTW["and( gte from, lte to )"]
OP -->|"number: notBetween"| NBT["or( lt from, gt to )"]
OP -->|"date preset"| DATE["resolveDate, then<br/>and( gte start, lt end )"]
OP -->|"anything else"| LEAF["one cond leaf<br/>{ field, op, value or values }"]
CompiledWhere shape:
type CompiledWhere = | { type: "cond"; cond: CompiledCond } | { type: "and"; nodes: CompiledWhere[] } | { type: "or"; nodes: CompiledWhere[] } | { type: "not"; node: CompiledWhere };Adapters
Section titled “Adapters”Every adapter exposes typed dateField/textField/numberField/enumField/
booleanField/arrayField spec builders (the allow-list + column/path
mapping) and buildWhere / buildFilterNode (the in-memory adapter’s are
buildFilterPredicate / buildFilterNodePredicate). They differ only in the
column reference type and the WHERE representation.
Drizzle — @xtandard/lib/filters/drizzle (peer drizzle-orm v0.45+ or v1, incl. 1.0.0-beta)
Section titled “Drizzle — @xtandard/lib/filters/drizzle (peer drizzle-orm v0.45+ or v1, incl. 1.0.0-beta)”The spec builders constrain the column by its SELECT type, so a kind↔column
mismatch is a compile error (dateField needs ColumnOf<Date>, etc.).
import { buildWhere, buildOrderBy, createDrizzleKeyset, dateField, textField, numberField, enumField,} from "@xtandard/lib/filters/drizzle";
const spec = { name: textField({ column: tasks.name }), status: enumField({ column: tasks.status }), amount: numberField({ column: tasks.amount }), createdAt: dateField({ column: tasks.createdAt }),};
const { where } = buildWhere({ spec, filters, resolveDate });const { orderBy } = buildOrderBy({ sort, columns: { name: tasks.name, createdAt: tasks.createdAt },});
const rows = await db .select() .from(tasks) .where(where) .orderBy(...orderBy);For cursor pagination, createDrizzleKeyset({ sort, columns }) returns
keys()/orderBy()/where() (rendered from the portable @xtandard/lib/pagination
keyset — self-contained, no separate pagination/drizzle import needed), and
combineWhere(...) ANDs the filter WHERE with the keyset seek. Use
toDrizzleWhere({ where, columns }) to render a pre-compiled AST directly.
drizzle-orm v0.45 and v1 are both supported. The peer range is
>=0.45.0 || >=1.0.0-0, so this adapter works on1.0.0-betaand the stable v1 line too — only the core SQL expression builders (eq/and/or/ilike/arrayContains/…,SQL,AnyColumn) are used, which are unchanged across the v1 RQBv2 break. A consumer pinned to a single v1-beta install gets no seconddrizzle-ormcopy.
Drizzle RQB v2 — @xtandard/lib/filters/drizzle-rqb (no driver dependency)
Section titled “Drizzle RQB v2 — @xtandard/lib/filters/drizzle-rqb (no driver dependency)”For drizzle v1’s relational query builder (db.query.<table>.findMany), the
where is a plain OBJECT, not a SQL. This adapter renders the AST to that
object so you can use the RQB (with its relation filters, nested with, etc.)
instead of db.select(). It emits a plain object — no drizzle-orm import,
no peer. Its typings need TypeScript 5.4+ (they use NoInfer).
import { buildWhere, textField, numberField, dateField } from "@xtandard/lib/filters/drizzle-rqb";
// `column` is the RQBv2 schema PROPERTY key (e.g. "createdAt"), not the SQL column name.const spec = { name: textField({ column: "name" }), amount: numberField({ column: "amount" }), createdAt: dateField({ column: "createdAt" }),};
const { where } = buildWhere({ spec, filters, resolveDate });const rows = await db.query.tasks.findMany({ where, limit: 20 });// where → { AND: [ { name: { ilike: "%ab%" } }, { amount: { gte: 1 } }, … ] }Operator map (1:1 with RQBv2): eq/ne/gt/gte/lt/lte; set →
in/notIn; text → like/ilike/notIlike (contains/startsWith/endsWith
lower to ilike); isNull/isNotNull → { isNull: true }/{ isNotNull: true };
array → arrayContains/arrayContained/arrayOverlaps; tree → AND/OR/NOT.
between/notBetween are lowered upstream to gte+lte / lt+gt.
The v2 object’s text matches are Postgres-only. A v2 column filter takes a bare pattern (there is no
ESCAPEoption), and drizzle renders theilikekey asilike, which SQLite and MySQL don’t have. The escaped%/_/\ofcontains/startsWith/endsWithrely on Postgres’s default backslash escape. On SQLite/MySQL use the v1 callback below or@xtandard/lib/filters/drizzle, which renderlike … escape.
Why the native object beats
where: { RAW: sql }. Feeding a raw columnSQLinto the RQB breaks because the RQB aliases the root table (invalid reference to FROM-clause entry). The native object references columns by their property key, so drizzle resolves them against the aliased table itself — sidestepping that footgun. For keyset/cursor pagination on the RQB, pair it with@xtandard/lib/pagination/drizzle-rqb(toDrizzleRqbKeyset→where+orderByobjects). Typing note: the emitted object is a structuralDrizzleRqbWhere; if drizzle’s generated per-tablewheretype is stricter, annotate at the call site.
Legacy RQB v1 (the older callback where: (fields, operators) => SQL, e.g.
db._query on drizzle v1 or db.query on 0.x) is in the same subpath:
buildRqbV1Where/buildRqbV1FilterNode return { where } where where is that
callback. It builds via the operators and fields the callback provides (not
raw imported columns), so column refs resolve against the aliased table — same
alias-safety as the v2 object. Drizzle’s v1 operators have no array helpers, so
the array ops are built with the sql tag they do carry (Postgres
@>/<@/&&, values bound through the column like drizzle’s own
arrayContains). On a SQLite or MySQL column (read from the column drizzle
passes in), text matches render as like … escape instead of ilike, as in the
drizzle adapter.
import { buildRqbV1Where, textField } from "@xtandard/lib/filters/drizzle-rqb";
const { where } = buildRqbV1Where({ spec: { name: textField({ column: "name" }) }, filters });const rows = await db._query.tasks.findMany({ where }); // where: (fields, ops) => SQL | undefinedKysely — @xtandard/lib/filters/kysely (peer kysely)
Section titled “Kysely — @xtandard/lib/filters/kysely (peer kysely)”Columns are string references (passed to sql.ref) or sql RawBuilders.
Dialect-aware via dialect (default "postgres") — see
SQL dialects below.
import { buildWhere, buildOrderBy, textField, dateField } from "@xtandard/lib/filters/kysely";
const spec = { name: textField({ column: "tasks.name" }), createdAt: dateField({ column: "tasks.created_at" }),};
let q = db.selectFrom("tasks").selectAll();const { where } = buildWhere({ spec, filters, resolveDate }); // dialect: "mysql" | "sqlite" to switchif (where) q = q.where(where);for (const o of buildOrderBy({ sort, columns: { name: "tasks.name" } }).orderBy) q = q.orderBy(o);Knex — @xtandard/lib/filters/knex (no driver dependency)
Section titled “Knex — @xtandard/lib/filters/knex (no driver dependency)”Renders raw, parameterized SQL (? bindings); column identifiers are
server-owned and validated (col or table.col, quoted per part).
Dialect-aware via dialect (default "postgres").
import { applyFiltersToKnex, buildWhereSql, textField, numberField,} from "@xtandard/lib/filters/knex";
const spec = { name: textField({ column: "name" }), amount: numberField({ column: "amount" }) };
// apply directly:const rows = await applyFiltersToKnex(knex("tasks"), { spec, filters, resolveDate });// or get the fragment (pass dialect for MySQL/SQLite):const fragment = buildWhereSql({ spec, filters, resolveDate, dialect: "mysql" }); // { sql, bindings } | nullif (fragment) query.whereRaw(fragment.sql, fragment.bindings);Bun.sql / postgres.js — @xtandard/lib/filters/sql-tag (no driver dependency)
Section titled “Bun.sql / postgres.js — @xtandard/lib/filters/sql-tag (no driver dependency)”For tagged-template SQL clients: Bun.sql
(sql / new SQL(…), on Postgres, MySQL/MariaDB or SQLite) and
postgres.js (v3 and v4, including the sql of a
transaction or reserved connection). You pass your sql; the result is a fragment of
that client that you embed in your own query, so there’s no driver import and nothing
to apply. Columns are strings (validated col / table.col, then quoted by your
client’s sql(identifier)) or any fragment of your sql (e.g. sql`lower(name)`).
Dialect-aware via dialect (default "postgres"; "mysql" / "sqlite" for
Bun.sql’s other adapters) — see SQL dialects below.
import postgres from "postgres"; // or: import { sql } from "bun";import { buildOrderBy, buildWhere, numberField, textField } from "@xtandard/lib/filters/sql-tag";
const sql = postgres(process.env.DATABASE_URL);const spec = { name: textField({ column: "tasks.name" }), amount: numberField({ column: "tasks.amount" }),};
const { where } = buildWhere({ sql, spec, filters, resolveDate }); // fragment | undefinedconst { orderBy } = buildOrderBy({ sql, sort, columns: { name: "tasks.name" } }); // ONE fragmentconst rows = await sql` select * from tasks ${where ? sql`where ${where}` : sql``} order by ${orderBy ?? sql`id`} limit ${limit}`;// select * from tasks where ("tasks"."name" ILIKE $1 AND "tasks"."amount" >= $2) order by …Every keyword is fixed template text and every value a parameter: the adapter never
calls sql.unsafe, and IN lists bind one parameter per value (IN ($1, $2)). It
renders the same SQL as the Knex adapter, with the client numbering the placeholders
($n on Postgres, ? on MySQL/SQLite) and quoting identifiers (backticks on MySQL).
- The fragments are lazy queries (thenables): embed them; never
awaitone on its own or return it alone from anasyncfunction, since that runs it as a query. orderByis one comma-joined fragment rather than an array, because both clients join an array of fragments with spaces.- A client
transform.column.to(postgres.jstransform: postgres.camel, Buntransform: SQL.camel) also renames the column strings you map, like everysql("name"). - Bun.sql’s SQLite adapter can’t bind a
Date(it throws), sodatepresets need Bun.sql on Postgres or MySQL (or another SQLite driver that accepts dates).
Mongo / Mongoose — @xtandard/lib/filters/mongo (no driver dependency)
Section titled “Mongo / Mongoose — @xtandard/lib/filters/mongo (no driver dependency)”Returns a plain Mongo filter object. Columns are dotted paths.
import { buildFilter, textField, numberField, dateField } from "@xtandard/lib/filters/mongo";
const spec = { name: textField({ path: "name" }), amount: numberField({ path: "amount" }), createdAt: dateField({ path: "createdAt" }),};const { filter } = buildFilter({ spec, filters, resolveDate });const docs = await collection.find(filter ?? {}).toArray();Mapping: scalar → $eq/$ne/$lt/…; text → $regex (like/ilike translate
the SQL pattern to a regex); set → $in/$nin; arrayContains (@>) → $all,
arrayOverlaps (&&) → $in, arrayContained (<@) →
{ $expr: { $setIsSubset: ["$path", values] } }; and/or/not →
$and/$or/$nor; isNull → { $eq: null }.
Prisma — @xtandard/lib/filters/prisma (no driver dependency)
Section titled “Prisma — @xtandard/lib/filters/prisma (no driver dependency)”Returns a plain Prisma where object. Columns are field names.
import { buildWhere, textField, numberField } from "@xtandard/lib/filters/prisma";
const spec = { name: textField({ field: "name" }), amount: numberField({ field: "amount" }) };const { where } = buildWhere({ spec, filters, resolveDate });const rows = await prisma.task.findMany({ where });Mapping: scalar → equals/not/lt/…; text → contains/startsWith/endsWith
with mode: "insensitive"; set → in/notIn; array → hasEvery (@>) /
hasSome (&&); and/or/not → AND/OR/NOT.
Limitations (throw with a clear message): Prisma’s where has no raw LIKE,
so like/ilike/notIlike reduce to contains/startsWith/endsWith when
the pattern allows (%x%/x%/%x); patterns with internal %/_ throw (use
$queryRaw). arrayContained has no Prisma operator and throws.
In memory — @xtandard/lib/filters/memory (no dependencies)
Section titled “In memory — @xtandard/lib/filters/memory (no dependencies)”Evaluates the AST in JavaScript: a plain (row) => boolean predicate, plus a sort
comparator and synchronous offset/cursor pagination over arrays. Use it for
client-side tables, tests, or an in-browser “server” that must answer exactly like
the real one. Fields read a property key, a dot path ("address.city") or a getter
function.
import { applyFiltersToArray, buildComparator, buildFilterPredicate, createMemoryPaginator, dateField, numberField, textField,} from "@xtandard/lib/filters/memory";
const spec = { name: textField({ path: "name" }), city: textField({ path: "address.city" }), total: numberField({ path: (o: Order) => o.cents / 100 }), createdAt: dateField({ path: "createdAt" }), // Date, ISO string, epoch ms or Temporal.Instant};
const { predicate } = buildFilterPredicate({ spec, filters, resolveDate }); // (row) => booleanconst matching = applyFiltersToArray(orders, { spec, filters, resolveDate }); // same, as a new array
const { compare } = buildComparator({ sort, paths: { name: "name", createdAt: "createdAt" } });const sorted = [...matching].sort(compare);
const paginator = createMemoryPaginator({ rows: matching, sort: [{ key: "createdAt", order: "desc" }, { key: "id" }], // unique tiebreaker last});const page = paginator.paginate({ type: "cursor", limit: 20, cursor }); // sync, no awaitbuildFilterNodePredicate takes a FilterNode tree and toFilterPredicate({ where, paths }) renders a pre-compiled CompiledWhere. When no filter survives the
allow-list, the predicate matches every row.
Same semantics as the SQL adapters (a test runs one fixture through this adapter and through knex, kysely and drizzle on a real SQLite, and checks they pick the same rows):
- NULL is SQL’s three-valued logic. A comparison with NULL (or a missing
property) is UNKNOWN,
notkeeps it UNKNOWN, and a row matches only when the whole tree is TRUE. Sone,notInArrayandnotIlikenever match NULL,not (amount > 5)doesn’t match a NULLamount, andx IN (1, NULL)is TRUE for 1 but UNKNOWN for 2 (NOT INa list with a NULL never matches). An emptyIN ()is FALSE andNOT IN ()TRUE. - Text uses
LIKEpatterns over characters:%,_, and\escapes the next character.contains/startsWith/endsWithescape the input (escapeLike), socontains "50%"matches a literal50%. A number matches by its text. - Dates: a
Datevalue compares by time with aDate, an ISO-8601 string, epoch milliseconds, or anything with a numericepochMilliseconds(Temporal.Instant,Temporal.ZonedDateTime). An unparsable value is UNKNOWN. - Types aren’t coerced.
5never equals"5"(abigintcompares with a number numerically); mismatched types are UNKNOWN, even undernot. - Array ops follow Postgres:
arrayContains(@>),arrayContained(<@),arrayOverlaps(&&), with typed elements (2isn’t"2").
dialect (default "postgres", like the kysely/knex option) picks the engine to
copy where Postgres and SQLite disagree:
| behaviour | postgres (default) |
sqlite |
|---|---|---|
like |
case-sensitive | ignores ASCII case |
ilike, contains, … |
ignores case, Unicode (Á = á) |
ignores ASCII case only (Á ≠ á) |
| NULLs in a sort | largest: last ascending, first descending | smallest: first ascending, last descending |
| array op on a NULL array | UNKNOWN (no match, even under not) |
an empty list (json_each): arrayContained matches it |
There is no mysql: MySQL’s = and LIKE follow the column collation (usually
case- and accent-insensitive), which an evaluator can’t know.
Sorting. buildComparator({ sort, paths, defaultSort }) is the in-memory
buildOrderBy: fields missing from paths are dropped, defaultSort applies when
nothing is left, keys apply in order and ties keep the input order
(Array.prototype.sort is stable). Strings compare by code point (SQLite’s BINARY,
Postgres’s "C" collation), not by locale; booleans false before true. NULLs
follow dialect, or pass nulls: "first" | "last" for NULLS FIRST/NULLS LAST.
Pagination. createMemoryPaginator({ rows, sort }) is createPaginator from
@xtandard/lib/pagination with array fetchers, so every input style works and
paginate returns a plain value: page/offset requests slice the sorted rows and
report totalItems; cursor requests seek with createMemoryKeyset (the in-memory
createDrizzleKeyset: keys(), compare(direction), where(cursor, direction),
fromItem(row)), forward or backward. The seek uses the comparator’s order, NULLs
included, so rows with a NULL sort key page correctly (SQL’s > never matches NULL).
PostgREST / Supabase — @xtandard/lib/filters/postgrest (no driver dependency)
Section titled “PostgREST / Supabase — @xtandard/lib/filters/postgrest (no driver dependency)”Returns PostgREST query parameters as unencoded [key, value] pairs
(PostgrestParams). Columns are PostgREST column names, optionally with
->/->> JSON path steps (meta->>city); anything else throws.
import { applyParamsToPostgrest, buildOrder, buildParams, numberField, textField,} from "@xtandard/lib/filters/postgrest";
const spec = { name: textField({ column: "name" }), amount: numberField({ column: "amount" }) };const { params } = buildParams({ spec, filters, resolveDate });// → [["name", "ilike.*ann*"], ["amount", "gte.100"]]
// plain fetch (any PostgREST server):const qs = new URLSearchParams([...params, ["order", "created_at.desc"], ["limit", "20"]]);const rows = await fetch(`${POSTGREST_URL}/tasks?${qs}`).then((r) => r.json());
// supabase-js / postgrest-js: the same params through the builder's public methodsconst { order } = buildOrder({ sort, columns: { createdAt: "created_at" }, nulls: "last" });let query = applyParamsToPostgrest(supabase.from("tasks").select("*"), params);for (const t of order) query = query.order(t.column, t);const { data } = await query.range(offset, offset + limit - 1);Mapping: eq/ne/lt/… → eq./neq./lt.; set → in.(…) / not.in.(…);
isNull → is.null, isNotNull → not.is.null; contains/startsWith/
endsWith → ilike with * wildcards (the user’s %, _, \ escaped);
like/ilike/notIlike pass the pattern through with % spelled *; array
ops → cs/cd/ov (@>/<@/&&) with a Postgres array literal; dates →
ISO-8601 instants. A top-level and becomes one param per condition (PostgREST
ANDs them), or → or=(…), a negated group → not.or=(…)/not.and=(…), a
negated condition → the not. operator prefix.
How values are spelled (checked against PostgREST’s parser,
ApiRequest/QueryParams.hs):
- Top-level values are raw. In
name=eq.a,beverything aftereq.is the value, so nothing is quoted there (quotes would become part of the value). - Inside
or=(…)/and=(…)andin.(…), a value holding a reserved character (, . : * ( )), a"/\, edge whitespace, or nothing at all is double-quoted, with"and\backslash-escaped:or=(name.eq."Rent, May",…). - Array literals always quote their string elements:
cs.{"a,b","x"}. - A literal
*in a pattern. PostgREST turns every*in alike/ilikevalue into%and has no escape for it, so a pattern with a literal*is sent asmatch/imatch(POSIX regex~/~*) with an escaped, anchored regex instead:contains "a*b"→imatch.a\*b. Literal%/_are fine: they’re backslash-escaped (Postgres’s defaultLIKEescape). - Reserved column names. A filter on a column named
order,limit,select,or, … can’t be a top-level param, so it’s wrapped:and=(order.eq.a).
applyParamsToPostgrest(builder, params) works with anything that has
filter(column, operator, value) and or(filters) (postgrest-js, supabase-js,
@neondatabase/postgrest-js): column params go through .filter(), logic
params through .or() (and=(…) as .or("and(…)")). applyFiltersToPostgrest
compiles and applies in one call. Filters on embedded resources
(author.name=…) are out of scope: expose the column through a view.
Sorting → buildOrder({ sort, columns, defaultSort, nulls }) gives
{ column, ascending, nullsFirst? } terms, ready for postgrest-js’s
.order(column, { ascending, nullsFirst }); formatOrder(terms) gives the raw
order= value (created_at.desc.nullslast,id.asc). Keyset pagination →
createPostgrestKeyset({ sort, columns }) (keys(), orderBy(direction),
where(cursor, direction) → [["or", "(created_at.lt.…,and(created_at.eq.…,id.lt.9))"]]).
Offset pagination is PostgREST’s own limit/offset (or .range(from, to)).
Elasticsearch / OpenSearch — @xtandard/lib/filters/elasticsearch (no client dependency)
Section titled “Elasticsearch / OpenSearch — @xtandard/lib/filters/elasticsearch (no client dependency)”Returns a Query DSL clause (plain objects) for @elastic/elasticsearch,
@opensearch-project/opensearch or a raw _search body. Fields are index
field names (dot paths allowed).
import { buildQuery, buildSort, dateField, numberField, textField,} from "@xtandard/lib/filters/elasticsearch";
const spec = { name: textField({ field: "name.keyword" }), // keyword sub-field, see below amount: numberField({ field: "amount" }), createdAt: dateField({ field: "createdAt" }),};const { query } = buildQuery({ spec, filters, resolveDate });const { sort } = buildSort({ sort: request.sort, fields: { createdAt: "createdAt" } });const res = await client.search({ index: "tasks", query: { bool: { filter: query ? [query, { term: { tenantId } }] : [{ term: { tenantId } }] } }, sort, size: 20,});Mapping: eq → term; lt/gt/… → range; set → terms; isNotNull →
exists, isNull → must_not: exists; contains/endsWith → wildcard and
startsWith → prefix, both with case_insensitive: true; like/ilike →
wildcard (% → *, _ → ?; literal *, ?, \ escaped with \, Lucene’s
wildcard escape) — like case-sensitive, ilike with case_insensitive;
arrayContains → one term per value in bool.filter (all must be present),
arrayOverlaps → terms; dates → ISO-8601 strings in range; and →
bool.filter, or → bool.should + minimum_should_match: 1. Everything is
filter context (no scoring) — put the clause in your bool.filter and keep
full-text match queries in must.
NULL semantics match SQL. exists is false for a missing field, null,
[], and values dropped by ignore_above/ignore_malformed — all treated as
SQL NULL. In SQL, amount <> 5 and NOT (amount < 5) are UNKNOWN (no match)
when amount is NULL; a naive must_not would match those documents. So ne,
notInArray, notIlike and every not add an exists guard
({ bool: { filter: [{ exists }], must_not: [p] } }), and a not over a group
is pushed down with De Morgan, so every adapter returns the same rows. (On a
multi-valued field, ne means “has values, none equal”.)
Mapping assumptions:
text/enumfields must bekeyword(or a text field’s.keywordsub-field).term/prefix/wildcardmatch the indexed term, so on an analyzedtextfield they compare against tokens, not the original value. Anormalizeron the keyword field (e.g.lowercase) also changeseq.case_insensitiveneeds Elasticsearch 7.10+ (any OpenSearch).- Leading-wildcard patterns (
contains,endsWith) scan the terms dictionary; on large indices prefer thewildcardfield type or an n-gram subfield. datefields parse the ISO strings with theirformat(the defaultstrict_date_optional_time||epoch_millisdoes).
Not expressible: arrayContained (every element of the field is in the
list) has no script-free Query DSL form, so it throws. If you need it, use a
terms_set query with
minimum_should_match_script: { source: "doc['tags'].size()" }. An empty array
and a missing field are indistinguishable in the index, so [] behaves like
NULL (Postgres would treat '{}' as a value).
Sorting → buildSort({ sort, fields, defaultSort, nulls }) gives the sort
array ([{ createdAt: { order: "desc" } }]); nulls sets missing
(Elasticsearch’s default is _last in both directions, unlike Postgres).
Keyset pagination → createElasticsearchKeyset({ sort, fields }) with
sort(direction) and searchAfter(cursor) for search_after — see
docs/PAGINATION.md.
Operator support matrix
Section titled “Operator support matrix”| op | drizzle | kysely | knex | sql-tag | mongo | prisma | memory | postgrest | elasticsearch |
|---|---|---|---|---|---|---|---|---|---|
| scalar, set, unary | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ exists guard |
between/notBetween (→ half-open) |
✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
contains/startsWith/endsWith |
✅ ILIKE | ✅ ILIKE | ✅ ILIKE | ✅ ILIKE | ✅ regex | ✅ mode | ✅ ILIKE | ✅ ilike |
✅ wildcard/prefix |
like/ilike/notIlike (raw pattern) |
✅ | ✅ | ✅ | ✅ | ✅ regex | ⚠️ reduced or throws | ✅ | ✅ (imatch for *) |
✅ wildcard |
arrayContains (@>) |
✅ PG | ✅ multi | ✅ multi | ✅ multi | ✅ $all |
✅ hasEvery |
✅ PG/SQL | ✅ cs |
✅ terms |
arrayOverlaps (&&) |
✅ PG | ✅ multi | ✅ multi | ✅ multi | ✅ $in |
✅ hasSome |
✅ PG/SQL | ✅ ov |
✅ terms |
arrayContained (<@) |
✅ PG | ✅ multi | ✅ multi | ✅ multi | ✅ $setIsSubset |
❌ throws | ✅ PG/SQL | ✅ cd |
❌ throws |
| date preset (→ gte/lt) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
drizzle-rqb(the RQBv2whereobject) supports every operator above natively — RQBv2 hasilike+ the array ops built in — so it matches thedrizzlecolumn on Postgres (its text matches are Postgres-only, see above). It’s listed separately because it returns an object fordb.query, not aSQLfordb.select().
memory evaluates every operator with the SQL semantics of its
dialect(postgresorsqlite, see above);PG/SQLmeans the array ops follow Postgres or SQLite’sjson_eachreading of a NULL array.
postgrest renders PostgREST’s own operators, so it inherits Postgres semantics exactly. elasticsearch keeps SQL’s NULL semantics with
existsguards (see its section);arrayContainedhas no script-free equivalent.
drizzle emits the PG array operators only — its array helpers are Postgres-specific. kysely / knex / sql-tag (
multi) render thearrayops for all three SQL dialects via theirdialectoption — see below. For MySQL/SQLite the “array” column is a JSON column (no native array type).
SQL dialects (array ops + ilike)
Section titled “SQL dialects (array ops + ilike)”The kysely, knex and sql-tag adapters take an optional dialect: "postgres" | "mysql" | "sqlite" (default "postgres"). It changes the ops with no portable
spelling — the array ops and case-insensitive ilike — plus the LIKE
escape clause and (knex only) identifier quoting; everything else is identical
across dialects.
| op | postgres |
mysql (JSON column) |
sqlite (JSON column, JSON1) |
|---|---|---|---|
arrayContains (A ⊇ B) |
col @> ? |
JSON_CONTAINS(col, ?) |
NOT EXISTS (… json_each(?) … NOT IN (json_each(col))) |
arrayContained (A ⊆ B) |
col <@ ? |
JSON_CONTAINS(?, col) |
NOT EXISTS (… json_each(col) … NOT IN (json_each(?))) |
arrayOverlaps (A ∩ B≠∅) |
col && ? |
JSON_OVERLAPS(col, ?) |
EXISTS (… json_each(col) … IN (json_each(?))) |
contains/…/ilike |
col ILIKE ? |
col LIKE ? ESCAPE CHAR(92) |
col LIKE ? ESCAPE '\' |
// MySQL: arrayContains on a JSON column → JSON_CONTAINS, candidate bound as JSON textbuildWhereSql({ spec: { tags: arrayField({ column: "tags" }) }, filters: [ { field: "tags", filter: { kind: "array", operator: "arrayContains", values: ["a", "b"] } }, ], dialect: "mysql",});// → { sql: "JSON_CONTAINS(`tags`, ?)", bindings: ['["a","b"]'] }Notes:
- MySQL needs the column typed
JSON;JSON_OVERLAPSrequires MySQL 8.0.17+. - SQLite needs the JSON1 extension (bundled by default since 3.38) and the
list stored as a JSON array text; the
json_each(…)subqueries handle duplicates correctly (set semantics). ilikeis Postgres-only syntax — on MySQL/SQLite it folds toLIKE(case-insensitive by collation / ASCII), the closest portable spelling.like(case-sensitive intent) is unchanged everywhere.LIKEescaping:contains/startsWith/endsWithescape the user’s%,_and\with a backslash (escapeLike), so they match literally. Backslash is Postgres’s defaultLIKEescape; SQLite has none and MySQL loses its default underNO_BACKSLASH_ESCAPES, so those dialects add anESCAPEclause (MySQL spells itCHAR(92), which means\in everysql_mode). Your ownlike/ilike/notIlikepatterns get the same clause, so\escapes a wildcard on all three dialects.- knex on MySQL quotes identifiers with backticks (
`tasks`.`status`); double quotes would be string literals unlessANSI_QUOTESis on. Kysely quotes through its own dialect, and sql-tag through your client’ssql(identifier)(Bun.sql uses backticks on MySQL). - drizzle has no
dialectoption: it reads the dialect from the spec’s columns. On a SQLite or MySQL column, text matches render aslike ? escape '\'/like ? escape char(92)(same reasoning as above); its array helpers stay Postgres-only.drizzle-rqb’s v1 callback does the same; its v2 object can’t (see the RQB section).
Writing your own adapter
Section titled “Writing your own adapter”Call compileFilters and walk the CompiledWhere AST. A minimal sketch:
import { compileFilters, type CompiledWhere } from "@xtandard/lib/filters";
function render(node: CompiledWhere): MyWhere { switch (node.type) { case "cond": return myLeaf(node.cond); // CompiledCond: { field, op } + value | values (none for isNull/isNotNull) case "and": return myAnd(node.nodes.map(render)); case "or": return myOr(node.nodes.map(render)); case "not": return myNot(render(node.node)); }}
export function buildWhere(input: { spec: Record<string, FieldKind>; filters: ColumnFilter[]; resolveDate?: DateFilterResolver;}) { const { where } = compileFilters(input); return where ? render(where) : undefined;}The AST already resolves dates, lowers between, and drops non-allow-listed
fields, so an adapter only maps the 19 normalized leaf ops (CompiledOp) + and/or/not.