Skip to main content
Version: Latest - 1.0.0-alpha.38

Filters

Durcno provides a set of type-safe filter operators for building WHERE and CHECK clauses.

Operator Reference​

OperatorDescriptionExample
eq(col, val)Equaleq(Users.type, "admin")
ne(col, val)Not equalne(Users.type, "admin")
gt(col, val)Greater thangt(Users.id, 10n)
gte(col, val)Greater than or equalgte(Users.id, 10n)
lt(col, val)Less thanlt(Users.id, 10n)
lte(col, val)Less than or equallte(Users.id, 10n)
isNull(col)IS NULLisNull(Users.email)
isNotNull(col)IS NOT NULLisNotNull(Users.email)
isIn(col, arrOrSubquery)IN array or subqueryisIn(Users.id, [1n, 2n, 3n])
notIn(col, values)NOT IN arraynotIn(Users.type, ["banned", "deleted"])
exists(subquery)Subquery returns at least one rowexists(db.from(Posts)...)
notExists(subquery)Subquery returns no rowsnotExists(db.from(Posts)...)
startsWith(col, val)Starts with (starts_with(), case-sensitive)startsWith(Users.username, "admin")
endsWith(col, val)Ends with (case-sensitive)endsWith(Users.email, "@test.com")
contains(col, val)Contains (case-sensitive)contains(Users.bio, "typescript")
like(col, pattern)Case-sensitive LIKE; chain .escape(ch)like(Users.code, "US%")
ilike(col, pattern)Case-insensitive ILIKE; chain .escape(ch)ilike(Users.code, "us%")
tsMatch(vector, query)Full-text match (@@)tsMatch(Articles.search, term)
and(...conditions)AND logic; null renders as SQL NULLand(eq(...), gte(...))
or(...conditions)OR logic; null renders as SQL NULLor(eq(...), eq(...))
arrayContains(col, values)Array contains all values (@>)arrayContains(Posts.tags, ["ts", "pg"])
arrayContainedBy(col, vals)Array subset of values (<@)arrayContainedBy(Posts.tags, ["ts", "pg"])
arrayOverlaps(col, values)Array overlaps values (&&)arrayOverlaps(Posts.tags, ["ts"])
arrayHas(col, value)Value exists in array (ANY)arrayHas(Posts.tags, "typescript")
arrayAll(col, value)All elements match value (ALL)arrayAll(Posts.flags, true)

Comparison Operators​

Equal (eq)​

Check if a column equals a value:

import { eq } from "durcno";

// Filter by exact value
await db
.from(Users)
.select("*")
.where(() => eq(Users.type, "admin"));

// Compare two columns
await db
.from(Users)
.innerJoin(Posts)
.on(() => eq(Users.id, Posts.userId))
.select("*");

// Compare against a scalar subquery
await db
.from(Users)
.select("*")
.where(() =>
gt(
Users.score,
db
.from(Users)
.select(() => ({ score: Users.score }))
.where(() => eq(Users.username, "benchmark"))
.limit(1),
)
);

A single-column SelectQuery is accepted wherever a comparison operand is expected; the value is typed T | null.

Column comparisons also accept null. It renders as SQL NULL, so eq(Users.email, null) produces "email" = NULL and matches no rows. Use isNull(Users.email) to match null values.

Not Equal (ne)​

Check if a column does not equal a value:

import { ne } from "durcno";

// Get all non-admin users
await db
.from(Users)
.select("*")
.where(() => ne(Users.type, "admin"));

Greater Than or Equal (gte)​

Check if a column is greater than or equal to a value:

import { gte } from "durcno";

// Get users created after a date
await db
.from(Users)
.select("*")
.where(() => gte(Users.createdAt, new Date("2024-01-01")));

// Get users with id >= 10
await db
.from(Users)
.select("*")
.where(() => gte(Users.id, 10n));

Less Than or Equal (lte)​

Check if a column is less than or equal to a value:

import { lte } from "durcno";

// Get users created before a date
await db
.from(Users)
.select("*")
.where(() => lte(Users.createdAt, new Date("2024-01-01")));

Greater Than (gt)​

Check if a column is strictly greater than a value:

import { gt } from "durcno";

// Get users with id > 10 (excludes 10)
await db
.from(Users)
.select("*")
.where(() => gt(Users.id, 10n));

// Get users created after a date
await db
.from(Users)
.select("*")
.where(() => gt(Users.createdAt, new Date("2024-01-01")));

Less Than (lt)​

Check if a column is strictly less than a value:

import { lt } from "durcno";

// Get users with id < 100 (excludes 100)
await db
.from(Users)
.select("*")
.where(() => lt(Users.id, 100n));

// Get users created before a date
await db
.from(Users)
.select("*")
.where(() => lt(Users.createdAt, new Date("2024-12-31")));

IS NULL (isNull)​

Check if a column is NULL:

import { isNull } from "durcno";

// Get users without an email
await db
.from(Users)
.select("*")
.where(() => isNull(Users.email));

IS NOT NULL (isNotNull)​

Check if a column is not NULL:

import { isNotNull } from "durcno";

// Get users with an email
await db
.from(Users)
.select("*")
.where(() => isNotNull(Users.email));

IN Array (isIn)​

Check if a column value is in an array:

import { isIn } from "durcno";

// Get users with specific IDs
await db
.from(Users)
.select("*")
.where(() => isIn(Users.id, [1n, 2n, 3n]));

// Get users with specific types
await db
.from(Users)
.select("*")
.where(() => isIn(Users.type, ["admin", "user"]));

NOT IN Array or Subquery (notIn)​

Check if a column value is not in an array or subquery:

import { notIn } from "durcno";

// Exclude specific statuses
await db
.from(Users)
.select("*")
.where(() => notIn(Users.type, ["banned", "deleted"]));

// Exclude users who have orders (subquery)
await db
.from(Users)
.select("*")
.where(() =>
notIn(
Users.id,
db.from(Orders).select(() => ({ userId: Orders.userId })),
)
);

Subquery Existence (exists, notExists)​

Check whether a subquery returns any rows using PostgreSQL's EXISTS and NOT EXISTS expressions:

import { eq, exists, notExists } from "durcno";

// Find users who have at least one post (correlated subquery)
const authors = await db
.from(Users)
.select("*")
.where(() =>
exists(
db
.from(Posts)
.select("*")
.where(() => eq(Posts.userId, Users.id)),
)
);

// Find users who have no posts
const nonAuthors = await db
.from(Users)
.select("*")
.where(() =>
notExists(
db
.from(Posts)
.select("*")
.where(() => eq(Posts.userId, Users.id)),
)
);

[!NOTE] isIn, notIn, exists, and notExists are PostgreSQL Subquery Functions. In addition to .where(), they can be used directly in .select() projections as boolean columns and inside caseWhen(...). See Subquery Functions for details.

String Filters​

Durcno provides case-sensitive text search operators:

  • startsWith uses PostgreSQL's starts_with() function
  • endsWith uses LIKE('%' || val)
  • contains uses LIKE('%' || val || '%')
import { contains, endsWith, startsWith } from "durcno";

// startsWith: Match records starting with a prefix (case-sensitive)
await db
.from(Users)
.select("*")
.where(() => startsWith(Users.username, "admin"));

// endsWith: Match records ending with a suffix (case-sensitive)
await db
.from(Users)
.select("*")
.where(() => endsWith(Users.email, "@example.com"));

// contains: Match records containing a substring (case-sensitive)
await db
.from(Users)
.select("*")
.where(() => contains(Users.bio, "typescript"));

LIKE (like)​

Case-sensitive pattern matching using PostgreSQL's LIKE operator. Use % for any sequence of characters and _ for any single character:

import { like } from "durcno";

// Match codes starting with "US" (case-sensitive)
await db
.from(Countries)
.select("*")
.where(() => like(Countries.code, "US%"));

// Match values with exactly 5 characters
await db
.from(Products)
.select("*")
.where(() => like(Products.sku, "_____"));

ILIKE (ilike)​

Case-insensitive pattern matching using PostgreSQL's ILIKE operator:

import { ilike } from "durcno";

// Match email pattern case-insensitively
await db
.from(Users)
.select("*")
.where(() => ilike(Users.email, "%@EXAMPLE.COM"));
tip

Case sensitivity — like, startsWith, endsWith, and contains are case-sensitive matching functions. For case-insensitive pattern matching, use ilike.

Custom escape character (.escape())​

% and _ are wildcards in LIKE and ILIKE patterns. When the pattern needs to match one of those characters literally, chain .escape() to choose an escape character:

import { like } from "durcno";

// Match codes that start with the literal text "100%"
await db
.from(Products)
.select("*")
.where(() => like(Products.code, "100!%%").escape("!"));

escape() returns a new condition and leaves the original predicate unchanged. It accepts a string literal or an Arg<string>; an Arg requires a prepared query:

import { Arg, like, prepare } from "durcno";

const search = prepare(
{ escape: new Arg<string>((value) => value) },
(args) =>
db
.prepare()
.from(Products)
.select("*")
.where(() => like(Products.code, "100!%%").escape(args.escape)),
);

const rows = await search.run(db, { escape: "!" });

Without escape(), PostgreSQL's default escape character is the backslash. Use .escape("") to disable escaping. PostgreSQL requires the escape character to be a single character (or empty).

Full-Text Search (tsMatch)​

tsMatch(vector, query) renders the PostgreSQL @@ operator. It accepts a tsvector expression on the left and a tsquery expression on the right, so a document vector cannot be compared against another vector by mistake.

import { toTsvector, tsMatch, websearchToTsquery } from "durcno";

const term = websearchToTsquery("postgres full text");

// Match the stored search vector
await db
.from(Articles)
.select("*")
.where(() => tsMatch(Articles.search, term));

// Match a vector computed from a text column
await db
.from(Articles)
.select("*")
.where(() => tsMatch(toTsvector(Articles.body, "english"), term));

Use websearchToTsquery for untrusted input, and toTsquery when you control the query syntax. See Full-Text Search Functions for ranking, highlighting, and vector utilities.

Trigram Similarity​

These predicates use PostgreSQL's pg_trgm operators. Each compares two text expressions; a nullable argument makes the result nullable, and a null argument yields SQL NULL.

PredicateSQLDescription
similar(left, right)left % rightWhole-string similarity above the threshold
wordSimilar(term, text)term <% textA word extent of text matches term
strictWordSimilar(term, text)term <<% textA whole word of text matches term

The thresholds come from the session settings pg_trgm.similarity_threshold, pg_trgm.word_similarity_threshold, and pg_trgm.strict_word_similarity_threshold.

import { similar, strictWordSimilar, wordSimilar } from "durcno";

// Whole strings above the similarity threshold
await db
.from(Articles)
.select("*")
.where(() => similar(Articles.title, "postgres"));

// A word extent of the title matches the term
await db
.from(Articles)
.select("*")
.where(() => wordSimilar("postgres", Articles.title));

// A whole word of the title matches the term
await db
.from(Articles)
.select("*")
.where(() => strictWordSimilar("postgres", Articles.title));

Scores for ordering are available as Trigram Similarity Functions. Enable the extension and index setup as described in pg_trgm.

Logical Operators​

Both and() and or() accept null, which renders as SQL NULL and follows PostgreSQL's three-valued logic. They require at least one condition and do not accept undefined. Omit an optional where clause entirely when no filter is needed.

Use true as the neutral condition for and() and false as the neutral condition for or():

const result = await db
.from(Users)
.select("*")
.where(() =>
and(
eq(Users.type, "admin"),
status ? eq(Users.status, "active") : true,
)
);

AND (and)​

Combine multiple conditions with AND logic:

import { and, eq, gte } from "durcno";

// Multiple conditions - all must be true
await db
.from(Users)
.select("*")
.where(() =>
and(eq(Users.type, "admin"), gte(Users.createdAt, new Date("2024-01-01")))
);

// Combine more than two conditions
await db
.from(Users)
.select("*")
.where(() =>
and(eq(Users.type, "admin"), gte(Users.id, 10n), isNotNull(Users.email))
);

OR (or)​

Combine multiple conditions with OR logic:

import { eq, or } from "durcno";

// Either condition can be true
await db
.from(Users)
.select("*")
.where(() => or(eq(Users.type, "admin"), eq(Users.type, "user")));

Combining AND and OR​

Nest and() and or() for complex conditions:

import { and, eq, gte, isNotNull, or } from "durcno";

// (type = 'admin' OR type = 'moderator') AND createdAt >= date
await db
.from(Users)
.select("*")
.where(() =>
and(
or(eq(Users.type, "admin"), eq(Users.type, "moderator")),
gte(Users.createdAt, new Date("2024-01-01")),
)
);

Boolean Literals​

Pass true or false anywhere a filter expression is accepted — .where(), .having(), join .on(), check constraints, and partial index predicates. They render as the PostgreSQL constants TRUE and FALSE.

// Matches every row
await db.from(Users).select("*").where(() => true);

// `false` makes an AND impossible and an OR neutral
await db
.from(Users)
.select("*")
.where(() => and(false, eq(Users.type, "admin")));

await db
.from(Users)
.select("*")
.where(() => or(true, eq(Users.type, "admin")));

Array Operators​

Array operators are useful when working with PostgreSQL array columns.

Array Contains (arrayContains)​

Checks if an array column contains all provided values (@>):

import { arrayContains } from "durcno";

await db
.from(Posts)
.select("*")
.where(() => arrayContains(Posts.tags, ["typescript", "postgres"]));

Array Contained By (arrayContainedBy)​

Checks if an array column is a subset of provided values (<@):

import { arrayContainedBy } from "durcno";

await db
.from(Posts)
.select("*")
.where(() => arrayContainedBy(Posts.tags, ["typescript", "postgres", "orm"]));

Array Overlaps (arrayOverlaps)​

Checks if two arrays share at least one value (&&):

import { arrayOverlaps } from "durcno";

await db
.from(Posts)
.select("*")
.where(() => arrayOverlaps(Posts.tags, ["postgres"]));

Array Has (arrayHas)​

Checks if a value exists in an array column (= ANY(column)):

import { arrayHas } from "durcno";

await db
.from(Posts)
.select("*")
.where(() => arrayHas(Posts.tags, "typescript"));

Array All (arrayAll)​

Checks if all elements in an array column equal the provided value (= ALL(column)):

import { arrayAll } from "durcno";

await db
.from(Posts)
.select("*")
.where(() => arrayAll(Posts.publishedFlags, true));

Column Comparisons​

All comparison operators support comparing two columns:

import { eq, gte } from "durcno";

// Join condition: compare columns from different tables
await db
.from(Users)
.innerJoin(Posts)
.on(() => eq(Users.id, Posts.userId))
.select("*");

// Compare columns from the same table
await db
.from(Events)
.select("*")
.where(() => gte(Events.endDate, Events.startDate));

Raw SQL in Filters​

Use sql() for custom SQL expressions in filters:

import { sql } from "durcno";

await db
.from(Users)
.select("*")
.where(() => sql`LOWER(username) = 'admin'`);