validateDatabaseSchema method

Future<void> validateDatabaseSchema({
  1. bool validateDropped = true,
})

Compares and validates the schema of the current database with what the generated code expects.

When changing tables or other elements of your database schema, you need to increate your GeneratedDatabase.schemaVersion and write a migration to transform your existing tables to the new structure.

For queries, drift always assumes that your database schema matches the structure of your defined tables. This isn't the case when you forget to write a schema migration, which can cause all kinds of problems later.

For this reason, the validateDatabaseSchema method can be used in your database, (perhaps in a MigrationStrategy.beforeOpen callback) to verify that your database schema is what drift expects.

When validateDropped is enabled (it is by default), this method also verifies that all schema elements that you've deleted at some point are no longer present in your runtime schema.

Implementation

Future<void> validateDatabaseSchema({bool validateDropped = true}) async {
  final virtualTables = allTables
      .whereType<VirtualTableInfo>()
      .map((e) => e.entityName)
      .toList();

  final schemaOfThisDatabase = await collectSchemaInput(virtualTables);

  // The expectedSchema expando will store the expected schema for this
  // database when it's opened in a migration test. This allows this method
  // to be used in migration tests -- otherwise, this would always compare the
  // runtime schema to the latest schema from generated code.
  var referenceSchema = expectedSchema[this];

  if (referenceSchema == null) {
    // Collect the schema how it would be if we just called `createAll` on a
    // clean database.
    final referenceDb = _GenerateFromScratch(this, NativeDatabase.memory());
    referenceSchema = expectedSchema[this] ??
        await referenceDb.collectSchemaInput(virtualTables);
    await referenceDb.close();
  }

  verify(referenceSchema, schemaOfThisDatabase, validateDropped);
}