"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const database_config_1 = require("./helpers/database-config");
const test_config_1 = require("../config/test-config");
const db_migrate_1 = require("db-migrate");
const db_migrate_shared_1 = require("db-migrate-shared");
const pg_1 = require("pg");
db_migrate_shared_1.log.setLogLevel('error');
const schema = 'up_n_down_migrations_test';
async function initSchema(db) {
    const client = new pg_1.Client(db);
    await client.connect();
    await client.query(`DROP SCHEMA IF EXISTS ${db.schema} CASCADE`);
    await client.query(`CREATE SCHEMA IF NOT EXISTS ${db.schema}`);
    await client.end();
}
async function validateTablesHavePrimaryKeys(db) {
    const client = new pg_1.Client(db);
    await client.connect();
    const tables = await client.query(`SELECT 
        t.table_name
    FROM 
        information_schema.tables t
    LEFT JOIN 
        information_schema.table_constraints tc ON t.table_schema = tc.table_schema
        AND t.table_name = tc.table_name
        AND tc.constraint_type = 'PRIMARY KEY'
    WHERE 
        t.table_type = 'BASE TABLE'
        AND t.table_schema = '${schema}' 
        AND t.table_schema NOT IN ('pg_catalog', 'information_schema')
        AND tc.constraint_name IS NULL;
    `);
    await client.end();
    if ((tables.rowCount ?? 0) > 0) {
        throw new Error(`The following tables do not have a primary key defined: ${tables.rows
            .map((r) => r.table_name)
            .join(', ')}`);
    }
}
test('Up & down migrations work', async () => {
    jest.setTimeout(15000);
    const config = (0, test_config_1.createTestConfig)({
        db: {
            ...(0, database_config_1.getDbConfig)(),
            pool: { min: 1, max: 4 },
            schema: schema,
            ssl: false,
        },
    });
    await initSchema(config.db);
    const e2e = {
        ...config.db,
        connectionTimeoutMillis: 2000,
    };
    // disable Intellij/WebStorm from setting verbose CLI argument to db-migrator
    process.argv = process.argv.filter((it) => !it.includes('--verbose'));
    const dbm = (0, db_migrate_1.getInstance)(true, {
        cwd: `${__dirname}/../../`, // relative to src/test/e2e
        config: { e2e },
        env: 'e2e',
    });
    await dbm.up();
    await validateTablesHavePrimaryKeys(config.db);
    await dbm.reset();
});
//# sourceMappingURL=migrator.e2e.test.js.map