Quick start · Playground · Benchmarks · Docs
drizzle-resource builds the list endpoints of an app on top of Drizzle ORM. You define a resource once on a table: which relations it loads, which fields can be filtered, searched, sorted and counted, and the tenant condition every query must carry. Each request is then checked against that definition, turned into SQL, and returned as typed rows with page info, facet counts and totals.
Field paths such as customer.name or orderLines.product.category are typed from your schema and relations, so a typo is a compile error. The tenant scope comes from your server context, never from the request, so a client cannot remove it.
bun add drizzle-resource # or: pnpm add / npm installRequires drizzle-orm >= 1.0.0-rc.5 with relational queries.
import { createQueryEngine } from "drizzle-resource";
import { db } from "./db";
import { relations } from "./relations";
import { schema } from "./schema";
// Once per app. `withContext` declares what your server passes with each request.
export const engine = createQueryEngine({ db, schema, relations }).withContext<{ orgId: string }>();
export const ordersResource = engine.defineResource("orders", {
relations: {
customer: true,
orderLines: { with: { product: true } },
},
query: {
// Added to every statement on the server. The client cannot remove it.
scope: (f, ctx) => f.is("customer.orgId", ctx.orgId),
search: {
allowed: ["reference", "customer.name", "orderLines.product.name"],
defaults: ["reference", "customer.name"],
},
sort: { defaults: [{ key: "createdAt", dir: "desc" }] },
facets: { allowed: ["status", "customer.name", "orderLines.product.category"] },
pagination: { modes: ["cursor", "offset"] },
defaults: { pagination: { mode: "cursor", pageSize: 25 } },
},
});context comes from your server, request from the client.
const result = await ordersResource.query({
context: { orgId: "acme" },
request: {
pagination: { mode: "cursor", pageSize: 25 },
sorting: [{ key: "createdAt", dir: "desc" }],
search: { value: "laptop", fields: [] }, // [] searches the default fields
filters: [
{ type: "condition", key: "status", operator: "isAnyOf", value: ["pending", "processing"] },
],
facets: [{ key: "status", mode: "exclude-self", limit: 10 }],
},
});
result.rows; // typed rows, with customer and orderLines loaded
result.pageInfo; // next cursor, and the exact count when requested
result.facets; // bucket counts per requested facetThe resource generates the schema of the requests it accepts, for Zod, Valibot or Vine. It follows the resource's field rules, defaults and limits, so there is no second contract to keep in sync.
import { requestSchema } from "drizzle-resource/zod";
const parseOrdersRequest = requestSchema(ordersResource);
app.post("/orders/query", async (c) => {
const parsed = parseOrdersRequest.safeParse(await c.req.json());
if (!parsed.success) return c.json({ issues: parsed.error.issues }, 400); // e.g. an unknown field
return c.json(
await ordersResource.query({ request: parsed.data, context: { orgId: c.get("orgId") } }),
);
});Every request runs the same stages, in this order:
- Validate every key, operator and field path against the resource. Anything it doesn't allow fails before any SQL runs.
- Scope the query with the tenant condition from your server context.
- Count the matching rows, or compute your own totals with
summary: true. - Page ids: filters, search and sorting select the ids of one page, joining only the relations they touch.
- Rows: those ids load the full rows with their relations, in the shape of the view you ask for.
- Facets: bucket counts per value for filter sidebars. Facets that can share a statement do on small tables; above 100,000 estimated rows each facet runs as its own statement, which PostgreSQL can parallelise (
facets.splitAbove).
Each stage can be replaced with your own implementation through strategy.*. See it run in the playground, against 10,000 sample orders in your browser.
- Nested AND / OR filter groups, with the operators that fit each field's type
- Search across the fields and relations you allow
- Several sort keys at once, and fields where sorting is turned off
- Offset or cursor pagination, with an exact count or none
- Facet counts that ignore their own filter, for filter sidebars
- Totals from your own aggregates (
count(),sum(...)), typed from the expression - Field policy: hide a field, or stop it from being filtered, searched or sorted
- Views: several response shapes from one resource
- Request and response schemas for Zod, Valibot and Vine
Median time of one request on an orders table of 200,000, 1 million and 10 million rows, PostgreSQL 18 on 4 CPUs. The first three columns are the schema the benchmark starts with, and the last is the same request at 10 million rows after tuning.
| Request | 200k rows | 1M rows | 10M rows | 10M rows, tuned |
|---|---|---|---|---|
| Page of 50, no count | 0.29 ms | 0.31 ms | 0.27 ms | not tuned |
| Cursor page, 90% deep | 0.50 ms | 0.35 ms | 0.36 ms | not tuned |
| Page and exact count | 10.9 ms | 16.1 ms | 100.3 ms | 1.04 ms |
Sort by customer.name |
24.7 ms | 67.4 ms | 751.8 ms | 1.02 ms |
| 4 facets, 2 through customer | 32.4 ms | 127.4 ms | 1,354.5 ms | 1,404.7 ms |
Search "ord", with a count |
155.6 ms | 657.3 ms | 6,109.8 ms | 5.42 ms |
Tuned is a capped count, plus the indexes and the copied customer name that checkIndexes() asked for. These are single-client timings of the engine itself, not HTTP or production latency. Full results.
| Method | Use it when |
|---|---|
resource.query(...) |
You want a page: ids, rows, and facets or totals if requested. |
resource.findById(...) |
You need one row by id, with the scope applied. |
resource.queryIds(...) |
You only need the ids of a page and its page information. |
resource.queryRows(...) |
You already have ordered ids and need the rows. |
resource.queryFacets(...) |
You need facet counts without the page. |
resource.querySummary(...) |
You need the totals without the page. |
resource.scan(...) |
You need every matching row, in batches, for an export or a job. |
bun install
bun run ci # package checks, tests and the docs buildReleases use Changesets: add a note with bun run changeset. Merging the release PR on main publishes to npm.
MIT