tekartik / sqflite

SQLite flutter plugin
BSD 2-Clause "Simplified" License
2.86k stars 524 forks source link

Data does not update when I switch between databases #1117

Open haidang750 opened 2 months ago

haidang750 commented 2 months ago

I use floor package to auto generate sqflite database in my project. I tried to close the current database and used $FloorAppDatabase.databaseBuilder(dbPath).build() to switch to the new one but it kept the old data of the previous database.

Here is my code:

   @Database(version: 1, entities: [
     Customer,
     Product,
   ])
   abstract class AppDatabase extends FloorDatabase {
     AppDatabase();

     CustomerDao get customerDao;

     ProductDao get productDao;

     Future<void> deleteAllTables() async {
       await database.execute('DELETE FROM Customer');
       await database.execute('DELETE FROM Product');
     }
   }

   class DatabaseService {
     AppDatabase? _currentDatabase;
     CustomerDao? _customerDao;
     ProductDao? _productDao;

     Future<AppDatabase> _initDatabase(String dbPath) async {
       final database = await $FloorAppDatabase.databaseBuilder(dbPath).build();
       return database;
     }

     Future<void> switchDatabase(int? userId) async {
       // Close the current database if it exists
       await _closeCurrentDatabase();

       // Initialize the new database
       _currentDatabase =
           await _initDatabase('${userId?.toString() ?? AppConstants.APP_DATABASE_NAME}.db');
       _customerDao = _currentDatabase?.customerDao;
       _productDao = _currentDatabase?.productDao;
     }

     CustomerDao get customerDao => _customerDao!;
     ProductDao get productDao => _productDao!;

     Future<void> _closeCurrentDatabase() async {
       await _currentDatabase?.close();
       _currentDatabase = null;
     }
  }
alextekartik commented 2 months ago

I'm not familiar with floor so I cannot say whether it is correct or not. Have you reported this issue in floor (https://github.com/pinchbv/floor) first?