import { sql } from 'slonik';
const seedMigrationsIfNotExists = async (args) => {
    await args.connection.query(sql.unsafe `
    CREATE SCHEMA IF NOT EXISTS accounter_schema;
  `);
    await args.connection.query(sql.unsafe `
    CREATE TABLE IF NOT EXISTS accounter_schema.migration (
      "name" text NOT NULL,
      "hash" text NOT NULL,
      "date" timestamptz NOT NULL DEFAULT now(),
      CONSTRAINT "migration_pkey" PRIMARY KEY (name)
    );
  `);
};
async function runMigration(connection, migration) {
    const exists = await connection.maybeOneFirst(sql.unsafe `
    SELECT true
    FROM
      accounter_schema.migration
    WHERE
      "name" = ${migration.name}
  `);
    if (exists === true) {
        return;
    }
    const startTime = Date.now();
    console.log(`Running migration: ${migration.name}`);
    const result = await migration.run({ sql: sql.unsafe, connection });
    if (result) {
        await connection.query(result);
    }
    // TODO: hash verification (but tbh nobody cares about that)
    await connection.query(sql.unsafe `
    INSERT INTO accounter_schema.migration ("name", "hash")
    VALUES (${migration.name}, ${migration.name});
  `);
    const finishTime = Date.now();
    const delta = finishTime - startTime;
    console.log(`Finished in ${convertMsToTime(delta)}`);
}
export async function runMigrations(args) {
    console.log('Running PG migrations.');
    await seedMigrationsIfNotExists({ connection: args.slonik });
    for (const migration of args.migrations) {
        if (migration.noTransaction) {
            await runMigration(args.slonik, migration);
        }
        else {
            await args.slonik.transaction(connection => runMigration(connection, migration));
        }
        if (args.runTo && args.runTo === migration.name) {
            console.log(`reached migration '${migration.name}'. Stopping.`);
            break;
        }
    }
    console.log('Done.');
}
function padTo2Digits(num) {
    return num.toString().padStart(2, '0');
}
function convertMsToTime(milliseconds) {
    if (milliseconds < 1000) {
        return `${milliseconds}ms`;
    }
    const ms = milliseconds % 1000;
    const seconds = Math.floor(milliseconds / 1000) % 60;
    const minutes = Math.floor(seconds / 60) % 60;
    const hours = Math.floor(minutes / 60);
    if (hours === 0) {
        if (minutes === 0) {
            return `${seconds}.${ms}s`;
        }
        return `${minutes}:${padTo2Digits(seconds)}.${ms}min`;
    }
    return `${hours}:${padTo2Digits(minutes)}:${padTo2Digits(seconds)}.${ms}h`;
}
//# sourceMappingURL=pg-migrator.js.map