up method

  1. @override
Future up()
override

Implementation

@override
Future up() async {
  await _init();
  var result = await connection.execute('SELECT path from migrations;');
  var existing = <String>[];
  if (result.rows.isNotEmpty) {
    existing = result.rows.first.assoc().values.cast<String>().toList();
  }
  var toRun = <String>[];

  migrations.forEach((k, v) {
    if (!existing.contains(k)) toRun.add(k);
  });

  if (toRun.isNotEmpty) {
    var result =
        await connection.execute('SELECT MAX(batch) from migrations;');
    var curBatch = 0;
    if (result.rows.isNotEmpty) {
      var firstRow = result.rows.first;
      curBatch = int.tryParse(firstRow.colAt(0) ?? "0") ?? 0;
    }
    curBatch++;

    for (var k in toRun) {
      var migration = migrations[k]!;
      var schema = MySqlSchema();
      migration.up(schema);
      _log.info('Added "$k" into "migrations" table.');
      await schema.run(connection).then((_) async {
        var result = await connection
            .execute(
                "INSERT INTO migrations (batch, path) VALUES ($curBatch, '$k')")
            .catchError((e) {
          _log.severe('Failed to insert into "migrations" table.', e);
        });

        return result.affectedRows.toInt();
      });
    }
  } else {
    _log.warning('Nothing to add into "migrations" table.');
  }
}