idb-ts
    Preparing search index...

    Class Database

    Central access point for an IndexedDB database managed by idb-ts.

    A Database instance owns the IDB connection, maintains entity repositories, and runs retention-cleanup background jobs. Always obtain instances through the async factory Database.build - the constructor is private.

    Schema versioning. The declared database version is the highest version value across all registered @DataClass entities. On every onupgradeneeded event the full declared schema is reconciled against the actual one: missing stores and indexes are created and indexes that are no longer declared are removed. If the schema changed without a version bump, the drift is detected after opening and a follow-up upgrade is triggered automatically. If the declared version is lower than the version stored on disk (an entity's version was decreased), the database opens at the existing on-disk version instead of failing with a VersionError - IndexedDB cannot downgrade. Changes that would require destructive action (key-path changes, stores whose entity is no longer registered) are never applied automatically; they are reported through the error log instead.

    Retention cleanup. When entities declare @RetentionPolicy, a periodic setInterval job is started after the database opens. The interval is the GCD of all configured retention periods (in milliseconds), ensuring every policy is evaluated at the right frequency with a single timer.

    Repository access. After build resolves, each registered entity is accessible as a named property on the returned object:

    const db = await Database.build<{ User: EntityRepository<User> }>('mydb', [User]);
    await db.User.create(new User('u1', 'Alice'));
    const db = await Database.build<{
    User: EntityRepository<User>;
    Order: EntityRepository<Order>;
    }>('shop', [User, Order]);

    await db.User.create(new User('u1', 'Alice', 30));
    const alice = await db.User.read('u1');
    db.close();
    Index

    Methods

    • Opens a multi-store IDB transaction and returns a TransactionalDatabase with per-entity repositories that share the underlying IDBTransaction.

      Use the returned handle's commit() and rollback() methods to finalise or discard the transaction. For automatic commit/rollback, prefer the callback-based Database.transaction method.

      Parameters

      • entityNames: string[]

        Names of the entity classes whose stores will be enrolled in the transaction.

      • mode: IDBTransactionMode = 'readwrite'

        IDB transaction mode ('readonly' or 'readwrite'). Defaults to 'readwrite'.

      Returns Promise<TransactionalDatabase<Record<string, EntityRepository<any>>>>

      A promise resolving to a TransactionalDatabase handle.

      Error if any name in entityNames is not registered.

      const tx = await db.beginTransaction(['User', 'Order']);
      try {
      await tx.User.create(user);
      await tx.Order.create(order);
      await tx.commit();
      } catch (e) {
      await tx.rollback();
      }
    • Closes the underlying IDB connection and stops the retention cleanup timer. The instance must not be used after calling this method.

      Returns void

      db.close();
      
    • Exports every registered entity store as a plain, JSON-serialisable object keyed by entity class name.

      Records are exported verbatim, including the internal __idb_createdAt / __idb_updatedAt timestamp fields, so a subsequent Database.importDatabase restores them exactly.

      Returns Promise<Record<string, unknown[]>>

      A promise resolving to { EntityName: records[] }.

      const dump = await db.exportDatabase();
      localStorage.setItem('backup', JSON.stringify(dump));
    • Returns the names of all entity classes registered with this database.

      Returns string[]

      An array of entity class name strings.

    • Returns the actual version of the open IDB database.

      This is usually the highest version annotation across all registered entities, but can be higher when the on-disk database was created at a greater version (downgrades are ignored) or when a schema change without a version bump triggered an automatic reconciliation upgrade.

      Returns number

      The database version number.

    • Returns the schema version of a single registered entity.

      Parameters

      • entityName: string

        The class name of the entity to look up.

      Returns number | undefined

      The entity's version number, or undefined if not registered.

    • Returns a Map of each registered entity name to its configured schema version.

      Returns Map<string, number>

      A Map<string, number> where keys are entity class names and values are version numbers.

    • Imports a dump produced by Database.exportDatabase.

      Records are written verbatim with put semantics: records whose primary key already exists are overwritten, all others are inserted. Existing records not present in the dump are kept unless options.clear is set. Validation, key generation, and timestamp injection are intentionally bypassed so the imported data matches the exported data exactly.

      Dump entries whose entity name is not registered in this database are skipped (a debug message is logged).

      Parameters

      • dump: Record<string, unknown[]>

        { EntityName: records[] } as returned by exportDatabase.

      • options: { clear?: boolean } = {}

        Set clear: true to empty each store before importing.

      Returns Promise<void>

      await db.importDatabase(JSON.parse(backupJson));
      await db.importDatabase(dump, { clear: true }); // replace instead of merge
    • Pulls records from the given SyncAdapter and upserts them into the local stores by primary key.

      For each registered entity, adapter.pull(entityName) is called once. Returned records are written verbatim with put semantics (existing keys are overwritten, other local records are kept). When the adapter returns undefined for an entity, its local store is left untouched.

      Conflict resolution is intentionally delegated to the adapter/backend - locally, pulled records win by primary key.

      Parameters

      • adapter: SyncAdapter

        The sync adapter supplying the records.

      Returns Promise<void>

      await db.pullFrom(new RestAdapter());
      
    • Pushes the full contents of every registered entity store to the given SyncAdapter, one adapter.push(entityName, records) call per entity.

      Parameters

      • adapter: SyncAdapter

        The sync adapter receiving the records.

      Returns Promise<void>

      await db.pushTo(new RestAdapter());
      
    • Executes callback within a single readwrite IDB transaction that spans all registered entities. Commits automatically on success; rolls back and rethrows on any error.

      Type Parameters

      • T

        The type of the value returned by callback.

      Parameters

      • callback: (
            tx: TransactionalDatabase<Record<string, EntityRepository<any>>>,
        ) => T | Promise<T>

        An async or synchronous function receiving the TransactionalDatabase handle. The callback's return value is forwarded to the caller.

      Returns Promise<T>

      A promise resolving to the value returned by callback.

      Re-throws any error thrown by callback after rolling back.

      await db.transaction(async (tx) => {
      await tx.User.create(user);
      await tx.Order.create(order);
      await tx.OrderItem.create(item);
      });
    • Creates and initialises a new Database instance, opening the underlying IndexedDB database and generating entity repositories.

      This is the only public way to obtain a Database instance.

      Type Parameters

      • T extends Record<string, EntityRepository<any>>

        A Record mapping entity names to their EntityRepository types, used to type the returned object's named repository properties.

      Parameters

      • dbName: string

        The name passed to indexedDB.open.

      • classes: Function[]

        The @DataClass-decorated entity constructors to register.

      Returns Promise<DatabaseWithRepositories<T>>

      A promise resolving to a fully initialised DatabaseWithRepositories instance.

      Error - If any class is not decorated with @DataClass.

      IDBRequest error - If the underlying indexedDB.open call fails.

      const db = await Database.build<{
      User: EntityRepository<User>;
      Order: EntityRepository<Order>;
      }>('shop', [User, Order]);