symmetria-kit 3.2.0 → 3.3.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-CBU9Ug5e.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-CYsBI6_H.js";
3
+ import { d as formatDriftFindings, i as diffSchemas, u as detectDrift } from "./diff-D2EbyDmY.js";
4
+ import { _ as lintMigration, a as boundaryDifferences, c as MigrationExecutionError, d as generateMigration, f as loadMigrationState, g as formatLintFindings, h as recoverMigrationFiles, l as lintMigrationSQL, m as squashMigrations, n as schemaGraph, o as verifyMigrations, r as pullSchema, s as migrator, t as renderMermaid, u as discardMigration, v as parseMigrationSQL } from "./src-Dog3TEh8.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-CBU9Ug5e.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
8
  import { basename, dirname, extname, 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,40 @@ 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 latest = migrations.at(-1)?.id;
829
+ if (latest !== void 0) {
830
+ if (project.databaseUrl) {
831
+ const driver = postgres(project.databaseUrl);
832
+ try {
833
+ const entry = (await migrator({
834
+ driver,
835
+ ...project.runnerOptions
836
+ }).status()).find((status) => status.id === latest);
837
+ 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`);
838
+ } finally {
839
+ await driver.close();
840
+ }
841
+ } 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`);
842
+ }
843
+ const discarded = await discardMigration({
844
+ directory: project.directory,
845
+ ...id ? { id } : {},
846
+ ...values.force ? { allowEdited: true } : {}
847
+ });
848
+ const from = discarded.source === "git" ? " (the earlier snapshot came from Git)" : "";
849
+ context.emit({
850
+ json: discarded,
851
+ plain: () => discarded.id ? `Discarded ${discarded.id}; the snapshot is the schema before it${from}.` : `The snapshot matches the journal again${from}.`
852
+ });
853
+ };
819
854
  //#endregion
820
855
  //#region src/cli/commands/graph.ts
821
856
  /**
@@ -1332,24 +1367,27 @@ const generate = async (context, project, requestedName) => {
1332
1367
  ...values.online ? { online: true } : {}
1333
1368
  }));
1334
1369
  const directory = project.directory;
1370
+ const findings = migration ? lintMigration(plan, diffOptions.renames) : [];
1371
+ const review = findings.length ? `\n\nReview before applying:\n${formatLintFindings(findings)}` : "";
1335
1372
  context.emit({
1336
1373
  json: migration ? {
1337
1374
  id: migration.id,
1338
1375
  directory: resolve(directory, migration.id),
1339
1376
  metadataDirectory: resolve(directory, "meta"),
1340
1377
  up: migration.up,
1341
- down: migration.down
1378
+ down: migration.down,
1379
+ findings
1342
1380
  } : {
1343
1381
  id: null,
1344
1382
  changed: false
1345
1383
  },
1346
- pretty: () => migration ? formatCreated(directory, [
1384
+ pretty: () => migration ? `${formatCreated(directory, [
1347
1385
  `${migration.id}/up.sql`,
1348
1386
  `${migration.id}/down.sql`,
1349
1387
  "meta/snapshot.json",
1350
1388
  "meta/migration.json"
1351
- ], color) : "No schema changes.",
1352
- plain: () => migration ? `Generated ${migration.id}` : "No schema changes."
1389
+ ], color)}${review}` : "No schema changes.",
1390
+ plain: () => migration ? `Generated ${migration.id}${review}` : "No schema changes."
1353
1391
  });
1354
1392
  };
1355
1393
  //#endregion
@@ -1369,6 +1407,7 @@ const runCommand = async (command, name, context) => {
1369
1407
  switch (command) {
1370
1408
  case "recover": return recover(context, project);
1371
1409
  case "squash": return squash(context, project, name);
1410
+ case "discard": return discard(context, project, name);
1372
1411
  case "dashboard": return dashboard(context, project);
1373
1412
  case "inspect": return inspect$1(context, project, name);
1374
1413
  case "graph": return graph(context, project, name);
@@ -1397,6 +1436,7 @@ const help = `symmetria <command>
1397
1436
  graph [file] Print or write a Mermaid entity-relationship diagram
1398
1437
  profile Observe live application requests and SQL timings
1399
1438
  generate <name> Generate up.sql and down.sql, and update the snapshot
1439
+ discard [id] Take back the latest migration while no database has applied it
1400
1440
  migrate Apply pending migrations atomically
1401
1441
  status Show applied and pending migrations
1402
1442
  rollback Revert the latest migration
@@ -1432,7 +1472,7 @@ const help = `symmetria <command>
1432
1472
  --steps <number> Number of migrations to rollback (default: 1)
1433
1473
  --yes rollback: run down.sql without asking (required without a terminal)
1434
1474
  --strict Exit with code 1 when lint or drift report findings
1435
- --force Overwrite the file written by pull or graph
1475
+ --force pull/graph: overwrite the file; discard: without a database, or an edited up.sql
1436
1476
  --compact graph: entities and relations without column lists
1437
1477
  --sql Print executable SQL for diff
1438
1478
  --json Machine-readable output
@@ -1460,7 +1500,8 @@ const COMMANDS = [
1460
1500
  "profile",
1461
1501
  "verify",
1462
1502
  "repair",
1463
- "recover"
1503
+ "recover",
1504
+ "discard"
1464
1505
  ];
1465
1506
  /** Every flag; `--help`, the README and the reference list each one. */
1466
1507
  const FLAGS = {
@@ -1518,7 +1559,8 @@ const NAMED = [
1518
1559
  "pull",
1519
1560
  "graph",
1520
1561
  "squash",
1521
- "repair"
1562
+ "repair",
1563
+ "discard"
1522
1564
  ];
1523
1565
  /** Flags that belong to specific commands, with the exact refusal wording. */
1524
1566
  const SCOPED_FLAGS = [
@@ -1618,8 +1660,12 @@ const SCOPED_FLAGS = [
1618
1660
  },
1619
1661
  {
1620
1662
  flags: ["force"],
1621
- commands: ["pull", "graph"],
1622
- message: "symmetria: --force is a pull/graph option"
1663
+ commands: [
1664
+ "pull",
1665
+ "graph",
1666
+ "discard"
1667
+ ],
1668
+ message: "symmetria: --force is a pull/graph/discard option"
1623
1669
  },
1624
1670
  {
1625
1671
  flags: ["compact"],