@clickup/pg-microsharding
Version:
Microshards support for PostgreSQL
53 lines (39 loc) • 1.78 kB
text/typescript
import round from "lodash/round";
import { ident, shellQuote } from "./quote";
export const pubName = (schema: string): string =>
`pg_microsharding_move_${schema}_pub`;
export const subName = (schema: string): string =>
`pg_microsharding_move_${schema}_sub`;
export const pgDump = (fromDsn: string): string =>
`pg_dump --schema-only ${shellQuote(fromDsn)}`;
export const psql = (dsn: string): string =>
`psql ${shellQuote(dsn)} -vON_ERROR_STOP=on -At`;
export const shardNo = (schema: string): number | null =>
schema.match(/(\d+)/) ? parseInt(RegExp.$1) : null;
export const shardFactorFromComment = (comment: string): number | null =>
comment.match(/\bfactor\s*[=:]\s*(\d+(\.\d+)?)\b/)
? parseFloat(RegExp.$1)
: null;
export const shardFactorToComment = (factor: number): string =>
Math.abs(factor - 1) < 0.001 || Math.abs(factor) < 0.001
? ""
: `factor=${round(factor, 3)}`;
export const schemaOld = (schema: string, dateSuffix: string): string =>
`${schema}old${dateSuffix}`;
export const schemaNew = (schema: string): string => `${schema}new`;
export const schemaCleanupRe = (schemaNameRe: string): string =>
`^(${schemaNameRe})(old_\\d+|old\\d*|new)$`;
export const libSchema = (): ReturnType<typeof ident> => ident("microsharding");
export const dsnShort = (dsn: string): string => {
const url = new URL(dsn);
return url.hostname + url.pathname;
};
export const dsnFromToShort = (fromDsn: string, toDsn: string): string => {
const fromUrl = new URL(fromDsn);
const toUrl = new URL(toDsn);
const [fromStr, toStr] =
fromUrl.hostname === toUrl.hostname
? [fromUrl.hostname + fromUrl.pathname, toUrl.hostname + toUrl.pathname]
: [fromUrl.hostname, toUrl.hostname];
return `from ${fromStr} to ${toStr}`;
};