changeDB method

Future<void> changeDB(
  1. String? newDBName
)

Switches the application database to newDBName.

  • If newDBName already exists it is opened and becomes the current application database until the next call to changeDB.
  • Otherwise it is created, opened and becomes the current database.

The name (with the .db suffix appended if missing) is persisted to disk so that subsequent calls to db return the same database.

Implementation

Future<void> changeDB(String? newDBName) async {
  if (newDBName == null || newDBName.isEmpty) {
    debugPrint('changeDB called with a null or empty name.');
    return;
  }

  final String correctedName =
      newDBName.endsWith('.db') ? newDBName : '$newDBName.db';

  final String directory = await DiscData.instance.databasesPath;
  final String dbFilePath = '$directory${DiscData.instance.pathJoin}dbName';

  final String? saved = await DiscData.instance
      .saveDataToDisc(correctedName, DataType.text, path: dbFilePath);
  if (saved == null) return;

  if (_db != null) {
    await _db!.close();
    _db = null;
  }
  _db = await _factory.openDatabase(correctedName);
  debugPrint('Database successfully changed to $correctedName');
}