handleOpenDatabase method

Future handleOpenDatabase()

Handle open database.

Implementation

Future handleOpenDatabase() async {
  var path = argumentsMap['path'] as String;

  //devPrint('opening $path');
  var singleInstance = (argumentsMap['singleInstance'] as bool?) ?? false;
  var readOnly = (argumentsMap['readOnly'] as bool?) ?? false;
  if (singleInstance) {
    var database = ffiSingleInstanceDbs[path];
    if (database != null) {
      if (logLevel >= sqfliteLogLevelVerbose) {
        database.logResult(
            result: 'Reopening existing single database $database');
      }
      return database;
    }
  }
  ffi.Database? ffiDb;
  try {
    if (path == inMemoryDatabasePath) {
      ffiDb = ffi.sqlite3.openInMemory();
      initializeSupportFunctions(ffiDb);
    } else {
      if (readOnly) {
        // ignore: avoid_slow_async_io
        if (!(await File(path).exists())) {
          throw StateError('file $path not found');
        }
      } else {
        // ignore: avoid_slow_async_io
        if (!(await File(path).exists())) {
          // Make sure its parent exists
          try {
            await Directory(dirname(path)).create(recursive: true);
          } catch (_) {}
        }
      }
      final mode =
          readOnly ? ffi.OpenMode.readOnly : ffi.OpenMode.readWriteCreate;
      ffiDb = ffi.sqlite3.open(path, mode: mode);
      initializeSupportFunctions(ffiDb);

      // Handle hot-restart for single instance
      // The dart code is killed but the native code remains
      if (singleInstance) {
        tracker.markOpened(ffiDb);
      }
    }
  } on ffi.SqliteException catch (e) {
    throw wrapSqlException(e, code: 'open_failed');
  }

  var id = ++_lastFfiId;
  var database = SqfliteFfiDatabase(id, ffiDb,
      singleInstance: singleInstance,
      path: path,
      readOnly: readOnly,
      logLevel: logLevel);
  database.logResult(result: 'Opening database $database');
  if (singleInstance) {
    ffiSingleInstanceDbs[path] = database;
  }
  //devPrint('opened: $database');

  return <String, Object?>{'id': id};
}