symmetria-kit 1.1.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +112 -33
- package/dist/cli/query-inspect.d.ts +6 -0
- package/dist/cli/query-inspect.js +1 -283
- package/dist/cli.js +331 -280
- package/dist/cli.js.map +1 -1
- package/dist/{ddl-BMHqteKM.js → ddl-Ct-1bZI1.js} +21 -20
- package/dist/ddl-Ct-1bZI1.js.map +1 -0
- package/dist/diff-DXavyPT_.js +2177 -0
- package/dist/diff-DXavyPT_.js.map +1 -0
- package/dist/index.d.ts +53 -10
- package/dist/index.js +3 -3
- package/dist/query-inspector-ChvIIZep.js +1005 -0
- package/dist/query-inspector-ChvIIZep.js.map +1 -0
- package/dist/{src-WVQ1Pauy.js → src-t1x6buIR.js} +1934 -1316
- package/dist/src-t1x6buIR.js.map +1 -0
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/package.json +2 -2
- package/dist/cli/query-inspect.js.map +0 -1
- package/dist/ddl-BMHqteKM.js.map +0 -1
- package/dist/diff-Cm5kAu_c.js +0 -381
- package/dist/diff-Cm5kAu_c.js.map +0 -1
- package/dist/schema-browser-data-BhgnxWmI.js +0 -470
- package/dist/schema-browser-data-BhgnxWmI.js.map +0 -1
- package/dist/src-WVQ1Pauy.js.map +0 -1
package/README.md
CHANGED
|
@@ -56,12 +56,51 @@ export default defineMigrationConfig({
|
|
|
56
56
|
| `repair <id>` | Verify and resolve an incomplete migration |
|
|
57
57
|
| `recover` | Recover files after a crashed generator |
|
|
58
58
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
59
|
+
| Flag | Commands | Purpose |
|
|
60
|
+
| ------------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
61
|
+
| `--config <file>` | all | Config module (default `symmetria.config.ts`) |
|
|
62
|
+
| `--dir <directory>` | all with a project | Migrations directory, relative to the working directory |
|
|
63
|
+
| `--database-url <url>` | database commands, `pull`, `lint` | Connection; overrides `databaseUrl` and `DATABASE_URL` |
|
|
64
|
+
| `--json` | all | One JSON object on stdout, `{"error": …}` on failure |
|
|
65
|
+
| `--sql` | `diff` | Print executable SQL |
|
|
66
|
+
| `--diff <file.json>` | `generate`, `diff`, `lint` | Rename hints and `USING` conversions |
|
|
67
|
+
| `--empty` | `generate` | An empty, editable SQL migration |
|
|
68
|
+
| `--allow-destructive` | `generate` | Permit drops and narrowing type changes (`allowDestructive`) |
|
|
69
|
+
| `--transaction <mode>` | `generate` | `batch` (default), `each` or `none` (`transaction`) |
|
|
70
|
+
| `--online` | `generate`, `diff`, `lint` | Concurrent indexes and phased validation (`online`) |
|
|
71
|
+
| `--allow-custom-sql` | `squash` | Drop SQL that generate did not write (`allowCustomSQL`) |
|
|
72
|
+
| `--pending` | `lint` | Only migrations pending in the database |
|
|
73
|
+
| `--strict` | `lint`, `drift` | Exit with code 1 for any finding |
|
|
74
|
+
| `--to <id>` | `migrate`, `adopt` | Apply up to, or adopt through, a migration (`to`) |
|
|
75
|
+
| `--steps <n>` | `rollback` | Number of migrations to revert (`steps`) |
|
|
76
|
+
| `--yes` | `rollback` | Run `down.sql` without asking; required without a terminal |
|
|
77
|
+
| `--plan` | `migrate`, `rollback` | Show SQL and transaction groups without running them |
|
|
78
|
+
| `--action <action>` | `repair` | `retry` or `complete` (`action`) |
|
|
79
|
+
| `--verify-url <url>` | `verify`, `adopt`, `repair` | Server for disposable databases (`verificationDatabaseUrl`) |
|
|
80
|
+
| `--snapshot <file>` | `repair` | Snapshot file of the boundary to verify, instead of `--verify-url` |
|
|
81
|
+
| `--ignore-table <name>` | `pull`, `drift`, `adopt`, `repair`, `verify` | Leave an undeclared table out, repeatable (`ignoreTables`) |
|
|
82
|
+
| `--advisory-lock-timeout <ms>` | commands that run migrations | Migration lock wait (`advisoryLockTimeoutMs`, default 10000) |
|
|
83
|
+
| `--lock-timeout <ms>` | commands that run migrations | DDL lock wait (`lockTimeoutMs`, default 5000; 0 disables) |
|
|
84
|
+
| `--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
|
+
| `--compact` | `graph` | Entities and relations without column lists |
|
|
87
|
+
| `--relations` | `inspect` | Start on, or list, the relations |
|
|
88
|
+
| `--profile-url <url>` | `profile` | Profiler endpoint (default `http://127.0.0.1:7331`) |
|
|
89
|
+
| `--profile-token <token>` | `profile` | Profiler token (default `SYMMETRIA_PROFILE_TOKEN`) |
|
|
90
|
+
| `--no-interactive` | all | No dashboard, schema browser or rename questions |
|
|
91
|
+
| `--no-color`, `--no-animation` | all | Plain output; no logo or spinner animation |
|
|
92
|
+
| `--help`, `-h` | all | Show the commands and flags |
|
|
93
|
+
|
|
94
|
+
`--help` prints the same list. A flag of particular commands (`--sql`, `--plan`,
|
|
95
|
+
`--to`, `--ignore-table`, …) is refused by the others; connection, directory,
|
|
96
|
+
timeout and display flags are accepted everywhere. The names in parentheses are
|
|
97
|
+
the matching config and API options. With `--json`, every command prints one
|
|
98
|
+
JSON object: the result, with lists under a key (`findings`, `migrations`,
|
|
99
|
+
`steps`, `tables`, `requests`), or `{"error": {"message": …}}` with exit code 1.
|
|
100
|
+
Ctrl-C exits with 130 and SIGTERM with 143. Config paths resolve relative to the
|
|
101
|
+
config file. SQL lives in `migrations/<id>/`; metadata lives in
|
|
102
|
+
`migrations/meta/snapshot.json` and `migrations/meta/migration.json`. Commit SQL
|
|
103
|
+
and both JSON files together. `diff` compares snapshots, not live DB drift.
|
|
65
104
|
|
|
66
105
|
<picture>
|
|
67
106
|
<source media="(prefers-reduced-motion: reduce)" srcset="https://raw.githubusercontent.com/nokturnal3301/symmetria/main/docs/assets/kit-schema.png">
|
|
@@ -110,32 +149,53 @@ erDiagram
|
|
|
110
149
|
|
|
111
150
|
`symmetria pull` reads the connection's `current_schema()` and writes a schema
|
|
112
151
|
module in the Symmetria DSL: tables and columns under any names (with
|
|
113
|
-
`casing: "preserve"` and `.named()` where needed), defaults, identities
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
152
|
+
`casing: "preserve"` and `.named()` where needed), defaults, identities
|
|
153
|
+
(`GENERATED BY DEFAULT` as `.auto.byDefault`), collations, enums under their own
|
|
154
|
+
names (`oneOf(...).typeName("Role")`, shared by several columns too), foreign
|
|
155
|
+
keys as relations (including `ON UPDATE CASCADE`, keys to unique columns and
|
|
156
|
+
columns not named `*_id`, through `.by()` and `.column()`), junction tables,
|
|
157
|
+
primary keys, unique columns, indexes (including expression, partial, ordered,
|
|
158
|
+
`INCLUDE`, collated, `WITH (…)` and non-btree indexes) and CHECK constraints.
|
|
159
|
+
Conditions are predicates where the DSL can write them as PostgreSQL stored them
|
|
160
|
+
(`users.score.between(1, 10)`,
|
|
161
|
+
`and(users.status.is("active"), users.deletedAt.is(null))`), and `sql` text
|
|
162
|
+
otherwise. A schema written with the DSL, migrated and pulled back needs no
|
|
163
|
+
migration: `diff` and `generate` compare conditions in a normalized form, so
|
|
164
|
+
`above(-100)` and `> '-100'::integer` are the same check. Pulling a database
|
|
165
|
+
built from a pulled schema gives back the same schema. A database created by
|
|
166
|
+
Prisma pulls as is, and the Prisma client keeps working next to Symmetria;
|
|
167
|
+
`drift` then lists only what the warnings announced.
|
|
119
168
|
|
|
120
169
|
```sh
|
|
121
170
|
symmetria pull src/database/schema.ts --database-url "$DATABASE_URL"
|
|
122
171
|
```
|
|
123
172
|
|
|
124
173
|
Everything the DSL cannot express is kept as close as possible and listed for
|
|
125
|
-
review: constraints with non-conventional names
|
|
126
|
-
that fixes them), serial columns
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
and
|
|
174
|
+
review: constraints with non-conventional names, Prisma's `_AB_pkey` junction
|
|
175
|
+
keys included (with the `RENAME CONSTRAINT` that fixes them), serial columns
|
|
176
|
+
(with a fix that makes them `BY DEFAULT` identities continuing after the
|
|
177
|
+
existing rows and drops the old sequence), types without a builder such as
|
|
178
|
+
`money` (declared through `customType()`), multi-column unique constraints
|
|
179
|
+
(declared as unique indexes), unique indexes that stand in for constraints (with
|
|
180
|
+
the `ADD CONSTRAINT … USING INDEX` that converts them), composite or deferrable
|
|
181
|
+
foreign keys, and the views, materialized views and triggers the schema does not
|
|
182
|
+
manage. Things that exist only in the database are listed too, so nothing
|
|
183
|
+
disappears without a word: table inheritance (`inheritance`), row-level security
|
|
184
|
+
and policies (`row-security`), functions and procedures (`function`), sequences
|
|
185
|
+
no column owns or several columns share (`sequence`, without the identity fix,
|
|
186
|
+
which would drop the shared sequence) and the number of tables in other schemas,
|
|
187
|
+
which `pull` does not read (`other-schema`). The same list is in `--json` output
|
|
133
188
|
under `warnings`, each with a `code` and, when one exists, a `fix`. The file is
|
|
134
189
|
never overwritten without `--force`.
|
|
135
190
|
|
|
136
191
|
Then point `symmetria.config.ts` at the module, run `drift` until the remaining
|
|
137
192
|
findings are intended, generate the first migration with `generate initial` and
|
|
138
|
-
record it on the existing database with `adopt`.
|
|
193
|
+
record it on the existing database with `adopt`. Tables Symmetria should not
|
|
194
|
+
manage (another service's, PostGIS `spatial_ref_sys`) go in `ignoreTables` in
|
|
195
|
+
the config or `--ignore-table <name>`; `pull`, `drift`, `adopt`, `repair` and
|
|
196
|
+
`verify` leave them out (a table the schema declares is still compared), and the
|
|
197
|
+
CLI always leaves Prisma's `_prisma_migrations` out of the comparisons, so it
|
|
198
|
+
can stay until Prisma no longer deploys.
|
|
139
199
|
|
|
140
200
|
<picture>
|
|
141
201
|
<source media="(prefers-reduced-motion: reduce)" srcset="https://raw.githubusercontent.com/nokturnal3301/symmetria/main/docs/assets/migration-safety.png">
|
|
@@ -145,13 +205,28 @@ record it on the existing database with `adopt`.
|
|
|
145
205
|
## Deployment controls
|
|
146
206
|
|
|
147
207
|
- `generate` requires explicit rename hints or `--allow-destructive` for dropped
|
|
148
|
-
tables/columns
|
|
149
|
-
|
|
208
|
+
tables/columns and for type changes that narrow existing values (a shorter
|
|
209
|
+
`varchar`, fewer decimal places, a smaller integer type, an integer to
|
|
210
|
+
`boolean`). A shorter string type is altered without a truncating cast, so
|
|
211
|
+
PostgreSQL refuses values that do not fit instead of cutting them. Declared
|
|
212
|
+
column order is preserved; snapshot hashes are order-independent.
|
|
150
213
|
- `lint` checks actual `up.sql` even after generation and fails for destructive
|
|
151
|
-
or blocking findings
|
|
152
|
-
|
|
214
|
+
or blocking findings, reviewing every action of an `ALTER TABLE` and ignoring
|
|
215
|
+
comments and strings. `CHECK` and foreign keys added without `NOT VALID` are
|
|
216
|
+
blocking. `--strict` also fails for cautionary findings; `--pending` selects
|
|
217
|
+
unapplied migrations using database history.
|
|
153
218
|
- `migrate --plan --json` shows SQL and transaction groups. `batch` is the
|
|
154
|
-
atomic default;
|
|
219
|
+
atomic default; a migration that adds enum labels commits before the next one
|
|
220
|
+
so that it can use them, with every driver, including custom drivers that only
|
|
221
|
+
run whole transactions. `generate --transaction each|none` opts into other
|
|
222
|
+
boundaries; `none` needs a driver with sessions.
|
|
223
|
+
- Run migrations over a direct or session-pooled connection. Through a
|
|
224
|
+
transaction-mode pooler (PgBouncer `pool_mode = transaction`), which a session
|
|
225
|
+
lock cannot protect, the runner notices and locks each transaction with
|
|
226
|
+
`pg_advisory_xact_lock` instead, and refuses `none` migrations before anything
|
|
227
|
+
runs.
|
|
228
|
+
- `squash` refuses to drop SQL that generate did not write (seeds, views, edited
|
|
229
|
+
`up.sql`) and lists it; `--allow-custom-sql` confirms.
|
|
155
230
|
- `--online` generates concurrent indexes, phased constraint validation and
|
|
156
231
|
additive enum changes with commit boundaries. Incomplete nontransactional work
|
|
157
232
|
persists in the journal and requires explicit `repair`.
|
|
@@ -159,8 +234,12 @@ record it on the existing database with `adopt`.
|
|
|
159
234
|
SIGINT/SIGTERM cancel CLI work; the API accepts an abort signal and
|
|
160
235
|
statement-level events.
|
|
161
236
|
- `drift` checks defaults, identities, PK/FK/UNIQUE/CHECK definitions, FK
|
|
162
|
-
actions, enums, indexes and validation state.
|
|
163
|
-
|
|
237
|
+
actions, enums, indexes and validation state. On a database that is some
|
|
238
|
+
migrations behind the local chain (after `rollback`, say) it reports that
|
|
239
|
+
instead of listing the pending changes as drift, and with `--verify-url` it
|
|
240
|
+
checks the database against the last applied migration. `adopt` verifies the
|
|
241
|
+
live schema before rewriting history, and asks for `--to` when data-only
|
|
242
|
+
migrations make the baseline ambiguous.
|
|
164
243
|
- `verify --verify-url "$VERIFY_DATABASE_URL"` uses real disposable PostgreSQL
|
|
165
244
|
databases; the connection needs `CREATEDB`. Config/API hooks add
|
|
166
245
|
representative rows and assert data invariants during upgrade, rollback and
|
|
@@ -187,7 +266,7 @@ Enable `createProfiler()` in the application, pass it to
|
|
|
187
266
|
`profiler.fetch(handler)`, and call `await profiler.serve()`.
|
|
188
267
|
`symmetria profile` connects to `http://127.0.0.1:7331`; `--profile-url`
|
|
189
268
|
overrides it. Enter opens a request/query, `e` estimates a plan, `a` explicitly
|
|
190
|
-
runs ANALYZE, Escape goes back and `q` exits.
|
|
269
|
+
runs ANALYZE (both shown as a plan tree), Escape goes back and `q` exits.
|
|
191
270
|
|
|
192
271
|
The loopback endpoint checks Host and browser origin and requires the server's
|
|
193
272
|
token on every request. Export `SYMMETRIA_PROFILE_TOKEN` for both the
|
|
@@ -215,10 +294,10 @@ Exports: `defineMigrationConfig`, `migrationSnapshot`, `parseMigrationSnapshot`,
|
|
|
215
294
|
`generateMigration`, `loadMigrations`, `loadMigrationState`, `squashMigrations`,
|
|
216
295
|
`lintMigration`, `lintMigrationSQL`, `detectDrift`, `verifyMigrations`,
|
|
217
296
|
`recoverMigrationFiles`, `pullSchema`, their formatting helpers, and `migrator`
|
|
218
|
-
with their associated types. `pullSchema({ execute })` returns the
|
|
219
|
-
source, the declared tables and the review warnings without touching
|
|
220
|
-
system. `loadMigrationState` returns `{ migrations, snapshot }`; only
|
|
221
|
-
current schema snapshot is stored. Generated and squashed migrations include
|
|
297
|
+
with their associated types. `pullSchema({ execute, ignoreTables })` returns the
|
|
298
|
+
generated source, the declared tables and the review warnings without touching
|
|
299
|
+
the file system. `loadMigrationState` returns `{ migrations, snapshot }`; only
|
|
300
|
+
the current schema snapshot is stored. Generated and squashed migrations include
|
|
222
301
|
their new snapshot.
|
|
223
302
|
|
|
224
303
|
```ts
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { QueryInspectionController } from "symmetria/internal";
|
|
2
2
|
//#region src/cli/screens/query-inspector.d.ts
|
|
3
|
+
export declare const terminalText: (text: string) => string;
|
|
3
4
|
export declare const inspectValue: (value: unknown, expanded?: boolean) => string;
|
|
5
|
+
/**
|
|
6
|
+
* Plan lines wrapped to `width` under their tree gutter: a long relation or
|
|
7
|
+
* index name continues indented below its node instead of at the margin.
|
|
8
|
+
*/
|
|
9
|
+
export declare const wrapExplainLines: (lines: readonly string[], width: number) => string[];
|
|
4
10
|
export declare const explainLines: (plan: readonly Record<string, unknown>[]) => string[];
|
|
5
11
|
export declare const inspectQueryScreen: (inspection: QueryInspectionController, color?: boolean) => Promise<void>;
|
|
6
12
|
//#endregion
|
|
@@ -1,283 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import stringWidth from "string-width";
|
|
3
|
-
import { emitKeypressEvents } from "node:readline";
|
|
4
|
-
import { inspect, stripVTControlCharacters } from "node:util";
|
|
5
|
-
//#region src/cli/screens/query-inspector.ts
|
|
6
|
-
/**
|
|
7
|
-
* Query inspector (`symmetria-kit/inspect`): shows compiled SQL, parameters, decoded rows and EXPLAIN output
|
|
8
|
-
* for a query value, both as a one-off dump and as an interactive screen.
|
|
9
|
-
*/
|
|
10
|
-
const tabs = [
|
|
11
|
-
"SQL",
|
|
12
|
-
"Parameters",
|
|
13
|
-
"Results",
|
|
14
|
-
"Explain"
|
|
15
|
-
];
|
|
16
|
-
const terminalText = (text) => stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
|
|
17
|
-
const inspectValue = (value, expanded = false) => terminalText(inspect(value, {
|
|
18
|
-
colors: false,
|
|
19
|
-
depth: expanded ? null : 5,
|
|
20
|
-
compact: !expanded,
|
|
21
|
-
breakLength: expanded ? 72 : Infinity,
|
|
22
|
-
maxArrayLength: expanded ? null : 20,
|
|
23
|
-
customInspect: false,
|
|
24
|
-
getters: false
|
|
25
|
-
}));
|
|
26
|
-
const explainLines = (plan) => {
|
|
27
|
-
const lines = [];
|
|
28
|
-
const visit = (node, prefix, branch) => {
|
|
29
|
-
const label = [
|
|
30
|
-
node["Node Type"],
|
|
31
|
-
node["Relation Name"],
|
|
32
|
-
node["Index Name"] ? `using ${node["Index Name"]}` : void 0
|
|
33
|
-
].filter(Boolean).join(" ");
|
|
34
|
-
const actual = node["Actual Total Time"] === void 0 ? "" : ` · actual ${node["Actual Total Time"]} ms × ${node["Actual Loops"] ?? 1}`;
|
|
35
|
-
lines.push(`${prefix}${branch}${label} · rows ${node["Plan Rows"] ?? "?"} · cost ${node["Total Cost"] ?? "?"}${actual}`);
|
|
36
|
-
const continuation = prefix + (branch === "├─ " ? "│ " : branch ? " " : "");
|
|
37
|
-
for (const name of [
|
|
38
|
-
"Index Cond",
|
|
39
|
-
"Hash Cond",
|
|
40
|
-
"Merge Cond",
|
|
41
|
-
"Join Filter",
|
|
42
|
-
"Filter",
|
|
43
|
-
"Sort Key",
|
|
44
|
-
"Group Key",
|
|
45
|
-
"Rows Removed by Filter",
|
|
46
|
-
"Shared Hit Blocks",
|
|
47
|
-
"Shared Read Blocks"
|
|
48
|
-
]) if (node[name] !== void 0) lines.push(`${continuation} ${name}: ${Array.isArray(node[name]) ? node[name].join(", ") : String(node[name])}`);
|
|
49
|
-
const children = Array.isArray(node.Plans) ? node.Plans : [];
|
|
50
|
-
children.forEach((child, index) => {
|
|
51
|
-
if (child && typeof child === "object") visit(child, continuation, index === children.length - 1 ? "╰─ " : "├─ ");
|
|
52
|
-
});
|
|
53
|
-
};
|
|
54
|
-
for (const entry of plan) {
|
|
55
|
-
if (entry.Plan && typeof entry.Plan === "object") visit(entry.Plan, "", "");
|
|
56
|
-
for (const name of ["Planning Time", "Execution Time"]) if (entry[name] !== void 0) lines.push(`${name}: ${entry[name]} ms`);
|
|
57
|
-
}
|
|
58
|
-
return lines.length ? lines.map(terminalText) : [inspectValue(plan, true)];
|
|
59
|
-
};
|
|
60
|
-
const inspectQueryScreen = async (inspection, color = supportsColor()) => {
|
|
61
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("symmetria: interactive query inspection requires a terminal");
|
|
62
|
-
let pending;
|
|
63
|
-
await withScreen(() => new Promise((resolve, reject) => {
|
|
64
|
-
const { style, brand } = theme(color);
|
|
65
|
-
const { report } = inspection;
|
|
66
|
-
const errors = /* @__PURE__ */ new Map();
|
|
67
|
-
let tab = "SQL";
|
|
68
|
-
let busy;
|
|
69
|
-
let offset = 0;
|
|
70
|
-
let columnOffset = 0;
|
|
71
|
-
let expanded = false;
|
|
72
|
-
let detailOffset = 0;
|
|
73
|
-
let pageSize = 1;
|
|
74
|
-
let maximum = 0;
|
|
75
|
-
let finished = false;
|
|
76
|
-
let previousLines = [];
|
|
77
|
-
const wasRaw = process.stdin.isRaw;
|
|
78
|
-
const wasFlowing = process.stdin.readableFlowing === true;
|
|
79
|
-
const align = (line, width) => {
|
|
80
|
-
const clipped = fitLine(line, width);
|
|
81
|
-
return clipped + " ".repeat(Math.max(0, width - stringWidth(clipped)));
|
|
82
|
-
};
|
|
83
|
-
const load = (force = false, analyze = false) => {
|
|
84
|
-
if (finished || busy || tab !== "Results" && tab !== "Explain") return;
|
|
85
|
-
const requested = tab;
|
|
86
|
-
if (!inspection.connected) {
|
|
87
|
-
errors.set(tab, "Configure a query executor or driver to use this tab.");
|
|
88
|
-
return draw();
|
|
89
|
-
}
|
|
90
|
-
if (!force && (tab === "Results" ? report.results : report.explanation) || !force && errors.has(tab)) return;
|
|
91
|
-
errors.delete(tab);
|
|
92
|
-
busy = tab;
|
|
93
|
-
draw();
|
|
94
|
-
pending = (requested === "Results" ? inspection.execute() : inspection.explain(analyze)).catch((error) => {
|
|
95
|
-
errors.set(requested, error instanceof Error ? error.message : String(error));
|
|
96
|
-
}).finally(() => {
|
|
97
|
-
busy = void 0;
|
|
98
|
-
if (finished) return;
|
|
99
|
-
draw();
|
|
100
|
-
if (tab !== requested) load();
|
|
101
|
-
});
|
|
102
|
-
};
|
|
103
|
-
const render = () => {
|
|
104
|
-
const width = Math.max(1, Math.min(process.stdout.columns || 88, 160) - 4);
|
|
105
|
-
const height = process.stdout.rows || 24;
|
|
106
|
-
if (width < 32 || height < 12) return [
|
|
107
|
-
" symmetria / query",
|
|
108
|
-
fitLine(" Enlarge terminal to inspect", width),
|
|
109
|
-
" Esc to close"
|
|
110
|
-
].map((line) => fitLine(line, width));
|
|
111
|
-
const innerWidth = width - 4;
|
|
112
|
-
pageSize = height - 9;
|
|
113
|
-
let body = [];
|
|
114
|
-
let status = "";
|
|
115
|
-
let lines = [];
|
|
116
|
-
const error = errors.get(tab);
|
|
117
|
-
if (error) lines = wrapLines(style(terminalText(error), "danger"), innerWidth);
|
|
118
|
-
else if (busy === tab) lines = [style(`Running ${tab === "Results" ? "query" : "EXPLAIN"}…`, "pink")];
|
|
119
|
-
else if (tab === "SQL") lines = wrapLines(highlightSQL(terminalText(report.sql), color), innerWidth - 5).map((line, index) => `${style(String(index + 1).padStart(3), "muted")} ${line}`);
|
|
120
|
-
else if (tab === "Parameters") {
|
|
121
|
-
lines = report.parameters.flatMap((value, index) => [
|
|
122
|
-
style(`$${index + 1} ${value === null ? "null" : value instanceof Date ? "Date" : Array.isArray(value) ? "array" : typeof value}`, "violet"),
|
|
123
|
-
...wrapLines(inspectValue(value, true), innerWidth).map((line) => style(line, "text")),
|
|
124
|
-
""
|
|
125
|
-
]);
|
|
126
|
-
if (!lines.length) lines = [style("No bound parameters", "muted")];
|
|
127
|
-
} else if (tab === "Explain") {
|
|
128
|
-
lines = report.explanation ? wrapLines(expanded ? inspectValue(report.explanation.plan, true) : explainLines(report.explanation.plan).join("\n"), innerWidth) : ["No plan loaded"];
|
|
129
|
-
if (report.explanation) status = `${report.explanation.analyzed ? "ANALYZE · actual execution" : "Estimated plan"} · ${report.explanation.durationMs.toFixed(2)} ms`;
|
|
130
|
-
} else if (report.results) {
|
|
131
|
-
const rows = report.results.rows;
|
|
132
|
-
offset = Math.max(0, Math.min(offset, rows.length - 1));
|
|
133
|
-
status = `${rows.length} rows · ${report.results.durationMs.toFixed(2)} ms including decoding`;
|
|
134
|
-
if (!rows.length) lines = [style("Query returned no rows", "muted")];
|
|
135
|
-
else if (expanded) {
|
|
136
|
-
lines = wrapLines(inspectValue(rows[offset], true), innerWidth);
|
|
137
|
-
status = `Row ${offset + 1}/${rows.length} · ${status}`;
|
|
138
|
-
} else {
|
|
139
|
-
const columns = Object.keys(rows[0]);
|
|
140
|
-
columnOffset = Math.max(0, Math.min(columnOffset, columns.length - 1));
|
|
141
|
-
const visible = [];
|
|
142
|
-
let remaining = innerWidth - 2;
|
|
143
|
-
for (const name of columns.slice(columnOffset)) {
|
|
144
|
-
const preferred = Math.min(30, Math.max(10, stringWidth(name), ...rows.slice(offset, offset + pageSize).map((row) => stringWidth(inspectValue(row[name])))));
|
|
145
|
-
if (visible.length && remaining < Math.min(preferred, 12)) break;
|
|
146
|
-
const size = Math.min(preferred, remaining);
|
|
147
|
-
visible.push({
|
|
148
|
-
name,
|
|
149
|
-
width: size
|
|
150
|
-
});
|
|
151
|
-
remaining -= size + 2;
|
|
152
|
-
if (remaining < 1) break;
|
|
153
|
-
}
|
|
154
|
-
const rowLine = (row, header = false) => visible.map(({ name, width }) => align(header ? name : inspectValue(row[name]), width)).join(" ");
|
|
155
|
-
const available = pageSize - 2;
|
|
156
|
-
const start = Math.max(0, Math.min(offset - available + 1, rows.length - available));
|
|
157
|
-
body = [
|
|
158
|
-
style(` ${rowLine({}, true)}`, "accent"),
|
|
159
|
-
style("─".repeat(innerWidth), "border"),
|
|
160
|
-
...rows.slice(start, start + available).map((row, index) => {
|
|
161
|
-
const line = `${start + index === offset ? "›" : " "} ${rowLine(row)}`;
|
|
162
|
-
return start + index === offset ? style(align(line, innerWidth), "selected") : line;
|
|
163
|
-
})
|
|
164
|
-
];
|
|
165
|
-
maximum = Math.max(0, rows.length - 1);
|
|
166
|
-
status = `Row ${offset + 1}/${rows.length} · columns ${columnOffset + 1}–${columnOffset + visible.length}/${columns.length} · ${report.results.durationMs.toFixed(2)} ms`;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
if (!body.length) {
|
|
170
|
-
maximum = Math.max(0, lines.length - pageSize);
|
|
171
|
-
if (expanded && tab === "Results") detailOffset = Math.min(detailOffset, maximum);
|
|
172
|
-
else offset = Math.min(offset, maximum);
|
|
173
|
-
const start = expanded && tab === "Results" ? detailOffset : offset;
|
|
174
|
-
body = lines.slice(start, start + pageSize);
|
|
175
|
-
if (!status) status = `${tab} · ${lines.length} lines`;
|
|
176
|
-
}
|
|
177
|
-
while (body.length < pageSize) body.push("");
|
|
178
|
-
const labels = tabs.map((name, index) => style(tab === name ? `[${index + 1} ${name}]` : `${index + 1} ${name}`, tab === name ? "pink" : "muted")).join(" ");
|
|
179
|
-
const tabLine = stringWidth(labels) <= width ? labels : `${style(`‹ ${tab} ›`, "pink")} ${style(`${tabs.indexOf(tab) + 1}/4`, "muted")}`;
|
|
180
|
-
const hint = width >= 100 ? `←→ tabs · ${tab === "Results" ? "↑↓ rows · h/l columns · Enter details · r run again" : tab === "Explain" ? "↑↓ scroll · Enter JSON · a analyze · r estimate" : "↑↓ scroll · PgUp/PgDn page"} · Esc close` : width >= 64 ? `←→ tabs · ${tab === "Results" ? "↑↓ rows · h/l cols · Enter expand" : tab === "Explain" ? "↑↓ scroll · a analyze · Enter JSON" : "↑↓ scroll · PgUp/PgDn"} · Esc close` : "←→ tabs · ↑↓ scroll · Esc close";
|
|
181
|
-
return [
|
|
182
|
-
` ${brand()} ${style("/ query inspector", "muted")}`,
|
|
183
|
-
` ${style("●", inspection.connected ? "connected" : "muted")} ${style(`${inspection.connected ? "Executor ready" : "Offline"} · SQL ${report.compileMs.toFixed(3)} ms · ${report.parameters.length} parameters`, "muted")}`,
|
|
184
|
-
"",
|
|
185
|
-
` ${tabLine}`,
|
|
186
|
-
` ${style(`╭${"─".repeat(width - 2)}╮`, "border")}`,
|
|
187
|
-
...body.map((line) => ` ${style("│", "border")} ${align(line, innerWidth)} ${style("│", "border")}`),
|
|
188
|
-
` ${style(`╰${"─".repeat(width - 2)}╯`, "border")}`,
|
|
189
|
-
` ${style(fitLine(status || `${tab} · ready`, width), "violet")}`,
|
|
190
|
-
` ${style(fitLine(hint, width), "muted")}`
|
|
191
|
-
].map((line) => fitLine(line, width + 2));
|
|
192
|
-
};
|
|
193
|
-
const draw = () => {
|
|
194
|
-
if (finished) return;
|
|
195
|
-
try {
|
|
196
|
-
const lines = render();
|
|
197
|
-
const changes = lines.flatMap((line, index) => line === previousLines[index] ? [] : [`\u001b[${index + 1};1H\u001b[2K${line}`]);
|
|
198
|
-
for (let index = lines.length; index < previousLines.length; index++) changes.push(`\u001b[${index + 1};1H\u001b[2K`);
|
|
199
|
-
process.stdout.write(changes.join(""));
|
|
200
|
-
previousLines = lines;
|
|
201
|
-
} catch (error) {
|
|
202
|
-
finish(error);
|
|
203
|
-
}
|
|
204
|
-
};
|
|
205
|
-
const resize = () => {
|
|
206
|
-
previousLines = [];
|
|
207
|
-
process.stdout.write("\x1B[H\x1B[2J");
|
|
208
|
-
draw();
|
|
209
|
-
};
|
|
210
|
-
const finish = (error) => {
|
|
211
|
-
if (finished) return;
|
|
212
|
-
finished = true;
|
|
213
|
-
process.stdin.off("keypress", keypress);
|
|
214
|
-
process.stdin.off("end", end);
|
|
215
|
-
process.stdout.off("resize", resize);
|
|
216
|
-
process.stdin.setRawMode(wasRaw);
|
|
217
|
-
if (!wasFlowing) process.stdin.pause();
|
|
218
|
-
if (error) reject(error);
|
|
219
|
-
else resolve();
|
|
220
|
-
};
|
|
221
|
-
const end = () => finish();
|
|
222
|
-
const keypress = (input, key) => {
|
|
223
|
-
if (key.ctrl && ["c", "d"].includes(key.name ?? "") || key.name === "escape" || input === "q") return finish();
|
|
224
|
-
if ([
|
|
225
|
-
"left",
|
|
226
|
-
"right",
|
|
227
|
-
"tab"
|
|
228
|
-
].includes(key.name ?? "") || /^[1-4]$/.test(input)) {
|
|
229
|
-
tab = tabs[/^[1-4]$/.test(input) ? Number(input) - 1 : (tabs.indexOf(tab) + (key.name === "left" || key.name === "tab" && key.shift ? -1 : 1) + tabs.length) % tabs.length];
|
|
230
|
-
offset = 0;
|
|
231
|
-
detailOffset = 0;
|
|
232
|
-
expanded = false;
|
|
233
|
-
draw();
|
|
234
|
-
load();
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
if (input === "r") {
|
|
238
|
-
offset = 0;
|
|
239
|
-
detailOffset = 0;
|
|
240
|
-
load(true);
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
if (input === "a" && tab === "Explain") {
|
|
244
|
-
offset = 0;
|
|
245
|
-
load(true, true);
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
if (key.name === "return" && ["Results", "Explain"].includes(tab)) {
|
|
249
|
-
expanded = !expanded;
|
|
250
|
-
detailOffset = 0;
|
|
251
|
-
if (tab === "Explain") offset = 0;
|
|
252
|
-
} else if ((input === "h" || input === "l") && tab === "Results" && !expanded) columnOffset += input === "h" ? -1 : 1;
|
|
253
|
-
else if ([
|
|
254
|
-
"up",
|
|
255
|
-
"down",
|
|
256
|
-
"pageup",
|
|
257
|
-
"pagedown",
|
|
258
|
-
"home",
|
|
259
|
-
"end"
|
|
260
|
-
].includes(key.name ?? "")) {
|
|
261
|
-
const current = expanded && tab === "Results" ? detailOffset : offset;
|
|
262
|
-
const amount = key.name === "up" ? -1 : key.name === "down" ? 1 : key.name === "pageup" ? -pageSize : pageSize;
|
|
263
|
-
const next = Math.max(0, Math.min(maximum, key.name === "home" ? 0 : key.name === "end" ? maximum : current + amount));
|
|
264
|
-
if (expanded && tab === "Results") detailOffset = next;
|
|
265
|
-
else offset = next;
|
|
266
|
-
} else return;
|
|
267
|
-
draw();
|
|
268
|
-
};
|
|
269
|
-
emitKeypressEvents(process.stdin);
|
|
270
|
-
process.stdin.setRawMode(true);
|
|
271
|
-
process.stdin.resume();
|
|
272
|
-
process.stdin.on("keypress", keypress);
|
|
273
|
-
process.stdin.once("end", end);
|
|
274
|
-
process.stdout.on("resize", resize);
|
|
275
|
-
process.stdout.write("\x1B[?25l");
|
|
276
|
-
resize();
|
|
277
|
-
}));
|
|
278
|
-
await pending;
|
|
279
|
-
};
|
|
280
|
-
//#endregion
|
|
281
|
-
export { explainLines, inspectQueryScreen, inspectValue };
|
|
282
|
-
|
|
283
|
-
//# sourceMappingURL=query-inspect.js.map
|
|
1
|
+
export { t as explainLines, n as inspectQueryScreen, r as inspectValue, i as terminalText, a as wrapExplainLines } from "../query-inspector-ChvIIZep.js";
|