@tandemcreativedev/strabo 0.2.0 → 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 +28 -3
- package/dist/cli.js +10 -4
- package/dist/config.d.ts +2 -0
- package/dist/config.js +7 -5
- package/dist/diagram.d.ts +3 -2
- package/dist/diagram.js +5 -4
- package/dist/generate.d.ts +5 -2
- package/dist/generate.js +9 -5
- package/dist/model.d.ts +7 -1
- package/dist/parse.d.ts +2 -2
- package/dist/parse.js +85 -39
- package/dist/writers/dbml.js +1 -1
- package/dist/writers/puml.d.ts +2 -1
- package/dist/writers/puml.js +17 -3
- package/dist/writers/sql.js +3 -0
- package/package.json +1 -1
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.
|
|
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
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.
|
|
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
|
```
|
|
@@ -82,8 +86,27 @@ A typical `package.json` script, run after applying migrations locally:
|
|
|
82
86
|
- `enums: false` leaves enum definitions out, such as when another diagram already lists them.
|
|
83
87
|
- `formats` takes any of `dbml` (the default), `puml` and `svg`.
|
|
84
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.
|
|
85
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.
|
|
86
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
|
+
|
|
87
110
|
## Programmatic use
|
|
88
111
|
|
|
89
112
|
```ts
|
|
@@ -92,6 +115,8 @@ import { generate, resolveConfig } from "@tandemcreativedev/strabo";
|
|
|
92
115
|
const { files, warnings } = generate(dumpText, resolveConfig({ schemas: ["public"] }));
|
|
93
116
|
```
|
|
94
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
|
+
|
|
95
120
|
`parseDump`, `buildDiagram`, `writeSql`, `writeDbml`, `writePuml` and `writeSvg` are exported too, for custom output.
|
|
96
121
|
|
|
97
122
|
## Releasing
|
|
@@ -106,4 +131,4 @@ UPDATE_EXPECTED=1 pnpm test # accept output changes into test/fixtures/expected
|
|
|
106
131
|
pnpm fixture # rebuild the fixture dump from fixture.ddl.sql (needs local Supabase)
|
|
107
132
|
```
|
|
108
133
|
|
|
109
|
-
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
|
|
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) =>
|
|
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
|
@@ -25,6 +25,8 @@ export interface Config {
|
|
|
25
25
|
diagrams: DiagramConfig[];
|
|
26
26
|
/** Foreign keys to leave out of diagrams, as `schema.table.column`, each with the note to show instead. */
|
|
27
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>;
|
|
28
30
|
/** The pg_dump command, such as `pg_dump` or `docker exec -i supabase_db_app pg_dump`. */
|
|
29
31
|
pgDump: string;
|
|
30
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) {
|
|
@@ -58,11 +59,12 @@ export function resolveConfig(raw) {
|
|
|
58
59
|
fail("sql must be a file name or false");
|
|
59
60
|
if (input.diagrams !== undefined && !Array.isArray(input.diagrams))
|
|
60
61
|
fail("diagrams must be an array");
|
|
61
|
-
|
|
62
|
-
(
|
|
63
|
-
input
|
|
64
|
-
|
|
65
|
-
|
|
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}`);
|
|
66
68
|
return {
|
|
67
69
|
...DEFAULTS,
|
|
68
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,
|
|
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,
|
|
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 {
|
package/dist/generate.d.ts
CHANGED
|
@@ -9,5 +9,8 @@ export interface Result {
|
|
|
9
9
|
files: OutputFile[];
|
|
10
10
|
warnings: string[];
|
|
11
11
|
}
|
|
12
|
-
/**
|
|
13
|
-
|
|
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
|
-
/**
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
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
|
-
|
|
121
|
-
|
|
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
|
|
124
|
-
|
|
125
|
-
|
|
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
|
|
128
|
-
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
const definitions = (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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
}
|
package/dist/writers/dbml.js
CHANGED
|
@@ -59,7 +59,7 @@ function columnSettings(table, column, diagram) {
|
|
|
59
59
|
settings.push(fallback);
|
|
60
60
|
const notes = [
|
|
61
61
|
column.comment,
|
|
62
|
-
column.generated
|
|
62
|
+
column.generated,
|
|
63
63
|
diagram.hiddenRefs.get(`${table.name}.${column.name}`) ?? null,
|
|
64
64
|
].filter((note) => note !== null);
|
|
65
65
|
if (notes.length)
|
package/dist/writers/puml.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
import { type Diagram } from "../diagram.js";
|
|
2
|
-
|
|
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;
|
package/dist/writers/puml.js
CHANGED
|
@@ -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.
|
|
48
|
+
return `${alias(relation.refTable, diagram)} ||--${childEnd} ${alias(relation.table, diagram)} : "${relation.label.replace(/"/g, "'")}"`;
|
|
49
49
|
}
|
|
50
|
-
|
|
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
|
|
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");
|
package/dist/writers/sql.js
CHANGED
|
@@ -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.
|
|
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",
|