@sjoedev/monarch 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ export interface TableName {
2
+ readonly schema: string | null;
3
+ readonly name: string;
4
+ /** `schema.name`, unquoted, as the user wrote it. */
5
+ readonly display: string;
6
+ }
7
+ /** The settings that can appear in `monarch.json` or be passed as overrides. */
8
+ export interface Settings {
9
+ dir?: string;
10
+ table?: string;
11
+ envFile?: string;
12
+ urlEnv?: string;
13
+ allowedHosts?: readonly string[];
14
+ lockTimeout?: string;
15
+ }
16
+ /** A fully resolved configuration. */
17
+ export interface Config {
18
+ /** Project root (the working directory). */
19
+ readonly root: string;
20
+ /** Absolute path of the config file that was read, if any. */
21
+ readonly configFile: string | null;
22
+ /** Absolute base folder. */
23
+ readonly dir: string;
24
+ /** Absolute `<dir>/migrations`. */
25
+ readonly migrationsDir: string;
26
+ /** Absolute `<dir>/seed.sql`. */
27
+ readonly seedFile: string;
28
+ readonly table: TableName;
29
+ /** Absolute dotenv path. */
30
+ readonly envFile: string;
31
+ /** Name of the variable holding the connection string. */
32
+ readonly urlEnv: string;
33
+ readonly allowedHosts: readonly string[];
34
+ readonly lockTimeout: string | undefined;
35
+ /** Undefined when not set; see `requireConnectionString`. */
36
+ readonly connectionString: string | undefined;
37
+ }
38
+ export interface LoadConfigOptions {
39
+ cwd?: string;
40
+ /** Highest precedence. Relative paths resolve against `cwd`. */
41
+ overrides?: Settings;
42
+ /** A config file to read instead of `./monarch.json`. */
43
+ configPath?: string;
44
+ env?: NodeJS.ProcessEnv;
45
+ }
46
+ /** What is safe to show about a connection string. */
47
+ export interface ConnectionInfo {
48
+ user: string;
49
+ host: string;
50
+ port: string;
51
+ database: string;
52
+ /** `user@host:port/database`. */
53
+ target: string;
54
+ }
55
+ /** Parses `name` or `schema.name`. Each part must be a plain identifier. */
56
+ export declare function parseTableName(value: string): TableName;
57
+ /**
58
+ * Looks up the connection string: the real environment first, then the dotenv
59
+ * file. Nothing is written to `process.env`.
60
+ */
61
+ export declare function resolveConnectionString({ urlEnv, envFile, env, }: {
62
+ urlEnv: string;
63
+ envFile: string;
64
+ env: NodeJS.ProcessEnv;
65
+ }): Promise<string | undefined>;
66
+ /**
67
+ * Loads `monarch.json`, merges overrides (CLI flags) over it and the defaults,
68
+ * and resolves paths and the connection string.
69
+ *
70
+ * A missing connection string is not an error here, so commands that never
71
+ * touch the database (`new`) work without one; use `requireConnectionString`.
72
+ */
73
+ export declare function loadConfig({ cwd, overrides, configPath, env, }?: LoadConfigOptions): Promise<Config>;
74
+ export declare function requireConnectionString(config: Config): string;
75
+ /** Path as shown to the user: relative to the project root, with forward slashes. */
76
+ export declare function displayPath(config: Config, file: string): string;
77
+ /** The parts of a connection string that are safe to show. */
78
+ export declare function describeConnection(connectionString: string): ConnectionInfo;
79
+ /**
80
+ * The host a connection will reach: `?host=` if present, else the URL's
81
+ * hostname, lowercased, without IPv6 brackets. Empty or `/`-prefixed means a
82
+ * Unix socket.
83
+ */
84
+ export declare function hostFromUrl(connectionString: string | URL): string;
85
+ /** Same string with the database path replaced, used to reach the maintenance database. */
86
+ export declare function withDatabase(connectionString: string, database: string): string;
87
+ /**
88
+ * Removes anything from `text` that would reveal the password in
89
+ * `connectionString`: the URL itself and the `:password@` and `password=`
90
+ * forms. The bare password is not replaced everywhere, because a password
91
+ * such as "postgres" would also mangle the user and database names.
92
+ */
93
+ export declare function scrub(text: string, connectionString: string | undefined): string;
package/dist/config.js ADDED
@@ -0,0 +1,229 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { parseEnv } from "node:util";
4
+ import { CONFIG_FILE, DEFAULT_ALLOWED_HOSTS, DEFAULT_DIR, DEFAULT_ENV_FILE, DEFAULT_TABLE, DEFAULT_URL_ENV, } from "./constants.js";
5
+ import { MonarchError, hasErrnoCode } from "./errors.js";
6
+ const STRING_KEYS = ["dir", "table", "envFile", "urlEnv", "lockTimeout"];
7
+ const SETTING_KEYS = [...STRING_KEYS, "allowedHosts"];
8
+ const TABLE_NAME = /^(?:([A-Za-z_][A-Za-z0-9_]*)\.)?([A-Za-z_][A-Za-z0-9_]*)$/;
9
+ /** Parses `name` or `schema.name`. Each part must be a plain identifier. */
10
+ export function parseTableName(value) {
11
+ const match = TABLE_NAME.exec(value);
12
+ if (!match) {
13
+ throw new MonarchError("CONFIG_INVALID", `Invalid table name ${JSON.stringify(value)}: use "name" or "schema.name", ` +
14
+ "each part starting with a letter or underscore and containing only letters, digits and underscores.");
15
+ }
16
+ return { schema: match[1] ?? null, name: match[2], display: value };
17
+ }
18
+ function isRecord(value) {
19
+ return value !== null && typeof value === "object" && !Array.isArray(value);
20
+ }
21
+ /**
22
+ * Checks the shape of a settings object (from `monarch.json` or from overrides).
23
+ * @param source how to refer to it in error messages
24
+ */
25
+ function validateSettings(value, source) {
26
+ const fail = (msg) => new MonarchError("CONFIG_INVALID", `${source}: ${msg}`);
27
+ if (!isRecord(value))
28
+ throw fail("expected a JSON object.");
29
+ for (const key of Object.keys(value)) {
30
+ if (!SETTING_KEYS.includes(key)) {
31
+ throw fail(`unknown key ${JSON.stringify(key)} (known keys: ${SETTING_KEYS.join(", ")}).`);
32
+ }
33
+ }
34
+ const settings = {};
35
+ for (const key of STRING_KEYS) {
36
+ const v = value[key];
37
+ if (v === undefined)
38
+ continue;
39
+ if (typeof v !== "string" || v === "")
40
+ throw fail(`"${key}" must be a non-empty string.`);
41
+ settings[key] = v;
42
+ }
43
+ const hosts = value.allowedHosts;
44
+ if (hosts !== undefined) {
45
+ if (!Array.isArray(hosts) || !hosts.every((h) => typeof h === "string")) {
46
+ throw fail('"allowedHosts" must be an array of strings.');
47
+ }
48
+ settings.allowedHosts = hosts;
49
+ }
50
+ if (settings.table !== undefined) {
51
+ try {
52
+ parseTableName(settings.table);
53
+ }
54
+ catch (err) {
55
+ throw fail(err instanceof Error ? err.message : String(err));
56
+ }
57
+ }
58
+ return settings;
59
+ }
60
+ async function readConfigFile(file, { explicit }) {
61
+ let raw;
62
+ try {
63
+ raw = await readFile(file, "utf8");
64
+ }
65
+ catch (err) {
66
+ if (hasErrnoCode(err, "ENOENT")) {
67
+ if (!explicit)
68
+ return null;
69
+ throw new MonarchError("CONFIG_INVALID", `Config file not found: ${file}`);
70
+ }
71
+ throw new MonarchError("CONFIG_INVALID", `Could not read ${file}: ${errorMessage(err)}`);
72
+ }
73
+ let parsed;
74
+ try {
75
+ parsed = JSON.parse(stripBom(raw));
76
+ }
77
+ catch (err) {
78
+ throw new MonarchError("CONFIG_INVALID", `${file} is not valid JSON: ${errorMessage(err)}`);
79
+ }
80
+ return validateSettings(parsed, file);
81
+ }
82
+ const stripBom = (text) => text.replace(/^/, "");
83
+ const errorMessage = (err) => (err instanceof Error ? err.message : String(err));
84
+ /**
85
+ * Looks up the connection string: the real environment first, then the dotenv
86
+ * file. Nothing is written to `process.env`.
87
+ */
88
+ export async function resolveConnectionString({ urlEnv, envFile, env, }) {
89
+ const fromEnv = env[urlEnv];
90
+ if (fromEnv)
91
+ return fromEnv;
92
+ let content;
93
+ try {
94
+ content = await readFile(envFile, "utf8");
95
+ }
96
+ catch (err) {
97
+ if (hasErrnoCode(err, "ENOENT") || hasErrnoCode(err, "EISDIR"))
98
+ return undefined;
99
+ throw new MonarchError("CONFIG_INVALID", `Could not read ${envFile}: ${errorMessage(err)}`);
100
+ }
101
+ return parseEnv(stripBom(content))[urlEnv] || undefined;
102
+ }
103
+ /**
104
+ * Loads `monarch.json`, merges overrides (CLI flags) over it and the defaults,
105
+ * and resolves paths and the connection string.
106
+ *
107
+ * A missing connection string is not an error here, so commands that never
108
+ * touch the database (`new`) work without one; use `requireConnectionString`.
109
+ */
110
+ export async function loadConfig({ cwd = process.cwd(), overrides = {}, configPath, env = process.env, } = {}) {
111
+ const root = path.resolve(cwd);
112
+ const configFile = path.resolve(root, configPath ?? CONFIG_FILE);
113
+ const fromFile = await readConfigFile(configFile, { explicit: configPath !== undefined });
114
+ const fromOverrides = validateSettings(Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined)), "options");
115
+ /** A path setting: flags resolve against the cwd, the config file against its own directory. */
116
+ const pathSetting = (key, fallback) => {
117
+ const flag = fromOverrides[key];
118
+ if (flag !== undefined)
119
+ return path.resolve(root, flag);
120
+ const configured = fromFile?.[key];
121
+ if (configured !== undefined)
122
+ return path.resolve(path.dirname(configFile), configured);
123
+ return path.resolve(root, fallback);
124
+ };
125
+ const dir = pathSetting("dir", DEFAULT_DIR);
126
+ const envFile = pathSetting("envFile", DEFAULT_ENV_FILE);
127
+ const urlEnv = fromOverrides.urlEnv ?? fromFile?.urlEnv ?? DEFAULT_URL_ENV;
128
+ return Object.freeze({
129
+ root,
130
+ configFile: fromFile ? configFile : null,
131
+ dir,
132
+ migrationsDir: path.join(dir, "migrations"),
133
+ seedFile: path.join(dir, "seed.sql"),
134
+ table: Object.freeze(parseTableName(fromOverrides.table ?? fromFile?.table ?? DEFAULT_TABLE)),
135
+ envFile,
136
+ urlEnv,
137
+ allowedHosts: Object.freeze([...(fromOverrides.allowedHosts ?? fromFile?.allowedHosts ?? DEFAULT_ALLOWED_HOSTS)]),
138
+ lockTimeout: fromOverrides.lockTimeout ?? fromFile?.lockTimeout,
139
+ connectionString: await resolveConnectionString({ urlEnv, envFile, env }),
140
+ });
141
+ }
142
+ export function requireConnectionString(config) {
143
+ if (config.connectionString)
144
+ return config.connectionString;
145
+ throw new MonarchError("URL_MISSING", `${config.urlEnv} is not set (checked the environment and ${displayPath(config, config.envFile)}).`);
146
+ }
147
+ /** Path as shown to the user: relative to the project root, with forward slashes. */
148
+ export function displayPath(config, file) {
149
+ return path.relative(config.root, file).split(path.sep).join("/") || ".";
150
+ }
151
+ function parseUrl(connectionString) {
152
+ try {
153
+ return new URL(connectionString);
154
+ }
155
+ catch {
156
+ // Never echo the string: it may hold a password.
157
+ throw new MonarchError("URL_INVALID", "The connection string is not a valid URL.");
158
+ }
159
+ }
160
+ /** The parts of a connection string that are safe to show. */
161
+ export function describeConnection(connectionString) {
162
+ const url = parseUrl(connectionString);
163
+ const user = decodeURIComponent(url.username);
164
+ const host = hostFromUrl(url);
165
+ const port = url.port || "5432";
166
+ const database = decodeURIComponent(url.pathname.replace(/^\//, "")) || user;
167
+ return {
168
+ user,
169
+ host,
170
+ port,
171
+ database,
172
+ target: `${user ? `${user}@` : ""}${host}:${port}/${database}`,
173
+ };
174
+ }
175
+ /**
176
+ * The host a connection will reach: `?host=` if present, else the URL's
177
+ * hostname, lowercased, without IPv6 brackets. Empty or `/`-prefixed means a
178
+ * Unix socket.
179
+ */
180
+ export function hostFromUrl(connectionString) {
181
+ const url = typeof connectionString === "string" ? parseUrl(connectionString) : connectionString;
182
+ const raw = url.searchParams.get("host") ?? url.hostname;
183
+ return raw.replace(/^\[(.*)\]$/, "$1").toLowerCase();
184
+ }
185
+ /** Same string with the database path replaced, used to reach the maintenance database. */
186
+ export function withDatabase(connectionString, database) {
187
+ const url = parseUrl(connectionString);
188
+ url.pathname = `/${encodeURIComponent(database)}`;
189
+ return url.toString();
190
+ }
191
+ /**
192
+ * Removes anything from `text` that would reveal the password in
193
+ * `connectionString`: the URL itself and the `:password@` and `password=`
194
+ * forms. The bare password is not replaced everywhere, because a password
195
+ * such as "postgres" would also mangle the user and database names.
196
+ */
197
+ export function scrub(text, connectionString) {
198
+ if (!connectionString)
199
+ return text;
200
+ let out = text.split(connectionString).join(redactUrl(connectionString));
201
+ try {
202
+ const url = new URL(connectionString);
203
+ const passwords = [url.password, url.searchParams.get("password")].filter(Boolean);
204
+ for (const pw of passwords) {
205
+ let decoded = pw;
206
+ try {
207
+ decoded = decodeURIComponent(pw);
208
+ }
209
+ catch {
210
+ // not percent-encoded
211
+ }
212
+ for (const form of new Set([pw, decoded])) {
213
+ out = out.split(`:${form}@`).join(":***@").split(`password=${form}`).join("password=***");
214
+ }
215
+ }
216
+ }
217
+ catch {
218
+ // unparseable: nothing more to extract
219
+ }
220
+ return out;
221
+ }
222
+ function redactUrl(connectionString) {
223
+ try {
224
+ return describeConnection(connectionString).target;
225
+ }
226
+ catch {
227
+ return "<connection string>";
228
+ }
229
+ }
@@ -0,0 +1,18 @@
1
+ /** The name as typed on the command line and used in identifiers. */
2
+ export declare const NAME = "monarch";
3
+ /** The name as written in prose: help text, messages, documentation. */
4
+ export declare const DISPLAY_NAME = "Monarch";
5
+ export declare const CONFIG_FILE = "monarch.json";
6
+ export declare const DEFAULT_TABLE = "monarch_migrations";
7
+ export declare const DEFAULT_DIR = "db";
8
+ export declare const DEFAULT_ENV_FILE = ".env";
9
+ export declare const DEFAULT_URL_ENV = "DATABASE_URL";
10
+ export declare const DEFAULT_ALLOWED_HOSTS: readonly string[];
11
+ /** Header line that opts a migration out of its transaction. */
12
+ export declare const NO_TRANSACTION_DIRECTIVE = "-- monarch:no-transaction";
13
+ /** Prefix of the advisory lock key: `${LOCK_PREFIX}<qualified table>`. */
14
+ export declare const LOCK_PREFIX = "monarch:";
15
+ export declare const DEBUG_ENV: string;
16
+ export declare const TEST_URL_ENV: string;
17
+ /** Databases the dev commands never drop, even with --force. */
18
+ export declare const PROTECTED_DATABASES: readonly string[];
@@ -0,0 +1,20 @@
1
+ // Everything tied to the tool's name lives here, so renaming the package is a
2
+ // change to this file (plus package.json and the README).
3
+ /** The name as typed on the command line and used in identifiers. */
4
+ export const NAME = "monarch";
5
+ /** The name as written in prose: help text, messages, documentation. */
6
+ export const DISPLAY_NAME = "Monarch";
7
+ export const CONFIG_FILE = "monarch.json";
8
+ export const DEFAULT_TABLE = "monarch_migrations";
9
+ export const DEFAULT_DIR = "db";
10
+ export const DEFAULT_ENV_FILE = ".env";
11
+ export const DEFAULT_URL_ENV = "DATABASE_URL";
12
+ export const DEFAULT_ALLOWED_HOSTS = ["localhost", "127.0.0.1", "::1"];
13
+ /** Header line that opts a migration out of its transaction. */
14
+ export const NO_TRANSACTION_DIRECTIVE = `-- ${NAME}:no-transaction`;
15
+ /** Prefix of the advisory lock key: `${LOCK_PREFIX}<qualified table>`. */
16
+ export const LOCK_PREFIX = `${NAME}:`;
17
+ export const DEBUG_ENV = `${NAME.toUpperCase()}_DEBUG`;
18
+ export const TEST_URL_ENV = `${NAME.toUpperCase()}_TEST_DATABASE_URL`;
19
+ /** Databases the dev commands never drop, even with --force. */
20
+ export const PROTECTED_DATABASES = ["postgres", "template0", "template1"];
package/dist/db.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ import pg from "pg";
2
+ import { type Config, type TableName } from "./config.ts";
3
+ import { MonarchError } from "./errors.ts";
4
+ /** A connection failure. `pgCode` is the SQLSTATE or system error code, when there is one. */
5
+ export declare class ConnectionError extends MonarchError {
6
+ readonly pgCode: string | undefined;
7
+ constructor(message: string, cause: unknown);
8
+ }
9
+ export interface Connection {
10
+ client: pg.Client;
11
+ /** Redacted `user@host:port/database`. */
12
+ target: string;
13
+ }
14
+ /** The migrations table as used in SQL. */
15
+ export interface ResolvedTable {
16
+ schema: string | null;
17
+ name: string;
18
+ /** Fully quoted name. */
19
+ sql: string;
20
+ /** `schema.name`, unquoted. */
21
+ display: string;
22
+ }
23
+ /** A row of the migrations table. */
24
+ export interface AppliedRow {
25
+ id: string;
26
+ name: string;
27
+ checksum: string;
28
+ applied_at: Date;
29
+ }
30
+ /** Quotes an SQL identifier. */
31
+ export declare function quoteIdent(name: string): string;
32
+ /**
33
+ * Opens one `pg.Client` (never a Pool: session advisory locks belong to a
34
+ * single connection). Failures are reported with the redacted target only.
35
+ */
36
+ export declare function connectTo(connectionString: string): Promise<Connection>;
37
+ /** Connects using the configured connection string. */
38
+ export declare function connect(config: Config): Promise<Connection>;
39
+ /** Ends a client, ignoring errors from an already-broken connection. */
40
+ export declare function closeQuietly(client: pg.Client): Promise<void>;
41
+ /**
42
+ * Resolves the migrations table for use in SQL. An unqualified table is pinned
43
+ * to the schema it resolves to now, so a migration that changes `search_path`
44
+ * cannot redirect the tool's own queries.
45
+ */
46
+ export declare function resolveTable(client: pg.Client, table: TableName): Promise<ResolvedTable>;
47
+ export declare function tableExists(client: pg.Client, table: ResolvedTable): Promise<boolean>;
48
+ /**
49
+ * Creates the schema (when qualified) and the migrations table. Existence is
50
+ * checked first, so a role that can use but not create in the schema still works.
51
+ */
52
+ export declare function ensureTable(client: pg.Client, table: ResolvedTable): Promise<void>;
53
+ /** Reads every applied migration. A missing table means nothing is applied. */
54
+ export declare function readApplied(client: pg.Client, table: ResolvedTable): Promise<AppliedRow[]>;
55
+ /** Records a migration. */
56
+ export declare function insertApplied(client: pg.Client, table: ResolvedTable, migration: Pick<AppliedRow, "id" | "name" | "checksum">): Promise<void>;
57
+ /**
58
+ * Takes the session-level advisory lock for this table, waiting if another
59
+ * process holds it.
60
+ * @param onWait called once if the lock is not immediately free
61
+ */
62
+ export declare function acquireLock(client: pg.Client, table: ResolvedTable, onWait?: () => void): Promise<void>;
63
+ export declare function releaseLock(client: pg.Client, table: ResolvedTable): Promise<void>;
64
+ export interface PingResult {
65
+ /** Redacted `user@host:port/database`. */
66
+ target: string;
67
+ database: string;
68
+ user: string;
69
+ version: string;
70
+ }
71
+ /** Connects and asks the server who it is. */
72
+ export declare function ping(config: Config): Promise<PingResult>;
package/dist/db.js ADDED
@@ -0,0 +1,148 @@
1
+ import pg from "pg";
2
+ import { describeConnection, requireConnectionString, scrub } from "./config.js";
3
+ import { LOCK_PREFIX } from "./constants.js";
4
+ import { MonarchError, describeError } from "./errors.js";
5
+ /** A connection failure. `pgCode` is the SQLSTATE or system error code, when there is one. */
6
+ export class ConnectionError extends MonarchError {
7
+ pgCode;
8
+ constructor(message, cause) {
9
+ super("CONNECTION_FAILED", message, { cause });
10
+ this.pgCode = cause instanceof Error && "code" in cause ? String(cause.code) : undefined;
11
+ }
12
+ }
13
+ /** Quotes an SQL identifier. */
14
+ export function quoteIdent(name) {
15
+ if (name.includes("\0"))
16
+ throw new MonarchError("CONFIG_INVALID", "Identifiers cannot contain NUL.");
17
+ return `"${name.replaceAll('"', '""')}"`;
18
+ }
19
+ /** The only row of a query that always returns one. */
20
+ function onlyRow(result) {
21
+ const [row] = result.rows;
22
+ if (row === undefined)
23
+ throw new Error("Expected the query to return a row.");
24
+ return row;
25
+ }
26
+ /**
27
+ * Opens one `pg.Client` (never a Pool: session advisory locks belong to a
28
+ * single connection). Failures are reported with the redacted target only.
29
+ */
30
+ export async function connectTo(connectionString) {
31
+ const { target } = describeConnection(connectionString);
32
+ const client = new pg.Client({ connectionString });
33
+ // An idle connection that drops would otherwise crash the process.
34
+ client.on("error", () => { });
35
+ try {
36
+ await client.connect();
37
+ }
38
+ catch (err) {
39
+ client.end().catch(() => { });
40
+ throw new ConnectionError(`Could not connect to ${target}: ${scrub(describeError(err), connectionString)}`, err);
41
+ }
42
+ return { client, target };
43
+ }
44
+ /** Connects using the configured connection string. */
45
+ export function connect(config) {
46
+ return connectTo(requireConnectionString(config));
47
+ }
48
+ /** Ends a client, ignoring errors from an already-broken connection. */
49
+ export async function closeQuietly(client) {
50
+ try {
51
+ await client.end();
52
+ }
53
+ catch {
54
+ // nothing useful to do
55
+ }
56
+ }
57
+ /**
58
+ * Resolves the migrations table for use in SQL. An unqualified table is pinned
59
+ * to the schema it resolves to now, so a migration that changes `search_path`
60
+ * cannot redirect the tool's own queries.
61
+ */
62
+ export async function resolveTable(client, table) {
63
+ let schema = table.schema;
64
+ if (!schema) {
65
+ // null when search_path matches no schema
66
+ schema = onlyRow(await client.query("select current_schema() as schema")).schema;
67
+ }
68
+ return {
69
+ schema: table.schema,
70
+ name: table.name,
71
+ sql: schema ? `${quoteIdent(schema)}.${quoteIdent(table.name)}` : quoteIdent(table.name),
72
+ display: schema ? `${schema}.${table.name}` : table.name,
73
+ };
74
+ }
75
+ export async function tableExists(client, table) {
76
+ const result = await client.query("select to_regclass($1) is not null as present", [table.sql]);
77
+ return onlyRow(result).present;
78
+ }
79
+ /**
80
+ * Creates the schema (when qualified) and the migrations table. Existence is
81
+ * checked first, so a role that can use but not create in the schema still works.
82
+ */
83
+ export async function ensureTable(client, table) {
84
+ if (table.schema) {
85
+ const { rows } = await client.query("select 1 from pg_namespace where nspname = $1", [table.schema]);
86
+ if (rows.length === 0)
87
+ await client.query(`create schema if not exists ${quoteIdent(table.schema)}`);
88
+ }
89
+ if (await tableExists(client, table))
90
+ return;
91
+ await client.query(`create table if not exists ${table.sql} (
92
+ id text primary key,
93
+ name text not null,
94
+ checksum text not null,
95
+ applied_at timestamptz not null default now()
96
+ )`);
97
+ }
98
+ /** Reads every applied migration. A missing table means nothing is applied. */
99
+ export async function readApplied(client, table) {
100
+ if (!(await tableExists(client, table)))
101
+ return [];
102
+ const { rows } = await client.query(`select id, name, checksum, applied_at from ${table.sql} order by id`);
103
+ return rows;
104
+ }
105
+ /** Records a migration. */
106
+ export async function insertApplied(client, table, migration) {
107
+ await client.query(`insert into ${table.sql} (id, name, checksum) values ($1, $2, $3)`, [
108
+ migration.id,
109
+ migration.name,
110
+ migration.checksum,
111
+ ]);
112
+ }
113
+ function lockKey(table) {
114
+ return `${LOCK_PREFIX}${table.display}`;
115
+ }
116
+ /**
117
+ * Takes the session-level advisory lock for this table, waiting if another
118
+ * process holds it.
119
+ * @param onWait called once if the lock is not immediately free
120
+ */
121
+ export async function acquireLock(client, table, onWait) {
122
+ const key = lockKey(table);
123
+ const result = await client.query("select pg_try_advisory_lock(hashtext($1)) as locked", [key]);
124
+ if (onlyRow(result).locked)
125
+ return;
126
+ onWait?.();
127
+ await client.query("select pg_advisory_lock(hashtext($1))", [key]);
128
+ }
129
+ export async function releaseLock(client, table) {
130
+ try {
131
+ await client.query("select pg_advisory_unlock(hashtext($1))", [lockKey(table)]);
132
+ }
133
+ catch {
134
+ // The connection is gone, which releases the lock anyway.
135
+ }
136
+ }
137
+ /** Connects and asks the server who it is. */
138
+ export async function ping(config) {
139
+ const { client, target } = await connect(config);
140
+ try {
141
+ const result = await client.query("select current_database() as database, current_user as user, current_setting('server_version') as version");
142
+ const { database, user, version } = onlyRow(result);
143
+ return { target, database, user, version: version.split(" ")[0] ?? version };
144
+ }
145
+ finally {
146
+ await closeQuietly(client);
147
+ }
148
+ }
@@ -0,0 +1,43 @@
1
+ import pg from "pg";
2
+ /**
3
+ * Stable identifiers for expected failures. `USAGE` marks a mistake in how the
4
+ * tool was called (CLI exit code 2).
5
+ */
6
+ export type ErrorCode = "ABORTED" | "BAD_FILENAME" | "CONFIG_INVALID" | "CONNECTION_FAILED" | "DB_EXISTS" | "DRIFT" | "DUPLICATE_ID" | "HOST_NOT_ALLOWED" | "MIGRATION_DIR_MISSING" | "MIGRATION_FAILED" | "NOT_CONFIRMED" | "OUT_OF_ORDER" | "PROTECTED_DATABASE" | "SEED_FAILED" | "SEED_MISSING" | "URL_INVALID" | "URL_MISSING" | "USAGE";
7
+ /** An expected failure, as opposed to a bug. */
8
+ export declare class MonarchError extends Error {
9
+ readonly code: ErrorCode;
10
+ constructor(code: ErrorCode, message: string, options?: ErrorOptions);
11
+ }
12
+ /** Whether `err` is a Node system error (such as `ENOENT`) with this code. */
13
+ export declare function hasErrnoCode(err: unknown, code: string): boolean;
14
+ export declare function isDatabaseError(err: unknown): err is pg.DatabaseError;
15
+ /**
16
+ * Converts the 1-based character offset Postgres reports into a line and
17
+ * column (both 1-based). Postgres counts characters, not UTF-16 units, so
18
+ * astral characters are counted once.
19
+ * @param text exactly the string that was sent to the server
20
+ */
21
+ export declare function positionToLineColumn(text: string, position: number): {
22
+ line: number;
23
+ column: number;
24
+ };
25
+ /**
26
+ * Best human-readable text for an error thrown while talking to Postgres.
27
+ * Connection failures can carry an empty message (an AggregateError when
28
+ * `localhost` resolves to several addresses).
29
+ */
30
+ export declare function describeError(err: unknown): string;
31
+ /** Where a SQL error came from, so its position can be shown. */
32
+ export interface SqlSource {
33
+ /** The exact text that was sent to the server. */
34
+ text?: string;
35
+ /** The path to show for it. */
36
+ file?: string;
37
+ }
38
+ /**
39
+ * Formats a Postgres error for display. When the error has a `position`, the
40
+ * location in `file` and the offending line with a caret are included.
41
+ * @returns the message, without the leading `error: `
42
+ */
43
+ export declare function formatSqlError(err: pg.DatabaseError, { text, file }?: SqlSource): string;