@clickup/pg-microsharding
Version:
Microshards support for PostgreSQL
55 lines • 2.96 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resultCommit = resultCommit;
const compact_1 = __importDefault(require("lodash/compact"));
const p_retry_1 = __importDefault(require("p-retry"));
const logging_1 = require("./logging");
const names_1 = require("./names");
const quote_1 = require("./quote");
const runSql_1 = require("./runSql");
const ACTIVATION_RETRY_OPTIONS = {
factor: 1.5,
minTimeout: 100,
maxTimeout: 3000,
retries: 15,
};
/**
* Cleans up after the shard migration success.
*/
async function resultCommit({ activateOnDestination, deactivateSQL, fromDsn, tables, toDsn, schema, }) {
if (!activateOnDestination) {
await (0, runSql_1.runSql)(toDsn, (0, quote_1.sql) `
DROP SCHEMA IF EXISTS ${(0, quote_1.ident)((0, names_1.schemaNew)(schema))} CASCADE;
ALTER SCHEMA ${(0, quote_1.ident)(schema)} RENAME TO ${(0, quote_1.ident)((0, names_1.schemaNew)(schema))};
`, `Renaming just-migrated microshard on the destination to ${(0, names_1.schemaNew)(schema)}`);
return;
}
// E.g. 2023-01-09T07:09:54.253Z
const dateSuffix = new Date()
.toISOString()
.replace(/\..*$/, "")
.replace(/[-T:Z]/g, "");
const shard = (0, names_1.shardNo)(schema);
await (0, runSql_1.runSql)(fromDsn, (0, quote_1.join)((0, compact_1.default)([
(0, quote_1.sql) `BEGIN`,
shard !== null &&
(0, quote_1.sql) `SELECT ${(0, names_1.libSchema)()}.microsharding_ensure_inactive(${shard})`,
(0, quote_1.sql) `ALTER schema ${(0, quote_1.ident)(schema)} RENAME TO ${(0, quote_1.ident)((0, names_1.schemaOld)(schema, dateSuffix))}`,
(0, quote_1.sql) `COMMIT`,
]), "; "), "Renaming & deactivating microshard on the source");
if (shard !== null) {
await (0, p_retry_1.default)(async () => (0, runSql_1.runSql)(toDsn, (0, quote_1.sql) `SELECT ${(0, names_1.libSchema)()}.microsharding_ensure_active(${shard})`, "DON'T INTERRUPT: Activating microshard on the destination while holding the write lock").catch((e) => {
throw e instanceof Error ? e : Error(`${e}`);
}), {
...ACTIVATION_RETRY_OPTIONS,
onFailedAttempt: (error) => logging_1.log.warning(`Activation attempt ${error.attemptNumber} of ${error.attemptNumber + error.retriesLeft} failed: ${error.message}`),
});
}
if (deactivateSQL && tables.length > 0) {
await (0, runSql_1.runSql)(fromDsn, (0, quote_1.join)(tables.map(({ schema, name }) => deactivateSQL.replace(/\$1/g, (0, quote_1.sql) `${(0, quote_1.sql) `${(0, quote_1.ident)(schema)}.${(0, quote_1.ident)(name)}`.toString()}`.toString()) + ";"), "\n"), "Running custom deactivation script for microshard tables");
}
}
//# sourceMappingURL=resultCommit.js.map