---
title: Raw statements
description: "Bind and read values in SQL you send yourself, as each attribute stores them."
seo:
  description: "Send your own SQL beside Active Record: typeForAttribute’s serialize, deserialize, and cast convert values the way an attribute stores them, on D1 or Postgres."
---

:::warning[Postgres reads BIGINT cells as text]
`pg` reads a `BIGINT` cell as text, unless you set its type parsers. Active Record’s own clients convert it, but a query you send through your own `pg` client doesn’t. Pass `Number(cell)` to `deserialize`.
:::

## 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:

```ts invoice.ts
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;
}
```

```ts schema.ts
// 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"]> {}
}
```

```sql D1
-- 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
);
```

```sql Postgres
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:

```ts
import { Invoice } from "./models/invoice";

export async function paidSince(db: D1Database, since: Date) {
  const { serialize } = Invoice.typeForAttribute("paidAt");
  const { results } = await db
    .prepare("SELECT id, total FROM invoices WHERE paid_at >= ?")
    .bind(serialize(since)) // an integer, as paid_at holds it
    .all<{ id: number; total: number }>();
  return 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`:

```ts
import { Invoice } from "./models/invoice";

export async function paidAt(db: D1Database, id: number) {
  const { deserialize } = Invoice.typeForAttribute("paidAt");
  const row = await db
    .prepare("SELECT paid_at FROM invoices WHERE id = ?")
    .bind(id)
    .first<{ paid_at: number | null }>();
  return deserialize(row?.paid_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`.

- `serialize` and `cast` take what assigning would: a `Date` or an ISO string for a `datetime`, `"42"` for an `integer`. Anything else throws `TypeError` naming the Model and attribute, and so does `undefined`. Use `null` for NULL.
- `deserialize` reads a cell as loading a record does, and NULL and `undefined` are `null`. It throws the same `TypeError` for a cell that isn’t the attribute’s type. See [Fixing cells of the wrong type](/adopt-a-database#fixing-cells-of-the-wrong-type).
- A filtered attribute’s value is hidden in those errors, as it is anywhere else.

:::note
`typeForAttribute` needs no connection to a database, and the attribute’s name is checked when you compile.
:::

> **Compared with Rails**
>
> `typeForAttribute` is `type_for_attribute`, with the same `cast`, `serialize`, and `deserialize`. Active Record’s are strict: a value the attribute can’t hold throws, where Rails casts it leniently.
