dropAllTables static method

Future<void> dropAllTables(
  1. DatabaseExecutor database
)

Drops all tables and views of the database, e.g. for a destructive migration. Foreign keys are only checked once the transaction gets committed.

Implementation

static Future<void> dropAllTables(final DatabaseExecutor database) async {
  await database.execute('PRAGMA defer_foreign_keys = TRUE');

  Future<List<Map<String, Object?>>> schemaObjects(final String type) {
    return database.rawQuery(
      "SELECT name, sql FROM sqlite_master WHERE type = ? AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' AND name != 'android_metadata'",
      [type],
    );
  }

  for (final view in await schemaObjects('view')) {
    await database.execute('DROP VIEW IF EXISTS `${view['name']}`');
  }

  // dropping virtual tables drops their shadow tables as well
  final tables = await schemaObjects('table');
  final virtualTables = tables.where((table) =>
      (table['sql'] as String?)
          ?.trimLeft()
          .toUpperCase()
          .startsWith('CREATE VIRTUAL TABLE') ??
      false);
  for (final table in virtualTables) {
    await database.execute('DROP TABLE IF EXISTS `${table['name']}`');
  }
  for (final table in await schemaObjects('table')) {
    await database.execute('DROP TABLE IF EXISTS `${table['name']}`');
  }
}