Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Models

A Model describes one table, reads its attributes from your migrations, and declares only behavior.

At a glance

To Write
define a Model class Product extends ApplicationRecord {}
read a column as another type static override attributes = { archived: "boolean" } as const
ignore a column static override attributes = { legacyNotes: false } as const
add an attribute that isn’t a column termsOfService: { type: "boolean", virtual: true }
normalize a value as it’s assigned this.normalizes("email", { with: (email) => email.trim() })
give an attribute another name title: { aliasOf: "name" }
type an attribute more narrowly declare status: "draft" | "published"
use another table name static override table = "billing_accounts"
declare attributes for a view class ProductCount extends ApplicationRecord.define({ … }) {}
build a record without saving it Product.build({ name: "Lamp" }), never new Product()
take only some fields from a request Product.permit(await request.json(), "name", "metadata")
PropType
with(value) => value

The function `normalizes` runs. It takes a value already cast to the attribute’s type, and returns the one to keep.

Type(value) => value
applyToNull?boolean

Hands `null` to `normalizes`’s `with` too. By default, `null` is kept as it is.

Typeboolean
Defaultfalse

Each part of a Model has a page of its own:

To See
learn each type, and how values are cast Attribute types
give an attribute a fixed set of names Enums
see what changed before and after a save Change tracking
send records as JSON, and keep secrets out Serialization
check records before they’re saved Validations
run code as records are saved Callbacks
share behavior across every Model Shared behavior

The Models

The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:

import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static override attributes = {
    archived: { type: "boolean", default: () => false }, // 0 or 1 in a plain INTEGER column
    metadata: "json", // JSON in a plain TEXT column
    legacyNotes: false, // a column this app no longer uses: never read or written
    publicId: { generateId: true }, // generated in code, as a TEXT key is
    title: { aliasOf: "name" }, // another name for name, in queries too
  } as const;

  declare status: "draft" | "published"; // narrower than the column's string
}
import { Product } from "./product";

export class FeaturedProduct extends Product {} // shares products, and Product's declarations
import { ApplicationRecord } from "./application-record";

export class Account extends ApplicationRecord {
  static override table = "billing_accounts"; // in place of accounts
  static override attributes = {
    termsOfService: { type: "boolean", virtual: true }, // a form's checkbox, never a column
  } as const;

  static {
    this.normalizes("email", { with: (email) => email.trim().toLowerCase() });
  }
}
import { ApplicationRecord } from "./application-record";

// A view, which migrations don't describe, so the Model declares its attributes itself:
export class ProductCount extends ApplicationRecord.define({
  status: { type: "string", null: false },
  total: { type: "integer", null: false },
}) {
  static override table = "product_counts";
  static override primaryKey = "status";
}
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: e02b5fa3d693

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** billing_accounts — last changed by 0001_create_tables.sql */
export const billingAccounts = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** products — last changed by 0001_create_tables.sql */
export const products = {
  id: { type: "string", null: false, generateId: true },
  publicId: "string",
  name: { type: "string", null: false },
  status: { type: "string", null: false, default: () => "draft" },
  archived: { type: "integer", null: false, default: () => 0 },
  metadata: "string",
  legacyNotes: "string",
  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: {
    billing_accounts: { attributes: billingAccounts, primaryKey: "id" },
    products: { attributes: products, primaryKey: "id" },
  },
  models: { Account: "billing_accounts", Product: "products" },
});

declare module "../models/account" {
  interface Account
    extends TableAttributes<typeof billingAccounts, (typeof Account)["attributes"]> {}
}

declare module "../models/product" {
  interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}
CREATE TABLE products (
  id TEXT PRIMARY KEY NOT NULL,
  public_id TEXT,
  name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'draft',
  archived INTEGER NOT NULL DEFAULT 0,
  metadata TEXT,
  legacy_notes TEXT,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);
CREATE TABLE billing_accounts (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
CREATE VIEW product_counts AS
  SELECT status, COUNT(*) AS total FROM products GROUP BY status;
CREATE TABLE products (
  id UUID PRIMARY KEY,
  public_id TEXT,
  name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'draft',
  archived INTEGER NOT NULL DEFAULT 0,
  metadata TEXT,
  legacy_notes TEXT,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE billing_accounts (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE VIEW product_counts AS
  SELECT status, COUNT(*)::integer AS total FROM products GROUP BY status;

Defining Models

Define each Model by extending ApplicationRecord, as Account does:

  • The class name names the table, so Product reads and writes products. The table’s attributes, primary key, and types come from src/db/schema.ts.
  • active-record schema writes that file from your migrations and your Models. Run it after you add a Model or a migration. active-record g model runs it for you.
  • The first time it runs, it writes src/models/application-record.ts. It’s an ordinary class, and yours to edit. The schema it holds gives each Model its attributes and the binding its queries use. Methods, callbacks, and scopes you write on it are every Model’s; see Shared behavior. It has no table of its own, so you can’t query it.
  • A subclass shares its parent’s table, as FeaturedProduct does, and inherits a copy of its parent’s attributes, validations, callbacks, scopes, and associations. Declaring more on the child never changes the parent. Single-table inheritance isn’t supported.
  • You can still set static primaryKey, as long as it names an attribute.

Overriding attributes

Override an attribute in static attributes when a column holds something its type doesn’t say, as Product does with a boolean in a plain INTEGER. Write the object as const, so TypeScript keeps each type name. An override is one of these:

Override Does
"boolean" (a type name) Reads and writes the attribute as that type
money (a custom type) Reads and writes the attribute as that type
{ type?, null?, default?, generateId? } Replaces those parts of the generated attribute; null: false makes it non-null in TypeScript
{ enum, prefix?, suffix?, … } Makes the attribute an enum, of its column’s type
{ enum: true }, { enum: false } Turns on the methods of an enum read from the database, or drops it
false Ignores the column: it’s never typed, read, or written, and queries name their columns instead of *
  • Changing a type drops the generated default or generateId, so the column’s own default applies unless you give one. archived gives one, so a new product reads false before it’s saved.
  • A default and generateId replace each other, so an attribute has one or the other. generateId is only for strings.
  • A default isn’t type-checked yet (#74). One that returns a value the type can’t cast throws TypeError when a record is built.
  • Ignoring a NOT NULL column without a default makes inserts fail, so give it a default in a migration first.
  • An override of an attribute the table doesn’t have throws InvalidModel, and active-record schema reports it. So does an override that changes a column or ignores the primary key.

Adding virtual attributes

Add virtual: true for a value a form sends but the table doesn’t keep, as Account does with termsOfService:

import { class AccountAccount } from "./models/account";

const 
const form: {
    email: string;
    termsOfService: string;
}
form
= { email: stringemail: "jane@example.com", termsOfService: stringtermsOfService: "1" };
const
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, {
    readonly termsOfService: {
        readonly type: "boolean";
        readonly virtual: true;
    };
}>>, "email" | "termsOfService">>
permitted
= class AccountAccount.
Model.permit<typeof Account, "email" | "termsOfService">(this: typeof Account, input: unknown, ...names: ("email" | "termsOfService")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, {
    readonly termsOfService: {
        readonly type: "boolean";
        readonly virtual: true;
    };
}>>, "email" | "termsOfService">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(
const form: {
    email: string;
    termsOfService: string;
}
form
, "email", "termsOfService");
const const account: Accountaccount = class AccountAccount.
build<typeof Account>(this: typeof Account, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, {
    readonly termsOfService: {
        readonly type: "boolean";
        readonly virtual: true;
    };
}>>> | undefined, init?: ((record: Account) => void) | undefined): Account
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
(
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, {
    readonly termsOfService: {
        readonly type: "boolean";
        readonly virtual: true;
    };
}>>, "email" | "termsOfService">>
permitted
);
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const account: Accountaccount.termsOfService: boolean | nulltermsOfService); // true, cast from the form's "1"
await const account: Accountaccount.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
(); // inserts the email alone
  • It’s typed and cast like a column’s attribute. permit takes it, and its changes are tracked.
  • It’s never saved. An insert or an update leaves it out. A save that changes only virtual attributes sets updatedAt alone, or writes nothing on a table without timestamps.
  • A loaded record starts it at its default, or null, and so does reload.
  • A query can’t name it, since there’s no column to match. where, order, select, pluck, insert, and updateAll throw UnknownAttribute.
  • It’s in toJSON(), unless a confirmation rule reads it. A record keeps it after a create, so list a secret one in hiddenAttributes, or Response.json(user) sends it back. For a password, declare a secure password instead, which toJSON() leaves out.

Normalizing attributes

Declare a normalization in static {} to change each value assigned to an attribute into one form, as Account does with email:

import { class AccountAccount } from "./models/account";

const const account: Accountaccount = await class AccountAccount.
create<typeof Account>(this: typeof Account, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, {
    readonly termsOfService: {
        readonly type: "boolean";
        readonly virtual: true;
    };
}>>> | undefined, init?: Init<Account> | undefined): Promise<Account>
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
({ email?: string | undefinedemail: " Jane@Example.COM " });
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const account: Accountaccount.email: stringemail); // "jane@example.com"
const const found: Account | nullfound = await class AccountAccount.findBy<typeof Account>(this: typeof Account, conditions: SafeSql | Conditions<Account>): Promise<Account | null>
The first record matching `conditions` (in no particular order), or null.
findBy
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "JANE@example.com" }); // the same account
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(class AccountAccount.Model.normalizeValueFor<typeof Account, "email">(this: typeof Account, name: "email", value: unknown): string
`value` as assigning it to `name` keeps it: cast, then normalized (#354), so `Account.normalizeValueFor("email", " Jane@Example.com")` is `"jane@example.com"`.
normalizeValueFor
("email", " Sam@Example.com")); // "sam@example.com"
  • It runs whenever a value is assigned. That covers the setter, build, create, update, a default, and bulk writes such as insert, upsert, and updateAll. Several normalizations of one attribute run in order, a parent class’s first.
  • Queries normalize their values too. where, findBy, find, lists, comparisons, and column() values in an sql fragment match what was stored. Plain values in an sql fragment are left as they are, and where({ email: null }) still matches NULL.
  • Account.normalizeValueFor("email", value) returns a value as assigning it would keep it.

Aliasing attributes

Add aliasOf to give an attribute a second name, as Product does with title for name:

import { class ProductProduct } from "./models/product";

const const lamp: Productlamp = await class ProductProduct.
create<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    ...;
}>>> | 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
({ title?: string | undefinedtitle: "Lamp" }); // writes name
var console: Consoleconsole.Console.log(...data: any[]): void
The **`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.name: stringname); // "Lamp"
const const titles: string[]titles = await class ProductProduct.where<typeof Product>(this: typeof Product, conditions: SafeSql | Conditions<Product>): Relation<Product, ScopesOf<typeof Product>>where({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Lamp" }).Relation<Product, ScopesOf<typeof Product>>.pluck<"title">(attribute: "title"): Promise<string[]> (+1 overload)
Converted values of one attribute, or tuples of several, in this Relation's order.
pluck
("title");
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const titles: string[]titles); // ["Lamp"]
const lamp: Productlamp.title: stringtitle = "Desk lamp"; var console: Consoleconsole.Console.log(...data: any[]): void
The **`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.Model.changes(): Changes
Each changed attribute's value before and after: `{ email: [old, new] }`.
changes
()); // { name: ["Lamp", "Desk lamp"] }
  • It reads and writes the attribute it names, typed as that attribute.
  • Queries and writes take either name: where, order, pluck, select, group, the calculations, build, create, permit, insert, upsert, and updateAll.
  • The record holds the value once, under the attribute’s name. attributes(), toJSON(), and changes() list name, and so does a record select("title") loads. attributeWas("title") and the other methods that take a name read it through the alias.
  • A row that gives both title and name throws TypeError, since they’re one column.
  • validates("title", …) reads through the alias, and its errors go under title.

Narrowing types

Declare an attribute in the class to give it a narrower type than its column’s, as Product does with status:

  • product.status is typed "draft" | "published", when you read it and when you assign it.
  • where and build still take any string, and nothing checks the value read from the database. To have the values checked, and get a method for each, declare an enum instead.

Declaring attributes yourself

Declare the attributes with define for a view, or a table your migrations don’t make, as ProductCount does:

import { class ProductCountProductCount } from "./models/product-count";

const const counts: ProductCount[]counts = await class ProductCountProductCount.order<typeof ProductCount>(this: typeof ProductCount, spec: SafeSql | OrderSpec<ProductCount>): Relation<ProductCount, ScopesOf<typeof ProductCount>>
Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc", nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
order
({
status?: OrderDirection | {
    direction: OrderDirection;
    nulls?: NullsPlacement;
} | undefined
status
: "asc" }).Relation<ProductCount, ScopesOf<typeof ProductCount>>.toArray(): Promise<ProductCount[]>toArray();
// [ProductCount { status: "draft", total: 1 }, ProductCount { status: "published", total: 2 }]
  • TypeScript infers the record’s properties from the object.
  • An attribute is a type name, or { type, column?, null?, default? }.
  • Calling define on ApplicationRecord shares your base class’s behavior and binding.

Naming Models

A Model’s name is its class name, read with modelName:

import { class AccountAccount } from "./models/account";
import { class FeaturedProductFeaturedProduct } from "./models/featured-product";

var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(class FeaturedProductFeaturedProduct.Model.modelName: string
The Model's name: its class name unless set (`static modelName = "BlogPost"`), so names inferred from it survive a bundler that renames classes.
modelName
); // "FeaturedProduct"
const const published: FeaturedProduct[]published = await class FeaturedProductFeaturedProduct.where<typeof FeaturedProduct>(this: typeof FeaturedProduct, conditions: SafeSql | Conditions<FeaturedProduct>): Relation<FeaturedProduct, ScopesOf<typeof FeaturedProduct>>where({ status?: string | readonly string[] | Comparison<string> | undefinedstatus: "published" }).Relation<FeaturedProduct, ScopesOf<typeof FeaturedProduct>>.toArray(): Promise<FeaturedProduct[]>toArray(); // from products const const account: Accountaccount = await class AccountAccount.
create<typeof Account>(this: typeof Account, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, {
    readonly termsOfService: {
        readonly type: "boolean";
        readonly virtual: true;
    };
}>>> | undefined, init?: Init<Account> | undefined): Promise<Account>
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
({ email?: string | undefinedemail: "jane@example.com" }); // into billing_accounts
  • The generated schema lists the Model by its name, and its table name, its foreign keys, and its error messages are made from it.
  • If your bundler renames classes, set static override modelName = "BlogPost", so the Model keeps its name once bundled. Without it, a bundler that renames User to e makes the first query throw InvalidModel, because no Model named e is in the generated schema. Wrangler keeps class names by default, even when minifying.
  • A subclass inherits a modelName its parent sets. Otherwise, each class has its own: FeaturedProduct.modelName is "FeaturedProduct", though it shares Product’s table.

Naming tables

A Model takes its table name from its name, snake_case and pluralized, unless it sets static table, as Account does:

Class Table
User users
BlogPost blog_posts
Category categories
Person people
Sheep sheep

A class with no name to take one from must set static table.

Mapping columns

Attributes are camelCase, and map to snake_case columns:

Attribute Column
createdAt created_at
externalAccountId external_account_id
htmlURL html_url
userID user_id
sha256Hash sha256_hash

To map an attribute to a column with another name, give it { column: "..." }. Conditions, ordering, and association keys always name attributes; only SQL fragments name columns.

Building records

Build a record without touching the database with build:

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 publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    ...;
}>>> | 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" });
var console: Consoleconsole.Console.log(...data: any[]): void
The **`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.id: stringid); // generated already, before saving: "3b241101-…"
var console: Consoleconsole.Console.log(...data: any[]): void
The **`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.Product.status: "draft" | "published"status); // "draft", the column's default
var console: Consoleconsole.Console.log(...data: any[]): void
The **`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.archived: booleanarchived); // false, read as a boolean
var console: Consoleconsole.Console.log(...data: any[]): void
The **`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
const lamp: Productlamp.
Model.assign(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    ...;
}>>>): Product
Assigns several attributes without saving.
assign
({ status?: string | undefinedstatus: "published", metadata?: unknownmetadata: { color: stringcolor: "red" } });
await const lamp: Productlamp.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
(); // sets createdAt and updatedAt
  • Defaults and generated ids run at build(), so a key generated in code exists before the record is saved. That lets records that point at each other be saved together, in one atomic batch.
  • Unassigned attributes read as null, and aren’t written on insert, so the column’s database default applies. After the insert, the record loads what the database stored.
  • Unknown attributes throw UnknownAttribute, and undefined throws TypeError. Use null to store NULL.
  • assign(attrs) sets several attributes without saving. update(attrs) assigns, then saves.

Permitting fields

Keep only the attributes you name from untrusted input with permit, whose result goes straight into build, create, or update:

import { class ProductProduct } from "./models/product";

export async function function createProduct(request: Request): Promise<Product>createProduct(request: Requestrequest: Request) {
  const 
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    ...;
}>>, "name" | "metadata">>
permitted
= class ProductProduct.
Model.permit<typeof Product, "name" | "metadata">(this: typeof Product, input: unknown, ...names: ("name" | "metadata")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        ...;
    };
    readonly updatedAt: {
        ...;
    };
}, {
    ...;
}>>, "name" | "metadata">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(await request: Requestrequest.Body.json(): Promise<any>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)
json
(), "name", "metadata");
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 publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    ...;
}>>> | 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
(
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly publicId: "string";
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly archived: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly metadata: "string";
    readonly legacyNotes: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    ...;
}>>, "name" | "metadata">>
permitted
); // any other key in the body is dropped
}

It casts each value as assigning would, and reads three kinds of input:

Input Read
a plain object its own keys only, so __proto__ and inherited keys never count
FormData each field; a repeated key takes its last value
URLSearchParams each parameter; a repeated key takes its last value
  • Keys you don’t name are dropped. A named attribute the input doesn’t have is left out, and a null is kept.
  • A name that isn’t an attribute is a compile error, and throws UnknownAttribute.
  • TypeError is thrown for a value that can’t be cast, a file from a form (read a file’s bytes for a binary attribute), and any other input: an array, a Map, Headers, a class instance, null, or a string.

Untrusted input shows permit in a Worker.

Generating ids

A TEXT or UUID primary key gets its value from the Model’s generateId when you don’t give one. By default, that’s a UUID:

  • To use another kind of id across your app, override it on your app’s base class: static override generateId = () => uuidv7(). It gets the attribute’s name, so it can prefix ids: `${attribute}_${uuidv7()}`.
  • To generate another string attribute the same way, turn it on with an override, as Product does with publicId: { generateId: true }.
  • For one attribute with its own format, use a default: shareToken: { default: () => `share_${uuidv7()}` }. A value made from other attributes, such as a slug, belongs in a callback, since generateId never sees the record.

Using timestamps

Declare createdAt and updatedAt as datetime attributes, and they’re managed for you:

  • Both are set when a record is created, and updatedAt whenever a save changes something.
  • A save with nothing to change leaves updatedAt alone, and a timestamp you assign yourself is kept.

Checking declarations

A Model’s declaration is checked the first time it’s used, by its first query or db.model(X), and it throws InvalidModel for:

  • A Model active-record schema hasn’t seen, or whose table has changed since. Run it again.
  • No table name: an empty table, or a class with no name to infer one from.
  • A modelName that isn’t a string.
  • An override of an attribute the table doesn’t have.
  • A primaryKey that isn’t an attribute.
  • An attribute named like a record method, such as save or attributes.
  • A class field that hides an attribute, such as email!: string in the class body.
  • A normalization of a name that isn’t one of the Model’s attributes.

After that, a Model’s declarations are fixed, so request code can’t change them.

Last updated on