rollback method

  1. @override
Future rollback()
override

Implementation

@override
Future rollback() async {
  await _init();

  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;
  }
  result = await connection
      .execute('SELECT path from migrations WHERE batch = $curBatch;');
  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) {
    for (var k in toRun.reversed) {
      var migration = migrations[k]!;
      var schema = MySqlSchema();
      migration.down(schema);
      _log.info('Removed "$k" from "migrations" table.');
      await schema.run(connection).then((_) {
        return connection
            .execute('DELETE FROM migrations WHERE path = \'$k\';');
      });
    }
  } else {
    _log.warning('Nothing to remove from "migrations" table.');
  }
}