Skip to content

Introduction to WebDB ORM (@ahmadmoussawi/webdb/orm) ​

The WebDB ORM lets you work with your browser database using clean TypeScript classes instead of raw table rows and manual conversions. It is completely optional (adding 0 bytes unless you import @ahmadmoussawi/webdb/orm) and runs on top of the exact same WebDB database you already use.


Why Use the ORM? ​

If you are building a real application—tasks, notes, customer workspaces, offline forms, or dashboards—the ORM saves you time and prevents everyday mistakes.

Less Boilerplate, Full Autocomplete ​

Define a model's shape once and get instant TypeScript autocomplete and type checking across every query, filter, create, and update. Your editor immediately catches misspelled column names and mismatched value types before you ever run the app.

Natural JavaScript Values ​

Read and write real Date, boolean, JSON objects, and enums directly in your application code. You never have to convert 1/0, epoch timestamps, or JSON.stringify strings back and forth by hand.

Built-in Relationships ​

Link related models together through clear methods like user.posts(), post.author(), and user.roles(), then load nested data in a single clean call instead of writing manual lookup loops.

Effortless Updates ​

Edit properties directly on a fetched object—like user.name = "Maya"—and call await user.save(). WebDB automatically tracks what changed and writes only the updated columns back to the database.

Reactive UI Out of the Box ​

Subscribe to ORM queries with .live() so your components refresh whenever a model or any of its related tables change—even across open browser tabs.

Seamless Escape Hatches ​

Using the ORM never locks you out of lower-level APIs. Whenever you need raw SQL-style aggregations or custom queries, the underlying WebDB instance is always available on orm.db.


A Simple First Example ​

Here is what using the ORM feels like in practice:

typescript
import { WebDB, WasmEngine, IdbStorage } from "@ahmadmoussawi/webdb";
import { Model, col, createOrm, type HasMany, type BelongsTo } from "@ahmadmoussawi/webdb/orm";

// 1. Define your models
class User extends Model.define({
  table: "users",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    name: col.text().notNull(),
    active: col.boolean().default(true),
  },
}) {
  public posts(): HasMany<Post, "authorId"> {
    return this.hasMany(() => Post, { foreignKey: "authorId", localKey: "id" });
  }
}

class Post extends Model.define({
  table: "posts",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    authorId: col.ulid().notNull(),
    title: col.text().notNull(),
    published: col.boolean().default(false),
  },
}) {
  public author(): BelongsTo<User> {
    return this.belongsTo(() => User, { foreignKey: "authorId", ownerKey: "id" });
  }
}

// 2. Connect to WebDB and create tables
const db = await WebDB.open({
  name: "my_app",
  engine: new WasmEngine(),
  storage: new IdbStorage("my_app"),
});

const orm = createOrm(db, { users: User, posts: Post });
await orm.syncSchema();

// 3. Create & connect data
const alice = await orm.users.create({ name: "Alice" });
await alice.posts().create({ title: "Hello Browser DB!", published: true });

// 4. Query with related records already attached
const authors = await orm.users.query().where("active", "=", true).with({ posts: true }).get();
console.log(authors[0].name);                       // "Alice"
console.log(authors[0].relations.posts[0].title);   // "Hello Browser DB!"

// 5. Edit & save changes naturally
alice.name = "Alice M.";
await alice.save();

ORM vs. Core Query Builder ​

You can use WebDB's core Query Builder on its own, use the ORM everywhere, or mix both in the same app. The core Query Builder gives you lightweight, direct access to plain row objects and raw database primitives (1/0, epoch timestamps, and raw strings), making it ideal for reporting queries, bulk imports, or minimal bundles.

The ORM layers typed Model classes on top of those same tables. Instead of manually converting values, joining and grouping rows, or writing explicit update filters every time, you work with natural JavaScript types (boolean, Date, typed JSON, and enums), load connected records in one call via .with(...), and save changes by editing properties directly on an instance.

Side-by-Side: The Same Task Both Ways ​

typescript
// Fetch active users with their published posts
const authors = await orm.users
  .query()
  .where("active", "=", true)
  .with({ posts: { where: (q) => q.where("published", "=", true) } })
  .get();

// Update the first user
authors[0].name = "Alice M.";
await authors[0].save();
typescript
// Fetch active users, then query and attach their published posts
const activeUsers = await db.from("users").where("active", "=", 1).toArray();
const posts = await db
  .from("posts")
  .whereIn("authorId", activeUsers.map((u) => u.id))
  .where("published", "=", 1)
  .toArray();

// Update the first user
await db.from("users").where("id", "=", activeUsers[0].id).update({ name: "Alice M." });

Which One Should You Pick? ​

When to Start with the ORM ​

Choose the ORM when your app revolves around domain objects like User, Todo, Project, Invoice, or Message—especially when records have relationships, dates, booleans, JSON settings, or interactive edit forms.

When to Use the Core Query Builder ​

Reach for db.from(...) when building reporting tables, running GROUP BY and SUM analytics across large datasets, importing bulk data, or keeping bundle size as small as possible.

Mixing Both in One App ​

You never have to commit to only one style. Because orm.db exposes the underlying WebDB instance directly, you can use clean ORM models for everyday app logic and drop down to orm.db.from(...) for custom reporting or raw SQL queries in the same codebase.


Growing into Production (Migrations) ​

When starting out, await orm.syncSchema() creates all of your model tables and indexes automatically in one line.

Once your app is live and your models change between releases—adding new columns, renaming fields, or backfilling existing user data—your model definitions plug directly into WebDB's transactional migration system (@ahmadmoussawi/webdb/migrations). See Schema Sync & Migrations to learn how they work together.


Explore the Guides ​

Follow the guides in order, or jump to the feature you need:

GuideWhat You'll Learn
1. Models & ColumnsColumn types (Date, booleans, JSON, enums, UUID/ULID), modifiers, and custom classes
2. Creating, Updating & DeletingSaving records, upserts, dirty tracking, soft deletes, and automatic hooks
3. Querying, Scopes & PaginationFiltering, search helpers, sorting, .paginate(), aggregates, and reusable scopes
4. Relations & Eager LoadingOne-to-one, one-to-many, many-to-many pivot tables, .with(), and .whereHas()
5. Schema Sync & MigrationsQuick setup with syncSchema() and upgrading shipped schemas with Migrator
6. Transactions & Live QueriesAtomic multi-step writes, reactive .live() queries, and React / Vue / Angular usage

Released under the MIT License.