@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Sturm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Monarch
2
+
3
+ TODO.
@@ -0,0 +1,69 @@
1
+ import { type Config, type ConnectionInfo } from "./config.ts";
2
+ import { type UpEvent } from "./migrate.ts";
3
+ export interface AdminOptions {
4
+ /** Run even if the host is not in `allowedHosts`. */
5
+ force?: boolean;
6
+ }
7
+ export type ResetEvent = {
8
+ type: "dropped" | "created";
9
+ database: string;
10
+ } | {
11
+ type: "seeded";
12
+ file: string;
13
+ } | {
14
+ type: "seed_skipped";
15
+ } | UpEvent;
16
+ export interface ResetOptions extends AdminOptions {
17
+ onEvent?: (event: ResetEvent) => void;
18
+ }
19
+ export interface ResetResult {
20
+ /** False when the database did not exist yet. */
21
+ dropped: boolean;
22
+ /** Stems of the migrations applied. */
23
+ applied: string[];
24
+ seeded: boolean;
25
+ }
26
+ export interface CheckTargetOptions extends AdminOptions {
27
+ /** Shown in messages, such as `db drop`. */
28
+ command: string;
29
+ /** Also refuse system databases, even with `force`. */
30
+ destructive?: boolean;
31
+ }
32
+ /**
33
+ * Whether a host is local enough for the dev commands. An empty host or one
34
+ * starting with `/` is a Unix socket and always allowed.
35
+ */
36
+ export declare function isHostAllowed(host: string, allowedHosts: readonly string[]): boolean;
37
+ /**
38
+ * Checks that a dev command may touch the configured database, and returns
39
+ * what it will touch. Throws `HOST_NOT_ALLOWED` for a host off the allowlist
40
+ * (unless `force`) and `PROTECTED_DATABASE` for a system database when
41
+ * `destructive`, even with `force`.
42
+ */
43
+ export declare function checkTarget(config: Config, { command, force, destructive }: CheckTargetOptions): ConnectionInfo;
44
+ /** Creates the database named in the connection string. */
45
+ export declare function createDatabase(config: Config, { force }?: AdminOptions): Promise<{
46
+ database: string;
47
+ }>;
48
+ /**
49
+ * Drops the database named in the connection string, ending other sessions on
50
+ * it. Does nothing when it does not exist. Postgres 13 or newer.
51
+ */
52
+ export declare function dropDatabase(config: Config, { force }?: AdminOptions): Promise<{
53
+ database: string;
54
+ dropped: boolean;
55
+ }>;
56
+ /**
57
+ * Runs the seed file against the target database as one transaction.
58
+ * @returns the seed file, relative to the project root
59
+ */
60
+ export declare function seed(config: Config, { force }?: AdminOptions): Promise<{
61
+ file: string;
62
+ }>;
63
+ /**
64
+ * Rebuilds the dev database: drop if it exists, create, migrate, seed. There
65
+ * is no prompt here; confirming is the caller's job.
66
+ *
67
+ * Migration files are validated before anything is dropped.
68
+ */
69
+ export declare function reset(config: Config, { force, onEvent }?: ResetOptions): Promise<ResetResult>;
package/dist/admin.js ADDED
@@ -0,0 +1,169 @@
1
+ import { access } from "node:fs/promises";
2
+ import { describeConnection, displayPath, hostFromUrl, requireConnectionString, withDatabase, } from "./config.js";
3
+ import { CONFIG_FILE, PROTECTED_DATABASES } from "./constants.js";
4
+ import { closeQuietly, connect, connectTo, ConnectionError, quoteIdent } from "./db.js";
5
+ import { MonarchError, describeError, formatSqlError, hasErrnoCode, isDatabaseError } from "./errors.js";
6
+ import { discoverMigrations, readNormalized } from "./files.js";
7
+ import { upWithFiles } from "./migrate.js";
8
+ /**
9
+ * Whether a host is local enough for the dev commands. An empty host or one
10
+ * starting with `/` is a Unix socket and always allowed.
11
+ */
12
+ export function isHostAllowed(host, allowedHosts) {
13
+ if (host === "" || host.startsWith("/"))
14
+ return true;
15
+ return allowedHosts.includes(host);
16
+ }
17
+ /**
18
+ * Checks that a dev command may touch the configured database, and returns
19
+ * what it will touch. Throws `HOST_NOT_ALLOWED` for a host off the allowlist
20
+ * (unless `force`) and `PROTECTED_DATABASE` for a system database when
21
+ * `destructive`, even with `force`.
22
+ */
23
+ export function checkTarget(config, { command, force = false, destructive = false }) {
24
+ const connectionString = requireConnectionString(config);
25
+ const connection = describeConnection(connectionString);
26
+ if (destructive && PROTECTED_DATABASES.includes(connection.database)) {
27
+ throw new MonarchError("PROTECTED_DATABASE", `Refusing to run \`${command}\` against ${connection.database}: it is a system database.`);
28
+ }
29
+ const host = hostFromUrl(connectionString);
30
+ if (!force && !isHostAllowed(host, config.allowedHosts)) {
31
+ throw new MonarchError("HOST_NOT_ALLOWED", `Refusing to run \`${command}\` against ${host}: host is not in\n` +
32
+ `allowedHosts (${config.allowedHosts.join(", ")}). db commands are for local\n` +
33
+ `databases. Add the host to allowedHosts in ${CONFIG_FILE}, or pass --force.`);
34
+ }
35
+ return connection;
36
+ }
37
+ /** Connects to the maintenance database (`postgres`, falling back to `template1` when that does not exist). */
38
+ async function connectMaintenance(connectionString) {
39
+ try {
40
+ return await connectTo(withDatabase(connectionString, "postgres"));
41
+ }
42
+ catch (err) {
43
+ if (!(err instanceof ConnectionError) || err.pgCode !== "3D000")
44
+ throw err;
45
+ return connectTo(withDatabase(connectionString, "template1"));
46
+ }
47
+ }
48
+ async function databaseExists(client, database) {
49
+ const { rows } = await client.query("select 1 from pg_database where datname = $1", [database]);
50
+ return rows.length > 0;
51
+ }
52
+ /** Creates the database named in the connection string. */
53
+ export async function createDatabase(config, { force = false } = {}) {
54
+ const { database } = checkTarget(config, { command: "db create", force });
55
+ return createDatabaseUnchecked(config, database);
56
+ }
57
+ async function createDatabaseUnchecked(config, database) {
58
+ const { client } = await connectMaintenance(requireConnectionString(config));
59
+ try {
60
+ const exists = () => new MonarchError("DB_EXISTS", `Database ${database} already exists.`);
61
+ if (await databaseExists(client, database))
62
+ throw exists();
63
+ try {
64
+ await client.query(`create database ${quoteIdent(database)}`);
65
+ }
66
+ catch (err) {
67
+ if (isDatabaseError(err) && err.code === "42P04")
68
+ throw exists(); // created by someone else meanwhile
69
+ throw err;
70
+ }
71
+ return { database };
72
+ }
73
+ finally {
74
+ await closeQuietly(client);
75
+ }
76
+ }
77
+ /**
78
+ * Drops the database named in the connection string, ending other sessions on
79
+ * it. Does nothing when it does not exist. Postgres 13 or newer.
80
+ */
81
+ export async function dropDatabase(config, { force = false } = {}) {
82
+ const { database } = checkTarget(config, { command: "db drop", force, destructive: true });
83
+ return dropDatabaseUnchecked(config, database);
84
+ }
85
+ async function dropDatabaseUnchecked(config, database) {
86
+ const { client } = await connectMaintenance(requireConnectionString(config));
87
+ try {
88
+ if (!(await databaseExists(client, database)))
89
+ return { database, dropped: false };
90
+ await client.query(`drop database if exists ${quoteIdent(database)} with (force)`);
91
+ return { database, dropped: true };
92
+ }
93
+ finally {
94
+ await closeQuietly(client);
95
+ }
96
+ }
97
+ /**
98
+ * Runs the seed file against the target database as one transaction.
99
+ * @returns the seed file, relative to the project root
100
+ */
101
+ export async function seed(config, { force = false } = {}) {
102
+ checkTarget(config, { command: "db seed", force });
103
+ const text = await readSeedFile(config);
104
+ if (text === null) {
105
+ throw new MonarchError("SEED_MISSING", `Seed file not found: ${displayPath(config, config.seedFile)}`);
106
+ }
107
+ return seedWithText(config, text);
108
+ }
109
+ /** @returns normalized contents, or null if there is no seed file */
110
+ async function readSeedFile(config) {
111
+ try {
112
+ await access(config.seedFile);
113
+ }
114
+ catch (err) {
115
+ if (hasErrnoCode(err, "ENOENT"))
116
+ return null;
117
+ throw err;
118
+ }
119
+ return readNormalized(config.seedFile);
120
+ }
121
+ async function seedWithText(config, text) {
122
+ const file = displayPath(config, config.seedFile);
123
+ const { client } = await connect(config);
124
+ try {
125
+ await client.query("begin");
126
+ try {
127
+ await client.query(text);
128
+ await client.query("commit");
129
+ }
130
+ catch (err) {
131
+ await client.query("rollback").catch(() => { });
132
+ throw err;
133
+ }
134
+ return { file };
135
+ }
136
+ catch (err) {
137
+ if (err instanceof MonarchError)
138
+ throw err;
139
+ const message = isDatabaseError(err) ? formatSqlError(err, { text, file }) : describeError(err);
140
+ throw new MonarchError("SEED_FAILED", message, { cause: err });
141
+ }
142
+ finally {
143
+ await closeQuietly(client);
144
+ }
145
+ }
146
+ /**
147
+ * Rebuilds the dev database: drop if it exists, create, migrate, seed. There
148
+ * is no prompt here; confirming is the caller's job.
149
+ *
150
+ * Migration files are validated before anything is dropped.
151
+ */
152
+ export async function reset(config, { force = false, onEvent = () => { } } = {}) {
153
+ const { database } = checkTarget(config, { command: "db reset", force, destructive: true });
154
+ const files = await discoverMigrations(config.migrationsDir);
155
+ const seedText = await readSeedFile(config);
156
+ const { dropped } = await dropDatabaseUnchecked(config, database);
157
+ if (dropped)
158
+ onEvent({ type: "dropped", database });
159
+ await createDatabaseUnchecked(config, database);
160
+ onEvent({ type: "created", database });
161
+ const { applied } = await upWithFiles(config, files, { onEvent });
162
+ if (seedText === null) {
163
+ onEvent({ type: "seed_skipped" });
164
+ return { dropped, applied, seeded: false };
165
+ }
166
+ const { file } = await seedWithText(config, seedText);
167
+ onEvent({ type: "seeded", file });
168
+ return { dropped, applied, seeded: true };
169
+ }
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli.js";
3
+ process.exitCode = await main(process.argv.slice(2));
package/dist/cli.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /** Where the CLI reads from and writes to. Everything defaults to the process. */
2
+ export interface Io {
3
+ cwd?: string;
4
+ env?: NodeJS.ProcessEnv;
5
+ stdout?: {
6
+ write(text: string): unknown;
7
+ };
8
+ stderr?: {
9
+ write(text: string): unknown;
10
+ };
11
+ stdin?: NodeJS.ReadableStream & {
12
+ isTTY?: boolean;
13
+ };
14
+ }
15
+ /**
16
+ * Runs the CLI and returns the exit code. The only place that prints.
17
+ */
18
+ export declare function main(argv: string[], io?: Io): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,302 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { once } from "node:events";
3
+ import readline from "node:readline/promises";
4
+ import { parseArgs } from "node:util";
5
+ import { checkTarget, createDatabase, dropDatabase, reset, seed } from "./admin.js";
6
+ import { loadConfig, scrub } from "./config.js";
7
+ import { DEBUG_ENV, DISPLAY_NAME, NAME } from "./constants.js";
8
+ import { ping } from "./db.js";
9
+ import { MonarchError } from "./errors.js";
10
+ import { newMigration } from "./index.js";
11
+ import { MigrationFailedError, status, up } from "./migrate.js";
12
+ const OPTIONS = {
13
+ dir: { type: "string" },
14
+ table: { type: "string" },
15
+ "env-file": { type: "string" },
16
+ "url-env": { type: "string" },
17
+ "lock-timeout": { type: "string" },
18
+ config: { type: "string" },
19
+ force: { type: "boolean" },
20
+ yes: { type: "boolean" },
21
+ check: { type: "boolean" },
22
+ to: { type: "string" },
23
+ help: { type: "boolean", short: "h" },
24
+ version: { type: "boolean", short: "v" },
25
+ };
26
+ const USAGE = `${DISPLAY_NAME}: forward-only SQL migrations for Postgres.
27
+
28
+ Usage: ${NAME} <command> [options]
29
+
30
+ Commands:
31
+ ping Test the connection settings
32
+ status [--check] Show applied, pending and problem migrations
33
+ new [name] Create a migration file
34
+ up [--to <id>] Apply pending migrations
35
+ db create Create the database (dev only)
36
+ db drop Drop the database (dev only)
37
+ db seed Run seed.sql (dev only)
38
+ db reset Drop, create, migrate and seed (dev only)
39
+
40
+ Options:
41
+ --dir <path> Base folder (default: db)
42
+ --table <name> Migrations table, optionally schema-qualified (default: ${NAME}_migrations)
43
+ --env-file <path> Dotenv file to read (default: .env)
44
+ --url-env <NAME> Variable holding the connection string (default: DATABASE_URL)
45
+ --lock-timeout <value> Postgres lock_timeout for migrations, such as 5s
46
+ --config <path> Config file to read (default: ./${NAME}.json)
47
+ --check With status: exit 1 when migrations are pending
48
+ --to <id> With up: stop after this migration ID
49
+ --force Let db commands run against hosts outside allowedHosts
50
+ --yes Skip the confirmation prompt on db drop and db reset
51
+ -h, --help Show this help
52
+ -v, --version Show the version
53
+ `;
54
+ /** Flags that only make sense for one command. */
55
+ const COMMAND_FLAGS = { check: "status", to: "up" };
56
+ const DB_COMMANDS = ["create", "drop", "seed", "reset"];
57
+ /** @param date `YYYY-MM-DD HH:MM:SSZ` */
58
+ const formatTimestamp = (date) => `${date.toISOString().slice(0, 19).replace("T", " ")}Z`;
59
+ const isUsageError = (err) => err instanceof MonarchError && err.code === "USAGE";
60
+ /**
61
+ * Runs the CLI and returns the exit code. The only place that prints.
62
+ */
63
+ export async function main(argv, io = {}) {
64
+ const { cwd = process.cwd(), env = process.env, stdout = process.stdout, stderr = process.stderr } = io;
65
+ const stdin = io.stdin ?? process.stdin;
66
+ // Set once the config is loaded, so everything printed afterwards is scrubbed.
67
+ let connectionString;
68
+ const emit = (stream, text) => stream.write(`${scrub(text, connectionString)}\n`);
69
+ const out = (text = "") => emit(stdout, text);
70
+ const err = (text = "") => emit(stderr, text);
71
+ try {
72
+ return await run();
73
+ }
74
+ catch (error) {
75
+ return report(error);
76
+ }
77
+ async function run() {
78
+ let parsed;
79
+ try {
80
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
81
+ }
82
+ catch (e) {
83
+ throw new MonarchError("USAGE", e instanceof Error ? e.message : String(e));
84
+ }
85
+ const { values: flags, positionals } = parsed;
86
+ if (flags.help) {
87
+ out(USAGE.trimEnd());
88
+ return 0;
89
+ }
90
+ if (flags.version) {
91
+ const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
92
+ out(pkg.version);
93
+ return 0;
94
+ }
95
+ const [command, ...rest] = positionals;
96
+ if (!command)
97
+ throw new MonarchError("USAGE", "Missing command.");
98
+ for (const [flag, owner] of Object.entries(COMMAND_FLAGS)) {
99
+ if (flags[flag] !== undefined && command !== owner) {
100
+ throw new MonarchError("USAGE", `Unknown option '--${flag}' for \`${command}\`.`);
101
+ }
102
+ }
103
+ const load = async () => {
104
+ const config = await loadConfig({
105
+ cwd,
106
+ env,
107
+ configPath: flags.config,
108
+ overrides: {
109
+ dir: flags.dir,
110
+ table: flags.table,
111
+ envFile: flags["env-file"],
112
+ urlEnv: flags["url-env"],
113
+ lockTimeout: flags["lock-timeout"],
114
+ },
115
+ });
116
+ connectionString = config.connectionString;
117
+ return config;
118
+ };
119
+ switch (command) {
120
+ case "ping":
121
+ expectArgs(command, rest, 0);
122
+ return cmdPing(await load());
123
+ case "status":
124
+ expectArgs(command, rest, 0);
125
+ return cmdStatus(await load(), flags.check ?? false);
126
+ case "new":
127
+ expectArgs(command, rest, 0, 1);
128
+ return cmdNew(await load(), rest[0]);
129
+ case "up":
130
+ expectArgs(command, rest, 0);
131
+ return cmdUp(await load(), flags.to);
132
+ case "db": {
133
+ const [sub, ...extra] = rest;
134
+ if (!isDbCommand(sub)) {
135
+ throw new MonarchError("USAGE", sub ? `Unknown db command '${sub}'.` : `Missing db command (${DB_COMMANDS.join(", ")}).`);
136
+ }
137
+ expectArgs(`db ${sub}`, extra, 0);
138
+ return cmdDb(await load(), sub, flags);
139
+ }
140
+ default:
141
+ throw new MonarchError("USAGE", `Unknown command '${command}'.`);
142
+ }
143
+ }
144
+ function isDbCommand(value) {
145
+ return DB_COMMANDS.some((c) => c === value);
146
+ }
147
+ function expectArgs(command, args, min, max = min) {
148
+ if (args.length < min)
149
+ throw new MonarchError("USAGE", `Missing argument for \`${command}\`.`);
150
+ if (args.length > max)
151
+ throw new MonarchError("USAGE", `Unexpected argument '${args[max]}' for \`${command}\`.`);
152
+ }
153
+ /** Prints a failure and returns the exit code. */
154
+ function report(error) {
155
+ if (isUsageError(error)) {
156
+ err(`error: ${error.message}`);
157
+ err();
158
+ err(USAGE.trimEnd());
159
+ return 2;
160
+ }
161
+ if (error instanceof MigrationFailedError) {
162
+ err();
163
+ err(`error: ${error.message}`);
164
+ err();
165
+ const failed = `${error.applied.length} applied, 1 failed.`;
166
+ err(error.remaining > 0 ? `${failed} Later migrations were not attempted.` : failed);
167
+ }
168
+ else if (error instanceof MonarchError) {
169
+ err(error.code === "ABORTED" ? error.message : `error: ${error.message}`);
170
+ }
171
+ else {
172
+ err(`error: ${error instanceof Error ? error.message : String(error)}`);
173
+ if (env[DEBUG_ENV] === "1" && error instanceof Error && error.stack)
174
+ err(error.stack);
175
+ }
176
+ return 1;
177
+ }
178
+ /**
179
+ * Asks before a destructive command. Without a terminal, `--yes` is required.
180
+ * @param question what will happen, such as `This will DROP app on localhost:5432.`
181
+ */
182
+ async function confirm(question, { database, verb }, yes) {
183
+ if (yes)
184
+ return;
185
+ if (!stdin.isTTY) {
186
+ throw new MonarchError("NOT_CONFIRMED", `Refusing to ${verb} ${database} without confirmation: not running in a terminal. Pass --yes to continue.`);
187
+ }
188
+ stdout.write(`${question} Continue? [y/N] `);
189
+ const rl = readline.createInterface({ input: stdin });
190
+ try {
191
+ // Input that ends without an answer (Ctrl-D) counts as no.
192
+ const asked = rl.question("");
193
+ asked.catch(() => { });
194
+ const answer = await Promise.race([asked, once(rl, "close").then(() => "")]);
195
+ if (["y", "yes"].includes(answer.trim().toLowerCase()))
196
+ return;
197
+ }
198
+ finally {
199
+ rl.close();
200
+ }
201
+ throw new MonarchError("ABORTED", "Aborted.");
202
+ }
203
+ async function cmdPing(config) {
204
+ const result = await ping(config);
205
+ out(`Connected to ${result.target} (PostgreSQL ${result.version}) ✅`);
206
+ return 0;
207
+ }
208
+ async function cmdStatus(config, check) {
209
+ const { migrations, problems } = await status(config);
210
+ const width = Math.max(0, ...migrations.map((m) => m.stem.length)) + 3;
211
+ for (const m of migrations) {
212
+ out(m.appliedAt
213
+ ? `${m.stem.padEnd(width)}applied ${formatTimestamp(m.appliedAt)}`
214
+ : `${m.stem.padEnd(width)}pending`);
215
+ }
216
+ const applied = migrations.filter((m) => m.state === "applied").length;
217
+ const pending = migrations.length - applied;
218
+ if (migrations.length > 0)
219
+ out();
220
+ out(`${applied} applied, ${pending} pending`);
221
+ if (problems.length > 0) {
222
+ const label = { changed: "changed", missing: "missing", out_of_order: "out of order" };
223
+ out();
224
+ out("Problems:");
225
+ for (const p of problems)
226
+ out(` ${label[p.kind].padEnd(14)}${p.stem} (${p.detail})`);
227
+ }
228
+ return problems.length > 0 || (check && pending > 0) ? 1 : 0;
229
+ }
230
+ async function cmdNew(config, name) {
231
+ const created = await newMigration(config, { name });
232
+ out(`Created ${created.relativePath}`);
233
+ return 0;
234
+ }
235
+ /** Prints progress lines as `up` and `db reset` work. */
236
+ function progress(event) {
237
+ switch (event.type) {
238
+ case "waiting_for_lock":
239
+ out(`Waiting for another ${DISPLAY_NAME} process to finish...`);
240
+ break;
241
+ case "applied":
242
+ out(`${event.stem} applied ✅`);
243
+ break;
244
+ case "failed":
245
+ out(`${event.stem} ERROR ❌`);
246
+ break;
247
+ case "dropped":
248
+ out(`Dropped ${event.database}`);
249
+ break;
250
+ case "created":
251
+ out(`Created ${event.database}`);
252
+ break;
253
+ case "seeded":
254
+ out(`Seeded from ${event.file} ✅`);
255
+ break;
256
+ case "seed_skipped":
257
+ out("No seed file, skipping.");
258
+ break;
259
+ }
260
+ }
261
+ async function cmdUp(config, to) {
262
+ const result = await up(config, { to, onEvent: progress });
263
+ if (result.alreadyApplied) {
264
+ out(`${result.alreadyApplied} is already applied. Nothing to do.`);
265
+ }
266
+ else if (result.applied.length === 0) {
267
+ out("Nothing to apply. Database is up to date.");
268
+ }
269
+ else {
270
+ out(`${result.applied.length} applied.`);
271
+ }
272
+ return 0;
273
+ }
274
+ async function cmdDb(config, sub, flags) {
275
+ const force = flags.force ?? false;
276
+ switch (sub) {
277
+ case "create": {
278
+ const { database } = await createDatabase(config, { force });
279
+ out(`Created ${database}`);
280
+ return 0;
281
+ }
282
+ case "drop": {
283
+ const target = checkTarget(config, { command: "db drop", force, destructive: true });
284
+ await confirm(`This will DROP ${target.database} on ${target.host}:${target.port}.`, { database: target.database, verb: "drop" }, flags.yes);
285
+ const { database, dropped } = await dropDatabase(config, { force });
286
+ out(dropped ? `Dropped ${database}` : `Database ${database} does not exist.`);
287
+ return 0;
288
+ }
289
+ case "seed": {
290
+ const { file } = await seed(config, { force });
291
+ out(`Seeded from ${file} ✅`);
292
+ return 0;
293
+ }
294
+ case "reset": {
295
+ const target = checkTarget(config, { command: "db reset", force, destructive: true });
296
+ await confirm(`This will DROP and recreate ${target.database} on ${target.host}:${target.port}.`, { database: target.database, verb: "reset" }, flags.yes);
297
+ await reset(config, { force, onEvent: progress });
298
+ return 0;
299
+ }
300
+ }
301
+ }
302
+ }