Attribute types
Each attribute holds one type of value, and every value you assign is cast to it.
At a glance
| Type | JavaScript | D1 column | Postgres column |
|---|---|---|---|
string |
string |
TEXT |
TEXT, UUID |
integer |
number |
INTEGER |
INTEGER, BIGINT |
real |
number |
REAL |
DOUBLE PRECISION |
decimal |
string |
NUMERIC, DECIMAL |
NUMERIC |
boolean |
boolean |
BOOLEAN, stored as 0 or 1 |
BOOLEAN |
datetime |
Date |
DATETIME, as ISO-8601 text, or a Unix time |
TIMESTAMPTZ |
date |
string |
DATE, as text |
DATE |
time |
string |
TIME, as text |
TIME |
json |
any JSON value | JSON, as JSON text |
JSONB |
binary |
Uint8Array |
BLOB |
BYTEA |
An attribute can be null unless its column is NOT NULL, and its TypeScript type includes | null to match.
The Model
The examples use this Model, whose attributes come from its table through the schema active-record schema generates:
import { ApplicationRecord } from "./application-record";
export class Product extends ApplicationRecord {}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: d6a91373e2cc
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** products — last changed by 0001_create_products.sql */
export const products = {
id: { type: "string", null: false, generateId: true },
name: { type: "string", null: false },
price: { type: "decimal", null: false, precision: 10, scale: 2 },
weightKg: "real",
stock: { type: "integer", null: false },
inStock: { type: "boolean", null: false },
launchesOn: "date",
opensAt: "time",
details: "json",
photo: "binary",
createdAt: { type: "datetime", null: false },
updatedAt: { type: "datetime", null: false },
} 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: {
products: { attributes: products, primaryKey: "id" },
},
models: { Product: "products" },
});
declare module "../models/product" {
interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}CREATE TABLE products (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
price NUMERIC(10, 2) NOT NULL,
weight_kg REAL,
stock INTEGER NOT NULL,
in_stock BOOLEAN NOT NULL,
launches_on DATE,
opens_at TIME,
details JSON,
photo BLOB,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);CREATE TABLE products (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10, 2) NOT NULL,
weight_kg DOUBLE PRECISION,
stock INTEGER NOT NULL,
in_stock BOOLEAN NOT NULL,
launches_on DATE,
opens_at TIME,
details JSONB,
photo BYTEA,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);Assigning values
Assign each attribute its type’s JavaScript value:
import { class ProductProduct } from "./models/product";
const const lamp: Productlamp = class ProductProduct.build<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly price: {
readonly type: "decimal";
readonly null: false;
readonly precision: 10;
readonly scale: 2;
};
readonly weightKg: "real";
readonly stock: {
readonly type: "integer";
readonly null: false;
};
readonly inStock: {
readonly type: "boolean";
readonly null: false;
};
readonly launchesOn: "date";
readonly opensAt: "time";
readonly details: "json";
readonly photo: "binary";
readonly createdAt: {
...;
};
readonly updatedAt: {
...;
};
}, Readonly<...> | undefined>>> | undefined, init?: ((record: Product) => void) | undefined): Product
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing
awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it
joins the association, and saving the owner saves it too (autosave).build({
name?: string | undefinedname: "Lamp",
price?: string | undefinedprice: "12.50",
weightKg?: number | null | undefinedweightKg: 1.2,
stock?: number | undefinedstock: 3,
inStock?: boolean | undefinedinStock: true,
launchesOn?: string | null | undefinedlaunchesOn: "2026-01-02",
opensAt?: string | null | undefinedopensAt: "09:30",
details?: unknowndetails: { colors: string[]colors: ["red", "blue"] },
photo?: Uint8Array<ArrayBufferLike> | null | undefinedphoto: new var Uint8Array: Uint8ArrayConstructor
new (elements: Iterable<number>) => Uint8Array<ArrayBuffer> (+6 overloads)
Uint8Array([1, 2, 3]),
});
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const lamp: Productlamp.price: stringprice); // "12.5"
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const lamp: Productlamp.opensAt: string | nullopensAt); // "09:30:00"
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const lamp: Productlamp.createdAt: DatecreatedAt); // null until it's saved- A
datetimeread from text with no time zone, such as SQLite’sDEFAULT CURRENT_TIMESTAMPwrites, is UTC in any time zone. - A
datetimecan be kept as a Unix time in anINTEGERcolumn, as Drizzle writes it. Declare it withstorage: "unixSeconds"or"unixMilliseconds"; Reading Unix timestamps shows how. - For a value none of these hold, such as money, define a custom type.
Storing bytes
Read a file’s bytes before you assign them to a binary attribute, since a file from a form is read asynchronously:
import { class ProductProduct } from "./models/product";
export async function function addPhoto(form: FormData): Promise<Product>addPhoto(form: FormDataform: FormData) {
const const file: Filefile = form: FormDataform.FormData.get(name: string): FormDataEntryValue | nullThe **`get()`** method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)get("photo") as File;
const const photo: Uint8Array<ArrayBuffer>photo = new var Uint8Array: Uint8ArrayConstructor
new <ArrayBuffer>(buffer: ArrayBuffer, byteOffset?: number, length?: number) => Uint8Array<ArrayBuffer> (+6 overloads)
Uint8Array(await const file: Filefile.Blob.arrayBuffer(): Promise<ArrayBuffer>The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer)arrayBuffer()); // read before assigning
return class ProductProduct.create<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly price: {
readonly type: "decimal";
readonly null: false;
readonly precision: 10;
readonly scale: 2;
};
readonly weightKg: "real";
readonly stock: {
readonly type: "integer";
readonly null: false;
};
readonly inStock: {
readonly type: "boolean";
readonly null: false;
};
readonly launchesOn: "date";
readonly opensAt: "time";
readonly details: "json";
readonly photo: "binary";
readonly createdAt: {
...;
};
readonly updatedAt: {
...;
};
}, Readonly<...> | undefined>>> | undefined, init?: Init<...> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or
not it was saved (check `isPersisted()`).create({ name?: string | undefinedname: const file: Filefile.File.name: stringThe **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)name, price?: string | undefinedprice: "0", stock?: number | undefinedstock: 0, inStock?: boolean | undefinedinStock: false, photo?: Uint8Array<ArrayBufferLike> | null | undefinedphoto });
}- It reads back as a
Uint8Array, and prints as<3 bytes of binary data>, so logs never hold the bytes. - A D1 row holds at most 2 MB. Keep larger files in R2, and store their keys.
Storing exact numbers, days, and times
A decimal holds an exact number, such as a price, as text, and a date and a time hold a day and a time of day:
- A decimal takes text, a number, or a
bigint, and reads in one form, without trailing zeros or an exponent, so"12.50"and"12.5"are the same value. A number keeps 16 significant digits, so0.1 + 0.2is"0.3". - Conditions, comparisons, and
ordercompare decimals as numbers, and so do thenumericalityandcomparisonvalidations. - A column’s
scale, fromNUMERIC(10, 2), rounds a decimal to that many places, half away from zero, as Postgres rounds, so a record holds what the database stores. Itsprecisionlimits its digits in all. A value with too many digits before the point throwsTypeError, and aprecisionwithout ascalerounds to whole numbers. - A
dateholds a day, such as"2026-01-02", and atimea time of day, such as"09:30:00". Neither has a time zone. A time always has its seconds, and a fraction only when it has one:"09:30:15.25". The end of the day is"24:00:00". - Days and times compare and sort in order. A
Datecan’t be assigned to either, since its day and time depend on the time zone. For today’s date in UTC, assignnew Date().toISOString().slice(0, 10).
Casting assigned values
Every value is cast to its attribute’s type when it’s assigned, so text from JSON, a form, or a query string becomes the right type:
import { class ProductProduct } from "./models/product";
const const lamp: Productlamp = class ProductProduct.build<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly price: {
readonly type: "decimal";
readonly null: false;
readonly precision: 10;
readonly scale: 2;
};
readonly weightKg: "real";
readonly stock: {
readonly type: "integer";
readonly null: false;
};
readonly inStock: {
readonly type: "boolean";
readonly null: false;
};
readonly launchesOn: "date";
readonly opensAt: "time";
readonly details: "json";
readonly photo: "binary";
readonly createdAt: {
...;
};
readonly updatedAt: {
...;
};
}, Readonly<...> | undefined>>> | undefined, init?: ((record: Product) => void) | undefined): Product
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing
awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it
joins the association, and saving the owner saves it too (autosave).build({ name?: string | undefinedname: "Lamp", price?: string | undefinedprice: "1.555", stock?: number | undefinedstock: 0, inStock?: boolean | undefinedinStock: false });
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const lamp: Productlamp.price: stringprice); // "1.56", rounded to the column's scale of 2
// Values from JSON, a form or a query string often arrive as text:
const lamp: Productlamp.Model.assign(attributes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly price: {
readonly type: "decimal";
readonly null: false;
readonly precision: 10;
readonly scale: 2;
};
readonly weightKg: "real";
readonly stock: {
readonly type: "integer";
readonly null: false;
};
readonly inStock: {
readonly type: "boolean";
readonly null: false;
};
readonly launchesOn: "date";
readonly opensAt: "time";
readonly details: "json";
readonly photo: "binary";
readonly createdAt: {
readonly type: "datetime";
readonly null: false;
};
readonly updatedAt: {
...;
};
}, Readonly<...> | undefined>>>): Product
Assigns several attributes without saving.assign(var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.JSON.JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.parse('{ "stock": " 42 ", "inStock": "true" }'));
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const lamp: Productlamp.stock: numberstock); // 42
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const lamp: Productlamp.inStock: booleaninStock); // true, not the string "true"Values are cast wherever they’re assigned: build, create, assign, update, a property setter, a default, permit, and the values given to insert, insertAll, upsert, upsertAll, and updateAll. null is always NULL. Only unambiguous values are accepted:
| Type | Accepts |
|---|---|
boolean |
true, false, 1, 0, "1", "0", and "true", "false", "on", "off" in any case |
integer |
a safe integer, or a string that’s wholly one, with an optional sign and spaces around it: "42", " -7 ", "+3" |
real |
a finite number, or a string that’s wholly one, with an optional sign, point, and exponent: "1.5", ".5", "5.", "-2e3" |
decimal |
a finite number, a bigint, or a string that’s wholly a decimal number, as for a real: "12.50", "-2e3" |
string |
a string |
datetime |
a valid Date; a date, "2026-01-02" (midnight UTC); or a date and time with Z or a ±HH:MM offset: "2026-01-02T09:30:00+02:00" |
date |
a day that exists, as "YYYY-MM-DD": "2026-01-02" |
time |
a time of day, with or without seconds and up to six digits of a fraction: "09:30", "09:30:15.25" |
json |
any value JSON can write |
binary |
a Uint8Array, or an ArrayBuffer |
Refusing other values
Anything else throws TypeError naming the Model and the attribute, and the attribute keeps its value:
import { class ProductProduct } from "./models/product";
const const lamp: Productlamp = class ProductProduct.build<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly price: {
readonly type: "decimal";
readonly null: false;
readonly precision: 10;
readonly scale: 2;
};
readonly weightKg: "real";
readonly stock: {
readonly type: "integer";
readonly null: false;
};
readonly inStock: {
readonly type: "boolean";
readonly null: false;
};
readonly launchesOn: "date";
readonly opensAt: "time";
readonly details: "json";
readonly photo: "binary";
readonly createdAt: {
...;
};
readonly updatedAt: {
...;
};
}, Readonly<...> | undefined>>> | undefined, init?: ((record: Product) => void) | undefined): Product
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing
awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it
joins the association, and saving the owner saves it too (autosave).build({ name?: string | undefinedname: "Lamp", price?: string | undefinedprice: "1", stock?: number | undefinedstock: 0, inStock?: boolean | undefinedinStock: false });
const lamp: Productlamp.Model.assign(attributes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly price: {
readonly type: "decimal";
readonly null: false;
readonly precision: 10;
readonly scale: 2;
};
readonly weightKg: "real";
readonly stock: {
readonly type: "integer";
readonly null: false;
};
readonly inStock: {
readonly type: "boolean";
readonly null: false;
};
readonly launchesOn: "date";
readonly opensAt: "time";
readonly details: "json";
readonly photo: "binary";
readonly createdAt: {
readonly type: "datetime";
readonly null: false;
};
readonly updatedAt: {
...;
};
}, Readonly<...> | undefined>>>): Product
Assigns several attributes without saving.assign(var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.JSON.JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.parse('{ "inStock": "no" }'));
// TypeError: Product: "no" isn't a boolean for "inStock"The error shows at most 60 characters of the value, and none of a filtered attribute’s. Among the values refused:
""for every type butstring.1.7,"12abc","1e3", and integers pastNumber.MAX_SAFE_INTEGER, for aninteger.NaNandInfinity.- A number, boolean, or
Datefor astring. - For a
datetime: a time without an offset, a lowercasetorz, a day that doesn’t exist ("2026-02-30"), other formats, and numbers. - For a
decimal: text with anything but a number in it, a number too large or too small for a JavaScriptnumber, such as"1e400"or"1e-400", and one with more digits after its point than Postgres holds. - For a
dateor atime: aDate, a time zone, a day or time that doesn’t exist ("2026-02-30","24:00:01"), other formats ("2026-1-2","9:30"), and numbers. - For a
json: a value JSON can’t write, such as aBigInt, an object that refers to itself, a function, or a symbol. - For a
binary: text, an array of numbers, or another typed array.
Reading stored cells
A stored cell is checked the same way, when the record loads or pluck reads it. One that isn’t the attribute’s type fails with the same error, shows the same value, and fails a list that holds it whole. These cells fail:
- For a
boolean: anything but0and1. - For an
integer: text, a fraction, or a number outside the safe integer range. - For a
real: anything but a finite number. - For a
string: anything but text. - For a
datetime: text that isn’t a date or a date and time ("garbage","12"), or a number. A number is a Unix time, which needs astorage. - For a
datetimewith astorage: anything but a number, or one past what aDatecan hold. - For a
decimal: anything but a number or a decimal’s text. - For a
date: anything but a day’s text. A date and time, such as"2026-01-02T00:00:00.000Z", fails too; see ReadingDATEcolumns. - For a
time: anything but a time of day’s text. - For a
json: text that isn’t JSON. - For a
binary: anything but bytes.
See Fixing cells of the wrong type.
Casting conditions and keys
Conditions are cast the same way, so where({ stock: "42" }) finds 42. A condition value that can’t be cast matches nothing, so find("abc") on an integer key throws RecordNotFound.
- A condition reads a number as its digits for a
stringattribute, and a record built from that Relation starts with what it matched:where({ name: 7 }).build()has the name"7". - A key copied from another record through an association is cast too, so an integer key written into a text foreign key becomes its digits.
- A
jsonvalue JSON can’t write matches nothing, never the rows whose cell isNULL. In a list, it’s left out and the rest still match.