initialize method

Future<void> initialize()

Open (or create) the local database and load the vector extension.

Implementation

Future<void> initialize() async {
  if (_db != null) return;

  // Load the sqlite-vec extension globally.
  sqlite3.loadSqliteVectorExtension();

  final appDir = await getApplicationSupportDirectory();
  final dbPath = '${appDir.path}/$_dbName';

  _db = sqlite3.open(dbPath);

  // Create tables if they don't exist.
  _db!.execute('''
    CREATE TABLE IF NOT EXISTS local_chunks (
      id TEXT PRIMARY KEY,
      topic_id TEXT NOT NULL,
      book_id TEXT NOT NULL,
      chunk_index INTEGER NOT NULL,
      content TEXT NOT NULL,
      page_number INTEGER,
      token_count INTEGER,
      metadata TEXT DEFAULT '{}',
      embedding TEXT
    )
  ''');

  _db!.execute('''
    CREATE INDEX IF NOT EXISTS idx_local_chunks_topic
      ON local_chunks(topic_id)
  ''');

  _db!.execute('''
    CREATE INDEX IF NOT EXISTS idx_local_chunks_topic_index
      ON local_chunks(topic_id, chunk_index)
  ''');

  dev.log(
    'Local vector store initialized at $dbPath',
    name: 'LocalVectorStore',
  );
}