Skip to content

Filters: compiler and database adapters

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 conditions

Lowering rules (uniform across every adapter):

  • A field not in spec, or whose filter kind mismatches the spec, is dropped.
  • date preset → gte + lt (resolved Dates).
  • between → gte AND lte; notBetween → lt OR gt. No adapter emits SQL BETWEEN.
  • Text-match ops (contains/ilike/…) stay semantic in the AST so each adapter renders them natively (SQL ILIKE, Mongo $regex, Prisma contains-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 };

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 on 1.0.0-beta and 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 second drizzle-orm copy.

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 ESCAPE option), and drizzle renders the ilike key as ilike, which SQLite and MySQL don’t have. The escaped %/_/\ of contains/startsWith/endsWith rely on Postgres’s default backslash escape. On SQLite/MySQL use the v1 callback below or @xtandard/lib/filters/drizzle, which render like … escape.

Why the native object beats where: { RAW: sql }. Feeding a raw column SQL into 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 + orderBy objects). Typing note: the emitted object is a structural DrizzleRqbWhere; if drizzle’s generated per-table where type 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 | undefined

Kysely — @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 switch
if (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 } | null
if (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 | undefined
const { orderBy } = buildOrderBy({ sql, sort, columns: { name: "tasks.name" } }); // ONE fragment
const 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 await one on its own or return it alone from an async function, since that runs it as a query.
  • orderBy is one comma-joined fragment rather than an array, because both clients join an array of fragments with spaces.
  • A client transform.column.to (postgres.js transform: postgres.camel, Bun transform: SQL.camel) also renames the column strings you map, like every sql("name").
  • Bun.sql’s SQLite adapter can’t bind a Date (it throws), so date presets 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) => boolean
const 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 await

buildFilterNodePredicate 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, not keeps it UNKNOWN, and a row matches only when the whole tree is TRUE. So ne, notInArray and notIlike never match NULL, not (amount > 5) doesn’t match a NULL amount, and x IN (1, NULL) is TRUE for 1 but UNKNOWN for 2 (NOT IN a list with a NULL never matches). An empty IN () is FALSE and NOT IN () TRUE.
  • Text uses LIKE patterns over characters: %, _, and \ escapes the next character. contains/startsWith/endsWith escape the input (escapeLike), so contains "50%" matches a literal 50%. A number matches by its text.
  • Dates: a Date value compares by time with a Date, an ISO-8601 string, epoch milliseconds, or anything with a numeric epochMilliseconds (Temporal.Instant, Temporal.ZonedDateTime). An unparsable value is UNKNOWN.
  • Types aren’t coerced. 5 never equals "5" (a bigint compares with a number numerically); mismatched types are UNKNOWN, even under not.
  • Array ops follow Postgres: arrayContains (@>), arrayContained (<@), arrayOverlaps (&&), with typed elements (2 isn’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 methods
const { 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,b everything after eq. is the value, so nothing is quoted there (quotes would become part of the value).
  • Inside or=(…)/and=(…) and in.(…), 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 a like/ilike value into % and has no escape for it, so a pattern with a literal * is sent as match/imatch (POSIX regex ~/~*) with an escaped, anchored regex instead: contains "a*b" → imatch.a\*b. Literal %/_ are fine: they’re backslash-escaped (Postgres’s default LIKE escape).
  • 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/enum fields must be keyword (or a text field’s .keyword sub-field). term/prefix/wildcard match the indexed term, so on an analyzed text field they compare against tokens, not the original value. A normalizer on the keyword field (e.g. lowercase) also changes eq.
  • case_insensitive needs Elasticsearch 7.10+ (any OpenSearch).
  • Leading-wildcard patterns (contains, endsWith) scan the terms dictionary; on large indices prefer the wildcard field type or an n-gram subfield.
  • date fields parse the ISO strings with their format (the default strict_date_optional_time||epoch_millis does).

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.

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 RQBv2 where object) supports every operator above natively — RQBv2 has ilike + the array ops built in — so it matches the drizzle column on Postgres (its text matches are Postgres-only, see above). It’s listed separately because it returns an object for db.query, not a SQL for db.select().

memory evaluates every operator with the SQL semantics of its dialect (postgres or sqlite, see above); PG/SQL means the array ops follow Postgres or SQLite’s json_each reading of a NULL array.

postgrest renders PostgREST’s own operators, so it inherits Postgres semantics exactly. elasticsearch keeps SQL’s NULL semantics with exists guards (see its section); arrayContained has no script-free equivalent.

drizzle emits the PG array operators only — its array helpers are Postgres-specific. kysely / knex / sql-tag (multi) render the array ops for all three SQL dialects via their dialect option — see below. For MySQL/SQLite the “array” column is a JSON column (no native array type).

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 text
buildWhereSql({
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_OVERLAPS requires 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).
  • ilike is Postgres-only syntax — on MySQL/SQLite it folds to LIKE (case-insensitive by collation / ASCII), the closest portable spelling. like (case-sensitive intent) is unchanged everywhere.
  • LIKE escaping: contains/startsWith/endsWith escape the user’s %, _ and \ with a backslash (escapeLike), so they match literally. Backslash is Postgres’s default LIKE escape; SQLite has none and MySQL loses its default under NO_BACKSLASH_ESCAPES, so those dialects add an ESCAPE clause (MySQL spells it CHAR(92), which means \ in every sql_mode). Your own like/ilike/notIlike patterns 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 unless ANSI_QUOTES is on. Kysely quotes through its own dialect, and sql-tag through your client’s sql(identifier) (Bun.sql uses backticks on MySQL).
  • drizzle has no dialect option: it reads the dialect from the spec’s columns. On a SQLite or MySQL column, text matches render as like ? 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).

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.