Read-only records
Load records that can’t be saved, and attributes that are set only on create.
At a glance
| To | Write |
|---|---|
| load records that can’t be saved | Article.readonly().toArray() |
| make one record read-only | article.markReadonly() |
| ask whether a record is read-only | article.isReadonly() |
| catch a refused write | catch (error) { if (error instanceof ReadonlyRecord) … } |
| set an attribute only when it’s created | slug: { readonly: true } in the Model’s attributes |
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 Article extends ApplicationRecord {
static override attributes = {
slug: { readonly: true }, // set when the article is created, never changed after
} as const;
}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: df347ceeec61
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** articles — last changed by 0001_create_articles.sql */
export const articles = {
id: { type: "string", null: false, generateId: true },
title: { type: "string", null: false },
slug: { type: "string", null: false },
body: "string",
updatedAt: "datetime",
} 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: {
articles: { attributes: articles, primaryKey: "id" },
},
models: { Article: "articles" },
});
declare module "../models/article" {
interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}CREATE TABLE articles (
id TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
body TEXT,
updated_at DATETIME
);CREATE TABLE articles (
id UUID PRIMARY KEY,
title TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
body TEXT,
updated_at TIMESTAMPTZ
);Loading read-only records
Call readonly() on a query, and the records it loads can’t be saved:
import { class ArticleArticle } from "./models/article";
const const articles: Article[]articles = await class ArticleArticle.readonly<typeof Article>(this: typeof Article, flag?: boolean | undefined): Relation<Article, ScopesOf<typeof Article>>Makes the records this Relation loads read-only (#358): saving or destroying one throws
`ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
`readonly(false)` undoes it.readonly().Relation<Article, ScopesOf<typeof Article>>.order(spec: SafeSql | OrderSpec<Article>): Relation<Article, ScopesOf<typeof Article>>Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc",
nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.order({ title?: OrderDirection | {
direction: OrderDirection;
nulls?: NullsPlacement;
} | undefined
title: "asc" }).Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray();
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)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 articles: Article[]articles[0]?.ReadonlyMarks.isReadonly(this: Model): booleanWhether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation.isReadonly()); // true
const const article: Articlearticle = await class ArticleArticle.readonly<typeof Article>(this: typeof Article, flag?: boolean | undefined): Relation<Article, ScopesOf<typeof Article>>Makes the records this Relation loads read-only (#358): saving or destroying one throws
`ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
`readonly(false)` undoes it.readonly().Relation<Article, ScopesOf<typeof Article>>.findByOrThrow(conditions: SafeSql | Conditions<Article>): Promise<Article>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ slug?: string | readonly string[] | Comparison<string> | undefinedslug: "hello" });
const article: Articlearticle.title: stringtitle = "Hello, world";
await const article: Articlearticle.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(); // throws ReadonlyRecord, and sends nothing- Every way a query loads records marks them:
toArray(),find,findBy,first,sole,findEach, and the rest. - Chaining keeps it, and so does
merge. A scope, a default scope, or an association’sscopecan call it too.readonly(false)undoes it. - The records
includespreloads aren’t read-only, unless an association’sscopecallsreadonly(). Records the query builds or creates aren’t read-only either.
Marking one record
markReadonly() makes a record you already have read-only:
import { class ArticleArticle } from "./models/article";
const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ slug?: string | readonly string[] | Comparison<string> | undefinedslug: "hello" });
const article: Articlearticle.ReadonlyMarks.markReadonly<Article>(this: Article): ArticleMarks the record read-only: saving, destroying, touching it or writing its columns throws
`ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.markReadonly();
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)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 article: Articlearticle.ReadonlyMarks.isReadonly(this: Model): booleanWhether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation.isReadonly()); // true
await const article: Articlearticle.Model.destroy(): Promise<false | Article>Deletes the row and resolves to this record, now a read-only destroyed snapshot.
A row that's already gone still counts. `false` means a `beforeDestroy` or `aroundDestroy`
callback aborted (or an `aroundDestroy` didn't call `next()`), or a `restrictWithError`
association refused.destroy(); // throws ReadonlyRecord, and the article staysA read-only record can still change in memory, and reload() still reads its row. It stays read-only.
Refusing writes
Saving, updating, destroying, or touching a read-only record throws ReadonlyRecord, and so do updateColumns, updateColumn, incrementColumn, decrementColumn, and toggleColumn:
import { class ReadonlyRecordA write of a read-only record (#358): one marked by `markReadonly()`, or loaded through a
`readonly()` Relation. Nothing ran and nothing was sent.ReadonlyRecord } from "@forestfuture/active-record";
import { class ArticleArticle } from "./models/article";
const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ slug?: string | readonly string[] | Comparison<string> | undefinedslug: "hello" });
const article: Articlearticle.ReadonlyMarks.markReadonly<Article>(this: Article): ArticleMarks the record read-only: saving, destroying, touching it or writing its columns throws
`ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.markReadonly();
try {
await const article: Articlearticle.AttributeWrites.touch<Article>(this: Article, ...args: TouchArguments<Article>): Promise<boolean>Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the
row, with no validation or save callback. Resolves to whether there was a row to write. Inside
its Model's `noTouching` block, it writes nothing (#496).touch();
} catch (var error: unknownerror) {
if (!(var error: unknownerror instanceof class ReadonlyRecordA write of a read-only record (#358): one marked by `markReadonly()`, or loaded through a
`readonly()` Relation. Nothing ran and nothing was sent.ReadonlyRecord)) throw var error: unknownerror;
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)The **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(var error: ReadonlyRecorderror.ReadonlyRecord.action: ReadonlyActionaction); // "touch"
}- It throws before validation or any callback runs, and sends nothing.
save()throws too, rather than returningfalse.- The error’s
recordis the refused record, and itsactionnames what was refused:"save","destroy","touch", or the column method. - A write that would reach a read-only record through another throws too, and writes nothing. Saving an owner that autosaves a changed read-only record, a batch holding one, and a has-many’s
pushthrow before any callback runs. So does a write that would touch a loaded read-only record. - Some records are only loaded partway through a write: the record a has-one’s new record replaces, and a
dependent: "destroy"association’s records. A read-only one throws once it’s loaded, after the owner’s before-callbacks, and nothing is written.
Writing past it
Bulk writes don’t load records, so readonly() doesn’t stop them:
import { class ArticleArticle } from "./models/article";
const const updated: numberupdated = await class ArticleArticle.readonly<typeof Article>(this: typeof Article, flag?: boolean | undefined): Relation<Article, ScopesOf<typeof Article>>Makes the records this Relation loads read-only (#358): saving or destroying one throws
`ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
`readonly(false)` undoes it.readonly().Relation<Article, ScopesOf<typeof Article>>.where(conditions: SafeSql | Conditions<Article>): Relation<Article, ScopesOf<typeof Article>>where({ slug?: string | readonly string[] | Comparison<string> | undefinedslug: "hello" }).Relation<Article, ScopesOf<typeof Article>>.updateAll(changes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
readonly slug: {
readonly type: "string";
readonly null: false;
};
readonly body: "string";
readonly updatedAt: "datetime";
}, {
readonly slug: {
readonly readonly: true;
};
}>>> | SafeSql): Promise<number>
Updates every row this Relation matches, now, setting attribute values or an `sql`
fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone.
A `none()` Relation sends nothing and resolves to 0.updateAll({ body?: string | null | undefinedbody: "" });
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)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 updated: numberupdated); // 1: a bulk write doesn't load records, so it isn't refusedupdateAll, deleteAll, insert, and upsert all write as usual. So do the removals that work like them: dependent: "delete", a has-one replacement whose dependent is "delete", and a has-many’s delete() and clear().
Declaring read-only attributes
Give an attribute readonly: true, and it’s written when its record is created, then never changed by it:
import { class ArticleArticle } from "./models/article";
const const article: Articlearticle = await class ArticleArticle.create<typeof Article>(this: typeof Article, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
readonly slug: {
readonly type: "string";
readonly null: false;
};
readonly body: "string";
readonly updatedAt: "datetime";
}, {
readonly slug: {
readonly readonly: true;
};
}>>> | undefined, init?: Init<Article> | undefined): Promise<Article>
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: "Getting started", slug?: string | undefinedslug: "getting-started" });
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)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 article: Articlearticle.slug: stringslug); // "getting-started"
const article: Articlearticle.slug: stringslug = "first-steps"; // throws ReadonlyAttribute: it's set when it's created- Assigning a saved record a new value throws
ReadonlyAttributestraight away, whether you assign it,update()it, or write it withupdateColumns. The error’sattributenames it. - Pointing a belongs-to at another record throws
ReadonlyAttributewhen its read-only foreign key would change. So does saving a record whose read-only foreign key a new record would fill once it’s inserted. - Changing a JSON value or a
Datein place makes the save throw before anything runs.touch()refuses a read-only datetime the same way. - A new record can change it until it’s saved.
- A counter cache still counts a read-only column, so a save can’t overwrite the count.
Model.updateCountersandtouchAllwrite rows without loading them, asupdateAlldoes, so they write a read-only column too. - An
upsertleaves the value of a row it updates alone.updateAllstill writes it. - A virtual attribute, a secure password, and a secure token can’t be read-only. Neither can
updatedAtorlockVersion, which every save writes.
Posting it back from a form
Assigning the value an attribute already holds isn’t a change, so a form that sends every field back still saves:
import { class ReadonlyAttributeAssigning a persisted record's read-only attribute a value other than the one it holds (#358):
it's written when the record is created, and never changed by it after.ReadonlyAttribute } from "@forestfuture/active-record";
import { class ArticleArticle } from "./models/article";
export async function function updateArticle(request: Request): Promise<Response>updateArticle(request: Request<unknown, CfProperties<unknown>>request: interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>The **`Request`** interface of the Fetch API represents a resource request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)Request): interface Promise<T>Represents the completion of an asynchronous operationPromise<Response> {
const const id: stringid = new var URL: new (url: string | URL, base?: string | URL) => URLThe **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)URL(request: Request<unknown, CfProperties<unknown>>request.Request<unknown, CfProperties<unknown>>.url: stringThe **`url`** read-only property of the Request interface contains the URL of the request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)url).URL.searchParams: URLSearchParamsThe **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)searchParams.URLSearchParams.get(name: string): string | nullThe **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)get("id") ?? "";
const const article: Articlearticle = await class ArticleArticle.OverloadedStatics.find: <typeof Article>(this: typeof Article, id: string | number) => Promise<Article> (+2 overloads)find(const id: stringid);
const const form: FormDataform = await request: Request<unknown, CfProperties<unknown>>request.Body.formData(): Promise<FormData> (+1 overload)[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData)formData();
const const changes: Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
readonly slug: {
readonly type: "string";
readonly null: false;
};
readonly body: "string";
readonly updatedAt: "datetime";
}, {
readonly slug: {
readonly readonly: true;
};
}>>, "slug" | "title">>
changes = class ArticleArticle.Model.permit<typeof Article, "slug" | "title">(this: typeof Article, input: unknown, ...names: ("slug" | "title")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
readonly slug: {
readonly type: "string";
readonly null: false;
};
readonly body: "string";
readonly updatedAt: "datetime";
}, {
readonly slug: {
readonly readonly: true;
};
}>>, "slug" | "title">>
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: FormDataform, "title", "slug");
try {
// A form that posts the slug back unchanged saves; one that changes it doesn't
await const article: Articlearticle.Model.updateOrThrow(attributes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
readonly slug: {
readonly type: "string";
readonly null: false;
};
readonly body: "string";
readonly updatedAt: "datetime";
}, {
readonly slug: {
readonly readonly: true;
};
}>>>): Promise<true>
`assign` then `saveOrThrow`.updateOrThrow(const changes: Partial<Pick<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
readonly slug: {
readonly type: "string";
readonly null: false;
};
readonly body: "string";
readonly updatedAt: "datetime";
}, {
readonly slug: {
readonly readonly: true;
};
}>>, "slug" | "title">>
changes);
} catch (function (local var) error: unknownerror) {
if (!(function (local var) error: unknownerror instanceof class ReadonlyAttributeAssigning a persisted record's read-only attribute a value other than the one it holds (#358):
it's written when the record is created, and never changed by it after.ReadonlyAttribute)) throw function (local var) error: unknownerror;
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response(`An article's ${function (local var) error: ReadonlyAttributeerror.ReadonlyAttribute.attribute: stringattribute} can't be changed.`, { ResponseInit.status?: number | undefinedstatus: 422 });
}
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response("Saved");
}The value is compared after it’s cast and normalized, so " Hello " matches "hello" when a normalization trims and lowercases it.