Skip to content

Models & Columns ​

Models define the shape of your tables, how database primitives map to TypeScript values, which constraints and indexes exist, and what relationships connect your tables.

You can define models in three ways depending on how much structure you need:

  • Model.define({ ... }) (recommended) — define columns once and automatically infer typed fields, readonly modifiers, and nullability onto a class where you add relations, scopes, and getters.
  • defineModel({ ... }) — standalone one-liner for lookup tables or simple models that don't need custom methods or relations.
  • class MyModel extends Model — explicit class syntax with static readonly metadata and declare fields.

1. Defining Models (Model.define() & defineModel()) ​

Extending Model.define({ ... }) gives you a single source of truth for columns while keeping relations, scopes, getters, and methods inside the class body:

typescript
import {
  Model,
  defineModel,
  col,
  type HasOne,
  type HasMany,
  type BelongsTo,
  type BelongsToMany,
  type ModelQueryBuilder,
} from "@ahmadmoussawi/webdb/orm";

export class User extends Model.define({
  table: "users",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    name: col.text().notNull(),
    email: col.text().notNull().unique(),
    passwordHash: col.text().column("password_hash").notNull().hidden(),
    isActive: col.boolean().column("is_active").default(true),
    role: col.enum(["admin", "member"] as const).default("member"),
    meta: col.json<{ bio?: string; tags?: string[] }>().nullable(),
    createdAt: col.timestamp().column("created_at"),
    updatedAt: col.timestamp().column("updated_at"),
    deletedAt: col.timestamp().column("deleted_at").nullable(),
  },
  // Secondary & unique composite indexes (column names checked at compile time)
  indexes: [
    { columns: ["role", "isActive"], name: "idx_users_role_active" },
  ],
  // Auto-managed timestamp keys (checked against `columns`)
  timestamps: {
    createdAt: "createdAt",
    updatedAt: "updatedAt",
  },
  // Soft-delete timestamp key (checked against `columns`)
  softDeletes: "deletedAt",
  // Lifecycle hooks (`user` is already fully typed from `columns`)
  hooks: {
    beforeCreate: (user) => {
      user.email = user.email.toLowerCase();
    },
  },
}) {
  // All columns (`id`, `name`, `email`, `meta`, etc.)
  // are automatically typed on `this` — no `declare` lines needed.

  // Optional reusable query scopes
  static readonly scopes: {
    active: (q: ModelQueryBuilder<typeof User>) => void;
    byRole: (q: ModelQueryBuilder<typeof User>, role: "admin" | "member") => void;
  } = {
    active: (q) => q.where("isActive", "=", true),
    byRole: (q, role) => q.where("role", "=", role),
  };

  // Explicit relation methods
  public profile(): HasOne<Profile, "userId"> {
    return this.hasOne(() => Profile, { foreignKey: "userId", localKey: "id" });
  }

  public posts(): HasMany<Post, "authorId"> {
    return this.hasMany(() => Post, { foreignKey: "authorId", localKey: "id" });
  }

  public roles(): BelongsToMany<Role, { assignedAt: Date }> {
    return this.belongsToMany(() => Role, {
      pivotTable: "role_user",
      foreignPivotKey: "user_id",
      relatedPivotKey: "role_id",
      pivotColumns: {
        assignedAt: col.timestamp().column("assigned_at").default(() => new Date()),
      },
    });
  }

  // Computed getters & instance helper methods work naturally
  public get displayName(): string {
    return `${this.name} <${this.email}>`;
  }
}

// For simple entities with no custom methods or relations,
// `defineModel(...)` works standalone without subclassing:
export const Tag = defineModel({
  table: "tags",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    slug: col.text().notNull().unique(),
  },
});

Explicit Class Syntax (extends Model + declare) ​

If you prefer writing all static metadata and property types explicitly in the class body, extending Model directly is 100% equivalent:

typescript
export class Profile extends Model {
  static readonly table = "profiles";
  static readonly columns = {
    id: col.ulid().primaryKey().autoUlid(),
    userId: col.ulid().column("user_id").notNull().unique(),
    bio: col.text().notNull(),
  };

  declare id: string;
  declare userId: string;
  declare bio: string;

  public user(): BelongsTo<User> {
    return this.belongsTo(() => User, { foreignKey: "userId", ownerKey: "id" });
  }
}

IMPORTANT

When extending Model directly, always use declare for column fields (declare bio: string;), never definite assignment (public bio!: string;). With target: ESNext / useDefineForClassFields: true, uninitialized class fields emit this.bio = undefined after super(), overwriting hydrated values when a model is constructed.

When you register an explicit Model subclass with createOrm(db, { profiles: Profile }), TypeScript verifies that every key and type in static readonly columns matches the instance fields declared on the class (including | null for .nullable() columns).


2. Column Builders (col.*) ​

All 7 native WebDB storage types and higher-level application codecs are built via col:

BuilderStorage TypeTypeScript TypeNotes
col.int32()INT32numberSupports .primaryKey().autoInc() (rejects non-32-bit ints/NaN)
col.int64()INT64bigintSupports .primaryKey().autoInc() (64-bit signed bigint)
col.float64()FLOAT64number64-bit IEEE float (rejects NaN)
col.text()TEXTstringUTF-8 string
col.blob()BLOBUint8ArrayRaw binary bytes
col.uuid()UUIDstring16-byte packed binary UUID; .autoUuid() generates v4 UUID
col.ulid()ULIDstring16-byte packed binary ULID; .autoUlid() generates monotonic ULID
col.boolean()INT32booleanStored as 1 / 0
col.timestamp() / col.date()INT64 (or TEXT)DateEpoch ms (INT64) by default, or ISO-8601 (TEXT) via .asIsoString()
col.json<T>()TEXTTAutomatic JSON.stringify / JSON.parse with deep dirty tracking
col.enum(values)TEXT / INT32 / FLOAT64Union literalValidates allowed values on both read and write
col.custom(dbType, codec)Any DataTypeCustom TModelCustom toDb(value) / fromDb(raw) bidirectional codec

TIP

Why ULIDs for Primary Keys? For offline-first apps that sync with a remote server, col.ulid().primaryKey().autoUlid() generates collision-free, lexicographically time-sortable 26-character IDs directly in the browser without waiting for a server round-trip, while storing them as 16 compact binary bytes.

Timestamps: Epoch INT64 vs ISO-8601 TEXT ​

By default, col.timestamp() and col.date() store Date values as compact 64-bit epoch milliseconds (INT64). Chain .asIsoString() to store canonical ISO-8601 strings in a TEXT column while still reading/writing Date objects in TypeScript:

typescript
export class Article extends Model.define({
  table: "articles",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    publishedAt: col.timestamp().column("published_at").nullable(),
    scheduledIso: col.timestamp().column("scheduled_iso").asIsoString().nullable(),
  },
}) {}

Both formats support chronological comparisons (>, <=, orderBy, latest(), oldest(), min(), max()) in queries.

Custom Binary/Text Codecs (col.custom) ​

Use col.custom(dbType, codec) to map any domain type onto any WebDB storage column type:

typescript
import { DataType } from "@ahmadmoussawi/webdb";
import { Model, col } from "@ahmadmoussawi/webdb/orm";

export class Invoice extends Model.define({
  table: "invoices",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    amount: col
      .custom<{ cents: number; currency: "USD" | "EUR" }, string>(DataType.TEXT, {
        toDb: (v) => `${v.currency}:${v.cents}`,
        fromDb: (raw) => {
          const [currency, cents] = raw.split(":");
          return { currency: currency as "USD" | "EUR", cents: Number(cents) };
        },
      })
      .notNull(),
  },
}) {}

Standalone ULID Helper (generateUlid) ​

If you want to pre-generate sortable ULIDs outside of .autoUlid(), import generateUlid:

typescript
import { generateUlid } from "@ahmadmoussawi/webdb/orm";

const id = generateUlid(); // 26-char Crockford Base32 string, monotonic within the same ms

3. Column Modifiers ​

ModifierEffect
.primaryKey()Marks the column as primary key (implies .notNull(); multiple columns form a composite PK).
.autoInc()Marks an int32() or int64() key as auto-incremented (optional on create()).
.autoUuid() / .autoUlid()Generates a UUID v4 or monotonic ULID automatically on create() / make() / upsert() when omitted.
.notNull()Enforces NOT NULL at both the schema and TypeScript levels.
.nullable()Types the attribute as T | null and makes it optional on create() (defaults to null).
.default(valueOrFn)Supplies a static value or factory function () => T when omitted on create() / make().
.unique()Emits a unique B+Tree index for this column when syncing tables or extracting index definitions.
.indexed()Emits a non-unique B+Tree index for this column when syncing tables or extracting index definitions.
.column("db_name")Maps a camelCase TS property name to a different DB column name (e.g. "password_hash").
.hidden()Excludes the property from instance.toObject() and JSON.stringify(instance) (toJSON()).
.readonly()Excludes the field from query().update(), instance.update(), and upsert({ mode: "merge" }), makes it readonly on Model.define() instances, and rejects post-persist fill().

4. Composite Keys & Indexes ​

Composite Primary Keys ​

Mark multiple columns with .primaryKey() when modeling join entities or multi-tenant keys:

typescript
export class Membership extends Model.define({
  table: "memberships",
  columns: {
    tenantId: col.ulid().column("tenant_id").primaryKey(),
    userId: col.ulid().column("user_id").primaryKey(),
    role: col.enum(["owner", "editor", "viewer"] as const).default("viewer"),
  },
}) {}

// Lookups take an object matching all composite PK fields:
const membership = await orm.memberships.find({ tenantId, userId });
const many = await orm.memberships.findMany([
  { tenantId, userId: alice.id },
  { tenantId, userId: bob.id },
]);
await orm.memberships.deleteById({ tenantId, userId });

Composite Indexes (indexes) ​

Declare single or multi-column indexes referencing TypeScript property names—.column("db_name") mapping is handled automatically:

typescript
export class Post extends Model.define({
  table: "posts",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    authorId: col.ulid().column("author_id").notNull(),
    slug: col.text().notNull(),
    published: col.boolean().default(false),
  },
  indexes: [
    { columns: ["authorId", "published"] },
    { columns: ["authorId", "slug"], unique: true, name: "idx_posts_author_slug" },
  ],
}) {}

TIP

If an index in indexes matches the same column list as a column's .unique() modifier, WebDB upgrades it cleanly to unique without emitting duplicate index definitions, and auto-generated index names are capped at 64 characters.


5. Type Inference Helpers ​

The ORM exports utility types so DTOs, API payloads, and UI forms stay derived from your model classes:

typescript
import type {
  InferAttributes,
  InferInsert,
  InferUpdate,
  InferSerialized,
  PrimaryKeyValue,
} from "@ahmadmoussawi/webdb/orm";

type UserCols = typeof User.columns;

type UserRow = InferAttributes<UserCols>;       // All attributes
type NewUserInput = InferInsert<UserCols>;      // Auto-inc/default/nullable optional
type PatchUserInput = InferUpdate<UserCols>;    // All updatable (non-readonly) optional
type PublicUserDto = InferSerialized<UserCols>; // Omits .hidden() fields (e.g. passwordHash)
type UserPk = PrimaryKeyValue<UserCols>;        // string (or { ... } for composite PKs)

Next Steps ​

Released under the MIT License.