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();

  await connection.runTransaction((abstractContext) async {
    final context = abstractContext as PostgreSQLDatabaseContext;

    if (await _schemaExists(context)) {
      if (!ignoreMigration) {
        String? versionString;
        try {
          versionString = await context.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, context);

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

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

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

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

  _initialized = true;
}