clearAllData method
Clear all data (database and index files) and reset the engine.
This is a destructive operation that:
- Closes the database connection
- Deletes the SQLite database file
- Deletes the HNSW index file
- Re-initializes the database and service
Implementation
Future<void> clearAllData() async {
debugPrint('[RagEngine] clearAllData: Starting...');
// A deferred warmup may still be reading from SQLite. Let it leave the
// shared database before closing the pool and deleting its files.
try {
await _ragService.warmupFuture;
} catch (error) {
debugPrint(
'[RagEngine] clearAllData: Previous warmup failed; continuing reset: $error',
);
}
// 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...');
RagEmbeddingFingerprintLock? resetLock;
await _ragService.initForEngine(
// A destructive reset is complete only when the replacement indexes are
// ready. Returning with another background warmup would let an immediate
// ingest race the same database that clearAllData just recreated.
deferIndexWarmup: false,
afterDatabaseInitialized: () async {
resetLock = await _resolveFingerprintGate(currentEmbeddingFingerprint);
},
);
_fingerprintLock = resetLock;
_collectionServices
..clear()
..[SourceRagService.defaultCollectionId] = _ragService;
_initializedCollections
..clear()
..add(SourceRagService.defaultCollectionId);
_collectionInitInFlight.clear();
debugPrint('[RagEngine] clearAllData: Service initialized. Done.');
}