open static method

Future<Database> open(
  1. String dirPath, {
  2. VfsAdapter? vfsAdapter,
})

Implementation

static Future<Database> open(String dirPath, {VfsAdapter? vfsAdapter}) async {
  // Use the provided adapter, or auto-detect based on platform
  final vfs = vfsAdapter ?? createVfsAdapter();

  final db = Database._(dirPath, vfs);
  await vfs.ensureDir(dirPath);

  // ── Step 1: Open storage layers ─────────────────────────────────────
  db.pager = await Pager.open('$dirPath/data.ndb', vfs: vfs);
  db.cache = PageCache(db.pager, capacity: 256);
  db.wal   = await Wal.open('$dirPath/wal.log', vfs: vfs);
  db.pager.setWalFlushedLsn(db.wal.flushedLsn);

  // ── Step 2: Init transaction manager V2 ─────────────────────────────
  db.txnManager = TransactionManagerV2(
    lockManager: LockManagerV2(),
    dataDir:     dirPath,
    vfs:         vfs,
  );

  // ── Step 3: Load catalog ─────────────────────────────────────────────
  await db._loadCatalog();

  // ── Step 4: WAL recovery ──────────────────────────────────────────────
  final walMaxTxnId = await db._recover();

  // ── Step 5: Restore txn state ────────────────────────────────────────
  await db.txnManager.restoreFromPersistence(walMaxTxnId: walMaxTxnId);

  // ── Step 6: Recalculate row IDs ──────────────────────────────────────
  for (final t in db.tables.values) {
    await t.recalcNextRowId();
  }

  // ── Step 7: Populate in-memory MVCC stores ───────────────────────────
  await db._populateMvccStores();

  // ── Step 8: Load persisted statistics ───────────────────────────────
  final statsPath = '$dirPath/stats.json';
  final loadedRegistry = await StatsPersistence.load(statsPath, vfs: vfs);
  for (final ts in loadedRegistry.allStats.values) {
    db.statsRegistry.update(ts);
  }

  // ── Step 9: Wire up incremental checkpoint manager ───────────────────
  db._checkpointMgr = CheckpointManager(
    cache:           db.cache,
    pager:           db.pager,
    wal:             db.wal,
    dataDir:         dirPath,
    getTables:       () => db.pageTables,
    persistTxnState: (lsn) => db.txnManager.persistStateAt(lsn),
    persistStats:    ()    => StatsPersistence.save(
                                db.statsRegistry, '$dirPath/stats.json',
                                vfs: vfs),
    persistCatalog:  ()    => db._saveCatalog(),
    persistIndexes:  (pts) => db._persistAllIndexes(),
  );

  print('[NebulaDB] Database opened at $dirPath  '
        '(tables=${db.tables.length}, web=${vfs.isWeb})');
  return db;
}