Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/filter-condition-logic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@softzweig/spindle-drizzle": minor
---

Conditions compose. `and(...)` and `or(...)` take filter conditions and apply them to the
column their filter key resolved to, reusing drizzle's own `and` and `or`, so one key can
express several operators (#28):

```ts
await assets.findMany({ key: or(ilike("%.png"), like("%.jpg")) });
// ... where ("key" ilike $1 or "key" like $2)
```

An empty `and` is true and an empty `or` is false, the identities drizzle's own functions
give them.
8 changes: 8 additions & 0 deletions packages/drizzle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,14 @@ A `null` value already covers `is null`. Every helper comes from the package roo
surface drizzle uses for its own operators. `ilike` and `notIlike` are Postgres only: SQLite
rejects them, and its `like` is already case insensitive for ASCII.

Conditions compose. `and(...)` and `or(...)` take conditions and apply them to the same
column, so one key can express several operators:

```ts
await assets.findMany({ key: or(ilike("%.png"), like("%.jpg")) });
// ... where ("key" ilike $1 or "key" like $2)
```

Anything the helpers do not cover is `condition(...)` with any drizzle expression, for
example a cast on the column before comparing it. A raw `SQL` value still works too, and
keeps meaning the right-hand side of `=`.
Expand Down
17 changes: 17 additions & 0 deletions packages/drizzle/src/filter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { Column, SQL } from "drizzle-orm";
import {
sql,
and as sqlAnd,
between as sqlBetween,
eq as sqlEq,
gt as sqlGt,
Expand All @@ -15,6 +17,7 @@ import {
notIlike as sqlNotIlike,
notInArray as sqlNotInArray,
notLike as sqlNotLike,
or as sqlOr,
} from "drizzle-orm";

/** Marks a value as a condition, with a well-known symbol no JSON column can reproduce. */
Expand Down Expand Up @@ -48,6 +51,20 @@ export function isFilterCondition(value: unknown): value is FilterCondition {
return (value as { [FILTER_CONDITION]?: unknown })[FILTER_CONDITION] === true;
}

/** @see {@link sqlAnd}, {@link FilterCondition} */
export function and(...conditions: readonly FilterCondition[]): FilterCondition {
return condition(
(column) => sqlAnd(...conditions.map((part) => part.build(column))) ?? sql`true`,
);
}

/** @see {@link sqlOr}, {@link FilterCondition} */
export function or(...conditions: readonly FilterCondition[]): FilterCondition {
return condition(
(column) => sqlOr(...conditions.map((part) => part.build(column))) ?? sql`false`,
);
}

/** @see {@link sqlEq}, {@link FilterCondition} */
export function eq(value: unknown): FilterCondition {
return condition((column) => sqlEq(column, value));
Expand Down
14 changes: 13 additions & 1 deletion packages/drizzle/test/pg-core/repositories.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
type Asset,
describeRepositoryContract,
} from "../../../core/test/contract/repository.contract.js";
import { between, ilike } from "../../src/filter.js";
import { and, between, eq, gt, ilike, like, lt, or } from "../../src/filter.js";
import { PostgresRepository } from "../../src/pg-core/repositories.js";
import { type CreatedAtCursor, pagingByCreatedAt } from "../../src/repository.js";
import { type AssetFilter, type AssetSizeFilter, assets, assetsDdl } from "../support/assets.js";
Expand Down Expand Up @@ -66,6 +66,18 @@ describe("pg-core filter conditions", () => {

expect(found.map((asset) => asset.id)).toEqual(["a_1"]);
});

it("matches composed alternatives on one column", async () => {
const found = await repository.findMany({ key: or(ilike("%.png"), like("%.jpg")) });

expect(found.map((asset) => asset.id).sort()).toEqual(["a_1", "a_2"]);
});

it("nests composed requirements inside alternatives", async () => {
const found = await repository.findMany({ size: or(and(gt(10), lt(50)), eq(7)) });

expect(found.map((asset) => asset.id).sort()).toEqual(["a_1", "a_2"]);
});
});

/** A table whose id and timestamp come from the database, not the caller. */
Expand Down
97 changes: 96 additions & 1 deletion packages/drizzle/test/repository.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,19 @@ import { pgTable, text } from "drizzle-orm/pg-core";
import { drizzle } from "drizzle-orm/pg-proxy";
import { describe, expect, it } from "vitest";
import type { Asset } from "../../core/test/contract/repository.contract.js";
import { between, gt, ilike, isFilterCondition, isNotNull, like, oneOf } from "../src/filter.js";
import {
and,
between,
eq,
gt,
ilike,
isFilterCondition,
isNotNull,
like,
lt,
oneOf,
or,
} from "../src/filter.js";
import { PostgresRepository } from "../src/pg-core/repositories.js";
import {
AbstractDrizzleRepository,
Expand Down Expand Up @@ -464,5 +476,88 @@ describe("AbstractDrizzleRepository", () => {
expect(isFilterCondition({ build: () => undefined })).toBe(false);
expect(isFilterCondition(ilike("%.png"))).toBe(true);
});

it("composes alternatives on one column", async () => {
const { repository, queries } = createRepository();

await repository.findMany({ key: or(ilike("%.png"), like("%.jpg")) });

expect(queries[0]?.sql).toContain('("assets"."key" ilike $1 or "assets"."key" like $2)');
expect(queries[0]?.params).toEqual(["%.png", "%.jpg"]);
});

it("composes requirements on one column", async () => {
const { repository, queries } = createRepository();

await repository.findMany({ size: and(gt(1), lt(10)) });

expect(queries[0]?.sql).toContain('"assets"."size" > $1 and "assets"."size" < $2');
expect(queries[0]?.params).toEqual([1, 10]);
});

it("binds every alternative in the order it was given", async () => {
const { repository, queries } = createRepository();

await repository.findMany({ key: or(ilike("%a%"), like("%b%"), like("%c%")) });

expect(queries[0]?.sql).toContain(
'("assets"."key" ilike $1 or "assets"."key" like $2 or "assets"."key" like $3)',
);
expect(queries[0]?.params).toEqual(["%a%", "%b%", "%c%"]);
});

it("nests requirements inside alternatives", async () => {
const { repository, queries } = createRepository();

await repository.findMany({ size: or(and(gt(1), lt(10)), eq(42)) });

expect(queries[0]?.sql).toContain('"assets"."size" > $1');
expect(queries[0]?.sql).toContain('"assets"."size" < $2');
expect(queries[0]?.sql).toContain('"assets"."size" = $3');
expect(queries[0]?.params).toEqual([1, 10, 42]);
});

it("composes inside a filter with other keys", async () => {
const { repository, queries } = createRepository();

await repository.findMany({ key: or(ilike("%.png"), like("%.jpg")), size: gt(20) });

expect(queries[0]?.sql).toContain('("assets"."key" ilike $1 or "assets"."key" like $2)');
expect(queries[0]?.sql).toContain('"assets"."size" > $3');
expect(queries[0]?.params).toEqual(["%.png", "%.jpg", 20]);
});

it("composes inside a filter write", async () => {
const { repository, queries } = createRepository();

await repository.patchWhere({ size: or(eq(1), eq(2)) }, { size: 5 });

expect(queries[0]?.sql).toContain('update "assets" set');
expect(queries[0]?.sql).toContain('"assets"."size" = $2 or "assets"."size" = $3');
expect(queries[0]?.params).toEqual([5, 1, 2]);
});

it("composes nothing to the logical identity", async () => {
const { repository, queries } = createRepository();

await repository.findMany({ size: or() });
await repository.findMany({ size: and() });

expect(queries[0]?.sql).toContain("where false");
expect(queries[1]?.sql).toContain("where true");
});

it("accepts composed conditions on an identity binding", async () => {
const queries: Query[] = [];
const repository = PostgresRepository.of(
createProxy(queries, () => []),
assets,
);

await repository.findMany({ size: or(eq(1), eq(2)) });

expect(queries[0]?.sql).toContain('("assets"."size" = $1 or "assets"."size" = $2)');
expect(queries[0]?.params).toEqual([1, 2]);
});
});
});
Loading