Autosaving
Save a record with the records built, changed, or marked for destruction through its associations.
At a glance
| To | Write |
|---|---|
| create a record with its owner’s key | article.comments().create({ body: "…" }) |
| build records to save with their owner | author.articles().build({ … }), author.profile.build({ … }) |
| save the owner and every record built through it | author.saveOrThrow() |
| save the loaded records that changed too | hasMany(Article, { autosave: true }) |
| destroy a record when its owner saves | article.markForDestruction() |
The Models
The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:
import { hasMany, hasOne } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
import { Profile } from "./profile";
export class Author extends ApplicationRecord {
articles = hasMany(Article, { autosave: true }); // saves changed articles with the author
profile = hasOne(Profile);
}import { belongsTo, hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Author } from "./author";
import { Comment } from "./comment";
export class Article extends ApplicationRecord {
author = belongsTo(Author);
comments = hasMany(Comment, { dependent: "destroy" }); // destroyed with their article
}import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
export class Comment extends ApplicationRecord {
article = belongsTo(Article);
}import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Author } from "./author";
export class Profile extends ApplicationRecord {
author = belongsTo(Author);
}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: d6e921e3fa3b
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** articles — last changed by 0001_create_tables.sql */
export const articles = {
id: { type: "string", null: false, generateId: true },
authorId: { type: "string", null: false },
title: { type: "string", null: false },
} as const;
/** authors — last changed by 0001_create_tables.sql */
export const authors = {
id: { type: "string", null: false, generateId: true },
name: { type: "string", null: false },
} as const;
/** comments — last changed by 0001_create_tables.sql */
export const comments = {
id: { type: "string", null: false, generateId: true },
articleId: { type: "string", null: false },
body: { type: "string", null: false },
} as const;
/** profiles — last changed by 0001_create_tables.sql */
export const profiles = {
id: { type: "string", null: false, generateId: true },
authorId: { type: "string", null: false },
bio: "string",
} 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" },
authors: { attributes: authors, primaryKey: "id" },
comments: { attributes: comments, primaryKey: "id" },
profiles: { attributes: profiles, primaryKey: "id" },
},
models: { Article: "articles", Author: "authors", Comment: "comments", Profile: "profiles" },
});
declare module "../models/article" {
interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}
declare module "../models/author" {
interface Author extends TableAttributes<typeof authors, (typeof Author)["attributes"]> {}
}
declare module "../models/comment" {
interface Comment extends TableAttributes<typeof comments, (typeof Comment)["attributes"]> {}
}
declare module "../models/profile" {
interface Profile extends TableAttributes<typeof profiles, (typeof Profile)["attributes"]> {}
}CREATE TABLE authors (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL
);
CREATE TABLE profiles (
id TEXT PRIMARY KEY NOT NULL,
author_id TEXT NOT NULL REFERENCES authors (id),
bio TEXT
);
CREATE TABLE articles (
id TEXT PRIMARY KEY NOT NULL,
author_id TEXT NOT NULL REFERENCES authors (id),
title TEXT NOT NULL
);
CREATE TABLE comments (
id TEXT PRIMARY KEY NOT NULL,
article_id TEXT NOT NULL REFERENCES articles (id),
body TEXT NOT NULL
);CREATE TABLE authors (
id UUID PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE profiles (
id UUID PRIMARY KEY,
author_id UUID NOT NULL REFERENCES authors (id),
bio TEXT
);
CREATE TABLE articles (
id UUID PRIMARY KEY,
author_id UUID NOT NULL REFERENCES authors (id),
title TEXT NOT NULL
);
CREATE TABLE comments (
id UUID PRIMARY KEY,
article_id UUID NOT NULL REFERENCES articles (id),
body TEXT NOT NULL
);Creating related records
Create a record through a hasMany, and it gets the owner’s key:
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({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "On Nothing" });
const const comment: Commentcomment = await const article: Articlearticle.Article.comments: () => HasManyCollection<Comment, ScopesOf<typeof Comment>>comments().Relation<Comment, ScopesOf<typeof Comment>>.create(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly articleId: {
readonly type: "string";
readonly null: false;
};
readonly body: {
readonly type: "string";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: Init<Comment> | undefined): Promise<Comment>
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({ body?: string | undefinedbody: "Lovely." }); // articleId filled inSaving a graph
Build records through an association, then save the owner, and they’re saved with it:
import { class AuthorAuthor } from "./models/author";
const const author: Authorauthor = class AuthorAuthor.build<typeof Author>(this: typeof Author, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Author) => void) | undefined): Author
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: "Sam" });
const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.build(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly authorId: {
readonly type: "string";
readonly null: false;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: ((record: Article) => void) | undefined): Article
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({ title?: string | undefinedtitle: "Getting started" });
const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.build(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly authorId: {
readonly type: "string";
readonly null: false;
};
readonly title: {
readonly type: "string";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: ((record: Article) => void) | undefined): Article
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({ title?: string | undefinedtitle: "Going further" });
const author: Authorauthor.Author.profile: HasOne<typeof Profile>profile.HasOne<typeof Profile>.build(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly authorId: {
readonly type: "string";
readonly null: false;
};
readonly bio: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined): Profile
build({ bio?: string | null | undefinedbio: "Writer" });
await const author: Authorauthor.Model.saveOrThrow(options?: SaveOptions): Promise<true>Like `save()`, but throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed` (a
record marked for destruction refused) instead of returning `false`.saveOrThrow(); // the author, both articles, and the profile, in one batch- The built records are validated with the owner. An invalid article makes the author invalid (“Articles is invalid”), with its own errors on the article. To validate the records an association loaded too, use
validatesAssociated. - Each built article’s
authoris the owner, without a query, even before either is saved. - When the owner’s key is generated in code, as here, everything is written in one atomic batch. Records on another database are written there separately.
Saving changed records
Declare an association with autosave: true, as Author’s articles does, to save the changes to its loaded records with their owner:
import { class AuthorAuthor } from "./models/author";
const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
const const articles: Article[]articles = await const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray();
for (const const article: Articlearticle of const articles: Article[]articles) const article: Articlearticle.title: stringtitle = const article: Articlearticle.title: stringtitle.String.toUpperCase(): stringConverts all the alphabetic characters in a string to uppercase.toUpperCase();
await const author: Authorauthor.Model.saveOrThrow(options?: SaveOptions): Promise<true>Like `save()`, but throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed` (a
record marked for destruction refused) instead of returning `false`.saveOrThrow(); // every article that changed, in one batch- By default, only new records are saved with their owner.
- Saving the author saves each article that changed, in the same atomic batch. Unchanged articles aren’t validated or written.
- Only the records the association holds count: those it loaded, and those built through it. A record you found with a query of its own isn’t saved.
- The changed records are validated with the owner. An invalid one’s errors are copied to the owner under the association’s name: an article with a blank title gives the author an
articles.titleerror, “Articles title can’t be blank”. autosave: trueworks on ahasOneand abelongsTotoo. AbelongsTo’s record is saved before its owner.
Removing records on save
Mark a record with markForDestruction() to destroy it when its owner is saved:
import { class AuthorAuthor } from "./models/author";
const const author: Authorauthor = await class AuthorAuthor.findByOrThrow<typeof Author>(this: typeof Author, conditions: SafeSql | Conditions<Author>): Promise<Author>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Jane" });
const const articles: Article[]articles = await const author: Authorauthor.Author.articles: () => HasManyCollection<Article, ScopesOf<typeof Article>>articles().Relation<Article, ScopesOf<typeof Article>>.toArray(): Promise<Article[]>toArray();
for (const const article: Articlearticle of const articles: Article[]articles) {
if (const article: Articlearticle.title: stringtitle.String.startsWith(searchString: string, position?: number): booleanReturns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.startsWith("Draft")) const article: Articlearticle.Model.markForDestruction(): voidMarks the record to be destroyed when its owner is saved, through an association declared
`autosave: true`. Nothing is written until then, and
`reload()` clears the mark.markForDestruction();
}
await const author: Authorauthor.Model.saveOrThrow(options?: SaveOptions): Promise<true>Like `save()`, but throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed` (a
record marked for destruction refused) instead of returning `false`.saveOrThrow(); // destroys the drafts, with their comments- Marking writes nothing, and the marked articles stay in
author.articles()until the author is saved. Then each is destroyed with its callbacks anddependentstrategies, in the same batch as the author, and leaves the association. Changed articles are saved after the destroys. isMarkedForDestruction()reads the mark, andreload()clears it. A marked record that was never saved is dropped from the association, and nothing is written for it.- Through a
belongsTo, the owner’s foreign key is set tonull, and the owner is written before its record is destroyed. - If a marked record refuses to be destroyed, because its
beforeDestroyaborts or arestrictWithErrorstrategy stops it, nothing is written.save()returnsfalse, andsaveOrThrow()throwsRecordNotDestroyed. The marked record holds the reason, inabortReasonorerrors.
Not built yet
These features aren’t in Active Record yet. The code shows the shape they’re likely to take.
- Autosaving through an association through another (#450):
articles = hasMany(Article, { through: "taggings", autosave: true }), which saves the tag’s changed articles with it. - Never autosaving (#378):
articles = hasMany(Article, { autosave: false }), which never saves the association’s records with the owner, not even new ones. - Numbered autosave errors (#379):
hasMany(Article, { autosave: true, indexErrors: true }), which names a copied error by the record’s position,articles[1].title.