@clickup/pg-microsharding
Version:
Microshards support for PostgreSQL
79 lines • 2.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
exports.createConnectedClient = createConnectedClient;
const pg_1 = require("pg");
/**
* A connected PG client with extra methods.
*/
class Client extends pg_1.Client {
async serverVersion() {
const { rows } = await this.query("SHOW server_version");
return String(rows[0]["server_version"])
.split(".")
.map((p) => parseInt(p));
}
async currentWalInsertLsn() {
const { rows } = await this.query("SELECT pg_current_wal_insert_lsn() AS lsn");
return rows[0].lsn;
}
async confirmedFlushLsn(slotName) {
const { rows } = await this.query(`SELECT confirmed_flush_lsn AS lsn
FROM pg_replication_slots
WHERE database = current_database() AND slot_name = $1`, [slotName]);
if (rows.length === 0) {
throw new Error(`Slot ${slotName} not found`);
}
return rows[0].lsn;
}
async isMaster() {
var _a;
const { rows } = await this.query("SELECT pg_is_in_recovery()");
return ((_a = rows[0]) === null || _a === void 0 ? void 0 : _a.pg_is_in_recovery) === false;
}
}
exports.Client = Client;
/**
* Node-postgres doesn't really support sslmode=prefer: it treats it as "ssl is
* required". This is a different default than e.g. psql has when no PGSSLMODE
* is set. Also, it is not always able to locate the local certs, so we have to
* use rejectUnauthorized=false. Thus, we try to set up an SSL connection first,
* and if it fails, then we try non-SSL.
*/
async function createConnectedClient(dsn) {
const dsnUrl = new URL(dsn);
dsnUrl.searchParams.delete("sslmode");
let sslError;
const config = {
connectionString: dsnUrl.toString(),
application_name: "pg-microsharding",
};
const clientSsl = new Client({
...config,
ssl: { rejectUnauthorized: false },
});
try {
await clientSsl.connect();
clientSsl.on("error", () => { });
return clientSsl;
}
catch (e) {
sslError = e;
if (!`${e}`.includes("The server does not support SSL connections") &&
!`${e}`.includes("no pg_hba.conf")) {
throw e;
}
}
const clientPlain = new Client(config);
try {
await clientPlain.connect();
clientPlain.on("error", () => { });
return clientPlain;
}
catch (e) {
throw (`Error connecting to ${dsn}:\n` +
` - with SSL: ${sslError}\n` +
` - without SSL: ${e}`);
}
}
//# sourceMappingURL=createConnectedClient.js.map