Skip to content

Schema Sync & Migrations ​

Your ORM Model classes describe the tables, columns, indexes, and pivot tables your app needs. Before querying or writing records, those tables must exist in WebDB.

WebDB supports two complementary ways to manage ORM schemas:

ApproachBest ForHow It Works
orm.syncSchema()Prototyping, unit tests, and initial v1 appsIdempotently creates any missing tables, indexes, and belongsToMany pivot tables from your registered models
@ahmadmoussawi/webdb/migrationsProduction local-first apps that evolve across releasesRuns versioned, ACID-transactional up() / down() migrations via Migrator or runMigrations(), using ORM schema helpers (toTableDefinition, toIndexDefinitions, toPivotTableDefinitions) plus ALTER TABLE

1. Quick Setup with orm.syncSchema() ​

Calling await orm.syncSchema() inspects every registered model and:

  1. Creates each model's table via db.createTableIfNotExists(...).
  2. Creates all secondary and unique B+Tree indexes via db.createIndexIfNotExists(...).
  3. Infers belongsToMany pivot tables (merging pivotColumns across both sides of the relation regardless of model registration order) and creates their tables and unique pair indexes.
typescript
const orm = createOrm(db, { users: User, posts: Post, roles: Role });

await orm.syncSchema();

// Optional flags if you manage indexes or pivot tables separately:
await orm.syncSchema({
  createIndexes: true,
  createPivotTables: true,
});

IMPORTANT

orm.syncSchema() is strictly additive at the table and index level (createTableIfNotExists / createIndexIfNotExists). If an existing user already has a users table from v1 and you add a new bio column in v2, syncSchema() will not modify the existing users table. Use versioned migrations below whenever your models change after release.


2. Versioned Migrations (@ahmadmoussawi/webdb/migrations) ​

For production apps, WebDB ships a dedicated, zero-overhead migration runner in @ahmadmoussawi/webdb/migrations (Migrator and runMigrations). Because every up(tx) and down(tx) callback receives an active ACID transaction tx: WebDB, schema changes (createTable, addColumn, renameColumn, dropColumn, createIndex) and data backfills commit—or roll back—together as one atomic unit.

The ORM exports three helpers that bridge your model definitions directly into WebDB migrations:

  • toTableDefinition(Model) → { table, columns } for tx.createTable(...) / tx.createTableIfNotExists(...)
  • toIndexDefinitions(Model) → Array<{ table, columns, options }> for tx.createIndex(...) / tx.createIndexIfNotExists(...)
  • toPivotTableDefinitions(models) → { tables, indexes } for all belongsToMany pivot tables across a models map

Example: Evolving an ORM App from v1 → v3 ​

typescript
import { WebDB, WasmEngine, IdbStorage } from "@ahmadmoussawi/webdb";
import { runMigrations, type Migration } from "@ahmadmoussawi/webdb/migrations";
import {
  Model,
  col,
  createOrm,
  toTableDefinition,
  toIndexDefinitions,
  toPivotTableDefinitions,
} from "@ahmadmoussawi/webdb/orm";
import { User, Post, Role } from "./models";

const models = { users: User, posts: Post, roles: Role };

export const MIGRATIONS: Migration[] = [
  // v1: Generate initial tables, indexes & pivot tables straight from ORM models
  {
    version: 1,
    name: "001_initial_orm_schema",
    async up(tx) {
      for (const ModelCtor of Object.values(models)) {
        const tableDef = toTableDefinition(ModelCtor);
        await tx.createTableIfNotExists(tableDef.table, tableDef.columns);

        for (const idx of toIndexDefinitions(ModelCtor)) {
          await tx.createIndexIfNotExists(idx.table, idx.columns, idx.options);
        }
      }

      const pivots = toPivotTableDefinitions(models);
      for (const pivotTable of pivots.tables) {
        await tx.createTableIfNotExists(pivotTable.table, pivotTable.columns);
      }
      for (const pivotIdx of pivots.indexes) {
        await tx.createIndexIfNotExists(
          pivotIdx.table,
          pivotIdx.columns,
          pivotIdx.options,
        );
      }
    },
    async down(tx) {
      await tx.dropTableIfExists("role_user");
      await tx.dropTableIfExists("posts");
      await tx.dropTableIfExists("roles");
      await tx.dropTableIfExists("users");
    },
  },

  // v2: Add a new column + index after adding `slug` to `Post`
  {
    version: 2,
    name: "002_add_post_slug",
    async up(tx) {
      await tx.addColumn("posts", { name: "slug", type: "TEXT" });
      await tx.createIndex("posts", ["slug"], {
        name: "idx_posts_slug",
        unique: true,
      });
    },
    async down(tx) {
      await tx.dropColumn("posts", "slug");
    },
  },

  // v3: Add a column and backfill existing rows atomically using the ORM inside `tx`
  {
    version: 3,
    name: "003_add_and_backfill_user_status",
    async up(tx) {
      await tx.addColumn(
        "users",
        { name: "status", type: "TEXT", notNull: true },
        "active", // default for existing rows
      );

      // You can bind a temporary ORM handle directly to the migration transaction `tx`
      const txOrm = createOrm(tx, models);
      const users = await txOrm.users.all();
      for (const user of users) {
        if (!user.isActive) {
          await user.update({ status: "inactive" });
        }
      }
    },
    async down(tx) {
      await tx.dropColumn("users", "status");
    },
  },
];

TIP

Be careful if v1 imports your latest User class after you add columns in v2/v3: toTableDefinition(User) reflects the columns currently declared on User. Either freeze a v1 snapshot definition for 001_initial (or guard later ALTER TABLE steps with tx.addColumnIfNotExists(...)), so a fresh install and an incremental upgrade converge on the exact same schema.


Run migrations before creating and using your application's orm handle:

typescript
import { WebDB, WasmEngine, IdbStorage } from "@ahmadmoussawi/webdb";
import { Migrator } from "@ahmadmoussawi/webdb/migrations";
import { createOrm } from "@ahmadmoussawi/webdb/orm";
import { MIGRATIONS } from "./migrations";
import { User, Post, Role } from "./models";

export async function initDatabase() {
  const db = await WebDB.open({
    name: "app_db",
    engine: new WasmEngine(),
    storage: new IdbStorage("app_db"),
  });

  // 1. Apply pending migrations atomically (multi-tab safe via Web Locks)
  const migrator = new Migrator(db, {
    migrations: MIGRATIONS,
    mode: "atomic",
  });
  await migrator.up();

  // 2. Bind the ORM now that all tables & columns are at the latest version
  const orm = createOrm(db, { users: User, posts: Post, roles: Role });
  return { db, orm, migrator };
}

Multi-Tab Safety During Startup ​

In browser apps where multiple tabs might open at once:

  • Migrator runs inside a WebDB write transaction protected by navigator.locks, so only one tab runs pending migrations at a time.
  • When Tab A finishes migrating, WebDB increments the schema epoch and notifies other open tabs via BroadcastChannel so Tab B refreshes its catalog before running queries.

  • Database Migrations — full guide to Migrator, runMigrations, status inspection, rollbacks (down, reset), and idempotent DDL helpers.
  • Schema Evolution (ALTER TABLE) — detailed reference for addColumn, addColumnIfNotExists, renameColumn, and dropColumn.

Released under the MIT License.