openDb method

  1. @override
Future<Database> openDb()
override

When the software/app is started, sqfentity checks the database was it initialized. If needed, initilizeDb method runs that CREATE TABLE / ALTER TABLE ADD COLUMN queries for you.

Implementation

@override
Future<Database> openDb() async {
  final lock = Lock();
  Database? _db;
  await lock.synchronized(() async {
    final databaseFactory = databaseFactoryFfi;
    sqfliteFfiInit();
    final path = join(
        getFinalDatabasePath(await databaseFactory.getDatabasesPath()),
        connection!.databaseName);
    final file = File(path);

    // check if file exists
    if (!file.existsSync()) {
      // Copy from asset if MyDbModel.bundledDatabasePath is not empty
      if (connection!.bundledDatabasePath != null &&
          connection!.bundledDatabasePath != '' &&
          connection!.bundledDatabasePath != 'null') {
        final ByteData data =
            await rootBundle.load(connection!.bundledDatabasePath!);
        await writeDatabase(data);
      }
    }

    // uncomment line below if you want to use sqlchiper
    // _db = await openDatabase(path, version: 1, onCreate: _createDb, password: _dbModel.password); // SQLChipher

    // uncomment line below if you want to use sqflite
    // _db = await openDatabase(path, version: 1, onCreate: _createDb); // SQFLite
    //} else {

    _db = await databaseFactory.openDatabase(path,
        options: OpenDatabaseOptions(
          version: connection!.dbVersion,
          onCreate: createDb,
          onConfigure: (db) async {
            if (connection!.password != null) {
              //https://github.com/davidmartos96/sqflite_sqlcipher/issues/28
              await db.rawQuery("PRAGMA KEY='${connection!.password!}'");
            }
          },
        ));
    //  }
  });
  //}
  return _db!;
}