4

The following only happens with the database just created as in the code. A previously existing database works all right.

I have the usual singleton setup for the database helper, the relevant part being:

Future<Database> get database async {
  // ...
  db ??= await openDatabase(
    path.join(await getDatabasesPath(), 'database.db'),
    onCreate: (db, version) async {
      final batch = db.batch();
      batch.execute('CREATE TABLE table1 ...');
      batch.execute('CREATE TABLE table2 ...');
      await batch.commit(noResult: true);
    },
  // ...
  return db;
}

Let's suppose the database doesn't exist yet. I call the following routine:

final db = await database;
await db.transaction((txn) async {
  await txn.delete('table1');
  final batch = txn.batch();
  for (data in newData1)
    batch.insert('table1', data.toJson()));
  await batch.commit(noResult: true);

  await txn.delete('table2');
  final batch = txn.batch();
  for (data in newData2)
    batch.insert('table2', data.toJson()));
  await batch.commit(noResult: true);
});

The transaction and batch calls execute without error. When the whole operation is actually executed at the end, it stops on the first DELETE FROM table1 SQL operation with a DatabaseException(attempt to write a readonly database(Sqlite code 1032) (running on Android).

I checked that the singleton is a singleton, openDatabase is not called twice. I also tried the transaction with exclusive: false, no difference.

Gábor
  • 9,466
  • 3
  • 65
  • 79

1 Answers1

1

The likely cause of the issue is that the table can't be accessed. A known workaround for this case is to open the database and close it before deleting, as mentioned in this GitHub issue thread.

Omatt
  • 8,564
  • 2
  • 42
  • 144