@@ -43,6 +43,8 @@ class DatabaseConnection {
4343class ConnectionPool {
4444 static final Map <String , DatabaseConnection > _connections = {};
4545 static int _currentGeneration = 1 ;
46+ // Persist the last used database name across hot restarts
47+ static String ? _lastUsedDatabaseName;
4648
4749 static DatabaseConnection ? getConnection (String dbName) {
4850 final connection = _connections[dbName];
@@ -55,6 +57,7 @@ class ConnectionPool {
5557
5658 static void storeConnection (String dbName, DatabaseConnection connection) {
5759 _connections[dbName] = connection;
60+ _lastUsedDatabaseName = dbName; // Remember the last used database name
5861 }
5962
6063 static void invalidateConnection (String dbName) {
@@ -78,6 +81,9 @@ class ConnectionPool {
7881 static void incrementGeneration () => _currentGeneration++ ;
7982
8083 static int get connectionCount => _connections.length;
84+
85+ // Getter for last used database name (survives hot restart)
86+ static String ? get lastUsedDatabaseName => _lastUsedDatabaseName;
8187}
8288
8389/// Typedef for the rust functions
@@ -93,9 +99,6 @@ typedef PointerListFFICallBack = Pointer<Utf8> Function(Pointer<AppDbState>);
9399/// Native database implementation using FFI and Rust backend
94100/// This implementation is used for mobile and desktop platforms
95101class DatabaseNative implements DatabaseInterface {
96- DatabaseNative ._();
97-
98- static final DatabaseNative instance = DatabaseNative ._();
99102
100103 Result <DynamicLibrary , String >? _lib;
101104 Pointer <AppDbState >? _dbInstance;
@@ -411,13 +414,25 @@ class DatabaseNative implements DatabaseInterface {
411414 }
412415 }
413416
414- if (_dbInstance == null || _dbInstance == nullptr) {
415- Log .w (
416- 'Database connection invalid (null pointer), attempting to reinitialize...' ,
417- );
417+ // Check if we have a database name stored (indicates previous initialization)
418+ final dbNameToRestore = _lastDatabaseName ?? ConnectionPool .lastUsedDatabaseName;
419+ if (dbNameToRestore != null && (_dbInstance == null || _dbInstance == nullptr)) {
420+ Log .i ('🔄 Hot restart detected - attempting to reconnect to existing database: $dbNameToRestore ' );
421+
422+ // Restore the database name for the instance
423+ if (_lastDatabaseName == null ) {
424+ _lastDatabaseName = dbNameToRestore;
425+ Log .i ('🔄 Restored database name from connection pool: $dbNameToRestore ' );
426+ }
427+
418428 return await _attemptReinitialization ();
419429 }
420430
431+ if (_dbInstance == null || _dbInstance == nullptr) {
432+ Log .w ('Database connection invalid (null pointer), no previous database name stored' );
433+ return false ;
434+ }
435+
421436 // Check connection pool first
422437 if (_lastDatabaseName != null ) {
423438 final poolConnection = ConnectionPool .getConnection (_lastDatabaseName! );
0 commit comments