Touching
Set a record’s updatedAt whenever a record it’s associated with changes.
At a glance
| To | Write |
|---|---|
| touch an article whenever a comment changes | belongsTo(Article, { touch: true }) |
| set another datetime attribute too | touch: "lastCommentedAt", or a list of names |
| touch a profile whenever its user changes | hasOne(Profile, { touch: true }) |
| touch a record yourself | comment.touch() |
| skip touches during an import | Article.noTouching(async () => { … }) |
The Models
The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
export class Comment extends ApplicationRecord {
article = belongsTo(Article, { touch: true }); // sets the article's updatedAt
}import { belongsTo, hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Blog } from "./blog";
import { Comment } from "./comment";
export class Article extends ApplicationRecord {
blog = belongsTo(Blog, { touch: true }); // touching an article touches its blog
comments = hasMany(Comment);
}import { ApplicationRecord } from "./application-record";
export class Blog extends ApplicationRecord {}import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";
export class Reply extends ApplicationRecord {
static override table = "comments";
article = belongsTo(Article, { touch: "lastCommentedAt" }); // and updatedAt
}import { hasOne } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Profile } from "./profile";
export class User extends ApplicationRecord {
profile = hasOne(Profile, { touch: true }); // sets the profile's updatedAt
}import { ApplicationRecord } from "./application-record";
export class Profile extends ApplicationRecord {}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 1b91f7d16771
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 },
blogId: { type: "string", null: false },
title: { type: "string", null: false },
updatedAt: "datetime",
lastCommentedAt: "datetime",
} as const;
/** blogs — last changed by 0001_create_tables.sql */
export const blogs = {
id: { type: "string", null: false, generateId: true },
updatedAt: "datetime",
} 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 },
updatedAt: "datetime",
} as const;
/** profiles — last changed by 0001_create_tables.sql */
export const profiles = {
id: { type: "string", null: false, generateId: true },
userId: { type: "string", null: false },
bio: "string",
updatedAt: "datetime",
} as const;
/** users — last changed by 0001_create_tables.sql */
export const users = {
id: { type: "string", null: false, generateId: true },
name: { type: "string", null: false },
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" },
blogs: { attributes: blogs, primaryKey: "id" },
comments: { attributes: comments, primaryKey: "id" },
profiles: { attributes: profiles, primaryKey: "id" },
users: { attributes: users, primaryKey: "id" },
},
models: {
Article: "articles",
Blog: "blogs",
Comment: "comments",
Profile: "profiles",
Reply: "comments",
User: "users",
},
});
declare module "../models/article" {
interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}
declare module "../models/blog" {
interface Blog extends TableAttributes<typeof blogs, (typeof Blog)["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"]> {}
}
declare module "../models/reply" {
interface Reply extends TableAttributes<typeof comments, (typeof Reply)["attributes"]> {}
}
declare module "../models/user" {
interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}CREATE TABLE blogs (
id TEXT PRIMARY KEY NOT NULL,
updated_at DATETIME
);
CREATE TABLE articles (
id TEXT PRIMARY KEY NOT NULL,
blog_id TEXT NOT NULL REFERENCES blogs (id),
title TEXT NOT NULL,
updated_at DATETIME,
last_commented_at DATETIME
);
CREATE TABLE comments (
id TEXT PRIMARY KEY NOT NULL,
article_id TEXT NOT NULL REFERENCES articles (id),
body TEXT NOT NULL,
updated_at DATETIME
);
CREATE TABLE users (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
updated_at DATETIME
);
CREATE TABLE profiles (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL REFERENCES users (id),
bio TEXT,
updated_at DATETIME
);CREATE TABLE blogs (
id UUID PRIMARY KEY,
updated_at TIMESTAMPTZ
);
CREATE TABLE articles (
id UUID PRIMARY KEY,
blog_id UUID NOT NULL REFERENCES blogs (id),
title TEXT NOT NULL,
updated_at TIMESTAMPTZ,
last_commented_at TIMESTAMPTZ
);
CREATE TABLE comments (
id UUID PRIMARY KEY,
article_id UUID NOT NULL REFERENCES articles (id),
body TEXT NOT NULL,
updated_at TIMESTAMPTZ
);
CREATE TABLE users (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
updated_at TIMESTAMPTZ
);
CREATE TABLE profiles (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users (id),
bio TEXT,
updated_at TIMESTAMPTZ
);Touching the record it belongs to
Declare touch: true on a comment’s belongsTo, as Comment does, and creating, updating, destroying, or touching a comment touches its article:
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: "Hello" });
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 updatedAt: "datetime";
}, 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: "First!" }); // sets article.updatedAt
await const comment: Commentcomment.Model.update(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 updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.update({ body?: string | undefinedbody: "Edited" }); // sets it again
await const comment: Commentcomment.AttributeWrites.touch<Comment>(this: Comment, ...args: TouchArguments<Comment>): 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(); // and again- The article’s new time is written in the same atomic batch as the comment. A save with nothing to write doesn’t touch it.
- Changing a comment’s
articleIdtouches both the old article and the new one. updateColumns,updateAll,insert, and the other bulk writes don’t touch the article, since they run no callbacks.- A Model without
updatedAtneeds a named attribute. Touching a Model on another database throwsInvalidModel, since the touch couldn’t be written in the same batch.
Setting another attribute
Name a datetime attribute, as Reply does, to set it to the same time as updatedAt:
import { class ArticleArticle } from "./models/article";
import { class ReplyReply } from "./models/reply";
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: "Hello" });
await class ReplyReply.create<typeof Reply>(this: typeof Reply, 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 updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<Reply> | 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({ articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody: "Agreed" }); // sets updatedAt and lastCommentedAtTo set several, list them: touch: ["lastCommentedAt", "lastActivityAt"].
Running the article’s callbacks
The article is touched as article.touch() touches it, so it runs its afterTouch callbacks, then its update commit callbacks:
- An article that declares
touchon its ownbelongsTo, asArticledoes, touches that record too: the comment touches the article, and the article its blog. - An article the same save creates, such as one built with
comment.article.build(), is touched after it’s inserted. It runsafterTouchand its create commit callbacks, but not the update ones. - A write touches each record once, however many of its comments touch it.
Loading the article
The article is loaded before the comment is written, so its callbacks can run. Preload the chain to skip those queries:
import { class CommentComment } from "./models/comment";
const const comments: Comment[]comments = await class CommentComment.includes<typeof Comment>(this: typeof Comment, ...args: ("article" | {
readonly article?: AssociationName<Article> | {
readonly blog?: {} | readonly {}[] | undefined;
readonly comments?: "article" | ... | readonly ("article" | ...)[] | undefined;
} | readonly (AssociationName<Article> | {
readonly blog?: {} | readonly {}[] | undefined;
readonly comments?: "article" | ... | readonly ("article" | ...)[] | undefined;
})[] | undefined;
})[]): Relation<Comment, ScopesOf<typeof Comment>>
Preloads associations for every record this Relation loads, so reading them afterwards
sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.includes({ article?: AssociationName<Article> | {
readonly blog?: {} | readonly {}[] | undefined;
readonly comments?: "article" | {
readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
} | readonly ("article" | {
readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
})[] | undefined;
} | readonly (AssociationName<Article> | {
readonly blog?: {} | readonly {}[] | undefined;
readonly comments?: "article" | {
readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
} | readonly ("article" | {
readonly article?: AssociationName<Article> | ... | readonly (AssociationName<Article> | ...)[] | undefined;
})[] | undefined;
})[] | undefined
article: "blog" }).Relation<Comment, ScopesOf<typeof Comment>>.toArray(): Promise<Comment[]>toArray();
for (const const comment: Commentcomment of const comments: Comment[]comments) await const comment: Commentcomment.AttributeWrites.touch<Comment>(this: Comment, ...args: TouchArguments<Comment>): 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(); // no query to load an article or blog- A loaded article sends no query, such as one reached through
article.comments(). Each level of the chain that isn’t loaded takes one query, and each one waits for the one before it. - The article is found through the association, so the association’s scope and Article’s default scope apply. An article they hide isn’t touched.
- Inside
noTouching, the touch doesn’t load the article.
Touching with a counter cache
A comment that also keeps a counter cache on the article touches it the same way, in the same batch as the count. An article the default scope hides is counted, but isn’t touched.
Turning touches off
Run an import in Article.noTouching to skip touching the article for each comment:
import { class ArticleArticle } from "./models/article";
import { class CommentComment } from "./models/comment";
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: "Hello" });
await class ArticleArticle.Model.noTouching<void>(fn: () => void | Promise<void>): Promise<void>Runs `fn` with this Model's records not touched, nor those of the Models extending it
(`Model.noTouching` covers every Model): a belongsTo's `touch`
leaves them alone, and their `touch()` writes nothing. Resolves to what `fn` returns.noTouching(async () => {
for (const const body: stringbody of ["One", "Two"]) {
await class CommentComment.create<typeof Comment>(this: typeof Comment, 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 updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<Comment> | 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({ articleId?: string | undefinedarticleId: const article: Articlearticle.id: stringid, body?: string | undefinedbody }); // doesn't touch the article
}
});
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(); // touch it once, after the import- Inside the block, no article is touched. A comment’s
belongsToleaves its article alone, andarticle.touch()writes nothing and resolves tofalse. Once the block ends, articles are touched again. noTouchingcovers the Model you call it on and the Models that extend it. To turn off touches for every Model, callApplicationRecord.noTouching.- It covers only the code the block runs and what that code awaits, so other requests still touch.
- The comments still set their own
updatedAtwhen they’re saved.Article.touchAll()andArticle.updateCounters(id, counters, { touch: true })still set the articles’updatedAt. A comment whosebelongsToalso keeps a counter cache still counts, but doesn’t touch the article.
Touching the record it has
Declare touch: true on a user’s hasOne, as User does, and updating, destroying, or touching a user touches its profile, in the same atomic batch:
import { class UserUser } from "./models/user";
const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>Like `findBy`, but throws `RecordNotFound` instead of returning null.findByOrThrow({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Sam" });
await const user: Useruser.Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.update({ name?: string | undefinedname: "Sam Smith" }); // sets the user's profile's updatedAt
await const user: Useruser.AttributeWrites.touch<User>(this: User, ...args: TouchArguments<User>): 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(); // and again- A save with nothing to write doesn’t touch the profile. A
hasOnethrough another touches the record it reaches. - The profile is touched as a
belongsTo’s record is. It takes the names of datetime attributes to set, runs itsafterTouchand update commit callbacks, and touches its own records in turn. - It’s found through the association, so a profile the association’s scope or Profile’s default scope hides isn’t touched. Inside
Profile.noTouching, it isn’t loaded or touched. - It isn’t touched when the user is new, when the user’s own save writes it (built through the user, or changed with
autosave: true), or when the user’sdependentremoves it with"destroy"or"delete". With"nullify", it’s touched once it no longer points at the user. - A profile saved as its own entry in the user’s batch is still touched, whether it comes before or after the user.