Models
Model rules belong to a table, not to a resource. Declare them once in the engine's models option; they apply wherever the table appears, as a root or through a relation.
| Rule | Returned by default | Selectable in a view | Usable in client queries |
|---|---|---|---|
private | no | no, rejected | no. The scope and custom stages can still use it. |
hidden | no | yes, explicitly | follows the resource's field rules |
virtual | no | yes, explicitly | yes, like a column: filter, search and sort |
hidden controls what is returned by default. It is not an access control. Use private for fields that must never leave the database.
import { sql } from "drizzle-orm";
import { createQueryEngine, virtual } from "drizzle-resource";
import { db } from "./db";
import { schema } from "./schema";
import { relations } from "./relations";
export const engine = createQueryEngine({
db,
schema,
relations,
models: {
orders: { private: ["deletedAt"] },
customers: {
hidden: ["orgId"],
virtual: (customer) => ({
displayName: virtual.text(sql`upper(${customer.name})`),
}),
},
},
}).withContext<{ orgId: string }>();
Virtual fields
A virtual field is a SQL expression computed by the database. Declare virtuals in a callback: it receives the table and the current database or transaction, and the names and value types it returns are inferred.
The text, number, boolean and timestamp helpers set how the value is decoded. Wrap a nullable expression in virtual.nullable(...). Avoid virtual.number for money unless converting to a JavaScript number is what you want.
Always correlate on the table parameter the callback receives, not on the imported table.
A value from another table
virtual.scalar turns a one-column Drizzle query into a correlated subquery. The value keeps its type, plus null when no row matches. It is computed in the same SQL statement, not with one query per row.
import { desc, eq } from "drizzle-orm";
import { createQueryEngine, virtual } from "drizzle-resource";
import { db } from "./db";
import { schema, orders } from "./schema";
import { relations } from "./relations";
const engine = createQueryEngine({
db,
schema,
relations,
models: {
customers: {
virtual: (customer, { db }) => ({
latestOrderReference: virtual.scalar(
db
.select({ value: orders.reference })
.from(orders)
.where(eq(orders.customerId, customer.id))
.orderBy(desc(orders.createdAt), desc(orders.id))
.limit(1),
),
}),
},
},
});
A query selecting more than one column is rejected. PostgreSQL rejects a scalar subquery that returns more than one row, so order and limit it.