Raw statements
Bind and read values in SQL you send yourself, as each attribute stores them.
At a glance
| To | Write |
|---|---|
| get an attribute’s conversions | Invoice.typeForAttribute("paidAt") |
| bind a value as the attribute stores it | serialize(date) |
| read a cell as the attribute’s value | deserialize(row.paid_at) |
| get the JavaScript value for an input | cast("2026-01-02") |
The Model
The example uses this Model, whose attributes come from its table through the schema active-record schema generates. Its table stores paid_at as Unix seconds, so the Model overrides it as a datetime:
import { ApplicationRecord } from "./application-record";
export class Invoice extends ApplicationRecord {
static override attributes = {
paidAt: { type: "datetime", storage: "unixSeconds" }, // an integer column of Unix seconds
} as const;
}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: c040bb92ffaf
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** invoices — last changed by 0001_create_invoices.sql */
export const invoices = {
id: { type: "integer", null: false },
total: { type: "integer", null: false },
paidAt: "integer",
} as const;
/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
adapter: d1({ binding: "DB" }),
tables: {
invoices: { attributes: invoices, primaryKey: "id" },
},
models: { Invoice: "invoices" },
});
declare module "../models/invoice" {
interface Invoice extends TableAttributes<typeof invoices, (typeof Invoice)["attributes"]> {}
}-- An integer Unix time column, as Drizzle's `integer({ mode: "timestamp" })` writes it.
CREATE TABLE invoices (
id INTEGER PRIMARY KEY,
total INTEGER NOT NULL,
paid_at INTEGER
);CREATE TABLE invoices (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
total INTEGER NOT NULL,
paid_at BIGINT
);Binding values
Bind what serialize gives when you send SQL yourself:
import { class InvoiceInvoice } from "./models/invoice";
export async function function paidSince(db: D1Database, since: Date): Promise<{
id: number;
total: number;
}[]>
paidSince(db: D1Databasedb: class D1DatabaseD1Database, since: Datesince: Date) {
const { const serialize: (input: unknown) => string | number | Uint8Array | null`input`, cast and normalized, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
are floored), `0` or `1`, JSON text, bytes for a `binary` attribute, or a custom type's value
as its stored type keeps it (#20). The value `column(attribute).value(input)` binds inside
an `sql` fragment; `undefined` throws as assigning it does.serialize } = class InvoiceInvoice.Model.typeForAttribute<typeof Invoice, "paidAt">(this: typeof Invoice, name: "paidAt"): AttributeConversions<Date | null>An attribute's conversions, for SQL the library doesn't write:
`Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
as, whatever its `storage`; `cast` and `deserialize` go the other way. `cast` and `serialize`
normalize the value, as assigning it does (#354).typeForAttribute("paidAt");
const { const results: {
id: number;
total: number;
}[]
results } = await db: D1Databasedb
.D1Database.prepare(query: string): D1PreparedStatementprepare("SELECT id, total FROM invoices WHERE paid_at >= ?")
.D1PreparedStatement.bind(...values: unknown[]): D1PreparedStatementbind(const serialize: (input: unknown) => string | number | Uint8Array | null`input`, cast and normalized, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
are floored), `0` or `1`, JSON text, bytes for a `binary` attribute, or a custom type's value
as its stored type keeps it (#20). The value `column(attribute).value(input)` binds inside
an `sql` fragment; `undefined` throws as assigning it does.serialize(since: Datesince)) // an integer, as paid_at holds it
.D1PreparedStatement.all<{
id: number;
total: number;
}>(): Promise<D1Result<{
id: number;
total: number;
}>>
all<{ id: numberid: number; total: numbertotal: number }>();
return const results: {
id: number;
total: number;
}[]
results;
}serialize writes the Date as paidAt stores it: an integer here, ISO text for a plain datetime. On Postgres, bind it as $1 through your pg client.
For a cache key, or the value a test expects of a raw row, serialize gives the stored form too.
Reading cells
Turn a cell from a raw query into the attribute’s value with deserialize:
import { class InvoiceInvoice } from "./models/invoice";
export async function function paidAt(db: D1Database, id: number): Promise<Date | null>paidAt(db: D1Databasedb: class D1DatabaseD1Database, id: numberid: number) {
const { const deserialize: (stored: unknown) => Date | nullA cell D1 returned, as the attribute's JavaScript value; `null` for NULL and `undefined`.
It reads as a record load does, so a cell that can't be read throws `TypeError` naming the
Model and attribute: text in a Unix time column, a number past the range of a `Date`, or text
in a `json` column that isn't JSON.deserialize } = class InvoiceInvoice.Model.typeForAttribute<typeof Invoice, "paidAt">(this: typeof Invoice, name: "paidAt"): AttributeConversions<Date | null>An attribute's conversions, for SQL the library doesn't write:
`Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
as, whatever its `storage`; `cast` and `deserialize` go the other way. `cast` and `serialize`
normalize the value, as assigning it does (#354).typeForAttribute("paidAt");
const const row: {
paid_at: number | null;
} | null
row = await db: D1Databasedb
.D1Database.prepare(query: string): D1PreparedStatementprepare("SELECT paid_at FROM invoices WHERE id = ?")
.D1PreparedStatement.bind(...values: unknown[]): D1PreparedStatementbind(id: numberid)
.D1PreparedStatement.first<{
paid_at: number | null;
}>(): Promise<{
paid_at: number | null;
} | null> (+1 overload)
first<{ paid_at: number | nullpaid_at: number | null }>();
return const deserialize: (stored: unknown) => Date | nullA cell D1 returned, as the attribute's JavaScript value; `null` for NULL and `undefined`.
It reads as a record load does, so a cell that can't be read throws `TypeError` naming the
Model and attribute: text in a Unix time column, a number past the range of a `Date`, or text
in a `json` column that isn't JSON.deserialize(const row: {
paid_at: number | null;
} | null
row?.paid_at: number | null | undefinedpaid_at); // a Date, or null
}Converting values
cast gives the JavaScript value for an input, without converting it to the stored form: cast("2026-01-02") is a Date. It keeps a Date’s milliseconds, where serialize floors them for unixSeconds.
serializeandcasttake what assigning would: aDateor an ISO string for adatetime,"42"for aninteger. Anything else throwsTypeErrornaming the Model and attribute, and so doesundefined. Usenullfor NULL.deserializereads a cell as loading a record does, and NULL andundefinedarenull. It throws the sameTypeErrorfor a cell that isn’t the attribute’s type. See Fixing cells of the wrong type.- A filtered attribute’s value is hidden in those errors, as it is anywhere else.