@tandemcreativedev/strabo 0.1.1 → 0.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
@@ -4,9 +4,9 @@ Named after the Greek geographer who wrote down the known world. Strabo writes d
4
4
 
5
5
  Generates a readable record of a Postgres schema from `pg_dump`: a tidy SQL reference plus DBML, PlantUML and SVG diagrams. Commit the output next to your migrations so people and AI agents can read the schema without a running database.
6
6
 
7
- - `schema.sql`: every enum, table, view, function and trigger, grouped and sorted. Each table carries its constraints, indexes, comments, row level security and policies. It is for reading only, never for running.
8
- - `.dbml`: diagrams for [dbdiagram.io](https://dbdiagram.io), split by domain or by schema. References to tables outside a diagram stay as comments.
9
- - `.puml`: the same diagrams as PlantUML entity-relationship diagrams.
7
+ - `schema.sql`: every schema comment, enum, composite type, domain, table, view, function and trigger, grouped and sorted. Each table carries its constraints, indexes, comments, row level security and policies. It is for reading only, never for running.
8
+ - `.dbml`: diagrams for [dbdiagram.io](https://dbdiagram.io), split by domain or by schema. Foreign keys sit on their column, and references to tables outside a diagram stay as comments there. Only composite foreign keys get a standalone `Ref:`, and only unique indexes not already shown on a column are listed.
9
+ - `.puml`: the same diagrams as PlantUML entity-relationship diagrams, with a region for hand-written notes that survives regeneration.
10
10
  - `.svg`: the DBML diagrams rendered, with the optional `@softwaretechnik/dbml-renderer`.
11
11
 
12
12
  Built for local Supabase stacks, and it works with any Postgres that `pg_dump` can reach.
@@ -44,6 +44,7 @@ A typical `package.json` script, run after applying migrations locally:
44
44
  | `--db-url <url>` | Database to dump. Defaults to local Supabase (`127.0.0.1:54322`). |
45
45
  | `--out <dir>` | Output directory. |
46
46
  | `--check` | Compare the output with the files on disk and write nothing. |
47
+ | `--strict` | Exit 1 if there are any warnings, such as a diagram table that no longer exists, a table no diagram lists, or a statement strabo skipped. |
47
48
  | `--allow-remote` | Allow a database that is not on this machine. Refused by default. |
48
49
 
49
50
  ## Config
@@ -70,6 +71,9 @@ A typical `package.json` script, run after applying migrations locally:
70
71
  ],
71
72
  "hiddenRefs": {
72
73
  "public.passages.document_id": "denormalised ref to documents.id"
74
+ },
75
+ "relationLabels": {
76
+ "public.profiles.tenant_id": "belongs to"
73
77
  }
74
78
  }
75
79
  ```
@@ -79,10 +83,30 @@ A typical `package.json` script, run after applying migrations locally:
79
83
  - `diagrams`: one entry per diagram. `name` is the output path without an extension, relative to `outDir`.
80
84
  - `tables` lists the tables to draw, in drawing order. Bare names belong to the first schema, and `*` is a wildcard. When any diagram uses `tables`, the run warns about tables that no diagram lists, so new tables don't go undocumented.
81
85
  - Without `tables`, a diagram draws every table in `schemas`, or in every dumped schema if `schemas` is also absent.
86
+ - `enums: false` leaves enum definitions out, such as when another diagram already lists them.
82
87
  - `formats` takes any of `dbml` (the default), `puml` and `svg`.
83
88
  - `hiddenRefs`: foreign keys to leave out of diagrams, each with a note to show on the column instead. Useful for denormalised columns that would tangle a diagram.
89
+ - `relationLabels`: labels for the PlantUML arrows, keyed like `hiddenRefs`. A composite key lists its columns joined by commas, as `schema.table.a,b`. Arrows without a label show their column names.
84
90
  - `pgDump`: the command that runs `pg_dump`. Without local client tools, use the Supabase container: `"docker exec supabase_db_<project> pg_dump"`, with `databaseUrl` set to `postgresql://postgres:postgres@localhost:5432/postgres`, which is the address inside the container.
85
91
 
92
+ ## Hand-written PlantUML
93
+
94
+ Each generated `.puml` ends with a keep region:
95
+
96
+ ```
97
+ ' strabo:keep: lines between these markers are written by hand and survive regeneration
98
+ note right of clients
99
+ slug is unique per tenant and used for routing
100
+ end note
101
+ ' strabo:end
102
+ ```
103
+
104
+ Anything between the markers, such as notes, `together` groups, entities from other domains or extra arrows, is copied into the regenerated file. Everything outside them is rewritten.
105
+
106
+ ## Warnings
107
+
108
+ strabo warns, without failing, when a diagram lists a table that does not exist, when tables appear in no diagram, and when the dump holds statements it does not handle, such as `skipped 2 statements of type AGGREGATE`. Pass `--strict` to make any warning exit 1, so CI catches drift.
109
+
86
110
  ## Programmatic use
87
111
 
88
112
  ```ts
@@ -91,6 +115,8 @@ import { generate, resolveConfig } from "@tandemcreativedev/strabo";
91
115
  const { files, warnings } = generate(dumpText, resolveConfig({ schemas: ["public"] }));
92
116
  ```
93
117
 
118
+ Pass a third argument, `(path) => string | undefined`, that returns each output file's current content to carry hand-written PlantUML regions over.
119
+
94
120
  `parseDump`, `buildDiagram`, `writeSql`, `writeDbml`, `writePuml` and `writeSvg` are exported too, for custom output.
95
121
 
96
122
  ## Releasing
@@ -105,4 +131,4 @@ UPDATE_EXPECTED=1 pnpm test # accept output changes into test/fixtures/expected
105
131
  pnpm fixture # rebuild the fixture dump from fixture.ddl.sql (needs local Supabase)
106
132
  ```
107
133
 
108
- The parser reads pg_dump's plain-text output. It splits the dump on the `-- Name: …; Type: …` header that pg_dump writes before every object, then parses each statement on its own. It is tested against pg_dump 18 output.
134
+ The parser reads pg_dump's plain-text output. It splits the dump on the `-- Name: …; Type: …` header that pg_dump writes before every object, then parses each statement on its own. Comments join the statement before them, since pg_dump writes an object's comments straight after it. It is tested against pg_dump 18 output.
package/dist/cli.js CHANGED
@@ -18,6 +18,7 @@ Options:
18
18
  --db-url <url> Database to dump (default: local Supabase)
19
19
  --out <dir> Output directory (default: ${DEFAULTS.outDir})
20
20
  --check Exit 1 if any output file is out of date, writing nothing
21
+ --strict Exit 1 if there are any warnings
21
22
  --allow-remote Allow dumping a database that is not on this machine
22
23
  -h, --help Show this help
23
24
  `;
@@ -41,6 +42,7 @@ function run() {
41
42
  "db-url": { type: "string" },
42
43
  out: { type: "string" },
43
44
  check: { type: "boolean" },
45
+ strict: { type: "boolean" },
44
46
  "allow-remote": { type: "boolean" },
45
47
  help: { type: "boolean", short: "h" },
46
48
  },
@@ -61,16 +63,20 @@ function run() {
61
63
  if (values.out)
62
64
  config.outDir = values.out;
63
65
  const dump = values.input ? fs.readFileSync(values.input, "utf8") : dumpSchema(config, values["allow-remote"]);
64
- const { schema, files, warnings } = generate(dump, config);
66
+ const read = (file) => (fs.existsSync(file) ? fs.readFileSync(file, "utf8") : undefined);
67
+ const { schema, files, warnings } = generate(dump, config, read);
65
68
  for (const warning of warnings)
66
69
  console.warn(`warning: ${warning}`);
70
+ const failed = Boolean(values.strict && warnings.length);
71
+ if (failed)
72
+ console.error("--strict: warnings count as failures.");
67
73
  if (values.check) {
68
- const stale = files.filter((file) => !fs.existsSync(file.path) || fs.readFileSync(file.path, "utf8") !== file.content);
74
+ const stale = files.filter((file) => read(file.path) !== file.content);
69
75
  for (const file of stale)
70
76
  console.error(`out of date: ${file.path}`);
71
77
  if (stale.length)
72
78
  console.error("Run strabo to regenerate.");
73
- return stale.length ? 1 : 0;
79
+ return stale.length || failed ? 1 : 0;
74
80
  }
75
81
  for (const file of files) {
76
82
  fs.mkdirSync(path.dirname(file.path), { recursive: true });
@@ -78,7 +84,7 @@ function run() {
78
84
  console.log(`wrote ${file.path}`);
79
85
  }
80
86
  console.log(`${schema.tables.size} tables, ${schema.enums.length} enums, ${schema.views.length} views, ${schema.functions.length} functions, ${schema.triggers.length} triggers`);
81
- return 0;
87
+ return failed ? 1 : 0;
82
88
  }
83
89
  try {
84
90
  process.exitCode = run();
package/dist/config.d.ts CHANGED
@@ -9,6 +9,8 @@ export interface DiagramConfig {
9
9
  tables?: string[];
10
10
  /** Schemas to draw in full when `tables` is not given. Defaults to every dumped schema. */
11
11
  schemas?: string[];
12
+ /** Set false to leave enum definitions out of this diagram, such as when another diagram already lists them. */
13
+ enums?: boolean;
12
14
  /** Defaults to `["dbml"]`. `svg` renders the DBML and needs `@softwaretechnik/dbml-renderer` installed. */
13
15
  formats?: DiagramFormat[];
14
16
  }
@@ -23,6 +25,8 @@ export interface Config {
23
25
  diagrams: DiagramConfig[];
24
26
  /** Foreign keys to leave out of diagrams, as `schema.table.column`, each with the note to show instead. */
25
27
  hiddenRefs: Record<string, string>;
28
+ /** PlantUML labels for foreign keys, as `schema.table.column` (`schema.table.a,b` for a composite key). Defaults to the column names. */
29
+ relationLabels: Record<string, string>;
26
30
  /** The pg_dump command, such as `pg_dump` or `docker exec -i supabase_db_app pg_dump`. */
27
31
  pgDump: string;
28
32
  }
package/dist/config.js CHANGED
@@ -9,6 +9,7 @@ export const DEFAULTS = {
9
9
  sql: "schema.sql",
10
10
  diagrams: [{ name: "schema" }],
11
11
  hiddenRefs: {},
12
+ relationLabels: {},
12
13
  pgDump: "pg_dump",
13
14
  };
14
15
  function fail(message) {
@@ -29,6 +30,8 @@ function validateDiagram(value, index) {
29
30
  for (const key of ["notes", "tables", "schemas"])
30
31
  if (diagram[key] !== undefined && !isStringArray(diagram[key]))
31
32
  fail(`${at}.${key} must be an array of strings`);
33
+ if (diagram.enums !== undefined && typeof diagram.enums !== "boolean")
34
+ fail(`${at}.enums must be a boolean`);
32
35
  if (diagram.formats !== undefined) {
33
36
  if (!isStringArray(diagram.formats))
34
37
  fail(`${at}.formats must be an array of strings`);
@@ -56,11 +59,12 @@ export function resolveConfig(raw) {
56
59
  fail("sql must be a file name or false");
57
60
  if (input.diagrams !== undefined && !Array.isArray(input.diagrams))
58
61
  fail("diagrams must be an array");
59
- if (input.hiddenRefs !== undefined &&
60
- (typeof input.hiddenRefs !== "object" ||
61
- input.hiddenRefs === null ||
62
- !Object.values(input.hiddenRefs).every((note) => typeof note === "string")))
63
- fail("hiddenRefs must map schema.table.column to a note");
62
+ for (const [key, value] of [["hiddenRefs", "a note"], ["relationLabels", "a label"]])
63
+ if (input[key] !== undefined &&
64
+ (typeof input[key] !== "object" ||
65
+ input[key] === null ||
66
+ !Object.values(input[key]).every((text) => typeof text === "string")))
67
+ fail(`${key} must map schema.table.column to ${value}`);
64
68
  return {
65
69
  ...DEFAULTS,
66
70
  ...input,
package/dist/diagram.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { DiagramConfig } from "./config.js";
1
+ import type { Config, DiagramConfig } from "./config.js";
2
2
  import type { Column, Enum, Schema, Table } from "./model.js";
3
3
  export type Cardinality = "one-to-one" | "many-to-one";
4
4
  export interface Relation {
@@ -9,6 +9,7 @@ export interface Relation {
9
9
  cardinality: Cardinality;
10
10
  /** False when the column must hold a value. */
11
11
  optional: boolean;
12
+ label: string;
12
13
  }
13
14
  export interface Diagram {
14
15
  name: string;
@@ -24,7 +25,7 @@ export interface Diagram {
24
25
  hiddenRefs: Map<string, string>;
25
26
  }
26
27
  export declare function selectTables(schema: Schema, config: Pick<DiagramConfig, "tables" | "schemas">, primarySchema: string, warn: (message: string) => void): Table[];
27
- export declare function buildDiagram(schema: Schema, config: DiagramConfig, primarySchema: string, hiddenRefs: Record<string, string>, warn: (message: string) => void): Diagram;
28
+ export declare function buildDiagram(schema: Schema, config: DiagramConfig, primarySchema: string, refs: Pick<Config, "hiddenRefs" | "relationLabels">, warn: (message: string) => void): Diagram;
28
29
  /** Drops the primary schema's prefix, so `public.users` reads as `users`. */
29
30
  export declare function displayName(qualified: string, primarySchema: string): string;
30
31
  /** Orders columns primary key first and timestamps last, as people read a table. */
package/dist/diagram.js CHANGED
@@ -25,7 +25,7 @@ function isUnique(table, columns) {
25
25
  table.uniques.some((unique) => sameColumns(unique, columns)) ||
26
26
  table.indexes.some((index) => index.unique && !index.partial && index.columns !== null && sameColumns(index.columns, columns)));
27
27
  }
28
- function toRelation(table, foreignKey) {
28
+ function toRelation(table, foreignKey, labels) {
29
29
  const columns = foreignKey.columns.map((name) => table.columns.find((column) => column.name === name));
30
30
  return {
31
31
  table: table.name,
@@ -34,23 +34,24 @@ function toRelation(table, foreignKey) {
34
34
  refColumns: foreignKey.refColumns,
35
35
  cardinality: isUnique(table, foreignKey.columns) ? "one-to-one" : "many-to-one",
36
36
  optional: columns.some((column) => !column?.notNull),
37
+ label: labels[`${table.name}.${foreignKey.columns.join(",")}`] ?? foreignKey.columns.join(", "),
37
38
  };
38
39
  }
39
40
  function enumsUsedBy(tables, enums) {
40
41
  const types = new Set(tables.flatMap((table) => table.columns.map((column) => column.type.replace(/\[\]$/, ""))));
41
42
  return enums.filter((candidate) => types.has(candidate.name));
42
43
  }
43
- export function buildDiagram(schema, config, primarySchema, hiddenRefs, warn) {
44
+ export function buildDiagram(schema, config, primarySchema, refs, warn) {
44
45
  const tables = selectTables(schema, config, primarySchema, warn);
45
46
  const drawn = new Set(tables.map((table) => table.name));
46
- const hidden = new Map(Object.entries(hiddenRefs));
47
+ const hidden = new Map(Object.entries(refs.hiddenRefs));
47
48
  const relations = [];
48
49
  const externalRelations = [];
49
50
  for (const table of tables)
50
51
  for (const foreignKey of table.foreignKeys) {
51
52
  if (foreignKey.columns.some((column) => hidden.has(`${table.name}.${column}`)))
52
53
  continue;
53
- const relation = toRelation(table, foreignKey);
54
+ const relation = toRelation(table, foreignKey, refs.relationLabels);
54
55
  (drawn.has(foreignKey.refTable) ? relations : externalRelations).push(relation);
55
56
  }
56
57
  return {
@@ -59,7 +60,7 @@ export function buildDiagram(schema, config, primarySchema, hiddenRefs, warn) {
59
60
  notes: config.notes ?? [],
60
61
  primarySchema,
61
62
  tables,
62
- enums: enumsUsedBy(tables, schema.enums),
63
+ enums: config.enums === false ? [] : enumsUsedBy(tables, schema.enums),
63
64
  relations,
64
65
  externalRelations,
65
66
  hiddenRefs: hidden,
@@ -9,5 +9,8 @@ export interface Result {
9
9
  files: OutputFile[];
10
10
  warnings: string[];
11
11
  }
12
- /** Turns a schema-only pg_dump into the SQL reference and diagram files the config asks for. Writes nothing. */
13
- export declare function generate(dump: string, config: Config): Result;
12
+ /**
13
+ * Turns a schema-only pg_dump into the SQL reference and diagram files the config asks for. Writes nothing.
14
+ * `read` returns a file's current content, so hand-written PlantUML regions carry over.
15
+ */
16
+ export declare function generate(dump: string, config: Config, read?: (file: string) => string | undefined): Result;
package/dist/generate.js CHANGED
@@ -11,22 +11,26 @@ function uncovered(schema, config) {
11
11
  const covered = new Set(config.diagrams.flatMap((diagram) => selectTables(schema, diagram, config.schemas[0], () => { }).map((table) => table.name)));
12
12
  return [...schema.tables.keys()].filter((name) => !covered.has(name));
13
13
  }
14
- /** Turns a schema-only pg_dump into the SQL reference and diagram files the config asks for. Writes nothing. */
15
- export function generate(dump, config) {
16
- const schema = parseDump(dump);
14
+ /**
15
+ * Turns a schema-only pg_dump into the SQL reference and diagram files the config asks for. Writes nothing.
16
+ * `read` returns a file's current content, so hand-written PlantUML regions carry over.
17
+ */
18
+ export function generate(dump, config, read = () => undefined) {
17
19
  const warnings = [];
20
+ const schema = parseDump(dump, (message) => warnings.push(message));
18
21
  const files = [];
19
22
  const at = (file) => path.join(config.outDir, file);
20
23
  if (config.sql)
21
24
  files.push({ path: at(config.sql), content: writeSql(schema) });
22
25
  for (const diagramConfig of config.diagrams) {
23
- const diagram = buildDiagram(schema, diagramConfig, config.schemas[0], config.hiddenRefs, (message) => warnings.push(`${diagramConfig.name}: ${message}`));
26
+ const diagram = buildDiagram(schema, diagramConfig, config.schemas[0], config, (message) => warnings.push(`${diagramConfig.name}: ${message}`));
24
27
  const formats = diagramConfig.formats ?? ["dbml"];
25
28
  const dbml = writeDbml(diagram);
26
29
  if (formats.includes("dbml"))
27
30
  files.push({ path: at(`${diagram.name}.dbml`), content: dbml });
31
+ const puml = at(`${diagram.name}.puml`);
28
32
  if (formats.includes("puml"))
29
- files.push({ path: at(`${diagram.name}.puml`), content: writePuml(diagram) });
33
+ files.push({ path: puml, content: writePuml(diagram, read(puml)) });
30
34
  if (formats.includes("svg"))
31
35
  files.push({ path: at(`${diagram.name}.svg`), content: writeSvg(dbml) });
32
36
  }
package/dist/model.d.ts CHANGED
@@ -4,7 +4,8 @@ export interface Column {
4
4
  notNull: boolean;
5
5
  default: string | null;
6
6
  identity: boolean;
7
- generated: boolean;
7
+ /** The `GENERATED ALWAYS AS (...)` clause, or null for an ordinary column. */
8
+ generated: string | null;
8
9
  comment: string | null;
9
10
  /** The column line as pg_dump wrote it, with any default or identity set later appended. */
10
11
  definition: string;
@@ -54,7 +55,12 @@ export interface Definition {
54
55
  body: string;
55
56
  }
56
57
  export interface Schema {
58
+ /** COMMENT ON SCHEMA statements, as pg_dump wrote them. */
59
+ schemaComments: string[];
57
60
  enums: Enum[];
61
+ /** Composite types. */
62
+ types: Definition[];
63
+ domains: Definition[];
58
64
  tables: Map<string, Table>;
59
65
  views: Definition[];
60
66
  functions: Definition[];
package/dist/parse.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import type { Schema } from "./model.js";
2
2
  export declare function unquote(identifier: string): string;
3
- /** Parses a `pg_dump --schema-only` dump into the tables, types and routines it defines. */
4
- export declare function parseDump(dump: string): Schema;
3
+ /** Parses a `pg_dump --schema-only` dump into the tables, types and routines it defines, warning about statements it skips. */
4
+ export declare function parseDump(dump: string, warn?: (message: string) => void): Schema;
package/dist/parse.js CHANGED
@@ -15,27 +15,53 @@ function schemaOf(qualified) {
15
15
  function byName(a, b) {
16
16
  return a.name.localeCompare(b.name);
17
17
  }
18
- /** Splits a dump on the `-- Name: ...; Type: ...` header pg_dump writes before every object. */
18
+ const HEADER = /^--\n-- (?:Data for )?Name: .*; Type: (.*?); Schema: .*; Owner: .*\n--\n/m;
19
+ /** Drops pg_dump's session settings, leaving dollar-quoted bodies untouched. */
20
+ function stripSettings(chunk) {
21
+ return chunk.replace(/(\$(?:[A-Za-z_]\w*)?\$)[\s\S]*?\1|^(?:SET |SELECT pg_catalog\.|\\(?:un)?restrict ).*$/gm, (match, quote) => (quote ? match : ""));
22
+ }
23
+ /**
24
+ * Splits a dump on the `-- Name: ...; Type: ...` header pg_dump writes before every object.
25
+ * pg_dump writes an object's comments straight after it, so each comment joins the statement before it.
26
+ */
19
27
  function splitStatements(dump) {
20
- return dump
21
- .replace(/^--\n-- PostgreSQL database dump complete\n--$/m, "")
22
- .split(/^--\n-- (?:Data for )?Name: .*\n--\n/m)
23
- .slice(1)
24
- .map((chunk) => chunk.replace(/^(?:SET |SELECT pg_catalog\.|\\(?:un)?restrict ).*$/gm, "").trim())
25
- .filter(Boolean);
28
+ const parts = dump.replace(/^--\n-- PostgreSQL database dump complete\n--$/m, "").split(HEADER);
29
+ const statements = [];
30
+ for (let at = 1; at < parts.length; at += 2) {
31
+ const sql = stripSettings(parts[at + 1]).trim();
32
+ if (!sql)
33
+ continue;
34
+ const owner = statements.at(-1);
35
+ if (parts[at] === "COMMENT" && owner)
36
+ owner.comments.push(sql);
37
+ else
38
+ statements.push({ type: parts[at], sql, comments: [] });
39
+ }
40
+ return statements;
41
+ }
42
+ /** Blanks out quoted literals and identifiers, keeping offsets, so keywords inside them are not matched. */
43
+ function maskQuoted(text) {
44
+ return text.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (quoted) => " ".repeat(quoted.length));
26
45
  }
27
46
  function parseColumn(line) {
28
47
  const match = line.match(new RegExp(`^(${NAME})\\s+(.*)$`));
29
48
  if (!match)
30
49
  throw new Error(`Unrecognised column definition: ${line}`);
31
50
  let rest = match[2];
32
- const notNull = /\bNOT NULL\b/.test(rest);
33
- rest = rest.replace(/\s*\bNOT NULL\b/, "");
34
- const generated = /\bGENERATED ALWAYS AS \(/.test(rest);
35
- rest = rest.replace(/\s*\bGENERATED ALWAYS AS \(.*\) STORED$/, "");
36
- rest = rest.replace(/\s*\bCOLLATE\s+\S+/, "");
51
+ const cut = (pattern) => {
52
+ const found = maskQuoted(rest).match(pattern);
53
+ if (!found || found.index === undefined)
54
+ return null;
55
+ const end = found.index + found[0].length;
56
+ const text = rest.slice(found.index, end);
57
+ rest = rest.slice(0, found.index) + rest.slice(end);
58
+ return text.trim();
59
+ };
60
+ const notNull = cut(/\s*\bNOT NULL\b/) !== null;
61
+ const generated = cut(/\s*\bGENERATED ALWAYS AS \(.*\)(?: STORED| VIRTUAL)?$/);
62
+ cut(/\s*\bCOLLATE\s+\S+/);
37
63
  let columnDefault = null;
38
- const defaultAt = rest.search(/\bDEFAULT\b/);
64
+ const defaultAt = maskQuoted(rest).search(/\bDEFAULT\b/);
39
65
  if (defaultAt >= 0) {
40
66
  columnDefault = rest.slice(defaultAt + "DEFAULT".length).trim();
41
67
  rest = rest.slice(0, defaultAt);
@@ -102,42 +128,56 @@ function parseIndex(match) {
102
128
  };
103
129
  }
104
130
  const PATTERNS = {
131
+ schema: new RegExp(`^CREATE SCHEMA ${NAME};$`),
105
132
  enum: new RegExp(`^CREATE TYPE (${QUALIFIED}) AS ENUM \\(\\n([\\s\\S]*?)\\n\\);$`),
133
+ compositeType: new RegExp(`^CREATE TYPE (${QUALIFIED}) AS \\(\\n`),
134
+ domain: new RegExp(`^CREATE DOMAIN (${QUALIFIED}) `),
106
135
  table: new RegExp(`^CREATE (?:UNLOGGED )?TABLE (${QUALIFIED}) \\(\\n([\\s\\S]*?)\\n\\)[^;]*;$`),
107
- setDefault: new RegExp(`^ALTER TABLE ONLY (${QUALIFIED}) ALTER COLUMN (${NAME}) SET DEFAULT (.+);$`),
136
+ setDefault: new RegExp(`^ALTER TABLE (?:ONLY )?(${QUALIFIED}) ALTER COLUMN (${NAME}) SET DEFAULT (.+);$`),
108
137
  identity: new RegExp(`^ALTER TABLE (${QUALIFIED}) ALTER COLUMN (${NAME}) ADD GENERATED (ALWAYS|BY DEFAULT) AS IDENTITY`),
109
- constraint: new RegExp(`^ALTER TABLE ONLY (${QUALIFIED})\\n\\s+ADD CONSTRAINT (${NAME} [\\s\\S]+);$`),
110
- index: new RegExp(`^CREATE (UNIQUE )?INDEX (${NAME}) ON (?:ONLY )?(${QUALIFIED}) USING \\w+ \\((.*?)\\)(?: INCLUDE \\(.*?\\))?( WHERE .*)?;$`),
138
+ constraint: new RegExp(`^ALTER TABLE (?:ONLY )?(${QUALIFIED})\\n\\s+ADD CONSTRAINT (${NAME} [\\s\\S]+);$`),
139
+ index: new RegExp(`^CREATE (UNIQUE )?INDEX (${NAME}) ON (?:ONLY )?(${QUALIFIED}) USING \\w+ \\((.*?)\\)(?: INCLUDE \\(.*?\\))?(?: NULLS NOT DISTINCT)?(?: WITH \\(.*?\\))?( WHERE .*)?;$`),
111
140
  rls: new RegExp(`^ALTER TABLE (${QUALIFIED}) ENABLE ROW LEVEL SECURITY;$`),
112
141
  policy: new RegExp(`^CREATE POLICY ${NAME} ON (${QUALIFIED}) `),
113
- tableComment: new RegExp(`^COMMENT ON TABLE (${QUALIFIED}) IS ('(?:[^']|'')*');$`),
114
- columnComment: new RegExp(`^COMMENT ON COLUMN (${QUALIFIED})\\.(${NAME}) IS ('(?:[^']|'')*');$`),
115
142
  view: new RegExp(`^CREATE (?:MATERIALIZED )?VIEW (${QUALIFIED}) `),
116
143
  function: new RegExp(`^CREATE (?:FUNCTION|PROCEDURE) (${QUALIFIED})\\(`),
117
144
  trigger: new RegExp(`^CREATE (?:CONSTRAINT )?TRIGGER (${NAME}) `),
118
- objectComment: new RegExp(`^COMMENT ON (?:TYPE|VIEW|MATERIALIZED VIEW|FUNCTION|PROCEDURE) (${QUALIFIED})[ (][\\s\\S]*;$`),
145
+ /** Statements strabo leaves out on purpose. */
146
+ ignored: /^(?:--|CREATE (?:EXTENSION|SEQUENCE) |ALTER SEQUENCE )/,
147
+ tableComment: new RegExp(`^COMMENT ON TABLE (${QUALIFIED}) IS ('(?:[^']|'')*');$`),
148
+ columnComment: new RegExp(`^COMMENT ON COLUMN (${QUALIFIED})\\.(${NAME}) IS ('(?:[^']|'')*');$`),
119
149
  };
120
- /** Parses a `pg_dump --schema-only` dump into the tables, types and routines it defines. */
121
- export function parseDump(dump) {
150
+ function warnSkipped(statements, handled, warn) {
151
+ const skipped = new Map();
152
+ for (const statement of statements)
153
+ if (!handled.has(statement))
154
+ skipped.set(statement.type, (skipped.get(statement.type) ?? 0) + 1);
155
+ for (const [type, count] of skipped)
156
+ warn(`skipped ${count} ${count === 1 ? "statement" : "statements"} of type ${type}`);
157
+ }
158
+ /** Parses a `pg_dump --schema-only` dump into the tables, types and routines it defines, warning about statements it skips. */
159
+ export function parseDump(dump, warn = () => { }) {
122
160
  const statements = splitStatements(dump);
123
- const matches = (pattern) => statements.flatMap((statement) => {
124
- const match = statement.match(pattern);
125
- return match ? [match] : [];
161
+ const handled = new Set();
162
+ const matching = (pattern) => statements.flatMap((statement) => {
163
+ const match = statement.sql.match(pattern);
164
+ if (!match)
165
+ return [];
166
+ handled.add(statement);
167
+ return [{ match, comments: statement.comments }];
126
168
  });
127
- const comments = new Map();
128
- for (const match of matches(PATTERNS.objectComment)) {
129
- const name = unquote(match[1]);
130
- comments.set(name, [...(comments.get(name) ?? []), match.input ?? ""]);
131
- }
132
- const definitions = (pattern) => matches(pattern)
133
- .map((match) => {
134
- const name = unquote(match[1]);
135
- return { name, body: [match.input ?? "", ...(comments.get(name) ?? [])].join("\n") };
136
- })
169
+ const matches = (pattern) => matching(pattern).map(({ match }) => match);
170
+ const commentMatches = (pattern) => statements.flatMap((statement) => statement.comments.flatMap((comment) => {
171
+ const match = comment.match(pattern);
172
+ return match ? [match] : [];
173
+ }));
174
+ const definitions = (pattern) => matching(pattern)
175
+ .map(({ match, comments }) => ({ name: unquote(match[1]), body: [match.input ?? "", ...comments].join("\n") }))
137
176
  .sort(byName);
138
- const enums = matches(PATTERNS.enum).map(([, name, body]) => ({
177
+ const schemaComments = matching(PATTERNS.schema).flatMap(({ comments }) => comments);
178
+ const enums = matching(PATTERNS.enum).map(({ match: [, name, body], comments }) => ({
139
179
  name: unquote(name),
140
- comments: comments.get(unquote(name)) ?? [],
180
+ comments,
141
181
  schema: schemaOf(unquote(name)),
142
182
  values: body
143
183
  .split("\n")
@@ -178,21 +218,27 @@ export function parseDump(dump) {
178
218
  }
179
219
  for (const match of matches(PATTERNS.policy))
180
220
  table(match[1])?.policies.push((match.input ?? "").replace(/\s+/g, " "));
181
- for (const [, name, literal] of matches(PATTERNS.tableComment)) {
221
+ for (const [, name, literal] of commentMatches(PATTERNS.tableComment)) {
182
222
  const target = table(name);
183
223
  if (target)
184
224
  target.comment = unescapeLiteral(literal);
185
225
  }
186
- for (const [, tableName, name, literal] of matches(PATTERNS.columnComment)) {
226
+ for (const [, tableName, name, literal] of commentMatches(PATTERNS.columnComment)) {
187
227
  const target = column(tableName, name);
188
228
  if (target)
189
229
  target.comment = unescapeLiteral(literal);
190
230
  }
191
- return {
231
+ const schema = {
232
+ schemaComments,
192
233
  enums: enums.sort(byName),
234
+ types: definitions(PATTERNS.compositeType),
235
+ domains: definitions(PATTERNS.domain),
193
236
  tables: new Map([...tables].sort(([a], [b]) => a.localeCompare(b))),
194
237
  views: definitions(PATTERNS.view),
195
238
  functions: definitions(PATTERNS.function),
196
239
  triggers: definitions(PATTERNS.trigger),
197
240
  };
241
+ matches(PATTERNS.ignored);
242
+ warnSkipped(statements, handled, warn);
243
+ return schema;
198
244
  }
@@ -25,6 +25,19 @@ function defaultValue(value) {
25
25
  return `default: ${text(string[1].replace(/''/g, "'"))}`;
26
26
  return `default: \`${value.replace(/`/g, "'")}\``;
27
27
  }
28
+ function endpoint(qualified, columns, diagram) {
29
+ const names = columns.map(identifier);
30
+ return `${tableName(qualified, diagram)}.${names.length === 1 ? names[0] : `(${names.join(", ")})`}`;
31
+ }
32
+ function target(relation, diagram) {
33
+ return `${relation.cardinality === "one-to-one" ? "-" : ">"} ${endpoint(relation.refTable, relation.refColumns, diagram)}`;
34
+ }
35
+ function ref(relation, diagram) {
36
+ return `Ref: ${endpoint(relation.table, relation.columns, diagram)} ${target(relation, diagram)}`;
37
+ }
38
+ function singleColumn(relations, table, column) {
39
+ return relations.find((relation) => relation.table === table.name && relation.columns.length === 1 && relation.columns[0] === column.name);
40
+ }
28
41
  function columnSettings(table, column, diagram) {
29
42
  const settings = [];
30
43
  const singlePk = table.primaryKey.length === 1 && table.primaryKey[0] === column.name;
@@ -38,12 +51,15 @@ function columnSettings(table, column, diagram) {
38
51
  table.indexes.some((index) => index.unique && !index.partial && index.columns?.length === 1 && index.columns[0] === column.name);
39
52
  if (unique && !singlePk)
40
53
  settings.push("unique");
54
+ const relation = singleColumn(diagram.relations, table, column);
55
+ if (relation)
56
+ settings.push(`ref: ${target(relation, diagram)}`);
41
57
  const fallback = column.default === null ? null : defaultValue(column.default);
42
58
  if (fallback)
43
59
  settings.push(fallback);
44
60
  const notes = [
45
61
  column.comment,
46
- column.generated ? "generated column" : null,
62
+ column.generated,
47
63
  diagram.hiddenRefs.get(`${table.name}.${column.name}`) ?? null,
48
64
  ].filter((note) => note !== null);
49
65
  if (notes.length)
@@ -55,9 +71,9 @@ function indexes(table) {
55
71
  const lines = [
56
72
  ...(table.primaryKey.length > 1 ? [`${columns(table.primaryKey)} [pk]`] : []),
57
73
  ...table.uniques.filter((unique) => unique.length > 1).map((unique) => `${columns(unique)} [unique]`),
58
- ...table.indexes.map((index) => {
74
+ ...table.indexes.filter((index) => index.unique && (index.partial || index.columns?.length !== 1)).map((index) => {
59
75
  const target = index.columns ? columns(index.columns) : `\`${index.expression}\``;
60
- const settings = [...(index.unique ? ["unique"] : []), `name: ${text(index.name)}`, ...(index.partial ? ["note: 'partial'"] : [])];
76
+ const settings = ["unique", `name: ${text(index.name)}`, ...(index.partial ? ["note: 'partial'"] : [])];
61
77
  return `${target} [${settings.join(", ")}]`;
62
78
  }),
63
79
  ];
@@ -68,7 +84,8 @@ function table(table, diagram) {
68
84
  `Table ${tableName(table.name, diagram)} {`,
69
85
  ...orderColumns(table).map((column) => {
70
86
  const settings = columnSettings(table, column, diagram);
71
- return ` ${identifier(column.name)} ${type(column, diagram)}${settings.length ? ` [${settings.join(", ")}]` : ""}`;
87
+ const external = singleColumn(diagram.externalRelations, table, column);
88
+ return ` ${identifier(column.name)} ${type(column, diagram)}${settings.length ? ` [${settings.join(", ")}]` : ""}${external ? ` // ref: ${target(external, diagram)}` : ""}`;
72
89
  }),
73
90
  ...indexes(table),
74
91
  ...(table.comment === null ? [] : ["", ` Note: ${text(table.comment)}`]),
@@ -76,13 +93,9 @@ function table(table, diagram) {
76
93
  "",
77
94
  ];
78
95
  }
79
- function endpoint(qualified, columns, diagram) {
80
- const names = columns.map(identifier);
81
- return `${tableName(qualified, diagram)}.${names.length === 1 ? names[0] : `(${names.join(", ")})`}`;
82
- }
83
- function ref(relation, diagram) {
84
- const operator = relation.cardinality === "one-to-one" ? "-" : ">";
85
- return `Ref: ${endpoint(relation.table, relation.columns, diagram)} ${operator} ${endpoint(relation.refTable, relation.refColumns, diagram)}`;
96
+ /** DBML can only reference several columns from a standalone Ref, so these stay out of the column lines. */
97
+ function composite(relations) {
98
+ return relations.filter((relation) => relation.columns.length > 1);
86
99
  }
87
100
  export function writeDbml(diagram) {
88
101
  const enums = diagram.enums.flatMap(({ name, values }) => [
@@ -98,9 +111,8 @@ export function writeDbml(diagram) {
98
111
  "",
99
112
  ...enums,
100
113
  ...diagram.tables.flatMap((entry) => table(entry, diagram)),
101
- ...diagram.relations.map((relation) => ref(relation, diagram)),
102
- ...(diagram.externalRelations.length ? ["", "// References to tables outside this diagram"] : []),
103
- ...diagram.externalRelations.map((relation) => `// ${ref(relation, diagram)}`),
114
+ ...composite(diagram.relations).map((relation) => ref(relation, diagram)),
115
+ ...composite(diagram.externalRelations).map((relation) => `// ${ref(relation, diagram)}`),
104
116
  ]
105
117
  .join("\n")
106
118
  .trimEnd()
@@ -1,2 +1,3 @@
1
1
  import { type Diagram } from "../diagram.js";
2
- export declare function writePuml(diagram: Diagram): string;
2
+ /** Writes the diagram as PlantUML, carrying over the keep region of `previous`, the file this one replaces. */
3
+ export declare function writePuml(diagram: Diagram, previous?: string): string;
@@ -45,9 +45,19 @@ function entity(table, diagram) {
45
45
  }
46
46
  function relation(relation, diagram) {
47
47
  const childEnd = relation.cardinality === "one-to-one" ? (relation.optional ? "o|" : "||") : relation.optional ? "o{" : "|{";
48
- return `${alias(relation.refTable, diagram)} ||--${childEnd} ${alias(relation.table, diagram)} : "${relation.columns.join(", ")}"`;
48
+ return `${alias(relation.refTable, diagram)} ||--${childEnd} ${alias(relation.table, diagram)} : "${relation.label.replace(/"/g, "'")}"`;
49
49
  }
50
- export function writePuml(diagram) {
50
+ const KEEP_START = "' strabo:keep";
51
+ const KEEP_END = "' strabo:end";
52
+ /** The hand-written lines between the keep markers of a previously generated file. */
53
+ function keptLines(previous) {
54
+ const lines = previous?.split("\n") ?? [];
55
+ const start = lines.findIndex((line) => line.startsWith(KEEP_START));
56
+ const end = lines.findIndex((line, index) => index > start && line.startsWith(KEEP_END));
57
+ return start >= 0 && end > start ? lines.slice(start + 1, end) : [];
58
+ }
59
+ /** Writes the diagram as PlantUML, carrying over the keep region of `previous`, the file this one replaces. */
60
+ export function writePuml(diagram, previous) {
51
61
  const enums = diagram.enums.flatMap(({ name, values }) => [
52
62
  `enum "${label(name, diagram)}" as ${alias(name, diagram)} {`,
53
63
  ...values.map((value) => ` ${value}`),
@@ -56,7 +66,7 @@ export function writePuml(diagram) {
56
66
  ]);
57
67
  return [
58
68
  `@startuml ${diagram.name.split("/").pop()}`,
59
- "' Generated by strabo: regenerate it rather than editing it.",
69
+ "' Generated by strabo: regenerate it, editing only between the strabo:keep and strabo:end markers.",
60
70
  "",
61
71
  ...STYLE,
62
72
  "",
@@ -69,6 +79,10 @@ export function writePuml(diagram) {
69
79
  ...(diagram.externalRelations.length ? ["", "' References to tables outside this diagram"] : []),
70
80
  ...diagram.externalRelations.map((entry) => `' ${label(entry.table, diagram)}.${entry.columns.join(", ")} -> ${label(entry.refTable, diagram)}.${entry.refColumns.join(", ")}`),
71
81
  "",
82
+ `${KEEP_START}: lines between these markers are written by hand and survive regeneration`,
83
+ ...keptLines(previous),
84
+ KEEP_END,
85
+ "",
72
86
  "@enduml",
73
87
  "",
74
88
  ].join("\n");
@@ -43,7 +43,10 @@ export function writeSql(schema) {
43
43
  return [
44
44
  ...HEADER,
45
45
  "",
46
+ ...section("Schemas", schema.schemaComments.map((comment) => [comment])),
46
47
  ...section("Enums", enums),
48
+ ...section("Types", bodies(schema.types)),
49
+ ...section("Domains", bodies(schema.domains)),
47
50
  ...section("Tables", [...schema.tables.values()].map(table)),
48
51
  ...section("Views", bodies(schema.views)),
49
52
  ...section("Functions", bodies(schema.functions)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tandemcreativedev/strabo",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Turn a Postgres schema into a readable record for people and AI: a tidy SQL reference plus DBML, PlantUML and SVG diagrams, generated from pg_dump.",
5
5
  "keywords": [
6
6
  "postgres",