up method

  1. @override
Future up()
override

Implementation

@override
Future up() async {
  await _init();
  var result = await connection.query('SELECT path from migrations;');

  var existing = <String>[];
  if (result.isNotEmpty) {
    existing = result.expand((x) => x).cast<String>().toList();
  }

  var toRun = <String>[];
  migrations.forEach((k, v) {
    if (!existing.contains(k)) toRun.add(k);
  });

  if (toRun.isNotEmpty) {
    var result = await connection.query('SELECT MAX(batch) from migrations;');
    var curBatch = 0;
    if (result.isNotEmpty) {
      var firstRow = result.toList();
      curBatch = int.tryParse(firstRow[0][0] ?? '0') as int;
    }
    var batch = curBatch + 1;

    for (var k in toRun) {
      var migration = migrations[k]!;
      var schema = MariaDbSchema();
      migration.up(schema);
      _log.info('Added "$k" into "migrations" table.');
      try {
        await schema.run(connection).then((_) async {
          var result = await connection.query(
              "INSERT INTO migrations (batch, path) VALUES ($batch, '$k')");

          return result.affectedRows;
        });
      } catch (e) {
        _log.severe('Failed to insert into "migrations" table.', e);
      }
    }
  } else {
    _log.warning('Nothing to add into "migrations" table.');
  }
}