@clickup/pg-microsharding
Version:
Microshards support for PostgreSQL
51 lines • 2.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanup = cleanup;
const getPublisherDsn_1 = require("../internal/getPublisherDsn");
const getSchemaName_1 = require("../internal/getSchemaName");
const listActiveSchemas_1 = require("../internal/listActiveSchemas");
const names_1 = require("../internal/names");
const quote_1 = require("../internal/quote");
const resultAbort_1 = require("../internal/resultAbort");
const runSql_1 = require("../internal/runSql");
/**
* Removes old and semi-migrated schemas, and optionally orphan microshard
* schemas (those matching the microshard pattern but absent from the active
* shards list).
*/
async function cleanup({ dsn, noOldShards, confirm, noOrphanShards, confirmOrphanShards, }) {
const dummyNo = 101;
const dummySchemaName = await (0, getSchemaName_1.getSchemaName)(dsn, dummyNo);
const schemaNameRe = dummySchemaName.replace(new RegExp(`0*${dummyNo}0*`), "\\d+");
const oldSchemaNameRe = (0, names_1.schemaCleanupRe)(schemaNameRe);
const allSchemas = await runSql_1.runSql.column(dsn, (0, quote_1.sql) `SELECT nspname FROM pg_namespace`);
const oldSchemas = allSchemas.filter((schema) => schema.match(oldSchemaNameRe));
if (oldSchemas.length === 0) {
await (noOldShards === null || noOldShards === void 0 ? void 0 : noOldShards(oldSchemaNameRe));
}
else if (!confirm || (await confirm(oldSchemas))) {
// Remove sequentially, otherwise there is a high chance of having
// shared_buffers OOM.
for (const schema of oldSchemas) {
await (0, runSql_1.runSql)(dsn, (0, quote_1.sql) `DROP SCHEMA ${(0, quote_1.ident)(schema)} CASCADE`, `Dropping redundant schema ${schema}`);
}
}
if (noOrphanShards || confirmOrphanShards) {
const activeSet = new Set(await (0, listActiveSchemas_1.listActiveSchemas)({ dsn }));
const orphanSchemas = allSchemas.filter((schema) => schema.match(new RegExp(`^${schemaNameRe}$`)) && !activeSet.has(schema));
if (orphanSchemas.length === 0) {
await (noOrphanShards === null || noOrphanShards === void 0 ? void 0 : noOrphanShards());
}
else if (!confirmOrphanShards ||
(await confirmOrphanShards(orphanSchemas))) {
for (const schema of orphanSchemas) {
// Discover the publisher's connection string from the subscription, so
// we can clean up both ends of any lingering replication. Falls back to
// the current DSN if no subscription exists (e.g. leftover source shard).
const fromDsn = (await (0, getPublisherDsn_1.getPublisherDsn)({ subscriberDsn: dsn, schema })) || dsn;
await (0, resultAbort_1.resultAbort)({ fromDsn, toDsn: dsn, schema });
}
}
}
}
//# sourceMappingURL=cleanup.js.map