"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get gatherPreMigrationDbSnapshot () {
        return gatherPreMigrationDbSnapshot;
    },
    get tryGatherPreMigrationDbSnapshot () {
        return tryGatherPreMigrationDbSnapshot;
    }
});
const _sequelize = require("sequelize");
/** From pg_database_size; **-1** if the size could not be read (do not treat as a real byte count). */ const DATABASE_SIZE_UNKNOWN = -1;
/** Max tables with a non-negative reltuples estimate (planner has a row count to report). */ const TABLE_ROW_ESTIMATE_LIMIT = 500;
async function gatherPreMigrationDbSnapshot(sequelize) {
    const [sizeRow] = await sequelize.query(`SELECT pg_database_size(current_database())::text AS bytes`, {
        type: _sequelize.QueryTypes.SELECT
    });
    const rows = await sequelize.query(`
      SELECT c.relname AS table_name, c.reltuples::bigint::text AS estimated_row_count
      FROM pg_class c
      JOIN pg_namespace n ON n.oid = c.relnamespace
      WHERE n.nspname = 'public'
        AND c.relkind = 'r'
        AND c.reltuples >= 0
      ORDER BY c.reltuples DESC
      LIMIT ${TABLE_ROW_ESTIMATE_LIMIT}
    `, {
        type: _sequelize.QueryTypes.SELECT
    });
    const tableRowEstimates = [];
    for (const row of rows){
        const estimatedRowCount = Number(row.estimated_row_count);
        if (!Number.isFinite(estimatedRowCount) || estimatedRowCount < 0) {
            continue;
        }
        tableRowEstimates.push({
            tableName: row.table_name,
            estimatedRowCount
        });
    }
    let databaseSizeBytes = DATABASE_SIZE_UNKNOWN;
    if (sizeRow) {
        const n = Number(sizeRow.bytes);
        databaseSizeBytes = Number.isFinite(n) ? n : DATABASE_SIZE_UNKNOWN;
    }
    return {
        databaseSizeBytes,
        tableRowEstimates
    };
}
async function tryGatherPreMigrationDbSnapshot(log, sequelize) {
    try {
        return await gatherPreMigrationDbSnapshot(sequelize);
    } catch (err) {
        log.warn('Could not gather pre-migration DB snapshot for audit log', err);
        return undefined;
    }
}

//# sourceMappingURL=gatherPreMigrationDbSnapshot.js.map