@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.
package/dist/errors.js ADDED
@@ -0,0 +1,79 @@
1
+ import pg from "pg";
2
+ /** An expected failure, as opposed to a bug. */
3
+ export class MonarchError extends Error {
4
+ code;
5
+ constructor(code, message, options) {
6
+ super(message, options);
7
+ this.name = "MonarchError";
8
+ this.code = code;
9
+ }
10
+ }
11
+ /** Whether `err` is a Node system error (such as `ENOENT`) with this code. */
12
+ export function hasErrnoCode(err, code) {
13
+ return err instanceof Error && "code" in err && err.code === code;
14
+ }
15
+ export function isDatabaseError(err) {
16
+ return err instanceof pg.DatabaseError;
17
+ }
18
+ /**
19
+ * Converts the 1-based character offset Postgres reports into a line and
20
+ * column (both 1-based). Postgres counts characters, not UTF-16 units, so
21
+ * astral characters are counted once.
22
+ * @param text exactly the string that was sent to the server
23
+ */
24
+ export function positionToLineColumn(text, position) {
25
+ const before = [...text].slice(0, Math.max(0, position - 1)).join("");
26
+ const lines = before.split("\n");
27
+ const last = lines[lines.length - 1] ?? "";
28
+ return { line: lines.length, column: [...last].length + 1 };
29
+ }
30
+ /**
31
+ * Best human-readable text for an error thrown while talking to Postgres.
32
+ * Connection failures can carry an empty message (an AggregateError when
33
+ * `localhost` resolves to several addresses).
34
+ */
35
+ export function describeError(err) {
36
+ if (!(err instanceof Error))
37
+ return String(err);
38
+ if (err.message)
39
+ return err.message;
40
+ if ("errors" in err && Array.isArray(err.errors)) {
41
+ const nested = err.errors.map((e) => (e instanceof Error ? e.message || codeOf(e) : undefined));
42
+ const messages = [...new Set(nested.filter(Boolean))];
43
+ if (messages.length > 0)
44
+ return messages.join("; ");
45
+ }
46
+ return codeOf(err) ?? String(err);
47
+ }
48
+ function codeOf(err) {
49
+ return "code" in err && typeof err.code === "string" ? err.code : undefined;
50
+ }
51
+ /**
52
+ * Formats a Postgres error for display. When the error has a `position`, the
53
+ * location in `file` and the offending line with a caret are included.
54
+ * @returns the message, without the leading `error: `
55
+ */
56
+ export function formatSqlError(err, { text, file } = {}) {
57
+ const out = [`${err.message}${err.code ? ` [${err.code}]` : ""}`];
58
+ const position = Number.parseInt(err.position ?? "", 10);
59
+ if (text !== undefined && file && position > 0) {
60
+ const { line, column } = positionToLineColumn(text, position);
61
+ const sourceLine = text.split("\n")[line - 1] ?? "";
62
+ const gutter = String(line);
63
+ // Keep tabs in the caret padding so the caret lines up in a terminal.
64
+ const pad = [...sourceLine]
65
+ .slice(0, column - 1)
66
+ .map((ch) => (ch === "\t" ? "\t" : " "))
67
+ .join("");
68
+ out.push(` at ${file}:${line}:${column}`, "", ` ${gutter} | ${sourceLine}`, ` ${" ".repeat(gutter.length)} | ${pad}^`);
69
+ }
70
+ if (err.detail)
71
+ out.push(`detail: ${err.detail}`);
72
+ if (err.hint)
73
+ out.push(`hint: ${err.hint}`);
74
+ if (err.internalQuery) {
75
+ const where = err.internalPosition ? ` (position ${err.internalPosition})` : "";
76
+ out.push(`context: ${err.internalQuery}${where}`);
77
+ }
78
+ return out.join("\n");
79
+ }
@@ -0,0 +1,64 @@
1
+ import { MonarchError } from "./errors.ts";
2
+ export interface MigrationName {
3
+ /** 14-digit UTC timestamp. */
4
+ id: string;
5
+ /** Slug, or "" when unnamed. */
6
+ name: string;
7
+ /** Filename without `.sql`. */
8
+ stem: string;
9
+ }
10
+ export interface MigrationFile extends MigrationName {
11
+ /** Absolute path. */
12
+ path: string;
13
+ /** Normalized contents. */
14
+ text: string;
15
+ /** SHA-256 hex of `text`. */
16
+ checksum: string;
17
+ noTransaction: boolean;
18
+ }
19
+ /** Several problems with the files in the migrations directory, reported together. */
20
+ export declare class FileErrors extends MonarchError {
21
+ readonly errors: readonly MonarchError[];
22
+ constructor(errors: readonly [MonarchError, ...MonarchError[]]);
23
+ }
24
+ /**
25
+ * Normalizes file contents before hashing or running: strips a leading BOM and
26
+ * converts CRLF and lone CR to LF.
27
+ */
28
+ export declare function normalize(text: string): string;
29
+ export declare function checksum(normalizedText: string): string;
30
+ /** Reads a file as UTF-8 and normalizes it. */
31
+ export declare function readNormalized(file: string): Promise<string>;
32
+ /**
33
+ * Turns a free-form name into a slug. Returns "" for an empty or missing name
34
+ * (an unnamed migration). Throws a usage error when a non-empty name has no
35
+ * usable characters.
36
+ */
37
+ export declare function slugify(input: string | undefined): string;
38
+ export declare function parseFilename(filename: string): MigrationName | null;
39
+ /**
40
+ * True when the leading comment block holds the exact no-transaction line.
41
+ * Scanning stops at the first line that is neither blank nor a `--` comment.
42
+ * @param text normalized contents
43
+ */
44
+ export declare function hasNoTransactionDirective(text: string): boolean;
45
+ /**
46
+ * Finds, reads and validates every migration. All file problems are collected
47
+ * and thrown together, so the user can fix them in one pass.
48
+ * @returns the migrations in ID order
49
+ */
50
+ export declare function discoverMigrations(migrationsDir: string): Promise<MigrationFile[]>;
51
+ /** `YYYYMMDDHHMMSS` in UTC. */
52
+ export declare function formatId(date: Date): string;
53
+ /**
54
+ * @param name slug, or "" for an unnamed file
55
+ */
56
+ export declare function migrationTemplate(id: string, name: string): string;
57
+ export interface CreateMigrationOptions {
58
+ name?: string;
59
+ now?: Date;
60
+ }
61
+ /** Creates a new migration file, never overwriting an existing one. */
62
+ export declare function createMigrationFile(migrationsDir: string, { name, now }?: CreateMigrationOptions): Promise<MigrationName & {
63
+ path: string;
64
+ }>;
package/dist/files.js ADDED
@@ -0,0 +1,178 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { NAME, NO_TRANSACTION_DIRECTIVE } from "./constants.js";
5
+ import { MonarchError, hasErrnoCode } from "./errors.js";
6
+ const FILENAME = /^(\d{14})(?:-([a-z0-9]+(?:-[a-z0-9]+)*))?\.sql$/;
7
+ /** Several problems with the files in the migrations directory, reported together. */
8
+ export class FileErrors extends MonarchError {
9
+ errors;
10
+ constructor(errors) {
11
+ super(errors[0].code, errors.map((e) => e.message).join("\n"));
12
+ this.errors = errors;
13
+ }
14
+ }
15
+ /**
16
+ * Normalizes file contents before hashing or running: strips a leading BOM and
17
+ * converts CRLF and lone CR to LF.
18
+ */
19
+ export function normalize(text) {
20
+ return text.replace(/^/, "").replace(/\r\n?/g, "\n");
21
+ }
22
+ export function checksum(normalizedText) {
23
+ return createHash("sha256").update(normalizedText, "utf8").digest("hex");
24
+ }
25
+ /** Reads a file as UTF-8 and normalizes it. */
26
+ export async function readNormalized(file) {
27
+ return normalize(await readFile(file, "utf8"));
28
+ }
29
+ /**
30
+ * Turns a free-form name into a slug. Returns "" for an empty or missing name
31
+ * (an unnamed migration). Throws a usage error when a non-empty name has no
32
+ * usable characters.
33
+ */
34
+ export function slugify(input) {
35
+ if (input === undefined || input === "")
36
+ return "";
37
+ const slug = input
38
+ .toLowerCase()
39
+ .replace(/[^a-z0-9]+/g, "-")
40
+ .replace(/^-+|-+$/g, "");
41
+ if (slug === "") {
42
+ throw new MonarchError("USAGE", `The name ${JSON.stringify(input)} has no letters or digits to build a filename from.`);
43
+ }
44
+ return slug;
45
+ }
46
+ export function parseFilename(filename) {
47
+ const match = FILENAME.exec(filename);
48
+ if (!match)
49
+ return null;
50
+ return { id: match[1], name: match[2] ?? "", stem: filename.slice(0, -".sql".length) };
51
+ }
52
+ /**
53
+ * True when the leading comment block holds the exact no-transaction line.
54
+ * Scanning stops at the first line that is neither blank nor a `--` comment.
55
+ * @param text normalized contents
56
+ */
57
+ export function hasNoTransactionDirective(text) {
58
+ for (const raw of text.split("\n")) {
59
+ const line = raw.trim();
60
+ if (line === "")
61
+ continue;
62
+ if (!line.startsWith("--"))
63
+ return false;
64
+ if (line === NO_TRANSACTION_DIRECTIVE)
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+ /**
70
+ * Finds, reads and validates every migration. All file problems are collected
71
+ * and thrown together, so the user can fix them in one pass.
72
+ * @returns the migrations in ID order
73
+ */
74
+ export async function discoverMigrations(migrationsDir) {
75
+ let entries;
76
+ try {
77
+ entries = await readdir(migrationsDir);
78
+ }
79
+ catch (err) {
80
+ if (hasErrnoCode(err, "ENOENT") || hasErrnoCode(err, "ENOTDIR")) {
81
+ throw new MonarchError("MIGRATION_DIR_MISSING", `Migrations directory not found: ${migrationsDir}. Run \`${NAME} new\` to create it.`);
82
+ }
83
+ throw err;
84
+ }
85
+ const problems = [];
86
+ const seen = new Map(); // id -> filename
87
+ const migrations = [];
88
+ for (const filename of entries.sort()) {
89
+ if (!filename.endsWith(".sql"))
90
+ continue;
91
+ const file = path.join(migrationsDir, filename);
92
+ if ((await stat(file)).isDirectory())
93
+ continue;
94
+ const parsed = parseFilename(filename);
95
+ if (!parsed) {
96
+ problems.push(new MonarchError("BAD_FILENAME", `Bad migration filename: ${filename}. Expected <14-digit UTC timestamp>[-<lowercase-slug>].sql, ` +
97
+ "such as 20261125143000-add-users.sql."));
98
+ continue;
99
+ }
100
+ const duplicateOf = seen.get(parsed.id);
101
+ if (duplicateOf !== undefined) {
102
+ problems.push(new MonarchError("DUPLICATE_ID", `Duplicate migration ID ${parsed.id}: ${duplicateOf} and ${filename}.`));
103
+ continue;
104
+ }
105
+ seen.set(parsed.id, filename);
106
+ const text = await readNormalized(file);
107
+ migrations.push({
108
+ ...parsed,
109
+ path: file,
110
+ text,
111
+ checksum: checksum(text),
112
+ noTransaction: hasNoTransactionDirective(text),
113
+ });
114
+ }
115
+ const [first, ...rest] = problems;
116
+ if (first)
117
+ throw rest.length === 0 ? first : new FileErrors([first, ...rest]);
118
+ return migrations.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
119
+ }
120
+ /** `YYYYMMDDHHMMSS` in UTC. */
121
+ export function formatId(date) {
122
+ return date.toISOString().slice(0, 19).replace(/[-T:]/g, "");
123
+ }
124
+ function parseId(id) {
125
+ const part = (start, end) => Number(id.slice(start, end));
126
+ return new Date(Date.UTC(part(0, 4), part(4, 6) - 1, part(6, 8), part(8, 10), part(10, 12), part(12, 14)));
127
+ }
128
+ /**
129
+ * IDs already taken in a directory, going by filename prefix only so that
130
+ * files with otherwise bad names still reserve their ID.
131
+ */
132
+ async function takenIds(migrationsDir) {
133
+ try {
134
+ const names = await readdir(migrationsDir);
135
+ return new Set(names.flatMap((n) => /^(\d{14})/.exec(n)?.[1] ?? []));
136
+ }
137
+ catch (err) {
138
+ if (hasErrnoCode(err, "ENOENT"))
139
+ return new Set();
140
+ throw err;
141
+ }
142
+ }
143
+ /**
144
+ * @param name slug, or "" for an unnamed file
145
+ */
146
+ export function migrationTemplate(id, name) {
147
+ return [
148
+ `-- ${name ? `${id}-${name}` : id}`,
149
+ "-- Runs in a transaction. To opt out, add a line reading exactly:",
150
+ `-- ${NO_TRANSACTION_DIRECTIVE}`,
151
+ "-- to this header. Opted-out files must contain a single statement.",
152
+ "",
153
+ "",
154
+ ].join("\n");
155
+ }
156
+ /** Creates a new migration file, never overwriting an existing one. */
157
+ export async function createMigrationFile(migrationsDir, { name, now = new Date() } = {}) {
158
+ const slug = slugify(name);
159
+ await mkdir(migrationsDir, { recursive: true });
160
+ const taken = await takenIds(migrationsDir);
161
+ let when = now;
162
+ for (;;) {
163
+ const id = formatId(when);
164
+ if (!taken.has(id)) {
165
+ const stem = slug ? `${id}-${slug}` : id;
166
+ const file = path.join(migrationsDir, `${stem}.sql`);
167
+ try {
168
+ await writeFile(file, migrationTemplate(id, slug), { flag: "wx" });
169
+ return { id, name: slug, stem, path: file };
170
+ }
171
+ catch (err) {
172
+ if (!hasErrnoCode(err, "EEXIST"))
173
+ throw err;
174
+ }
175
+ }
176
+ when = new Date(parseId(formatId(when)).getTime() + 1000);
177
+ }
178
+ }
@@ -0,0 +1,21 @@
1
+ import { type Config } from "./config.ts";
2
+ import { type CreateMigrationOptions, type MigrationName } from "./files.ts";
3
+ export { loadConfig } from "./config.ts";
4
+ export { ping } from "./db.ts";
5
+ export { status, up, HistoryError, MigrationFailedError } from "./migrate.ts";
6
+ export { createDatabase, dropDatabase, seed, reset } from "./admin.ts";
7
+ export { MonarchError } from "./errors.ts";
8
+ export type { Config, ConnectionInfo, LoadConfigOptions, Settings, TableName } from "./config.ts";
9
+ export type { PingResult } from "./db.ts";
10
+ export type { AdminOptions, ResetEvent, ResetOptions, ResetResult } from "./admin.ts";
11
+ export type { ErrorCode } from "./errors.ts";
12
+ export type { MigrationName } from "./files.ts";
13
+ export type { MigrationStatus, Problem, Status, UpEvent, UpOptions, UpResult } from "./migrate.ts";
14
+ export interface NewMigration extends MigrationName {
15
+ /** Absolute path. */
16
+ path: string;
17
+ /** Path relative to the project root, with forward slashes. */
18
+ relativePath: string;
19
+ }
20
+ /** Creates a new migration file. Needs no database connection. */
21
+ export declare function newMigration(config: Config, options?: CreateMigrationOptions): Promise<NewMigration>;
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import { displayPath } from "./config.js";
2
+ import { createMigrationFile } from "./files.js";
3
+ export { loadConfig } from "./config.js";
4
+ export { ping } from "./db.js";
5
+ export { status, up, HistoryError, MigrationFailedError } from "./migrate.js";
6
+ export { createDatabase, dropDatabase, seed, reset } from "./admin.js";
7
+ export { MonarchError } from "./errors.js";
8
+ /** Creates a new migration file. Needs no database connection. */
9
+ export async function newMigration(config, options = {}) {
10
+ const created = await createMigrationFile(config.migrationsDir, options);
11
+ return { ...created, relativePath: displayPath(config, created.path) };
12
+ }
@@ -0,0 +1,95 @@
1
+ import { type Config } from "./config.ts";
2
+ import { type AppliedRow } from "./db.ts";
3
+ import { MonarchError } from "./errors.ts";
4
+ import { type MigrationFile } from "./files.ts";
5
+ export interface MigrationStatus {
6
+ id: string;
7
+ name: string;
8
+ stem: string;
9
+ /** Absolute path. */
10
+ path: string;
11
+ state: "applied" | "pending";
12
+ appliedAt?: Date;
13
+ }
14
+ /** Something wrong with the history that stops `up`. */
15
+ export type Problem = {
16
+ kind: "changed" | "missing";
17
+ id: string;
18
+ stem: string;
19
+ detail: string;
20
+ } | {
21
+ kind: "out_of_order";
22
+ id: string;
23
+ stem: string;
24
+ detail: string;
25
+ latestApplied: string;
26
+ };
27
+ export interface Status {
28
+ migrations: MigrationStatus[];
29
+ problems: Problem[];
30
+ }
31
+ export interface Plan extends Status {
32
+ /** Migrations to apply, in ID order. */
33
+ pending: MigrationFile[];
34
+ }
35
+ export type UpEvent = {
36
+ type: "waiting_for_lock";
37
+ } | {
38
+ type: "applied";
39
+ stem: string;
40
+ } | {
41
+ type: "failed";
42
+ stem: string;
43
+ error: unknown;
44
+ };
45
+ export interface UpOptions {
46
+ /** Stop after this migration ID. */
47
+ to?: string;
48
+ onEvent?: (event: UpEvent) => void;
49
+ }
50
+ export interface UpResult {
51
+ /** Stems of the migrations applied by this run. */
52
+ applied: string[];
53
+ /** Set when `to` named a migration that was already applied. */
54
+ alreadyApplied?: string;
55
+ }
56
+ /** The history is inconsistent: edited or deleted migrations (`DRIFT`), or ones out of order (`OUT_OF_ORDER`). */
57
+ export declare class HistoryError extends MonarchError {
58
+ readonly problems: readonly Problem[];
59
+ constructor(problems: readonly Problem[]);
60
+ }
61
+ /** A migration failed. Earlier ones in the run stay applied. */
62
+ export declare class MigrationFailedError extends MonarchError {
63
+ /** Stems applied before the failure. */
64
+ readonly applied: readonly string[];
65
+ /** Stem of the migration that failed. */
66
+ readonly failed: string;
67
+ /** How many pending migrations were not attempted. */
68
+ readonly remaining: number;
69
+ constructor(message: string, details: {
70
+ applied: readonly string[];
71
+ failed: string;
72
+ remaining: number;
73
+ }, options: ErrorOptions);
74
+ }
75
+ /**
76
+ * Compares migration files with the rows of the migrations table. Pure: no
77
+ * I/O, so every rule can be unit tested.
78
+ * @param files in ID order
79
+ */
80
+ export declare function plan(files: readonly MigrationFile[], rows: readonly AppliedRow[]): Plan;
81
+ /**
82
+ * Reports the state of every migration. Read-only: takes no lock and never
83
+ * creates the table.
84
+ */
85
+ export declare function status(config: Config): Promise<Status>;
86
+ /**
87
+ * Applies pending migrations in ID order, one transaction each, while holding
88
+ * an advisory lock. Everything is validated before the first statement runs.
89
+ *
90
+ * Throws a `HistoryError` (`DRIFT` or `OUT_OF_ORDER`) when history is
91
+ * inconsistent, or a `MigrationFailedError` when a migration fails.
92
+ */
93
+ export declare function up(config: Config, options?: UpOptions): Promise<UpResult>;
94
+ /** `up` for callers that have already discovered the files. */
95
+ export declare function upWithFiles(config: Config, files: readonly MigrationFile[], { to, onEvent }: UpOptions): Promise<UpResult>;
@@ -0,0 +1,234 @@
1
+ import { displayPath } from "./config.js";
2
+ import { NAME } from "./constants.js";
3
+ import { acquireLock, closeQuietly, connect, ensureTable, insertApplied, readApplied, releaseLock, resolveTable, } from "./db.js";
4
+ import { MonarchError, describeError, formatSqlError, isDatabaseError } from "./errors.js";
5
+ import { discoverMigrations } from "./files.js";
6
+ /** The history is inconsistent: edited or deleted migrations (`DRIFT`), or ones out of order (`OUT_OF_ORDER`). */
7
+ export class HistoryError extends MonarchError {
8
+ problems;
9
+ constructor(problems) {
10
+ const drift = problems.some((p) => p.kind !== "out_of_order");
11
+ super(drift ? "DRIFT" : "OUT_OF_ORDER", problems.map(explain).join("\n\n"));
12
+ this.problems = problems;
13
+ }
14
+ }
15
+ /** A migration failed. Earlier ones in the run stay applied. */
16
+ export class MigrationFailedError extends MonarchError {
17
+ /** Stems applied before the failure. */
18
+ applied;
19
+ /** Stem of the migration that failed. */
20
+ failed;
21
+ /** How many pending migrations were not attempted. */
22
+ remaining;
23
+ constructor(message, details, options) {
24
+ super("MIGRATION_FAILED", message, options);
25
+ this.applied = details.applied;
26
+ this.failed = details.failed;
27
+ this.remaining = details.remaining;
28
+ }
29
+ }
30
+ /** The statement of a no-transaction migration ran, but recording it failed. */
31
+ class UnrecordedError extends Error {
32
+ constructor(cause) {
33
+ super("Recording the migration failed.", { cause });
34
+ }
35
+ }
36
+ const stemOf = (id, name) => (name ? `${id}-${name}` : id);
37
+ const day = (date) => date.toISOString().slice(0, 10);
38
+ /**
39
+ * Compares migration files with the rows of the migrations table. Pure: no
40
+ * I/O, so every rule can be unit tested.
41
+ * @param files in ID order
42
+ */
43
+ export function plan(files, rows) {
44
+ const byId = new Map(files.map((f) => [f.id, f]));
45
+ const applied = new Map(rows.map((r) => [r.id, r]));
46
+ const maxApplied = rows.reduce((max, r) => (r.id > max ? r.id : max), "");
47
+ const problems = [];
48
+ for (const row of rows) {
49
+ const file = byId.get(row.id);
50
+ if (!file) {
51
+ problems.push({
52
+ kind: "missing",
53
+ id: row.id,
54
+ stem: stemOf(row.id, row.name),
55
+ detail: `applied ${day(row.applied_at)}, file not found`,
56
+ });
57
+ }
58
+ else if (file.checksum !== row.checksum) {
59
+ problems.push({
60
+ kind: "changed",
61
+ id: row.id,
62
+ stem: file.stem,
63
+ detail: `applied ${day(row.applied_at)}, file edited since`,
64
+ });
65
+ }
66
+ }
67
+ const pending = files.filter((f) => !applied.has(f.id));
68
+ for (const file of pending) {
69
+ if (file.id < maxApplied) {
70
+ problems.push({
71
+ kind: "out_of_order",
72
+ id: file.id,
73
+ stem: file.stem,
74
+ detail: `older than latest applied ${maxApplied}`,
75
+ latestApplied: maxApplied,
76
+ });
77
+ }
78
+ }
79
+ const order = { missing: 0, changed: 1, out_of_order: 2 };
80
+ problems.sort((a, b) => order[a.kind] - order[b.kind] || (a.id < b.id ? -1 : 1));
81
+ const migrations = files.map((file) => {
82
+ const row = applied.get(file.id);
83
+ const { id, name, stem, path } = file;
84
+ return row
85
+ ? { id, name, stem, path, state: "applied", appliedAt: row.applied_at }
86
+ : { id, name, stem, path, state: "pending" };
87
+ });
88
+ return { migrations, problems, pending };
89
+ }
90
+ /**
91
+ * Reports the state of every migration. Read-only: takes no lock and never
92
+ * creates the table.
93
+ */
94
+ export async function status(config) {
95
+ const files = await discoverMigrations(config.migrationsDir);
96
+ const { client } = await connect(config);
97
+ try {
98
+ const table = await resolveTable(client, config.table);
99
+ const { migrations, problems } = plan(files, await readApplied(client, table));
100
+ return { migrations, problems };
101
+ }
102
+ finally {
103
+ await closeQuietly(client);
104
+ }
105
+ }
106
+ /** Explains a problem in full, with what to do about it. */
107
+ function explain(problem) {
108
+ switch (problem.kind) {
109
+ case "changed":
110
+ return (`Changed migration: ${problem.stem} was edited after it was applied (${problem.detail}). ` +
111
+ "Applied migrations are immutable: restore the file, and put the change in a new migration.");
112
+ case "missing":
113
+ return (`Missing migration: ${problem.stem} is recorded as applied (${problem.detail}). ` +
114
+ "Applied migrations cannot be deleted: restore the file.");
115
+ case "out_of_order": {
116
+ const slug = problem.stem.slice(problem.id.length + 1);
117
+ return (`Out-of-order migration: ${problem.stem} is older than the latest\n` +
118
+ `applied migration (${problem.latestApplied}). Rename it with a newer timestamp,\n` +
119
+ `for example by moving its contents into a file from \`${NAME} new${slug ? ` ${slug}` : ""}\`.\n` +
120
+ `In dev, then run \`${NAME} db reset\`.`);
121
+ }
122
+ }
123
+ }
124
+ /** Runs one migration inside its own transaction and records it. */
125
+ async function applyTransactional(client, table, migration) {
126
+ await client.query("begin");
127
+ try {
128
+ await client.query(migration.text);
129
+ await insertApplied(client, table, migration);
130
+ await client.query("commit");
131
+ }
132
+ catch (err) {
133
+ await client.query("rollback").catch(() => { });
134
+ throw err;
135
+ }
136
+ }
137
+ /** Runs a migration with no transaction, then records it on its own. */
138
+ async function applyUnwrapped(client, table, migration) {
139
+ await client.query(migration.text);
140
+ try {
141
+ await insertApplied(client, table, migration);
142
+ }
143
+ catch (err) {
144
+ throw new UnrecordedError(err);
145
+ }
146
+ }
147
+ /**
148
+ * Applies pending migrations in ID order, one transaction each, while holding
149
+ * an advisory lock. Everything is validated before the first statement runs.
150
+ *
151
+ * Throws a `HistoryError` (`DRIFT` or `OUT_OF_ORDER`) when history is
152
+ * inconsistent, or a `MigrationFailedError` when a migration fails.
153
+ */
154
+ export async function up(config, options = {}) {
155
+ const files = await discoverMigrations(config.migrationsDir);
156
+ return upWithFiles(config, files, options);
157
+ }
158
+ /** `up` for callers that have already discovered the files. */
159
+ export async function upWithFiles(config, files, { to, onEvent = () => { } }) {
160
+ let target;
161
+ if (to !== undefined) {
162
+ if (!/^\d{14}$/.test(to)) {
163
+ throw new MonarchError("USAGE", `--to takes a 14-digit migration ID, not ${JSON.stringify(to)}.`);
164
+ }
165
+ target = files.find((f) => f.id === to);
166
+ if (!target) {
167
+ throw new MonarchError("USAGE", `No migration file with ID ${to} in ${displayPath(config, config.migrationsDir)}.`);
168
+ }
169
+ }
170
+ const { client } = await connect(config);
171
+ let table;
172
+ try {
173
+ table = await resolveTable(client, config.table);
174
+ await acquireLock(client, table, () => onEvent({ type: "waiting_for_lock" }));
175
+ // After the lock, so the timeout bounds migration statements and not the
176
+ // wait for another `up`.
177
+ if (config.lockTimeout) {
178
+ try {
179
+ await client.query("select set_config('lock_timeout', $1, false)", [config.lockTimeout]);
180
+ }
181
+ catch (err) {
182
+ throw new MonarchError("CONFIG_INVALID", `Invalid lockTimeout ${JSON.stringify(config.lockTimeout)}: ${describeError(err)}`);
183
+ }
184
+ }
185
+ await ensureTable(client, table);
186
+ const rows = await readApplied(client, table);
187
+ const { problems, pending: allPending } = plan(files, rows);
188
+ if (problems.length > 0)
189
+ throw new HistoryError(problems);
190
+ let pending = allPending;
191
+ if (target) {
192
+ const targetId = target.id;
193
+ if (rows.some((r) => r.id === targetId))
194
+ return { applied: [], alreadyApplied: target.stem };
195
+ pending = allPending.slice(0, allPending.findIndex((f) => f.id === targetId) + 1);
196
+ }
197
+ const applied = [];
198
+ for (const migration of pending) {
199
+ try {
200
+ if (migration.noTransaction)
201
+ await applyUnwrapped(client, table, migration);
202
+ else
203
+ await applyTransactional(client, table, migration);
204
+ }
205
+ catch (err) {
206
+ const cause = err instanceof UnrecordedError ? err.cause : err;
207
+ onEvent({ type: "failed", stem: migration.stem, error: cause });
208
+ throw migrationFailure(config, migration, err, { applied, remaining: pending.length - applied.length - 1 });
209
+ }
210
+ applied.push(migration.stem);
211
+ onEvent({ type: "applied", stem: migration.stem });
212
+ }
213
+ return { applied };
214
+ }
215
+ finally {
216
+ if (table)
217
+ await releaseLock(client, table);
218
+ await closeQuietly(client);
219
+ }
220
+ }
221
+ function migrationFailure(config, migration, err, progress) {
222
+ const unrecorded = err instanceof UnrecordedError;
223
+ const cause = unrecorded ? err.cause : err;
224
+ let message = isDatabaseError(cause)
225
+ ? formatSqlError(cause, { text: migration.text, file: displayPath(config, migration.path) })
226
+ : describeError(cause);
227
+ if (unrecorded) {
228
+ message +=
229
+ `\nThe statement in ${migration.stem} ran, but recording it failed. ` +
230
+ "The change is applied but not recorded; fix the cause and run `up` again " +
231
+ "(the migration must be safe to run twice).";
232
+ }
233
+ return new MigrationFailedError(message, { ...progress, failed: migration.stem }, { cause });
234
+ }