@vstlmkh/designing-databases 0.0.0-stage → 1.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.
@@ -0,0 +1,220 @@
1
+ # Schema design
2
+
3
+ Load in Workflow A — modelling new tables, or reviewing an existing model.
4
+
5
+ ## Contents
6
+
7
+ - Normalize first, denormalize with a receipt
8
+ - Primary keys: the physical consequences
9
+ - Foreign keys
10
+ - Column types that cause incidents
11
+ - Constraints are the cheapest code you will ever write
12
+ - Dynamic attributes: JSON vs EAV vs columns
13
+ - Multi-tenancy
14
+ - Soft deletes
15
+ - Time, money, enums, text
16
+ - Naming conventions
17
+ - Antipattern checklist
18
+
19
+ ## Normalize first, denormalize with a receipt
20
+
21
+ Target 3NF for OLTP: every non-key attribute depends on the key, the whole key,
22
+ and nothing but the key. Violations show up as update anomalies — the same fact
23
+ stored twice, drifting apart.
24
+
25
+ ```sql
26
+ -- Anti-pattern: a customer-level fact stored on the line item
27
+ CREATE TABLE order_items (
28
+ order_id INT,
29
+ item_id INT,
30
+ customer_discount NUMERIC(5,2), -- belongs to the customer or the order
31
+ price NUMERIC(10,2)
32
+ );
33
+
34
+ -- 3NF
35
+ CREATE TABLE orders (
36
+ order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
37
+ customer_id BIGINT NOT NULL REFERENCES customers(customer_id),
38
+ applied_discount NUMERIC(5,2) NOT NULL DEFAULT 0.00,
39
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
40
+ );
41
+
42
+ CREATE TABLE order_items (
43
+ order_id BIGINT NOT NULL REFERENCES orders(order_id),
44
+ item_id BIGINT NOT NULL REFERENCES items(item_id),
45
+ unit_price NUMERIC(10,2) NOT NULL, -- intentional snapshot: the price
46
+ quantity INT NOT NULL CHECK (quantity > 0), -- at time of sale
47
+ PRIMARY KEY (order_id, item_id)
48
+ );
49
+ ```
50
+
51
+ Note the one deliberate denormalization above: `unit_price` is copied because the
52
+ business needs the price *as of* the sale, not today's price. That is the test —
53
+ a denormalized column is acceptable when it is a historical snapshot or when a
54
+ named query cannot meet its latency budget otherwise. Write the reason in a
55
+ `COMMENT ON COLUMN`, and state what keeps the copy in sync.
56
+
57
+ ## Primary keys: the physical consequences
58
+
59
+ The key choice is a storage-layout decision, not an aesthetic one.
60
+
61
+ | Key | Bytes | Monotonic | InnoDB | PostgreSQL |
62
+ |---|---|---|---|---|
63
+ | `BIGINT` identity | 8 | yes | Optimal: appends to the rightmost leaf, no random page splits | Optimal: sequential B-tree inserts, high cache hit ratio |
64
+ | UUIDv4 as `CHAR(36)`/`VARCHAR(36)` | 36 | no | Catastrophic: constant page splits, every secondary index ~4.5x larger | Poor: heavy index bloat, cache misses once the index exceeds RAM |
65
+ | UUIDv4 as `BINARY(16)`/`uuid` | 16 | no | Bad: page splits continue, smaller index overhead | Moderate: index misses cache, heap inserts stay fast |
66
+ | UUIDv7 / ULID as `BINARY(16)`/`uuid` | 16 | yes | Good: sequential leaf appends, compact secondary keys | Good: localized B-tree inserts, high cache locality |
67
+
68
+ Why it matters physically:
69
+
70
+ - **InnoDB: the primary key *is* the table.** The clustered index leaf page holds
71
+ the full row. A random key lands on an arbitrary page; when that 16 KB page is
72
+ full InnoDB splits it, copies ~half the records, and rewires parent pointers.
73
+ Pages stabilize at 50–67% fill, the index doubles in size, and the buffer pool
74
+ thrashes. Every secondary index leaf also stores the PK value as its row
75
+ pointer, so PK width multiplies across all of them.
76
+ - **PostgreSQL: the table is an unordered heap**, so random keys do not split
77
+ *data* pages — but they do scatter writes across the PK B-tree. Once that index
78
+ exceeds `shared_buffers`, each insert reads an uncached page from storage.
79
+
80
+ Default to `BIGINT GENERATED ALWAYS AS IDENTITY` (PostgreSQL) or
81
+ `BIGINT AUTO_INCREMENT` (MySQL). Use UUIDv7/ULID when IDs are exposed to clients
82
+ and must not be enumerable, stored as `uuid` (PostgreSQL) or `BINARY(16)`
83
+ (MySQL) — never as text. Natural keys (email, SKU) make poor primary keys because
84
+ they change and because every foreign key copies them.
85
+
86
+ Composite primary keys are right for pure join tables and for child tables that
87
+ only exist within a parent (`(order_id, item_id)`), and they cluster the children
88
+ of one parent together — a real win in InnoDB.
89
+
90
+ ## Foreign keys
91
+
92
+ - Declare them. "The application enforces it" means the application enforces it
93
+ until the one code path that doesn't.
94
+ - **Index the child column.** PostgreSQL never creates it for you: without it, a
95
+ parent `DELETE` or key `UPDATE` scans the whole child table while holding
96
+ locks — a classic source of connection-pool exhaustion. InnoDB *requires* an
97
+ index and silently creates a single-column one named after the constraint if
98
+ none exists — which is better than nothing but is rarely the index the queries
99
+ want, and it disappears as a concern only while the FK is declared. Columns
100
+ that are foreign keys *in spirit* but undeclared (common after
101
+ `foreign_key_checks=0` imports or ORM-managed relations) get nothing on either
102
+ engine.
103
+ - Match types exactly, including signedness and width. An `INT` child pointing at
104
+ a `BIGINT` parent overflows and can force an implicit cast that kills index
105
+ joins.
106
+ - Pick `ON DELETE` deliberately: `RESTRICT` (default, safest), `CASCADE` (only
107
+ when the child has no independent meaning), `SET NULL` (only when the column is
108
+ nullable by design). Cascades fire row-by-row and can turn one delete into a
109
+ lock storm.
110
+
111
+ ## Column types that cause incidents
112
+
113
+ | Need | Use | Not |
114
+ |---|---|---|
115
+ | Money | `NUMERIC(p,s)` / `DECIMAL(p,s)`, or integer minor units | `FLOAT`, `DOUBLE`, `REAL` — 0.1 is not representable, sums drift |
116
+ | Instant in time | `TIMESTAMPTZ` (PostgreSQL), `TIMESTAMP` or UTC `DATETIME` (MySQL) | `timestamp without time zone`, local-time strings |
117
+ | Date only | `DATE` | `VARCHAR(10)` |
118
+ | Enumerated state | lookup table + FK, or `CHECK (col IN (…))` | native `ENUM` — every new value is a migration, MySQL reorders silently |
119
+ | Boolean | `BOOLEAN` / `TINYINT(1)` | `VARCHAR('Y'/'N')` |
120
+ | Text of bounded length | `VARCHAR(n)` with a real business bound | unbounded `TEXT` in MySQL index keys and temp tables |
121
+ | Identifier from elsewhere | the same type as the source | `VARCHAR` holding digits |
122
+
123
+ MySQL specifics worth knowing: `utf8mb4` costs up to 4 bytes per character, so a
124
+ `VARCHAR(255)` index key is 1020 bytes against InnoDB's 3072-byte limit — three
125
+ such columns in one composite index is the ceiling. `DATETIME` stores no zone and
126
+ does no conversion; `TIMESTAMP` converts to/from UTC using the session zone and
127
+ ends in 2038.
128
+
129
+ ## Constraints are the cheapest code you will ever write
130
+
131
+ - `NOT NULL` by default. Nullability is a business statement; `NULL` propagates
132
+ through comparisons and silently changes aggregate results.
133
+ - `CHECK` for ranges, non-empty strings, and state machines.
134
+ - `UNIQUE` for every real-world identity (email, slug, external ID). A partial
135
+ unique index expresses "unique among live rows":
136
+ `CREATE UNIQUE INDEX ON users (email) WHERE deleted_at IS NULL;`
137
+ - PostgreSQL `DEFERRABLE INITIALLY DEFERRED` lets a batch violate a constraint
138
+ transiently and checks it at `COMMIT` — useful for circular references and
139
+ reordering operations.
140
+ - PostgreSQL `EXCLUDE USING gist (room WITH =, during WITH &&)` enforces
141
+ non-overlapping ranges (bookings, schedules) — no application locking needed.
142
+
143
+ ## Dynamic attributes: JSON vs EAV vs columns
144
+
145
+ Entity-Attribute-Value (`entity_id, attribute_name, attribute_value`) looks like
146
+ flexibility and destroys relational integrity: foreign keys cannot target generic
147
+ text, numbers and dates sort as strings, and reading one entity with ten
148
+ attributes takes ten self-joins.
149
+
150
+ When fields are genuinely user-defined, use the engine's semi-structured type:
151
+
152
+ ```sql
153
+ CREATE TABLE customer_profiles (
154
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
155
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb
156
+ );
157
+
158
+ -- Index the paths that are actually queried, not the whole document
159
+ CREATE INDEX idx_profiles_tier ON customer_profiles ((metadata->>'tier'));
160
+ CREATE INDEX idx_profiles_gin ON customer_profiles USING GIN (metadata jsonb_path_ops);
161
+
162
+ -- Keep invariants even inside the document
163
+ ALTER TABLE customer_profiles
164
+ ADD CONSTRAINT profile_tier_valid
165
+ CHECK (metadata->>'tier' IN ('free','pro','enterprise'));
166
+ ```
167
+
168
+ Rule of thumb: if a field is queried, sorted, or joined on by more than one
169
+ feature, promote it to a real column. JSON is for the long tail.
170
+
171
+ ## Multi-tenancy
172
+
173
+ Three shapes, in increasing isolation and operational cost:
174
+
175
+ 1. **Shared tables with `tenant_id`** — one schema, `tenant_id` as the leading
176
+ column of every index and primary key, and row-level security (PostgreSQL
177
+ `CREATE POLICY`) or a mandatory application filter. Cheapest; the risk is a
178
+ missing `WHERE tenant_id`.
179
+ 2. **Schema per tenant** — isolation without separate servers; migrations must
180
+ loop over schemas, and thousands of schemas strain the catalog.
181
+ 3. **Database per tenant** — strongest isolation, heaviest operations.
182
+
183
+ For (1), make `tenant_id` the first column of composite indexes — it is always an
184
+ equality predicate, which is exactly where the ESR rule puts it.
185
+
186
+ ## Soft deletes
187
+
188
+ A `deleted_at` column means every query must filter it and every index carries
189
+ dead rows. If you adopt it:
190
+
191
+ - Make the hot-path indexes partial: `… WHERE deleted_at IS NULL`.
192
+ - Make unique constraints partial too, or re-inserting a deleted email fails.
193
+ - Verify the ORM's default scope actually applies on every path, including raw
194
+ SQL, reports, and joins through the table.
195
+ - Consider an archive table instead: move the row, keep the live table small.
196
+
197
+ ## Naming conventions
198
+
199
+ Pick one and apply it mechanically: `snake_case`; plural table names; `id` for
200
+ the surrogate key; `<referenced_table_singular>_id` for FKs; `created_at` /
201
+ `updated_at` on every mutable table; index names that carry their purpose
202
+ (`idx_<table>_<cols>`, `uq_<table>_<cols>`, `fk_<table>_<ref>`). Consistency is
203
+ worth more than the specific choice — it is what makes a missing index obvious.
204
+
205
+ ## Antipattern checklist
206
+
207
+ Run `scripts/schema_audit.py` to catch these mechanically:
208
+
209
+ - Table with no primary key (InnoDB builds a hidden one you cannot use;
210
+ PostgreSQL loses replica identity for logical replication).
211
+ - Random UUIDv4 primary key, or a UUID stored as 36-byte text.
212
+ - Foreign key with no index on the child column (error on PostgreSQL;
213
+ on MySQL a warning — InnoDB auto-creates a narrow one).
214
+ - Child/parent type mismatch across a foreign key.
215
+ - Money in a binary float type.
216
+ - `timestamp without time zone` for an instant.
217
+ - An index that is a leftmost prefix of another index on the same table.
218
+ - EAV-shaped tables.
219
+ - Every column nullable.
220
+ - JSON column with no supporting index.
@@ -0,0 +1,279 @@
1
+ #!/usr/bin/env python3
2
+ """Analyze a PostgreSQL JSON execution plan and rank the real bottlenecks.
3
+
4
+ Input: the output of
5
+ EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) <query>;
6
+ saved to a file, or piped on stdin. MySQL `EXPLAIN FORMAT=JSON` is detected and
7
+ reported with the subset of checks that apply (MySQL reports no per-node
8
+ buffers and only reports timings with EXPLAIN ANALYZE).
9
+
10
+ Usage:
11
+ python3 explain_audit.py plan.json [--format text|json] [--top N]
12
+
13
+ What it computes that reading the plan by eye gets wrong:
14
+ * self time per node (total time x loops, minus children) — the loop
15
+ multiplier is the single most misread number in a nested plan;
16
+ * estimate vs actual row ratio per node, which is what makes the planner
17
+ pick a Nested Loop over a Hash Join;
18
+ * disk spills, lossy bitmaps, heap fetches and buffer read ratios.
19
+
20
+ Exit codes: 0 = no error-level findings, 1 = at least one, 2 = unparseable input.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+
28
+ # Thresholds. Each is a documented judgement call, not a magic constant.
29
+ MISESTIMATE_RATIO = 10.0 # planner picks wrong join algorithms past ~10x
30
+ MISESTIMATE_MIN_ROWS = 100.0 # below this, ratios are noise
31
+ SLOW_NODE_SHARE = 0.20 # a node owning >20% of runtime is worth naming
32
+ HIGH_LOOPS = 10_000 # loop counts where per-row cost dominates
33
+ FILTER_WASTE_RATIO = 10.0 # rows discarded per row returned
34
+
35
+
36
+ def child_nodes(node: dict) -> list[dict]:
37
+ kids = list(node.get("Plans", []))
38
+ return kids
39
+
40
+
41
+ def walk(node: dict, depth: int = 0, parent: dict | None = None):
42
+ yield node, depth, parent
43
+ for kid in child_nodes(node):
44
+ yield from walk(kid, depth + 1, node)
45
+
46
+
47
+ def total_time(node: dict) -> float:
48
+ """Inclusive wall time for every execution of this node, in ms."""
49
+ return float(node.get("Actual Total Time", 0.0)) * float(node.get("Actual Loops", 1) or 1)
50
+
51
+
52
+ def self_time(node: dict) -> float:
53
+ return max(0.0, total_time(node) - sum(total_time(k) for k in child_nodes(node)))
54
+
55
+
56
+ def node_label(node: dict) -> str:
57
+ label = node.get("Node Type", "?")
58
+ for key in ("Relation Name", "Index Name", "CTE Name", "Subplan Name"):
59
+ if node.get(key):
60
+ label += f" on {node[key]}"
61
+ break
62
+ return label
63
+
64
+
65
+ def analyze_postgres(plan_root: dict, execution_time: float | None) -> tuple[list[dict], list[dict]]:
66
+ findings: list[dict] = []
67
+ nodes: list[dict] = []
68
+
69
+ root_time = total_time(plan_root) or (execution_time or 0.0)
70
+
71
+ for node, depth, _parent in walk(plan_root):
72
+ loops = float(node.get("Actual Loops", 1) or 1)
73
+ act = float(node.get("Actual Rows", 0)) * loops
74
+ est = float(node.get("Plan Rows", 0)) * loops
75
+ st = self_time(node)
76
+ label = node_label(node)
77
+ nodes.append({
78
+ "node": label,
79
+ "depth": depth,
80
+ "self_time_ms": round(st, 3),
81
+ "total_time_ms": round(total_time(node), 3),
82
+ "loops": int(loops),
83
+ "actual_rows": int(act),
84
+ "estimated_rows": int(est),
85
+ })
86
+
87
+ def add(fid, sev, msg, fix):
88
+ findings.append({"id": fid, "severity": sev, "node": label,
89
+ "self_time_ms": round(st, 3), "message": msg, "fix": fix})
90
+
91
+ ntype = node.get("Node Type", "")
92
+
93
+ if root_time and st / root_time > SLOW_NODE_SHARE and st > 1.0:
94
+ add("PLAN001", "info",
95
+ f"Owns {st / root_time:.0%} of total runtime ({st:.1f} ms of {root_time:.1f} ms).",
96
+ "This is the node to fix; changes elsewhere cannot beat Amdahl's law.")
97
+
98
+ if est >= 1 and act >= MISESTIMATE_MIN_ROWS:
99
+ ratio = max(act / est, est / max(act, 1))
100
+ if ratio >= MISESTIMATE_RATIO:
101
+ add("PLAN002", "error",
102
+ f"Row estimate off by {ratio:.0f}x (estimated {int(est)}, actual {int(act)}).",
103
+ "The planner chose this shape from the wrong cardinality. Run ANALYZE on "
104
+ "the table; if it persists, raise the statistics target or add extended "
105
+ "statistics (CREATE STATISTICS) for correlated columns.")
106
+
107
+ if ntype == "Seq Scan" and act > 50_000:
108
+ add("PLAN003", "error",
109
+ f"Sequential scan returning {int(act)} rows from {node.get('Relation Name', '?')}.",
110
+ "Missing index, a non-sargable predicate, or a filter too unselective to "
111
+ "help. Check the Filter line before adding an index.")
112
+
113
+ removed = float(node.get("Rows Removed by Filter", 0)) * loops
114
+ if removed > 10_000 and removed > act * FILTER_WASTE_RATIO:
115
+ add("PLAN004", "warn",
116
+ f"Discarded {int(removed)} rows by filter to return {int(act)}.",
117
+ "The access path is far broader than the predicate. Move the filtered column "
118
+ "into the index key (equality columns first), or make it a partial index.")
119
+
120
+ if node.get("Sort Method", "").startswith("external") or node.get("Sort Space Type") == "Disk":
121
+ add("PLAN005", "error",
122
+ f"Sort spilled to disk ({node.get('Sort Method')}, "
123
+ f"{node.get('Sort Space Used', '?')} kB).",
124
+ "Raise work_mem for this statement (SET LOCAL work_mem = '64MB' inside the "
125
+ "transaction — it is per operation, not per connection), or supply the order "
126
+ "from an index so the sort disappears.")
127
+
128
+ if int(node.get("Hash Batches", 1) or 1) > 1:
129
+ add("PLAN006", "error",
130
+ f"Hash join spilled into {node.get('Hash Batches')} batches "
131
+ f"(peak {node.get('Peak Memory Usage', '?')} kB).",
132
+ "The build side exceeded work_mem. Raise work_mem for the statement or "
133
+ "reduce the build side with an earlier filter.")
134
+
135
+ heap_fetches = float(node.get("Heap Fetches", 0))
136
+ if ntype == "Index Only Scan" and heap_fetches > 0:
137
+ sev = "warn" if heap_fetches > max(act * 0.1, 100) else "info"
138
+ add("PLAN007", sev,
139
+ f"Index Only Scan performed {int(heap_fetches)} heap fetches.",
140
+ "The visibility map is stale, so the scan is not index-only in practice. "
141
+ "Run VACUUM (ANALYZE) on the table and tune autovacuum for its write rate.")
142
+
143
+ lossy = float(node.get("Lossy Heap Blocks", 0))
144
+ if lossy > 0:
145
+ add("PLAN008", "warn",
146
+ f"Bitmap degraded to lossy ({int(lossy)} lossy blocks).",
147
+ "The bitmap outgrew work_mem, so every row on those pages is rechecked. "
148
+ "Raise work_mem or make the index more selective.")
149
+
150
+ inner_loops = max((float(k.get("Actual Loops", 1) or 1) for k in child_nodes(node)), default=0)
151
+ if ntype == "Nested Loop" and inner_loops >= HIGH_LOOPS:
152
+ add("PLAN009", "warn",
153
+ f"Nested Loop drives its inner side {int(inner_loops)} times.",
154
+ "Usually a cardinality misestimate on the outer side. Fix statistics first; "
155
+ "a Hash Join is typically correct at this volume.")
156
+
157
+ # Buffer counters are cumulative over children — subtract them so the
158
+ # finding lands on the node that actually did the I/O.
159
+ read = float(node.get("Shared Read Blocks", 0)) - sum(
160
+ float(k.get("Shared Read Blocks", 0)) for k in child_nodes(node))
161
+ hit = float(node.get("Shared Hit Blocks", 0)) - sum(
162
+ float(k.get("Shared Hit Blocks", 0)) for k in child_nodes(node))
163
+ if read > 10_000 and read > hit:
164
+ add("PLAN010", "warn",
165
+ f"Read {int(read)} blocks from disk vs {int(hit)} cache hits.",
166
+ "The working set does not fit the buffer cache for this path. A covering or "
167
+ "partial index shrinks what must be resident.")
168
+
169
+ return findings, nodes
170
+
171
+
172
+ def analyze_mysql(block: dict) -> tuple[list[dict], list[dict]]:
173
+ findings: list[dict] = []
174
+ nodes: list[dict] = []
175
+
176
+ def visit(obj, path="query_block"):
177
+ if isinstance(obj, dict):
178
+ ti = obj.get("table")
179
+ if isinstance(ti, dict):
180
+ name = ti.get("table_name", "?")
181
+ access = ti.get("access_type", "?")
182
+ rows = ti.get("rows_examined_per_scan") or ti.get("rows") or 0
183
+ nodes.append({"node": f"{access} on {name}", "actual_rows": rows,
184
+ "key": ti.get("key"), "depth": 0,
185
+ "self_time_ms": None, "total_time_ms": None, "loops": None,
186
+ "estimated_rows": rows})
187
+ if access == "ALL" and float(rows or 0) > 50_000:
188
+ findings.append({"id": "MY001", "severity": "error", "node": name,
189
+ "self_time_ms": None,
190
+ "message": f"Full table scan (access_type ALL) over ~{rows} rows.",
191
+ "fix": "No usable index. Check possible_keys and the "
192
+ "leftmost-prefix rule for the WHERE predicate."})
193
+ if ti.get("using_filesort"):
194
+ findings.append({"id": "MY002", "severity": "warn", "node": name,
195
+ "self_time_ms": None,
196
+ "message": "Using filesort.",
197
+ "fix": "Order the composite index so the ORDER BY columns "
198
+ "follow the equality columns, in the same direction."})
199
+ if ti.get("using_temporary_table"):
200
+ findings.append({"id": "MY003", "severity": "warn", "node": name,
201
+ "self_time_ms": None,
202
+ "message": "Using temporary table.",
203
+ "fix": "GROUP BY/DISTINCT could not stream from an index. "
204
+ "Consider an index covering the grouping columns."})
205
+ for v in obj.values():
206
+ visit(v, path)
207
+ elif isinstance(obj, list):
208
+ for v in obj:
209
+ visit(v, path)
210
+
211
+ visit(block)
212
+ return findings, nodes
213
+
214
+
215
+ def main(argv=None) -> int:
216
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
217
+ ap.add_argument("file", nargs="?", help="JSON plan file; omit to read stdin")
218
+ ap.add_argument("--format", choices=["text", "json"], default="text")
219
+ ap.add_argument("--top", type=int, default=8, help="how many nodes to list by self time")
220
+ args = ap.parse_args(argv)
221
+
222
+ try:
223
+ raw = open(args.file, encoding="utf-8").read() if args.file else sys.stdin.read()
224
+ data = json.loads(raw)
225
+ except (OSError, json.JSONDecodeError) as exc:
226
+ print(f"ERROR: expected JSON. Re-run the plan with FORMAT JSON "
227
+ f"(PostgreSQL: EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ...). Detail: {exc}",
228
+ file=sys.stderr)
229
+ return 2
230
+
231
+ engine = "postgres"
232
+ if isinstance(data, list) and data and "Plan" in data[0]:
233
+ root = data[0]
234
+ findings, nodes = analyze_postgres(root["Plan"], root.get("Execution Time"))
235
+ exec_time = root.get("Execution Time")
236
+ planning = root.get("Planning Time")
237
+ elif isinstance(data, dict) and "Plan" in data:
238
+ findings, nodes = analyze_postgres(data["Plan"], data.get("Execution Time"))
239
+ exec_time = data.get("Execution Time")
240
+ planning = data.get("Planning Time")
241
+ elif isinstance(data, dict) and "query_block" in data:
242
+ engine = "mysql"
243
+ findings, nodes = analyze_mysql(data["query_block"])
244
+ exec_time = planning = None
245
+ else:
246
+ print("ERROR: unrecognized plan JSON (no 'Plan' or 'query_block' key).", file=sys.stderr)
247
+ return 2
248
+
249
+ if engine == "postgres" and not any(n.get("total_time_ms") for n in nodes):
250
+ print("WARNING: plan has no actual timings — you ran EXPLAIN without ANALYZE. "
251
+ "Estimates alone cannot show the bottleneck.", file=sys.stderr)
252
+
253
+ nodes_sorted = sorted(nodes, key=lambda n: -(n["self_time_ms"] or 0))[: args.top]
254
+ sev_rank = {"error": 0, "warn": 1, "info": 2}
255
+ findings.sort(key=lambda f: (sev_rank[f["severity"]], -(f["self_time_ms"] or 0)))
256
+
257
+ if args.format == "json":
258
+ print(json.dumps({"engine": engine, "execution_time_ms": exec_time,
259
+ "planning_time_ms": planning, "hot_nodes": nodes_sorted,
260
+ "findings": findings}, indent=2))
261
+ else:
262
+ if exec_time is not None:
263
+ print(f"Execution time: {exec_time} ms Planning time: {planning} ms")
264
+ print(f"\nHottest nodes by self time (total time x loops, children subtracted):")
265
+ for n in nodes_sorted:
266
+ st = f"{n['self_time_ms']:>9.2f} ms" if n["self_time_ms"] is not None else " -"
267
+ print(f" {st} rows={n['actual_rows']:<10} est={n['estimated_rows']:<10} "
268
+ f"loops={n['loops']} {n['node']}")
269
+ print(f"\n{len(findings)} finding(s):\n")
270
+ for f in findings:
271
+ print(f"[{f['severity'].upper():5}] {f['id']} {f['node']}")
272
+ print(f" {f['message']}")
273
+ print(f" FIX: {f['fix']}\n")
274
+
275
+ return 1 if any(f["severity"] == "error" for f in findings) else 0
276
+
277
+
278
+ if __name__ == "__main__":
279
+ sys.exit(main())