up method

  1. @override
Future up()
override

Implementation

@override
Future up() async {
  await _init();
  var r = await connection.execute('SELECT path from migrations;');
  var existing = r.expand((x) => x).cast<String>();
  var toRun = <String>[];

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

  if (toRun.isNotEmpty) {
    var r = await connection.execute('SELECT MAX(batch) from migrations;');
    var curBatch = (r[0][0] ?? 0) as int;
    var batch = curBatch + 1;

    for (var k in toRun) {
      var migration = migrations[k]!;
      var schema = PostgresSchema();
      migration.up(schema);

      var result = await schema.run(connection).then((_) {
        return connection.runTx((ctx) async {
          var result = await ctx.execute(
              "INSERT INTO MIGRATIONS (batch, path) VALUES ($batch, '$k')");

          return result.affectedRows;
        });
      }).catchError((e) {
        _log.severe('Failed to insert into "migrations" table.');
        return -1;
      });
      if (result > 0) {
        _log.info('Inserted "$k" into "migrations" table.');
      }
    }
  } else {
    _log.warning('Nothing to add into "migrations" table.');
  }
}