symmetria-kit 3.2.0 → 3.4.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/README.md CHANGED
@@ -45,6 +45,7 @@ export default defineMigrationConfig({
45
45
  | `diff` | Compare source schema to the latest local snapshot |
46
46
  | `lint` | Check saved SQL and ungenerated changes; fail on unsafe findings |
47
47
  | `generate <name>` | Generate migration SQL and metadata |
48
+ | `discard [id]` | Take back the latest migration while no database has applied it |
48
49
  | `migrate` | Apply pending migrations atomically |
49
50
  | `status` | Show applied/pending migrations |
50
51
  | `rollback` | Revert the latest migration |
@@ -82,7 +83,7 @@ export default defineMigrationConfig({
82
83
  | `--advisory-lock-timeout <ms>` | commands that run migrations | Migration lock wait (`advisoryLockTimeoutMs`, default 10000) |
83
84
  | `--lock-timeout <ms>` | commands that run migrations | DDL lock wait (`lockTimeoutMs`, default 5000; 0 disables) |
84
85
  | `--statement-timeout <ms>` | commands that run migrations | Statement duration (`statementTimeoutMs`, default 600000; no default limit in `transaction: "none"` migrations) |
85
- | `--force` | `pull`, `graph` | Overwrite the written file |
86
+ | `--force` | `pull`, `graph`, `discard` | Overwrite the written file; `discard`: no database to ask, or an `up.sql` edited after generation |
86
87
  | `--compact` | `graph` | Entities and relations without column lists |
87
88
  | `--relations` | `inspect` | Start on, or list, the relations |
88
89
  | `--profile-url <url>` | `profile` | Profiler endpoint (default `http://127.0.0.1:7331`) |
@@ -108,10 +109,26 @@ and both JSON files together. `diff` compares snapshots, not live DB drift.
108
109
  </picture>
109
110
 
110
111
  The snapshot holds the latest generated schema. The journal holds IDs, parents
111
- and schema hashes for the whole chain, without historical snapshot copies.
112
- Generation updates the same two files; migrate/rollback only change database
113
- history and use `up.sql`/`down.sql`. `generate --json` reports the SQL and
114
- metadata directories.
112
+ and schema hashes for the whole chain, without historical snapshot copies, and
113
+ the snapshot before the latest migration (`undo`), so that one step can be taken
114
+ back. Generation updates the same two files; migrate/rollback only change
115
+ database history and use `up.sql`/`down.sql`. `generate --json` reports the SQL
116
+ and metadata directories, and the findings `lint` would report for the new
117
+ migration, which `generate` also prints: a destructive change is refused without
118
+ `--allow-destructive`, and cautions (a table rewritten, an index built while
119
+ writes wait) are shown with the generated files.
120
+
121
+ `discard` removes the latest migration and puts the snapshot and the journal
122
+ back as they were before it was generated, so the next `generate` starts from
123
+ there. It asks the configured database first and refuses a migration that is
124
+ applied or incomplete there (roll it back, then discard it); without a database,
125
+ `--force` says that none has applied it. It also refuses an `up.sql` edited
126
+ after generation, which `--force` would lose. Migrations generated by earlier
127
+ releases have no `undo` record; `discard` then takes the earlier snapshot from
128
+ the Git history of `meta/snapshot.json`. When a migration was deleted by hand
129
+ and `generate`, `status` and `diff` stop with "latest snapshot checksum does not
130
+ match the migration journal", `discard` without an ID puts the snapshot back
131
+ from the same places.
115
132
 
116
133
  The database journal defaults to `public._symmetria_migrations`.
117
134
  `metadataSchema` and `metadataTable` configure its location; migrations create a
@@ -317,6 +334,8 @@ try {
317
334
 
318
335
  `symmetria-kit/testing` creates a unique PostgreSQL schema, creates the declared
319
336
  tables and returns a typed database. Closing it drops that schema and its data.
337
+ Extensions the schema needs, such as pgvector for a search by meaning, are
338
+ installed when missing and found on the search path without further options.
320
339
 
321
340
  ```ts
322
341
  import { testDatabase } from "symmetria-kit/testing";
@@ -1 +1 @@
1
- export { t as explainLines, n as inspectQueryScreen, r as inspectValue, i as terminalText, a as wrapExplainLines } from "../query-inspector-B6UEqDzn.js";
1
+ export { t as explainLines, n as inspectQueryScreen, r as inspectValue, i as terminalText, a as wrapExplainLines } from "../query-inspector-C-7K9wtB.js";
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { _ as migrationSnapshot, x as snapshotHash, y as parseMigrationSnapshot } from "./ddl-D5b2NczN.js";
3
- import { i as diffSchemas, l as detectDrift, u as formatDriftFindings } from "./diff-CRVCo1ym.js";
4
- import { _ as parseMigrationSQL, a as boundaryDifferences, c as MigrationExecutionError, d as loadMigrationState, g as lintMigration, h as formatLintFindings, l as lintMigrationSQL, m as recoverMigrationFiles, n as schemaGraph, o as verifyMigrations, p as squashMigrations, r as pullSchema, s as migrator, t as renderMermaid, u as generateMigration } from "./src-BsrOZ8vB.js";
5
- import { A as terminalWidth, C as view, D as formatError, E as fitLine, M as wrapLines, O as numberedLines, S as choose, T as withSpinner, _ as formatHelp, a as wrapExplainLines, b as formatStatus, c as inspectTableSQL, d as matchesTableName, f as matchingTables, g as formatExecution, h as formatDiff, i as terminalText, j as theme, k as supportsColor, l as inspectTabs, m as formatDashboard, o as highlightSQL, p as formatCreated, s as inspectEntries, t as explainLines, u as matchesEntry, v as formatPullWarnings, w as withScreen, x as ask, y as formatSchema } from "./query-inspector-B6UEqDzn.js";
2
+ import { _ as migrationSnapshot, x as snapshotHash, y as parseMigrationSnapshot } from "./ddl-CtdVeD9m.js";
3
+ import { c as parseMigrationSQL, g as formatDriftFindings, h as detectDrift, i as diffSchemas, o as lintMigrationSQL } from "./diff-DA7huWi5.js";
4
+ import { a as boundaryDifferences, c as MigrationExecutionError, d as loadMigrationState, g as lintMigration, h as formatLintFindings, l as discardMigration, m as recoverMigrationFiles, n as schemaGraph, o as verifyMigrations, p as squashMigrations, r as pullSchema, s as migrator, t as renderMermaid, u as generateMigration } from "./src-J1Nn7Wca.js";
5
+ import { A as terminalWidth, C as view, D as formatError, E as fitLine, M as wrapLines, O as numberedLines, S as choose, T as withSpinner, _ as formatHelp, a as wrapExplainLines, b as formatStatus, c as inspectTableSQL, d as matchesTableName, f as matchingTables, g as formatExecution, h as formatDiff, i as terminalText, j as theme, k as supportsColor, l as inspectTabs, m as formatDashboard, o as highlightSQL, p as formatCreated, s as inspectEntries, t as explainLines, u as matchesEntry, v as formatPullWarnings, w as withScreen, x as ask, y as formatSchema } from "./query-inspector-C-7K9wtB.js";
6
6
  import * as nodeModule from "node:module";
7
7
  import { access, lstat, mkdir, open, readFile, readdir, rm, writeFile } from "node:fs/promises";
8
- import { basename, dirname, extname, relative, resolve } from "node:path";
8
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
9
+ import { parseArgs, stripVTControlCharacters } from "node:util";
9
10
  import { postgres } from "symmetria/driver";
10
11
  import { sqlState } from "symmetria";
11
12
  import { pathToFileURL } from "node:url";
12
13
  import stringWidth from "string-width";
13
- import { parseArgs, stripVTControlCharacters } from "node:util";
14
14
  import { emitKeypressEvents } from "node:readline";
15
15
  //#region src/cli/context.ts
16
16
  /** Everything a command needs: terminal mode, output, the project configuration and a database driver. */
@@ -794,7 +794,8 @@ const rollback = (context, project) => withRunner(project, async (runner) => {
794
794
  //#endregion
795
795
  //#region src/cli/commands/files.ts
796
796
  /**
797
- * Filesystem-only CLI commands: recover a crashed generation and squash the chain.
797
+ * Filesystem CLI commands: recover a crashed generation, squash the chain and
798
+ * discard the latest migration.
798
799
  */
799
800
  /** `recover`: finish or roll back a publication left behind by a crashed generator. */
800
801
  const recover = async (context, project) => {
@@ -816,6 +817,41 @@ const squash = async (context, project, name) => {
816
817
  plain: () => squashed ? `Squashed into ${squashed.id}. Run "symmetria adopt" on databases that applied the old chain.` : "Nothing to squash."
817
818
  });
818
819
  };
820
+ /**
821
+ * `discard [id]`: take back the latest migration while no database has
822
+ * applied it. The configured database is asked first; without one, `--force`
823
+ * says that none has.
824
+ */
825
+ const discard = async (context, project, id) => {
826
+ const { values } = context;
827
+ const { migrations } = await loadMigrationState(project.directory).catch(() => ({ migrations: [] }));
828
+ const listed = migrations.length ? void 0 : await readFile(join(project.directory, "meta", "migration.json"), "utf8").then((text) => JSON.parse(text).migrations?.at(-1)?.id, () => void 0);
829
+ const latest = migrations.at(-1)?.id ?? (typeof listed === "string" ? listed : void 0);
830
+ if (latest !== void 0) {
831
+ if (project.databaseUrl) {
832
+ const driver = postgres(project.databaseUrl);
833
+ try {
834
+ const entry = (await migrator({
835
+ driver,
836
+ ...project.runnerOptions
837
+ }).status()).find((status) => status.id === latest);
838
+ if (entry && entry.status !== "pending") throw new Error(`symmetria: "${latest}" is ${entry.status} in the configured database; roll it back first (symmetria rollback), then discard it`);
839
+ } finally {
840
+ await driver.close();
841
+ }
842
+ } else if (!values.force) throw new Error(`symmetria: discard asks the database whether "${latest}" was applied; set databaseUrl in the config, DATABASE_URL or --database-url, or pass --force when no database has applied it`);
843
+ }
844
+ const discarded = await discardMigration({
845
+ directory: project.directory,
846
+ ...id ? { id } : {},
847
+ ...values.force ? { allowEdited: true } : {}
848
+ });
849
+ const from = discarded.source === "git" ? " (the earlier snapshot came from Git)" : "";
850
+ context.emit({
851
+ json: discarded,
852
+ plain: () => discarded.id ? `Discarded ${discarded.id}; the snapshot is the schema before it${from}.` : `The snapshot matches the journal again${from}.`
853
+ });
854
+ };
819
855
  //#endregion
820
856
  //#region src/cli/commands/graph.ts
821
857
  /**
@@ -1332,24 +1368,27 @@ const generate = async (context, project, requestedName) => {
1332
1368
  ...values.online ? { online: true } : {}
1333
1369
  }));
1334
1370
  const directory = project.directory;
1371
+ const findings = migration ? lintMigration(plan, diffOptions.renames) : [];
1372
+ const review = findings.length ? `\n\nReview before applying:\n${formatLintFindings(findings)}` : "";
1335
1373
  context.emit({
1336
1374
  json: migration ? {
1337
1375
  id: migration.id,
1338
1376
  directory: resolve(directory, migration.id),
1339
1377
  metadataDirectory: resolve(directory, "meta"),
1340
1378
  up: migration.up,
1341
- down: migration.down
1379
+ down: migration.down,
1380
+ findings
1342
1381
  } : {
1343
1382
  id: null,
1344
1383
  changed: false
1345
1384
  },
1346
- pretty: () => migration ? formatCreated(directory, [
1385
+ pretty: () => migration ? `${formatCreated(directory, [
1347
1386
  `${migration.id}/up.sql`,
1348
1387
  `${migration.id}/down.sql`,
1349
1388
  "meta/snapshot.json",
1350
1389
  "meta/migration.json"
1351
- ], color) : "No schema changes.",
1352
- plain: () => migration ? `Generated ${migration.id}` : "No schema changes."
1390
+ ], color)}${review}` : "No schema changes.",
1391
+ plain: () => migration ? `Generated ${migration.id}${review}` : "No schema changes."
1353
1392
  });
1354
1393
  };
1355
1394
  //#endregion
@@ -1369,6 +1408,7 @@ const runCommand = async (command, name, context) => {
1369
1408
  switch (command) {
1370
1409
  case "recover": return recover(context, project);
1371
1410
  case "squash": return squash(context, project, name);
1411
+ case "discard": return discard(context, project, name);
1372
1412
  case "dashboard": return dashboard(context, project);
1373
1413
  case "inspect": return inspect$1(context, project, name);
1374
1414
  case "graph": return graph(context, project, name);
@@ -1397,6 +1437,7 @@ const help = `symmetria <command>
1397
1437
  graph [file] Print or write a Mermaid entity-relationship diagram
1398
1438
  profile Observe live application requests and SQL timings
1399
1439
  generate <name> Generate up.sql and down.sql, and update the snapshot
1440
+ discard [id] Take back the latest migration while no database has applied it
1400
1441
  migrate Apply pending migrations atomically
1401
1442
  status Show applied and pending migrations
1402
1443
  rollback Revert the latest migration
@@ -1432,7 +1473,7 @@ const help = `symmetria <command>
1432
1473
  --steps <number> Number of migrations to rollback (default: 1)
1433
1474
  --yes rollback: run down.sql without asking (required without a terminal)
1434
1475
  --strict Exit with code 1 when lint or drift report findings
1435
- --force Overwrite the file written by pull or graph
1476
+ --force pull/graph: overwrite the file; discard: without a database, or an edited up.sql
1436
1477
  --compact graph: entities and relations without column lists
1437
1478
  --sql Print executable SQL for diff
1438
1479
  --json Machine-readable output
@@ -1460,7 +1501,8 @@ const COMMANDS = [
1460
1501
  "profile",
1461
1502
  "verify",
1462
1503
  "repair",
1463
- "recover"
1504
+ "recover",
1505
+ "discard"
1464
1506
  ];
1465
1507
  /** Every flag; `--help`, the README and the reference list each one. */
1466
1508
  const FLAGS = {
@@ -1518,7 +1560,8 @@ const NAMED = [
1518
1560
  "pull",
1519
1561
  "graph",
1520
1562
  "squash",
1521
- "repair"
1563
+ "repair",
1564
+ "discard"
1522
1565
  ];
1523
1566
  /** Flags that belong to specific commands, with the exact refusal wording. */
1524
1567
  const SCOPED_FLAGS = [
@@ -1618,8 +1661,12 @@ const SCOPED_FLAGS = [
1618
1661
  },
1619
1662
  {
1620
1663
  flags: ["force"],
1621
- commands: ["pull", "graph"],
1622
- message: "symmetria: --force is a pull/graph option"
1664
+ commands: [
1665
+ "pull",
1666
+ "graph",
1667
+ "discard"
1668
+ ],
1669
+ message: "symmetria: --force is a pull/graph/discard option"
1623
1670
  },
1624
1671
  {
1625
1672
  flags: ["compact"],