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

Optimistic locking

Stop two saves of one record from overwriting each other.

At a glance

To Write
turn locking on a lock_version INTEGER NOT NULL DEFAULT 0 column
catch a save from a stale copy catch (error) { if (error instanceof StaleRecord) … }
catch an edit made since a form loaded article.assign({ lockVersion: Number(form.get(…)) })
try again with the row’s values await article.reload(), then make the change again
write without checking the version article.updateColumns({ … })

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 {} // its lockVersion turns locking on
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 8e9f2af487ba

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 },
  body: "string",
  lockVersion: { type: "integer", null: false, default: () => 0 },
  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,
  body TEXT,
  lock_version INTEGER NOT NULL DEFAULT 0,
  updated_at DATETIME
);
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  body TEXT,
  lock_version INTEGER NOT NULL DEFAULT 0,
  updated_at TIMESTAMPTZ
);

Turning it on

Add a lock_version integer column to a table, and its Model’s records lock. Every save that writes the row checks that the row still has the record’s lockVersion, then adds 1 to it.

  • A record with no changes sends nothing, so its version stays the same.
  • A new record is saved with version 0 when it has none.
  • A row whose lock_version is NULL reads as version 0.

Saving a stale record

When another save changes the row after you load a record, saving your copy throws StaleRecord:

import { class ArticleArticle } from "./models/article";

const const mine: Articlemine = 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 theirs: Articletheirs = 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 const theirs: Articletheirs.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: "string";
    readonly lockVersion: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.
update
({ body?: string | null | undefinedbody: "Their edit" }); // the row's lockVersion goes from 0 to 1
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 theirs: Articletheirs.lockVersion: numberlockVersion); // 1
const mine: Articlemine.body: string | nullbody = "My edit"; await const mine: Articlemine.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 StaleRecord: mine still has version 0
  • save() throws, as saveOrThrow() does. Nothing in its write is kept, so the record’s autosaved records, counter caches, and touches roll back with it, as do the other records of a batch.
  • The error’s record is the stale record, and its action is "update", "destroy", or "touch".
  • The record keeps its changes, and the version it had.

Destroying a stale record

destroy() checks the version too:

import { class ArticleArticle } from "./models/article";

const const mine: Articlemine = 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 theirs: Articletheirs = 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 const theirs: Articletheirs.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: "string";
    readonly lockVersion: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.
update
({ title?: string | undefinedtitle: "Hello again" });
await const mine: Articlemine.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 StaleRecord, and the article stays

The article stays, and so do the records its dependent associations would have destroyed on its database. Those on another database are destroyed first, in a write of their own, so they’re gone.

Catching edits made in another request

Put the record’s lockVersion in its form, and assign it back when the form is sent. The save then checks the version the form was shown with:

import { class StaleRecord
A save, destroy or `touch()` of a record whose row another write changed since it was loaded (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
StaleRecord
} 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 operation
Promise
<Response> {
const const article: Articlearticle = await class ArticleArticle.OverloadedStatics.find: <typeof Article>(this: typeof Article, id: string | number) => Promise<Article> (+2 overloads)find(new var URL: new (url: string | URL, base?: string | URL) => URL
The **`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: string
The **`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: URLSearchParams
The **`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 | null
The **`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") ?? "");
// lockVersion is the version the form was shown with, from a hidden field const article: Articlearticle.
Model.assign(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: "string";
    readonly lockVersion: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Article
Assigns several attributes without saving.
assign
(class ArticleArticle.
Model.permit<typeof Article, "body" | "lockVersion">(this: typeof Article, input: unknown, ...names: ("body" | "lockVersion")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: "string";
    readonly lockVersion: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>, "body" | "lockVersion">>
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: Request<unknown, CfProperties<unknown>>request.Body.formData(): Promise<FormData> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData)
formData
(), "body", "lockVersion"));
try { await const article: Articlearticle.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
();
} catch (function (local var) error: unknownerror) { if (!(function (local var) error: unknownerror instanceof class StaleRecord
A save, destroy or `touch()` of a record whose row another write changed since it was loaded (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
StaleRecord
)) throw function (local var) error: unknownerror;
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
("Someone else changed this article. Reload it and try again.", {
ResponseInit.status?: number | undefinedstatus: 409, }); } return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
("Saved");
}

Recovering from a stale record

Reload the record to read the row’s values and its version, then make your change again:

import { class StaleRecord
A save, destroy or `touch()` of a record whose row another write changed since it was loaded (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
StaleRecord
} 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
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" });
await (await class ArticleArticle.OverloadedStatics.find: <typeof Article>(this: typeof Article, id: string | number) => Promise<Article> (+2 overloads)find(const article: Articlearticle.id: stringid)).
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
    readonly body: "string";
    readonly lockVersion: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
    readonly updatedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.
update
({ title?: string | undefinedtitle: "Hello, world" }); // another request's edit
const article: Articlearticle.body: string | nullbody = "A new paragraph."; try { await const article: Articlearticle.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
();
} catch (var error: unknownerror) { if (!(var error: unknownerror instanceof class StaleRecord
A save, destroy or `touch()` of a record whose row another write changed since it was loaded (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
StaleRecord
)) throw var error: unknownerror;
await const article: Articlearticle.Model.reload(): Promise<Article>
Loads the stored row again, discarding unsaved changes; `RecordNotFound` if it's gone.
reload
(); // the row's values, and its version
const article: Articlearticle.body: string | nullbody = "A new paragraph."; await const article: Articlearticle.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
();
}

Writing without the check

updateColumns, updateColumn, incrementColumn, decrementColumn, and toggleColumn write straight to the row. They don’t check lockVersion or change it, and neither do counters, counter caches, updateAll, deleteAll, touchAll, and Article.delete(ids).

Last updated on