clearAllData method

Future<void> clearAllData()

Clear all data (database and index files) and reset the engine.

This is a destructive operation that:

  1. Closes the database connection
  2. Deletes the SQLite database file
  3. Deletes the HNSW index file
  4. Re-initializes the database and service

Implementation

Future<void> clearAllData() async {
  debugPrint('[RagEngine] clearAllData: Starting...');
  // 1. Close DB pool
  debugPrint('[RagEngine] clearAllData: Closing DB pool...');
  await closeDbPool();
  debugPrint('[RagEngine] clearAllData: DB pool closed.');

  // 2. Delete DB file
  final dbFile = File(dbPath);
  if (await dbFile.exists()) {
    debugPrint('[RagEngine] clearAllData: Deleting DB file at $dbPath...');
    await dbFile.delete();
    debugPrint('[RagEngine] clearAllData: DB file deleted.');
  } else {
    debugPrint('[RagEngine] clearAllData: DB file not found.');
  }

  // 3. Delete index artifacts (new and legacy naming patterns)
  final baseNoExt = _stripDbExtension(dbPath);
  final indexStems = <String>{baseNoExt, '${baseNoExt}_hnsw'};
  final indexCandidates = <String>{
    for (final stem in indexStems) stem,
    for (final stem in indexStems) '$stem.pbin',
    for (final stem in indexStems) '$stem.hnsw.data',
    for (final stem in indexStems) '$stem.hnsw.graph',
  };

  for (final path in indexCandidates) {
    final file = File(path);
    if (await file.exists()) {
      debugPrint('[RagEngine] clearAllData: Deleting index artifact: $path');
      await file.delete();
    }
  }

  // 4. Re-initialize DB pool
  debugPrint('[RagEngine] clearAllData: Re-initializing DB pool...');
  await initDbPool(dbPath: dbPath, maxSize: 4);
  debugPrint('[RagEngine] clearAllData: DB pool initialized.');

  // 5. Re-initialize service
  debugPrint('[RagEngine] clearAllData: Re-initializing service...');
  await _ragService.init(deferIndexWarmup: _deferIndexWarmup);
  debugPrint('[RagEngine] clearAllData: Service initialized. Done.');
}