Skip to content

Creating, Updating & Deleting Records ​

Once your models are defined, repositories on your orm handle let you create, batch-insert, find, and upsert records, while fetched Model instances track dirty attributes, enforce .readonly() fields, handle soft deletes, and run lifecycle hooks.


1. Repository Creation & Lookups ​

Given const orm = createOrm(db, { users: User, posts: Post }), each repository provides strongly typed CRUD methods:

Creating & Instantiating Records ​

typescript
// Create and persist immediately (applies defaults, autoUuid/autoUlid, timestamps, hooks)
const alice = await orm.users.create({
  name: "Alice",
  email: "[email protected]", // normalized in beforeCreate hook -> "[email protected]"
  passwordHash: "hash_123",
});

// Batch create atomically (auto-wraps in a transaction if not already inside one)
const team = await orm.users.createMany([
  { name: "Bob", email: "[email protected]", passwordHash: "hash_bob" },
  { name: "Carol", email: "[email protected]", passwordHash: "hash_carol" },
]);

// Instantiate in memory WITHOUT saving to the DB (`orm.users.make(...)`)
// Bound to the ORM so calling `await draft.save()` later inserts it!
const draft = orm.users.make({
  name: "Draft User",
  email: "[email protected]",
  passwordHash: "hash_draft",
});
console.log(draft.isDirty()); // true
await draft.save();           // executes INSERT

// Hydrate from a raw DB row (e.g., returned from a custom `db.from(...)` query)
const rawRow = await orm.db.from("users").where("email", "=", "[email protected]").first();
const bob = rawRow ? orm.users.hydrate(rawRow) : null;

Finding & Deleting by Key ​

typescript
// Single primary key lookup (returns `null` if not found, ignores soft-deleted rows)
const user = await orm.users.find(alice.id);

// Throws `ModelNotFoundError` if missing
const strictUser = await orm.users.findOrFail(alice.id);

// Batch PK lookup (chunked safely past 5,000 keys; supports Date and composite PKs too)
const someUsers = await orm.users.findMany([alice.id, bob.id]);

// Fetch all non-deleted records
const everyone = await orm.users.all();

// Shorthand helpers on the repository
const found = await orm.users.where("role", "=", "admin").get();
const total = await orm.users.count();
const anyUsers = await orm.users.exists();

// Delete by primary key (triggers soft delete if configured, and delete hooks if defined)
const removed = await orm.users.deleteById(alice.id); // boolean

2. firstOrCreate, updateOrCreate & upsert ​

All three operations are concurrency-safe in-transaction helpers:

typescript
// Find matching row by `where`, or create using `{ ...defaults, ...where }`
const user = await orm.users.firstOrCreate(
  { email: "[email protected]" },
  { name: "Maya", passwordHash: "secret" },
);

// Find matching row and update it, or create with `{ ...where, ...values }`
const synced = await orm.users.updateOrCreate(
  { email: "[email protected]" },
  { name: "Maya Lin", passwordHash: "secret", isActive: true },
);

Native upsert() Modes ​

orm.users.upsert(data, options) delegates to WebDB's native upsert engine and returns 'inserted' | 'updated' | 'ignored':

typescript
// 1. Default `merge` mode:
//    Updates existing row ONLY with fields explicitly present in `data`,
//    automatically preserving `.readonly()` fields, `createdAt`, and omitted columns.
const outcome = await orm.users.upsert(
  {
    name: "Alice Merged",
    email: "[email protected]",
    passwordHash: "hash_123",
  },
  {
    conflictTarget: "email", // property name (mapped via `.column()` automatically)
    mode: "merge",
  },
);

// 2. `ignore` mode (insert if new, do nothing if conflict exists):
await orm.users.upsert(
  { name: "Ignored", email: "[email protected]", passwordHash: "x" },
  { conflictTarget: "email", mode: "ignore" },
);

// 3. `replace` mode (overwrites full row on conflict, including auto-defaults):
await orm.users.upsert(
  { name: "Alice Replaced", email: "[email protected]", passwordHash: "new_hash" },
  { conflictTarget: "email", mode: "replace" },
);

// 4. Conditional `where` guard on the conflict update:
await orm.users.upsert(
  { name: "Only If Active", email: "[email protected]", passwordHash: "hash_123" },
  {
    conflictTarget: "email",
    mode: "merge",
    where: "is_active = 1",
  },
);

3. Dirty Tracking, Partial Saves & refresh() ​

Persisted instances snapshot their committed database values, using deep structural equality for Date, Uint8Array, and JSON objects/arrays (col.json()):

typescript
const user = await orm.users.findOrFail(alice.id);

// Direct property mutation or `.fill()`
user.name = "Alice Updated";
user.meta = { bio: "Local-first engineer" };

user.isDirty();           // true
user.isDirty("name");     // true
user.isDirty("email");    // false
user.getOriginal("name"); // "Alice"
user.getDirty();          // { name: "Alice Updated", meta: { bio: "Local-first engineer" } }

// `save()` is a no-op if nothing is dirty; otherwise it updates ONLY dirty columns + `updatedAt`
await user.save();

user.isDirty();           // false (originals refreshed after save)
user.wasChanged("name");  // true
user.wasChanged("email"); // false

// Convenience fill + save in one call (`update()` rejects `.readonly()` keys at compile time & runtime)
await user.update({ isActive: false });

// Reload latest row from the DB, resetting dirty state and clearing stale `relations` / `counts`
await user.refresh();

NOTE

Unbound instances (new User() created manually without a repository or make()) throw InvalidModelConfigurationError if you call save(), update(), delete(), forceDelete(), restore(), refresh(), or load().


4. Soft Deletes ​

Add static readonly softDeletes = "deletedAt" as const; (paired with a nullable col.timestamp() column) to enable soft deletion:

typescript
// Marks `deletedAt` with current timestamp + fires `beforeDelete` / `afterDelete`
await user.delete();

// Default queries automatically exclude soft-deleted rows:
await orm.users.find(user.id); // null

// Opt in to trashed rows:
await orm.users.query().withTrashed().get(); // active + deleted
await orm.users.query().onlyTrashed().get(); // deleted only

// Restore a soft-deleted record (`beforeRestore` / `afterRestore` hooks run)
await user.restore();

// Permanently remove from the database table
await user.forceDelete();

Query-builder bulk mutations also support soft deletes:

typescript
await orm.users.where("isActive", "=", false).delete();      // bulk soft-delete
await orm.users.where("isActive", "=", false).restore();     // bulk restore
await orm.users.where("isActive", "=", false).forceDelete(); // bulk hard-delete

5. Lifecycle Hooks (static readonly hooks) ​

Models support 8 synchronous or async lifecycle hooks:

  • beforeCreate / afterCreate
  • beforeUpdate / afterUpdate
  • beforeDelete / afterDelete (triggered on both soft delete and forceDelete, and also called when deleting via repository.deleteById() or relation.delete())
  • beforeRestore / afterRestore

Mutating Attributes & Aborting Writes ​

Mutate attributes directly in before* hooks—the modified values are persisted automatically. Throwing an Error inside any before* hook aborts the database write cleanly:

typescript
export class User extends Model {
  // ...columns...
  static readonly hooks = {
    beforeCreate: async (user: User) => {
      user.email = user.email.trim().toLowerCase();
      if (!user.email.includes("@")) {
        throw new Error("Invalid email address");
      }
    },
    beforeUpdate: (user: User) => {
      if (user.isDirty("email")) {
        user.email = user.email.trim().toLowerCase();
      }
    },
    afterDelete: (user: User) => {
      console.log(`Archived user #${user.id}`);
    },
  };
}

6. Serialization (toObject() vs toJSON()) ​

Both toObject() and toJSON() exclude columns marked .hidden() (such as passwordHash), and include any loaded relations and counts:

  • user.toObject(): Preserves native JS types (Date, bigint, Uint8Array).
  • user.toJSON() / JSON.stringify(user): Recursively converts bigint values (including inside nested relations and pivot attributes) into strings so JSON.stringify() never throws TypeError: Do not know how to serialize a BigInt.
typescript
const obj = user.toObject();
// passwordHash is omitted; loaded relations/counts are included if `.with()` ran

const json = JSON.stringify(user);
// Safe even when the model uses `col.int64()` (`bigint`) primary keys or columns

7. Error Taxonomy ​

All ORM-specific errors extend OrmError:

Error ClassWhen It Is Thrown
OrmErrorBase class for all ORM errors
ModelNotFoundErrorfindOrFail(), firstOrFail(), or refresh() finds no matching row (includes .modelName and optional .key)
RelationNotFoundErrorCalling repository.relation(instance, name) or .with(...) / .whereHas(...) with an undefined relation
InvalidModelConfigurationErrorInvalid table / columns / timestamps / softDeletes setup, unbound Model persistence, missing PK, or mutating .readonly() fields on persisted models

Next Steps ​

Released under the MIT License.