@clickup/pg-microsharding
Version:
Microshards support for PostgreSQL
59 lines • 2.89 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.allocate = allocate;
const child_process_1 = require("child_process");
const pickBy_1 = __importDefault(require("lodash/pickBy"));
const discoverShards_1 = require("../internal/discoverShards");
const logging_1 = require("../internal/logging");
const names_1 = require("../internal/names");
const normalizeDsn_1 = require("../internal/normalizeDsn");
const quote_1 = require("../internal/quote");
const runSql_1 = require("../internal/runSql");
/**
* Ensures that all shards in the range exist on the DSN, then runs a shell
* script (presumably DB migration), and then optionally activates the shards.
*/
async function allocate({ dsns, from, to, migrateCmd, activate, }) {
const [dsn, ...otherDsns] = dsns;
const existingShards = await (0, discoverShards_1.discoverShards)({ dsns: otherDsns });
const errors = [];
for (let shard = from; shard <= to; shard++) {
const existingShard = existingShards.find((s) => s.shard === shard);
if (existingShard &&
(0, normalizeDsn_1.normalizeDsn)(existingShard.dsn) !== (0, normalizeDsn_1.normalizeDsn)(dsn)) {
errors.push(`- microshard ${shard} already exists on ${existingShard.dsn}`);
}
}
if (errors.length > 0) {
throw "Errors encountered:\n" + errors.join("\n");
}
await (0, runSql_1.runSql)(dsn, (0, quote_1.sql) `SELECT ${(0, names_1.libSchema)()}.microsharding_ensure_exist(${from}, ${to})`, `Ensuring that microshards ${from}-${to} exist on ${dsn}`);
(0, logging_1.log)(`Running DB migration shell command "${migrateCmd}"` +
(activate ? " (Microshards will only be activated if it succeeds.)" : ""));
const dsnUrl = new URL(dsn);
const { status } = (0, child_process_1.spawnSync)(migrateCmd, {
shell: true,
stdio: "inherit",
env: {
...process.env,
...(0, pickBy_1.default)({
PGUSER: decodeURIComponent(dsnUrl.username),
PGPASSWORD: decodeURIComponent(dsnUrl.password),
PGHOST: dsnUrl.hostname,
PGPORT: dsnUrl.port,
PGDATABASE: decodeURIComponent(dsnUrl.pathname.slice(1)),
PGSSLMODE: new URLSearchParams(dsnUrl.search).get("sslmode") || "",
}, (v) => v),
},
});
if (status !== 0) {
throw "Error detected. NEW MICROSHARDS WERE NOT ACTIVATED!";
}
if (activate) {
await (0, runSql_1.runSql)(dsn, (0, quote_1.sql) `SELECT ${(0, names_1.libSchema)()}.microsharding_ensure_active(${from}, ${to})`, `Ensuring that all microshards in the range ${from}-${to} are active`);
}
}
//# sourceMappingURL=allocate.js.map