Moor: Method to Clear Database

Created on 3 Dec 2019  路  7Comments  路  Source: simolus3/moor

I want to be able to clear the entire database record when user sign's out of my application.

question

Most helpful comment

There are two options here: You could either close the database, delete the file from the device and then re-open it. Or you can delete everything from all tables, without closing the database:

Future<void> deleteEverything() {
  return transaction(() async {
    // you only need this if you've manually enabled foreign keys
    // await customStatement('PRAGMA foreign_keys = OFF');
    for (final table in allTables) {
      await delete(table).go();
    }
  });
}

All 7 comments

There are two options here: You could either close the database, delete the file from the device and then re-open it. Or you can delete everything from all tables, without closing the database:

Future<void> deleteEverything() {
  return transaction(() async {
    // you only need this if you've manually enabled foreign keys
    // await customStatement('PRAGMA foreign_keys = OFF');
    for (final table in allTables) {
      await delete(table).go();
    }
  });
}

@simolus3, I encounter a problem when tables are not cleared when this method is called (most often this happens on real devices), maybe there is another way to clear all tables without closing the database? I use moor_flutter 3.0.0.

class Database extends _$Database {
  final LazyDatabase database;

  Database(this.database) : super(database);

  @override
  int get schemaVersion => 1;

  Future<void> deleteEverything() {
    return transaction(() async {
      for (final table in allTables) {
        await delete(table).go();
      }
    });
  }
}

I can鈥檛 understand the reason why this sometimes happens.

Do you get an error when that happens? Or does it just not clear data?

Do FKs need to be disabled for this to work?

Do you get an error when that happens? Or does it just not clear data?

There are no errors. This happens only on specific real devices that I don鈥檛 have, by the way, on Android and iOS emulators there is no such problem.

Are those devices known to ship with a buggy sqlite? I'd love to take a look at workarounds if there are some. But it's very weird that those statements don't do anything without causing an error. Even dropping the target table of a FK constraint seems to work.

To reduce device-specific behavior, you could try switching to moor_ffi, which ships a precompiled sqlite3 library along with your app.

@simolus3, in fact, the problem appears on most devices, but using the version with moor_ffi, it seems that users no longer have problems clearing tables.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kira1752 picture kira1752  路  3Comments

Ltei picture Ltei  路  3Comments

stx picture stx  路  3Comments

tony123S picture tony123S  路  4Comments

simolus3 picture simolus3  路  4Comments