initializeSchema method

  1. @override
Future<void> initializeSchema({
  1. bool ignoreMigration = false,
})
override

Checks and creates or migrates database tables according to the adapters schema.

TODO more docs? maybe on migration TODO migration

Implementation

@override
Future<void> initializeSchema({bool ignoreMigration = false}) async {
  final connection = await _connection();

  if (await _schemaExists(connection)) {
    if (!ignoreMigration) {
      String? versionString;
      try {
        versionString = await connection.getMetaValue(schemaVersionKey);
      } catch (e) {
        throw PersistenceException(
          'Could not query version for schema "${schema.name}".',
          cause: e,
        );
      }

      if (versionString == null) {
        throw PersistenceException(
            'Schema "${schema.name}" does not provide version.');
      }

      final version = int.parse(versionString);
      if (version != schema.version) {
        resolve<LogService>().i(
            'Migrating database schema from v$version to v${schema.version}.',
            sender: 'DataHub');
        final migrator = PostgreSQLDatabaseMigrator(schema, connection);

        await schema.migrate(migrator, version);
        await connection.setMetaValue(
            schemaVersionKey, schema.version.toString());
      }
    }
  } else {
    await connection.execute(RawSql('CREATE SCHEMA ${schema.name}'));

    await connection.execute(CreateTableBuilder(schema.name, metaTable)
      ..fields.addAll([
        PrimaryKey(FieldType.String, metaTable, 'key'),
        DataField(FieldType.String, metaTable, 'value')
      ]));

    await connection.setMetaValue(
        schemaVersionKey, schema.version.toString());

    // create scheme
    for (final layout in schema.beans) {
      await connection.execute(CreateTableBuilder.fromLayout(schema, layout));
    }
  }

  _initialized = true;
}