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

Change tracking

A record knows what’s changed since it was loaded or last saved.

At a glance

To Write
check for unsaved changes isChanged(), changed(), changes()
read an attribute’s value before the change attributeWas("email")
check one attribute’s change isAttributeChanged("email", { from: "…" }), willSaveChangeTo("email")
read what the last save changed savedChanges(), savedChangeTo("email"), hasSavedChangeTo("email")
undo unsaved changes restoreAttributes(), or restoreAttributes(["email"])

The Model

The examples use this Model, whose attributes come from its table through the schema active-record schema generates. Its afterSave callback reads what each save changed:

import { ApplicationRecord } from "./application-record";

export class User extends ApplicationRecord {
  static {
    // After a save, the record is clean: read what the save changed.
    this.afterSave((user) => {
      const change = user.savedChangeTo("email");
      if (change) console.log(`Email changed from ${change[0]} to ${change[1]}`);
    });
  }
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 7ace010c47bc

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** users — last changed by 0001_create_users.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  role: "string",
  isActive: "boolean",
  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: {
    users: { attributes: users, primaryKey: "id" },
  },
  models: { User: "users" },
});

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  role TEXT,
  is_active BOOLEAN,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  role TEXT,
  is_active BOOLEAN,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

Reading changes

Read a record’s changes before it’s saved, and what the save changed after:

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
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const user: Useruser.email: stringemail = "jane@work.example"; var console: Consoleconsole.Console.log(...data: any[]): void
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 user: Useruser.Model.changed(): string[]
The names of the changed attributes.
changed
()); // ["email"]
var console: Consoleconsole.Console.log(...data: any[]): void
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 user: Useruser.Model.attributeWas<User, "email">(this: User, name: "email"): string
The attribute's value before its unsaved change, as stored.
attributeWas
("email")); // "jane@example.com"
var console: Consoleconsole.Console.log(...data: any[]): void
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 user: Useruser.Model.isAttributeChanged<User, "email">(this: User, name: "email", options?: ChangeOptions<string>): boolean
Whether the attribute has an unsaved change, optionally `from` and/or `to` given values.
isAttributeChanged
("email", { ChangeOptions<string>.from?: string | undefinedfrom: "jane@example.com" })); // true
await const user: Useruser.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
(); // logs "Email changed from jane@example.com to jane@work.example"
var console: Consoleconsole.Console.log(...data: any[]): void
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 user: Useruser.Model.isChanged(): boolean
Whether any attribute differs from its value as last loaded or saved.
isChanged
()); // false
  • isChanged(), changed(), changedAttributes(), and changes() describe the unsaved changes. A new record’s changes run from its defaults, so a default it keeps isn’t a change.
  • attributeWas, isAttributeChanged, and willSaveChangeTo look at one attribute’s unsaved change. Use them in before-callbacks.
  • savedChanges(), savedChangeTo, hasSavedChangeTo, and attributeBeforeLastSave look at the last save. Use them in after-callbacks, where the record is already clean, as User does.
  • An update writes only the attributes that changed, and a save with nothing changed sends nothing.

Undoing changes

Undo unsaved changes with restoreAttributes, to every attribute or the ones you name:

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
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const user: Useruser.
Model.assign(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly role: "string";
    readonly isActive: "boolean";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): User
Assigns several attributes without saving.
assign
({ email?: string | undefinedemail: "typo@example", role?: string | null | undefinedrole: "owner" });
const user: Useruser.Model.restoreAttributes<User>(this: User, names?: readonly AttributeKey<User>[] | undefined): void
Undoes unsaved changes to these attributes (all of them by default).
restoreAttributes
(["email"]); // back to "jane@example.com"; role stays changed

Last updated on