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") |
with(value) => value
The function `normalizes` runs. It takes a value already cast to the attribute’s type, and returns the one to keep.
(value) => valueapplyToNull?boolean
Hands `null` to `normalizes`’s `with` too. By default, `null` is kept as it is.
booleanfalseEach 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 declarationsimport { 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
Productreads and writesproducts. The table’s attributes, primary key, and types come fromsrc/db/schema.ts. active-record schemawrites that file from your migrations and your Models. Run it after you add a Model or a migration.active-record g modelruns 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
FeaturedProductdoes, 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
typedrops the generated default orgenerateId, so the column’s own default applies unless you give one.archivedgives one, so a new product readsfalsebefore it’s saved. - A
defaultandgenerateIdreplace each other, so an attribute has one or the other.generateIdis only for strings. - A
defaultisn’t type-checked yet (#74). One that returns a value the type can’t cast throwsTypeErrorwhen a record is built. - Ignoring a
NOT NULLcolumn 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, andactive-record schemareports 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[]): 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 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.
permittakes 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
updatedAtalone, or writes nothing on a table without timestamps. - A loaded record starts it at its default, or
null, and so doesreload. - A query can’t name it, since there’s no column to match.
where,order,select,pluck,insert, andupdateAllthrowUnknownAttribute. - It’s in
toJSON(), unless aconfirmationrule reads it. A record keeps it after a create, so list a secret one inhiddenAttributes, orResponse.json(user)sends it back. For a password, declare a secure password instead, whichtoJSON()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[]): 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 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[]): voidThe **`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 asinsert,upsert, andupdateAll. Several normalizations of one attribute run in order, a parent class’s first. - Queries normalize their values too.
where,findBy,find, lists, comparisons, andcolumn()values in ansqlfragment match what was stored. Plain values in ansqlfragment are left as they are, andwhere({ email: null })still matchesNULL. 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[]): 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.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[]): 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 titles: string[]titles); // ["Lamp"]
const lamp: Productlamp.title: stringtitle = "Desk lamp";
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.Model.changes(): ChangesEach 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, andupdateAll. - The record holds the value once, under the attribute’s name.
attributes(),toJSON(), andchanges()listname, and so does a recordselect("title")loads.attributeWas("title")and the other methods that take a name read it through the alias. - A row that gives both
titleandnamethrowsTypeError, since they’re one column. validates("title", …)reads through the alias, and its errors go undertitle.
Narrowing types
Declare an attribute in the class to give it a narrower type than its column’s, as Product does with status:
product.statusis typed"draft" | "published", when you read it and when you assign it.whereandbuildstill 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
defineonApplicationRecordshares 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[]): voidThe **`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: stringThe 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 renamesUsertoemakes the first query throwInvalidModel, because no Model namedeis in the generated schema. Wrangler keeps class names by default, even when minifying. - A subclass inherits a
modelNameits parent sets. Otherwise, each class has its own:FeaturedProduct.modelNameis"FeaturedProduct", though it sharesProduct’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[]): 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.id: stringid); // generated already, before saving: "3b241101-…"
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.Product.status: "draft" | "published"status); // "draft", the column's default
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.archived: booleanarchived); // false, read as a boolean
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
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, andundefinedthrowsTypeError. Usenullto 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
nullis kept. - A name that isn’t an attribute is a compile error, and throws
UnknownAttribute. TypeErroris thrown for a value that can’t be cast, a file from a form (read a file’s bytes for abinaryattribute), and any other input: an array, aMap,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
Productdoes withpublicId: { 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, sincegenerateIdnever 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
updatedAtwhenever a save changes something. - A save with nothing to change leaves
updatedAtalone, 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 schemahasn’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
modelNamethat isn’t a string. - An override of an attribute the table doesn’t have.
- A
primaryKeythat isn’t an attribute. - An attribute named like a record method, such as
saveorattributes. - A class field that hides an attribute, such as
email!: stringin 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.