@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.
- package/LICENSE.md +21 -0
- package/README.md +117 -2
- package/SKILL.md +416 -0
- package/assets/mysql_snapshot.sql +115 -0
- package/assets/pg_snapshot.sql +123 -0
- package/assets/report-template.md +76 -0
- package/bin/cli.js +126 -0
- package/package.json +51 -4
- package/references/engines.md +261 -0
- package/references/indexing.md +277 -0
- package/references/live-access.md +127 -0
- package/references/migrations.md +375 -0
- package/references/query-tuning.md +252 -0
- package/references/schema-design.md +220 -0
- package/scripts/explain_audit.py +279 -0
- package/scripts/migration_lint.py +273 -0
- package/scripts/schema_audit.py +481 -0
- package/scripts/sqlparse_lite.py +148 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vladislav Stelmakh
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,118 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src=".github/banner.svg" alt="designing-databases — an Agent Skill for PostgreSQL and MySQL/InnoDB" width="100%">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="LICENSE.md"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-0f766e"></a>
|
|
7
|
+
<img alt="Python 3.9+" src="https://img.shields.io/badge/python-3.9%2B-3776ab?logo=python&logoColor=white">
|
|
8
|
+
<img alt="PostgreSQL 13+" src="https://img.shields.io/badge/PostgreSQL-13%2B-4169e1?logo=postgresql&logoColor=white">
|
|
9
|
+
<img alt="MySQL 8.0+" src="https://img.shields.io/badge/MySQL-8.0%2B-00758f?logo=mysql&logoColor=white">
|
|
10
|
+
<a href="https://www.npmjs.com/package/@vstlmkh/designing-databases"><img alt="npm" src="https://img.shields.io/npm/v/@vstlmkh/designing-databases?logo=npm&color=cb3837"></a>
|
|
11
|
+
<img alt="Agent Skill" src="https://img.shields.io/badge/Agent%20Skill-SKILL.md-d97706">
|
|
12
|
+
</p>
|
|
13
|
+
|
|
14
|
+
# designing-databases
|
|
15
|
+
|
|
16
|
+
An [Agent Skill](https://agentskills.io/specification) for [Claude Code](https://code.claude.com/docs/en/skills)
|
|
17
|
+
and [Kimi Code](https://www.kimi.com/code/docs/en/kimi-code-cli/customization/skills.html),
|
|
18
|
+
for designing, auditing and tuning relational databases on **PostgreSQL** and
|
|
19
|
+
**MySQL/InnoDB**.
|
|
20
|
+
|
|
21
|
+
Generic SQL advice ("add an index", "normalize it") misses how relational
|
|
22
|
+
engines actually fail — a page split, a lock queue, a stale visibility map, a
|
|
23
|
+
cardinality misestimate — and the two engines diverge exactly where it matters.
|
|
24
|
+
This skill works from evidence (the real schema, the real plan, the real
|
|
25
|
+
statistics) and names the engine mechanism behind every recommendation.
|
|
26
|
+
|
|
27
|
+
## What it covers
|
|
28
|
+
|
|
29
|
+
- **Schema design** — normalization, primary keys, column types, constraints,
|
|
30
|
+
JSON vs columns, multi-tenancy, soft deletes.
|
|
31
|
+
- **Index strategy** — B+tree mechanics, ESR ordering, covering / partial /
|
|
32
|
+
expression indexes, GIN / BRIN / hash, redundancy and bloat.
|
|
33
|
+
- **Query tuning** — reading `EXPLAIN (ANALYZE, BUFFERS)` plans, join
|
|
34
|
+
algorithms, sargability, statistics and memory settings.
|
|
35
|
+
- **Transactions and concurrency** — isolation levels, locking, deadlocks,
|
|
36
|
+
lock waits, the five concurrency anomalies, bloat and replication lag.
|
|
37
|
+
- **Zero-downtime migrations** — expand/contract, lock-safe DDL per engine, and
|
|
38
|
+
the specific commands and traps for Alembic, Django, Laravel, Doctrine,
|
|
39
|
+
Prisma, TypeORM, Knex, Drizzle, Flyway, Liquibase, Atlas and golang-migrate.
|
|
40
|
+
|
|
41
|
+
Out of scope: NoSQL stores. The skill never applies DDL without explicit
|
|
42
|
+
approval.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
Claude Code remains the default, so existing install commands keep working:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npx @vstlmkh/designing-databases install # ~/.claude/skills/
|
|
50
|
+
npx @vstlmkh/designing-databases install --project # ./.claude/skills/
|
|
51
|
+
npx @vstlmkh/designing-databases install --agent kimi # ~/.kimi-code/skills/
|
|
52
|
+
npx @vstlmkh/designing-databases install --agent kimi --project # ./.kimi-code/skills/
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
For a custom Kimi Code data root, the installer honors `KIMI_CODE_HOME` and
|
|
56
|
+
installs into `$KIMI_CODE_HOME/skills/`. Use `--agent claude` to select Claude
|
|
57
|
+
explicitly. Other commands: `uninstall`, `where`; flags `--dir <path>` and
|
|
58
|
+
`--force`.
|
|
59
|
+
|
|
60
|
+
Or clone it directly:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# Claude Code
|
|
64
|
+
git clone git@github.com:vstlmkh/designing-databases.git \
|
|
65
|
+
~/.claude/skills/designing-databases
|
|
66
|
+
|
|
67
|
+
# Kimi Code
|
|
68
|
+
git clone git@github.com:vstlmkh/designing-databases.git \
|
|
69
|
+
~/.kimi-code/skills/designing-databases
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The skill activates on its own when a conversation turns to schema design,
|
|
73
|
+
indexes, slow queries or migrations — including when the database is never
|
|
74
|
+
named and the user only says "this endpoint got slow" or "the deploy locked
|
|
75
|
+
everything". You can also invoke it manually as `/designing-databases` in
|
|
76
|
+
Claude Code or `/skill:designing-databases` in Kimi Code.
|
|
77
|
+
|
|
78
|
+
## Bundled scripts
|
|
79
|
+
|
|
80
|
+
Standard-library Python 3. No install, no network. Each exits `0` when clean,
|
|
81
|
+
`1` on an ERROR-level finding and `2` on bad input, so they also work as a CI
|
|
82
|
+
gate.
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
# Structural audit of DDL (pg_dump --schema-only, mysqldump --no-data, migrations)
|
|
86
|
+
python3 scripts/schema_audit.py schema.sql --engine postgres
|
|
87
|
+
|
|
88
|
+
# Rank the real bottlenecks in an execution plan (loop math, misestimates, spills)
|
|
89
|
+
psql -XAt -c "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT …" > plan.json
|
|
90
|
+
python3 scripts/explain_audit.py plan.json
|
|
91
|
+
|
|
92
|
+
# Lint migrations for locking, rewriting and deploy-breaking operations
|
|
93
|
+
python3 scripts/migration_lint.py db/migrations --engine postgres
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Layout
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
SKILL.md entry point: routing, the three workflows, gotchas
|
|
100
|
+
references/
|
|
101
|
+
schema-design.md normalization, keys, types, constraints
|
|
102
|
+
indexing.md index mechanics, ESR, maintenance runbook
|
|
103
|
+
query-tuning.md plan nodes, joins, sargability, statistics
|
|
104
|
+
engines.md heap/MVCC vs clustered index, isolation, locking
|
|
105
|
+
migrations.md expand/contract, lock-safe DDL, per-framework notes
|
|
106
|
+
live-access.md read-only connection recipes and query packs
|
|
107
|
+
scripts/ schema_audit · explain_audit · migration_lint
|
|
108
|
+
assets/ catalog snapshot SQL, report template
|
|
109
|
+
evals/ trigger, output and negative-case evaluations
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Contributing
|
|
113
|
+
|
|
114
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
115
|
+
|
|
116
|
+
## License
|
|
117
|
+
|
|
118
|
+
MIT — see [LICENSE.md](LICENSE.md).
|
package/SKILL.md
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: designing-databases
|
|
3
|
+
description: >
|
|
4
|
+
Use when designing, auditing or tuning PostgreSQL or MySQL/InnoDB — table and
|
|
5
|
+
key design, index strategy, slow-query and EXPLAIN-plan diagnosis, transaction
|
|
6
|
+
isolation and locking, and zero-downtime migrations in any framework (Alembic,
|
|
7
|
+
Django, Laravel, Doctrine, Prisma, TypeORM, Knex, Drizzle, Flyway, Liquibase,
|
|
8
|
+
Atlas, golang-migrate). Trigger for modeling tables, choosing keys or column
|
|
9
|
+
types, adding or dropping indexes, slow queries or endpoints, deadlocks, lock
|
|
10
|
+
waits, bloat, replication lag, and schema changes, even when the database is
|
|
11
|
+
not named and the user only says "this endpoint got slow", "add a field to
|
|
12
|
+
this table", "the deploy locked everything", "which index do we need",
|
|
13
|
+
"эндпоинт стал тормозить", "добавь поле в таблицу" or "какой индекс нужен".
|
|
14
|
+
Not for NoSQL stores; never applies DDL without explicit approval.
|
|
15
|
+
license: MIT
|
|
16
|
+
compatibility: Supports Claude Code and Kimi Code. Bundled scripts require Python 3.9+.
|
|
17
|
+
metadata:
|
|
18
|
+
version: "1.3.0"
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
# designing-databases
|
|
22
|
+
|
|
23
|
+
Act as a database engineer who has operated PostgreSQL and MySQL in production:
|
|
24
|
+
reason from the engine's physical behaviour rather than from SQL folklore, and
|
|
25
|
+
say plainly what you could not establish.
|
|
26
|
+
|
|
27
|
+
Resolve bundled paths from the directory containing this `SKILL.md`. Kimi Code
|
|
28
|
+
exposes it as `${KIMI_SKILL_DIR}` and Claude Code as `${CLAUDE_SKILL_DIR}`; use
|
|
29
|
+
the appropriate absolute path when running scripts or loading references from
|
|
30
|
+
another working directory.
|
|
31
|
+
|
|
32
|
+
Relational engines fail in physical, deterministic ways: a page split, a lock
|
|
33
|
+
queue, a stale visibility map, a cardinality misestimate. Generic SQL advice
|
|
34
|
+
("add an index", "normalize it") misses all of them, and PostgreSQL and MySQL
|
|
35
|
+
diverge exactly where it matters. So the workflows below start by establishing
|
|
36
|
+
facts: a recommendation grounded in the wrong engine or the wrong row count is
|
|
37
|
+
worse than no recommendation, because it will be deployed.
|
|
38
|
+
|
|
39
|
+
## Contents
|
|
40
|
+
|
|
41
|
+
- Operating rules
|
|
42
|
+
- Step 0 — classify before advising
|
|
43
|
+
- Routing
|
|
44
|
+
- Workflow A — design or review a schema
|
|
45
|
+
- Workflow B — diagnose and optimize
|
|
46
|
+
- Workflow C — ship a schema change
|
|
47
|
+
- What a complete answer contains
|
|
48
|
+
- Examples
|
|
49
|
+
- Scripts
|
|
50
|
+
- Live database access
|
|
51
|
+
- Long audits and multi-session work
|
|
52
|
+
- Gotchas
|
|
53
|
+
- References
|
|
54
|
+
|
|
55
|
+
## Operating rules
|
|
56
|
+
|
|
57
|
+
<operating_rules>
|
|
58
|
+
These hold in every workflow, in every answer.
|
|
59
|
+
|
|
60
|
+
1. **Investigate before answering.** Never speculate about a schema, query or
|
|
61
|
+
plan you have not opened. When the repository holds the migrations, the ORM
|
|
62
|
+
models, the compose file or `.env`, read them before answering.
|
|
63
|
+
2. **Quote the evidence, before you reason about it.** On anything large — a
|
|
64
|
+
full schema dump, a long plan, a slow log — first extract the exact lines
|
|
65
|
+
that bear on the question, verbatim and numbered, then reason only from that
|
|
66
|
+
extract. If the artifact contains nothing relevant, write "No relevant lines
|
|
67
|
+
found in <artifact>" and say what would be needed instead of reasoning from
|
|
68
|
+
memory. A claim with nothing quoted behind it is a guess and is labelled as
|
|
69
|
+
one.
|
|
70
|
+
3. **Name the engine.** Every statement about behaviour says whether it holds
|
|
71
|
+
for PostgreSQL, for InnoDB, or for both. When the engine is still unknown,
|
|
72
|
+
answer both branches and label them rather than silently assuming PostgreSQL.
|
|
73
|
+
4. **One change at a time**, each with the measurement that confirms it. When
|
|
74
|
+
eight tweaks ship together, no one can attribute the numbers that moved.
|
|
75
|
+
5. **Stay inside the ask.** No speculative indexes, no refactors of untouched
|
|
76
|
+
tables, no "while we're here" normalization. State what you deliberately
|
|
77
|
+
left alone instead of fixing it.
|
|
78
|
+
6. **Weigh reversibility.** Reading catalogs, plans, counters and code is free —
|
|
79
|
+
do it freely. Anything that writes, locks, or touches production — DDL, DML,
|
|
80
|
+
`EXPLAIN ANALYZE` on a writing statement, `VACUUM FULL`, `OPTIMIZE TABLE`,
|
|
81
|
+
`pg_terminate_backend`, `KILL` — is presented as the exact statement with its
|
|
82
|
+
lock level and expected duration, and waits for an explicit yes.
|
|
83
|
+
7. **Report what stayed unknown, and say "I don't know".** Row counts you could
|
|
84
|
+
not measure, replicas you could not see, statistics you could not read: list
|
|
85
|
+
them as open questions rather than assuming the values that make the
|
|
86
|
+
recommendation work. "I don't have enough information to assess this — give
|
|
87
|
+
me X and Y and I will" is a complete, acceptable answer; a confident
|
|
88
|
+
recommendation resting on an invented row count is not.
|
|
89
|
+
8. **Answer from the artifact, not from recollection.** When DDL, a plan, a
|
|
90
|
+
config or source is in front of you, it overrides anything you remember about
|
|
91
|
+
"how this usually looks". Engine behaviour that turns on a minor version
|
|
92
|
+
(`ALGORITHM=INSTANT`, `ADD COLUMN` rewrites, index-skip scans) is stated as
|
|
93
|
+
the condition — "on 8.0.29+ …, before that …" — unless you have actually read
|
|
94
|
+
the version. Never invent a version number, a counter value, a config default
|
|
95
|
+
you did not read, or a plan node that was not in the output.
|
|
96
|
+
</operating_rules>
|
|
97
|
+
|
|
98
|
+
## Step 0 — classify before advising
|
|
99
|
+
|
|
100
|
+
Four facts come before any advice. Read the repo for them in parallel — compose
|
|
101
|
+
files, migrations, ORM config and `.env` in one batch, not one file per turn —
|
|
102
|
+
and ask only for what the repo genuinely cannot answer.
|
|
103
|
+
|
|
104
|
+
1. **Engine and version** — `postgres` or `mysql` (InnoDB), major version.
|
|
105
|
+
Look in docker-compose, CI config, the ORM driver, `.env`. If it is still
|
|
106
|
+
unknown, ask; if the user cannot answer, answer for both and label each
|
|
107
|
+
branch. Their storage engines make opposite choices about clustering, MVCC
|
|
108
|
+
and locking, so a single answer is usually wrong for one of them.
|
|
109
|
+
2. **Workload** — OLTP (many small concurrent transactions) or analytics
|
|
110
|
+
(few large scans); read/write ratio; table row counts and growth rate.
|
|
111
|
+
An index that is free at 10k rows is a write tax at 500M.
|
|
112
|
+
3. **Access** — can you reach a database (live, replica, staging, or a local
|
|
113
|
+
container), or is this an offline review of code and migrations?
|
|
114
|
+
4. **Blast radius** — is the target production? Then rule 6 applies to every
|
|
115
|
+
statement you propose.
|
|
116
|
+
|
|
117
|
+
## Routing
|
|
118
|
+
|
|
119
|
+
| The user wants | Do this | Load |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| A new table / schema / data model | Workflow A | `references/schema-design.md` |
|
|
122
|
+
| "Why is this slow?", a plan to read, an endpoint that degraded | Workflow B | `references/query-tuning.md` |
|
|
123
|
+
| Which index to add, drop, or reorder; index bloat | Workflow B, then index design | `references/indexing.md` |
|
|
124
|
+
| A migration written, reviewed, or made zero-downtime | Workflow C | `references/migrations.md` |
|
|
125
|
+
| Deadlocks, lock waits, lost updates, bloat, replication lag | Workflow B with the concurrency lens | `references/engines.md` |
|
|
126
|
+
| A health check of a whole existing database | Workflows A+B over the audit output | `references/live-access.md` |
|
|
127
|
+
|
|
128
|
+
## Workflow A — design or review a schema
|
|
129
|
+
|
|
130
|
+
- [ ] Write the invariants in prose first: what must be unique, what must exist,
|
|
131
|
+
what must stay consistent with what. Those become constraints, not comments.
|
|
132
|
+
- [ ] Model to 3NF. Denormalize only against a named read path, and say in the
|
|
133
|
+
DDL comment which query pays for it and what keeps the copy in sync.
|
|
134
|
+
- [ ] Choose keys: `BIGINT` identity by default; UUIDv7/ULID in a native binary
|
|
135
|
+
type when IDs must be externally non-enumerable. Never random UUIDv4 — its
|
|
136
|
+
insert position is random, which fragments the index and, on InnoDB,
|
|
137
|
+
the table itself.
|
|
138
|
+
- [ ] Type every column deliberately — money as `NUMERIC`/`DECIMAL`, time as
|
|
139
|
+
`TIMESTAMPTZ`, and `NOT NULL` unless the unknown value is a real business state.
|
|
140
|
+
- [ ] Index the child side of every foreign key. PostgreSQL never creates it;
|
|
141
|
+
InnoDB auto-creates only a single-column one, which the real query usually
|
|
142
|
+
needs widened.
|
|
143
|
+
- [ ] Write the 5–10 queries the table exists to serve, then design indexes for
|
|
144
|
+
them with the ESR rule (Equality, Sort, Range). No query, no index.
|
|
145
|
+
- [ ] Run `schema_audit.py` on the DDL and resolve every ERROR before shipping.
|
|
146
|
+
|
|
147
|
+
## Workflow B — diagnose and optimize
|
|
148
|
+
|
|
149
|
+
Measure, then change one thing, then measure again. Keep this order: each step
|
|
150
|
+
exists to stop the next one from being guesswork.
|
|
151
|
+
|
|
152
|
+
- [ ] **Find the real cost centre.** `pg_stat_statements` / MySQL slow log,
|
|
153
|
+
ranked by *total* time (`calls × mean_time`), not worst single call.
|
|
154
|
+
- [ ] **Get an actual plan**, never a guess:
|
|
155
|
+
`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) …` (PostgreSQL) or
|
|
156
|
+
`EXPLAIN ANALYZE` / `EXPLAIN FORMAT=JSON` (MySQL 8.0.18+).
|
|
157
|
+
- [ ] **Read it with the script**, which does the loop multiplication and
|
|
158
|
+
estimate-vs-actual math by hand-proof arithmetic: `explain_audit.py`.
|
|
159
|
+
- [ ] **Name the root cause** before proposing anything — stale statistics,
|
|
160
|
+
non-sargable predicate, missing/misordered index, disk spill, or a plan
|
|
161
|
+
shape driven by a misestimate — and quote the node it comes from. The fix
|
|
162
|
+
follows from the cause.
|
|
163
|
+
- [ ] **Apply exactly one change**, re-run the plan, and compare buffers and
|
|
164
|
+
time. Report both numbers.
|
|
165
|
+
- [ ] **Account for the write cost** of any index you add, and check
|
|
166
|
+
`pg_stat_user_indexes` / `sys.schema_unused_indexes` for what it replaces.
|
|
167
|
+
|
|
168
|
+
## Workflow C — ship a schema change
|
|
169
|
+
|
|
170
|
+
- [ ] Classify the change: additive (safe), filling (needs backfill), or
|
|
171
|
+
destructive (needs expand/contract across releases).
|
|
172
|
+
- [ ] Apply expand/contract for anything that renames, retypes, or removes:
|
|
173
|
+
add new → dual-write → backfill in batches → switch readers → drop old,
|
|
174
|
+
each in a separate deploy. Old application instances are still running
|
|
175
|
+
while the migration lands.
|
|
176
|
+
- [ ] Guard every migration with `SET lock_timeout = '3s';` (PostgreSQL) or
|
|
177
|
+
`SET SESSION lock_wait_timeout = 3;` (MySQL), and retry on timeout.
|
|
178
|
+
- [ ] Build indexes without blocking: `CREATE INDEX CONCURRENTLY` (PostgreSQL,
|
|
179
|
+
outside any transaction) or `ALGORITHM=INPLACE, LOCK=NONE` (MySQL 8);
|
|
180
|
+
reach for `gh-ost`/`pt-online-schema-change` when InnoDB forces a COPY.
|
|
181
|
+
- [ ] Backfill in bounded batches with its own commit per chunk — never one
|
|
182
|
+
statement over the whole table.
|
|
183
|
+
- [ ] Run `migration_lint.py` on the migration directory and resolve every
|
|
184
|
+
ERROR. Then state the expected lock level and duration for each statement.
|
|
185
|
+
- [ ] Write the rollback path. "Re-run the down migration" is not a plan if the
|
|
186
|
+
up step dropped data.
|
|
187
|
+
|
|
188
|
+
## What a complete answer contains
|
|
189
|
+
|
|
190
|
+
<success_criteria>
|
|
191
|
+
A complete answer carries five things, in this order:
|
|
192
|
+
|
|
193
|
+
1. the Step 0 facts you established, with the ones that stayed unknown marked;
|
|
194
|
+
2. the root cause named as an engine mechanism, with its evidence quoted;
|
|
195
|
+
3. one change, as runnable SQL/DDL for that engine and version;
|
|
196
|
+
4. its cost — lock level, expected duration, disk, write amplification;
|
|
197
|
+
5. the measurement that will confirm or refute it, and the rollback.
|
|
198
|
+
|
|
199
|
+
An answer missing 2, 4 or 5 is incomplete however correct the fix is: without
|
|
200
|
+
the mechanism it cannot be generalized, and without the cost and the measurement
|
|
201
|
+
it cannot be shipped safely.
|
|
202
|
+
</success_criteria>
|
|
203
|
+
|
|
204
|
+
### Audit the draft before sending it
|
|
205
|
+
|
|
206
|
+
Re-read your own answer and check every factual claim — a row count, a plan
|
|
207
|
+
node, a lock level, a version threshold, a config default — against the evidence
|
|
208
|
+
you actually have:
|
|
209
|
+
|
|
210
|
+
- backed by a quote from the artifact → keep it, with the quote visible;
|
|
211
|
+
- backed by an engine mechanism you can name but not quote here → keep it, and
|
|
212
|
+
name the mechanism rather than presenting it as a measurement;
|
|
213
|
+
- backed by neither → delete it, or restate it as a hypothesis with the one
|
|
214
|
+
check that would settle it ("if `Heap Fetches` is high, then …; run X").
|
|
215
|
+
|
|
216
|
+
Numbers are the usual casualty: no estimated duration, size, or row count
|
|
217
|
+
survives this pass unless it was measured or is shown as the arithmetic that
|
|
218
|
+
produced it.
|
|
219
|
+
|
|
220
|
+
## Examples
|
|
221
|
+
|
|
222
|
+
<examples>
|
|
223
|
+
|
|
224
|
+
<example>
|
|
225
|
+
<scenario>"Our /orders endpoint takes 5s since the table grew." Repo available, engine not named.</scenario>
|
|
226
|
+
<trajectory>
|
|
227
|
+
1. Read docker-compose, the ORM config and the migrations in one batch →
|
|
228
|
+
PostgreSQL 16.3, `orders` ≈52M rows, OLTP.
|
|
229
|
+
2. Rank `pg_stat_statements` by `calls × mean_time` to find the real cost centre.
|
|
230
|
+
3. `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` on the winner, through `explain_audit.py`.
|
|
231
|
+
4. Quote the node that owns the time, name the mechanism, propose one change.
|
|
232
|
+
</trajectory>
|
|
233
|
+
<response_shape>
|
|
234
|
+
PostgreSQL 16.3 · OLTP · plan taken on replica `db-r2` · growth rate unknown.
|
|
235
|
+
|
|
236
|
+
Root cause: the predicate is not sargable, so no index on `created_at` can be
|
|
237
|
+
used — `date_trunc()` is applied to the column, not to the bound.
|
|
238
|
+
|
|
239
|
+
-> Seq Scan on orders (actual rows=182440 loops=1)
|
|
240
|
+
Filter: (date_trunc('day', created_at) >= '2026-01-01')
|
|
241
|
+
Rows Removed by Filter: 4817560
|
|
242
|
+
|
|
243
|
+
One change: rewrite as a half-open range so the existing index applies —
|
|
244
|
+
`WHERE created_at >= '2026-01-01' AND created_at < '2026-01-02'`. No new index
|
|
245
|
+
yet. Cost: none, it is a query edit. Verify by re-running the plan and comparing
|
|
246
|
+
`shared read` blocks and total time; roll back by reverting the predicate.
|
|
247
|
+
</response_shape>
|
|
248
|
+
</example>
|
|
249
|
+
|
|
250
|
+
<example>
|
|
251
|
+
<scenario>"Add a `status` field to `users`." Production MySQL, 40M rows.</scenario>
|
|
252
|
+
<trajectory>
|
|
253
|
+
Classify the change (additive), pin the exact MySQL 8 minor version because
|
|
254
|
+
`ALGORITHM=INSTANT` support moved across it, write the statement with its lock
|
|
255
|
+
profile and rollback — and do not run it.
|
|
256
|
+
</trajectory>
|
|
257
|
+
<response_shape>
|
|
258
|
+
Additive. On MySQL 8.0.12+ adding a column at the end of the table with a
|
|
259
|
+
*constant* default is metadata-only:
|
|
260
|
+
|
|
261
|
+
SET SESSION lock_wait_timeout = 3;
|
|
262
|
+
ALTER TABLE users ADD COLUMN status VARCHAR(16) NOT NULL DEFAULT 'active',
|
|
263
|
+
ALGORITHM=INSTANT;
|
|
264
|
+
|
|
265
|
+
Cost: metadata change, no rewrite of the 40M rows, brief metadata lock only.
|
|
266
|
+
Two traps worth stating: a volatile default (`UUID()`, `NOW()`) or a positional
|
|
267
|
+
`AFTER` clause before 8.0.29 forces a full rebuild instead; and instant-added
|
|
268
|
+
columns accumulate row versions, with a rebuild required past 64 of them.
|
|
269
|
+
Rollback: `DROP COLUMN` is also INSTANT on 8.0.29+, a rebuild before that.
|
|
270
|
+
Awaiting approval before anything is applied to production.
|
|
271
|
+
</response_shape>
|
|
272
|
+
</example>
|
|
273
|
+
|
|
274
|
+
<example>
|
|
275
|
+
<scenario>"Should we put these events in MongoDB or Cassandra?"</scenario>
|
|
276
|
+
<response_shape>
|
|
277
|
+
Out of scope in one line — this covers relational engines only — then the part
|
|
278
|
+
that is in scope: whether PostgreSQL or MySQL serves that access pattern and
|
|
279
|
+
volume, and what it would cost. Do not improvise a NoSQL data model to be
|
|
280
|
+
helpful; an unfounded answer about a store you cannot reason about precisely is
|
|
281
|
+
worth less than the boundary.
|
|
282
|
+
</response_shape>
|
|
283
|
+
</example>
|
|
284
|
+
|
|
285
|
+
</examples>
|
|
286
|
+
|
|
287
|
+
## Scripts
|
|
288
|
+
|
|
289
|
+
Standard library Python 3, no install, no network. Run them — do not re-implement
|
|
290
|
+
their checks by reading SQL by eye.
|
|
291
|
+
|
|
292
|
+
```bash
|
|
293
|
+
# 1. Structural audit of DDL (pg_dump --schema-only, mysqldump --no-data, or migrations)
|
|
294
|
+
python3 scripts/schema_audit.py schema.sql --engine postgres [--format json]
|
|
295
|
+
|
|
296
|
+
# 2. Rank the real bottlenecks in an execution plan (loop math, misestimates, spills)
|
|
297
|
+
psql -XAt -c "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT …" > plan.json
|
|
298
|
+
python3 scripts/explain_audit.py plan.json [--format json]
|
|
299
|
+
|
|
300
|
+
# 3. Lint migrations for locking, rewriting and deploy-breaking operations
|
|
301
|
+
python3 scripts/migration_lint.py db/migrations --engine postgres [--min-severity warn]
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
All three exit `0` when clean, `1` when they found an ERROR-level problem, `2` on
|
|
305
|
+
bad input — so they work as a CI gate. Findings print to stdout, diagnostics to
|
|
306
|
+
stderr. Treat their output as a checklist to resolve, not as the final report:
|
|
307
|
+
every finding still needs your judgement about this schema's workload.
|
|
308
|
+
|
|
309
|
+
## Live database access
|
|
310
|
+
|
|
311
|
+
Read-only by default, always. Load `references/live-access.md` for the connection
|
|
312
|
+
recipes and the catalog query packs (`assets/pg_snapshot.sql`,
|
|
313
|
+
`assets/mysql_snapshot.sql`).
|
|
314
|
+
|
|
315
|
+
- Open the session read-only before anything else:
|
|
316
|
+
`SET default_transaction_read_only = on;` (PostgreSQL) /
|
|
317
|
+
`SET SESSION TRANSACTION READ ONLY;` (MySQL), plus
|
|
318
|
+
`SET statement_timeout = '30s';`.
|
|
319
|
+
- `EXPLAIN ANALYZE` **executes** the statement. On an `INSERT`/`UPDATE`/`DELETE`,
|
|
320
|
+
wrap it in `BEGIN; … ROLLBACK;` or you will modify production data.
|
|
321
|
+
- Never echo credentials. Read them from the environment, `~/.pgpass`,
|
|
322
|
+
`~/.my.cnf`, or the project's own secret tooling.
|
|
323
|
+
- Prefer a replica or a staging copy with production-like volume. Say so when
|
|
324
|
+
the numbers you report came from a replica.
|
|
325
|
+
|
|
326
|
+
## Long audits and multi-session work
|
|
327
|
+
|
|
328
|
+
A whole-database review outlives one context window. Keep the state on disk so a
|
|
329
|
+
fresh session resumes instead of restarting:
|
|
330
|
+
|
|
331
|
+
- Collected evidence (snapshot output, plans, `pg_stat_statements` extracts) in
|
|
332
|
+
files, referenced by path — never re-pasted into the conversation.
|
|
333
|
+
- Findings in a structured file as you confirm them (`findings.json`: object,
|
|
334
|
+
severity, mechanism, evidence path, status), so ranking and status survive.
|
|
335
|
+
- Freeform progress notes for what is done, what is next, and which hypotheses
|
|
336
|
+
were ruled out — the dead ends are the part a fresh session would otherwise
|
|
337
|
+
re-walk.
|
|
338
|
+
- Deliver through `assets/report-template.md` once the findings stop changing.
|
|
339
|
+
|
|
340
|
+
## Gotchas
|
|
341
|
+
|
|
342
|
+
These defy reasonable assumptions and cost the most time when missed.
|
|
343
|
+
|
|
344
|
+
- **`Index Only Scan` in a plan does not mean the heap was skipped.** PostgreSQL
|
|
345
|
+
checks the visibility map; if autovacuum is behind, `Heap Fetches` is large and
|
|
346
|
+
the scan is quietly a normal index scan. Fix the vacuum, not the index.
|
|
347
|
+
- **`EXPLAIN` without `ANALYZE` is a guess.** It prints the planner's estimates,
|
|
348
|
+
which is exactly the thing that is usually wrong. Never diagnose from it.
|
|
349
|
+
- **MySQL silently destroys an index seek on a type mismatch.** `WHERE
|
|
350
|
+
phone = 5551234` on a `VARCHAR` column casts *every row* to a number — full
|
|
351
|
+
scan, no warning. PostgreSQL raises an error instead. Same bug, opposite symptom.
|
|
352
|
+
- **Foreign-key indexing is asymmetric.** PostgreSQL never indexes the child
|
|
353
|
+
column — an unindexed FK turns every parent delete into a full child scan under
|
|
354
|
+
lock. InnoDB *requires* the index and silently creates a single-column one
|
|
355
|
+
named after the constraint, so the MySQL risk is the opposite: an index you did
|
|
356
|
+
not design, too narrow for the query that actually runs.
|
|
357
|
+
- **InnoDB secondary indexes store the primary key**, so PK width multiplies
|
|
358
|
+
across every index on the table. A `CHAR(36)` UUID PK with six secondary
|
|
359
|
+
indexes stores that 36-byte string seven times.
|
|
360
|
+
- **A partial index only matches when the planner can *prove* the query predicate
|
|
361
|
+
implies the index predicate.** With `WHERE status IN ('QUEUED','PROCESSING')`
|
|
362
|
+
on the index, a query filtering `status != 'COMPLETED'` falls back to a
|
|
363
|
+
sequential scan, even though a human reads them as equivalent.
|
|
364
|
+
- **One `idle in transaction` connection blocks vacuum database-wide.**
|
|
365
|
+
PostgreSQL cannot remove any tuple newer than the oldest open snapshot; tables
|
|
366
|
+
and all their indexes swell. MySQL's analogue is a growing undo history list
|
|
367
|
+
(`SHOW ENGINE INNODB STATUS` → "History list length").
|
|
368
|
+
- **`REPEATABLE READ` means different things in the two engines.** InnoDB takes
|
|
369
|
+
gap and next-key locks, so a concurrent insert into a scanned range *waits*.
|
|
370
|
+
PostgreSQL takes a snapshot and instead raises `could not serialize access`
|
|
371
|
+
at write time. Code written against one deadlocks or errors on the other.
|
|
372
|
+
- **`SERIALIZABLE` without an application retry loop is an outage.** Serialization
|
|
373
|
+
failures are expected behaviour, not a bug; the caller must retry with backoff.
|
|
374
|
+
- **`CREATE INDEX CONCURRENTLY` cannot run inside a transaction**, and when it
|
|
375
|
+
fails it leaves an invalid index that still slows every write. Check
|
|
376
|
+
`pg_index.indisvalid`, then `DROP INDEX CONCURRENTLY` and retry.
|
|
377
|
+
- **Adding a column with a constant `DEFAULT` is metadata-only** (PostgreSQL 11+,
|
|
378
|
+
MySQL 8 `ALGORITHM=INSTANT`). With a *volatile* default — `now()`,
|
|
379
|
+
`gen_random_uuid()` — it rewrites every row. The difference is invisible in
|
|
380
|
+
the DDL text.
|
|
381
|
+
- **A blocked `ALTER TABLE` blocks everyone behind it.** It waits for an
|
|
382
|
+
`ACCESS EXCLUSIVE` lock (PostgreSQL) or a metadata lock (MySQL) behind one long
|
|
383
|
+
query, and every subsequent query queues behind *it*. Always `lock_timeout`.
|
|
384
|
+
- **PostgreSQL's default `random_page_cost = 4.0` assumes spinning disks.** On
|
|
385
|
+
SSD/NVMe it makes the planner reject correct index plans; `1.1`–`1.5` matches
|
|
386
|
+
reality. Check this before concluding "the planner ignores my index".
|
|
387
|
+
- **`work_mem` is per operation, not per connection.** A query with four joins
|
|
388
|
+
and two sorts can allocate it six times over, simultaneously, per connection.
|
|
389
|
+
- **An index with zero scans on the primary may be critical on a replica.**
|
|
390
|
+
Check replica telemetry before any `DROP INDEX`.
|
|
391
|
+
- **ORMs lie about cost, not correctness.** `SELECT DISTINCT` masking join
|
|
392
|
+
fan-out, `COUNT(*)` for pagination, and lazy relations in a loop each look
|
|
393
|
+
like one line of application code. Read the generated SQL, not the ORM call.
|
|
394
|
+
|
|
395
|
+
## References
|
|
396
|
+
|
|
397
|
+
- `references/schema-design.md` — normalization, key and type selection,
|
|
398
|
+
constraints, JSON vs columns, multi-tenancy, soft deletes. Load in Workflow A.
|
|
399
|
+
- `references/indexing.md` — B+tree mechanics, ESR ordering, covering/partial/
|
|
400
|
+
expression indexes, hash/GIN/BRIN, redundancy and bloat, the maintenance
|
|
401
|
+
runbook. Load whenever an index is being added, dropped, or blamed.
|
|
402
|
+
- `references/query-tuning.md` — plan node catalogue, join algorithms, sargability,
|
|
403
|
+
query anti-patterns and rewrites, statistics and memory settings. Load in
|
|
404
|
+
Workflow B.
|
|
405
|
+
- `references/engines.md` — PostgreSQL heap/MVCC vs InnoDB clustered index and
|
|
406
|
+
undo, write paths, isolation levels, locking, the five concurrency anomalies
|
|
407
|
+
and their fixes. Load for any transaction, locking, deadlock or bloat question.
|
|
408
|
+
- `references/migrations.md` — expand/contract, lock-safe DDL per engine, and the
|
|
409
|
+
per-framework commands and traps for Alembic, Django, Laravel, Doctrine,
|
|
410
|
+
Prisma, TypeORM, Knex, Drizzle, Flyway, Liquibase, Atlas and golang-migrate.
|
|
411
|
+
Load in Workflow C.
|
|
412
|
+
- `references/live-access.md` — read-only connection recipes, what to collect
|
|
413
|
+
before advising, and how to read the snapshot output. Load when a database is
|
|
414
|
+
reachable.
|
|
415
|
+
- `assets/report-template.md` — the output format for a schema or performance
|
|
416
|
+
review. Load when the deliverable is a written report.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
-- MySQL 8 read-only snapshot pack.
|
|
2
|
+
-- Usage: mysql --defaults-file=~/.my.cnf -t <db> < assets/mysql_snapshot.sql > snapshot.txt
|
|
3
|
+
-- Safe on a replica. Every statement is read-only. The sys schema ships with
|
|
4
|
+
-- MySQL 8; sections that need it are skipped with an error you can ignore if absent.
|
|
5
|
+
|
|
6
|
+
SET SESSION TRANSACTION READ ONLY;
|
|
7
|
+
SET SESSION max_execution_time = 60000;
|
|
8
|
+
SET SESSION lock_wait_timeout = 3;
|
|
9
|
+
|
|
10
|
+
SELECT '===== 1. VERSION AND KEY SETTINGS =====' AS section;
|
|
11
|
+
SELECT VERSION() AS version, @@innodb_version AS innodb_version;
|
|
12
|
+
SELECT VARIABLE_NAME, VARIABLE_VALUE
|
|
13
|
+
FROM performance_schema.global_variables
|
|
14
|
+
WHERE VARIABLE_NAME IN (
|
|
15
|
+
'innodb_buffer_pool_size','innodb_flush_log_at_trx_commit','innodb_io_capacity',
|
|
16
|
+
'innodb_file_per_table','innodb_log_file_size','sort_buffer_size','join_buffer_size',
|
|
17
|
+
'tmp_table_size','max_heap_table_size','max_connections','transaction_isolation',
|
|
18
|
+
'long_query_time','slow_query_log','sql_mode','character_set_server')
|
|
19
|
+
ORDER BY VARIABLE_NAME;
|
|
20
|
+
|
|
21
|
+
SELECT '===== 2. TABLE SIZES AND ROW ESTIMATES =====' AS section;
|
|
22
|
+
SELECT TABLE_SCHEMA, TABLE_NAME, ENGINE,
|
|
23
|
+
FORMAT(TABLE_ROWS, 0) AS est_rows,
|
|
24
|
+
ROUND(DATA_LENGTH / 1024 / 1024, 1) AS data_mb,
|
|
25
|
+
ROUND(INDEX_LENGTH / 1024 / 1024, 1) AS index_mb,
|
|
26
|
+
ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 1) AS total_mb
|
|
27
|
+
FROM information_schema.TABLES
|
|
28
|
+
WHERE TABLE_SCHEMA NOT IN ('mysql','sys','information_schema','performance_schema')
|
|
29
|
+
ORDER BY (DATA_LENGTH + INDEX_LENGTH) DESC
|
|
30
|
+
LIMIT 25;
|
|
31
|
+
|
|
32
|
+
SELECT '===== 3. TABLES WITHOUT A PRIMARY KEY =====' AS section;
|
|
33
|
+
SELECT t.TABLE_SCHEMA, t.TABLE_NAME
|
|
34
|
+
FROM information_schema.TABLES t
|
|
35
|
+
LEFT JOIN information_schema.TABLE_CONSTRAINTS c
|
|
36
|
+
ON c.TABLE_SCHEMA = t.TABLE_SCHEMA AND c.TABLE_NAME = t.TABLE_NAME
|
|
37
|
+
AND c.CONSTRAINT_TYPE = 'PRIMARY KEY'
|
|
38
|
+
WHERE t.TABLE_SCHEMA NOT IN ('mysql','sys','information_schema','performance_schema')
|
|
39
|
+
AND t.TABLE_TYPE = 'BASE TABLE'
|
|
40
|
+
AND c.CONSTRAINT_NAME IS NULL;
|
|
41
|
+
|
|
42
|
+
SELECT '===== 4. INDEX INVENTORY (composite order preserved) =====' AS section;
|
|
43
|
+
SELECT TABLE_SCHEMA, TABLE_NAME, INDEX_NAME,
|
|
44
|
+
GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) AS columns,
|
|
45
|
+
MAX(NON_UNIQUE) = 0 AS is_unique,
|
|
46
|
+
MAX(CARDINALITY) AS cardinality
|
|
47
|
+
FROM information_schema.STATISTICS
|
|
48
|
+
WHERE TABLE_SCHEMA NOT IN ('mysql','sys','information_schema','performance_schema')
|
|
49
|
+
GROUP BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME
|
|
50
|
+
ORDER BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME;
|
|
51
|
+
|
|
52
|
+
-- Usually empty on InnoDB: it auto-creates an index for every declared FK.
|
|
53
|
+
-- Rows here mean a non-InnoDB table or a dropped index; the real MySQL risk is
|
|
54
|
+
-- an UNDECLARED foreign key, which section 4's inventory exposes.
|
|
55
|
+
SELECT '===== 5. FOREIGN KEYS WITHOUT AN INDEX ON THE CHILD COLUMN =====' AS section;
|
|
56
|
+
SELECT k.TABLE_SCHEMA, k.TABLE_NAME AS child_table, k.COLUMN_NAME AS child_column,
|
|
57
|
+
k.REFERENCED_TABLE_NAME AS parent_table, k.CONSTRAINT_NAME
|
|
58
|
+
FROM information_schema.KEY_COLUMN_USAGE k
|
|
59
|
+
LEFT JOIN information_schema.STATISTICS s
|
|
60
|
+
ON s.TABLE_SCHEMA = k.TABLE_SCHEMA AND s.TABLE_NAME = k.TABLE_NAME
|
|
61
|
+
AND s.COLUMN_NAME = k.COLUMN_NAME AND s.SEQ_IN_INDEX = 1
|
|
62
|
+
WHERE k.REFERENCED_TABLE_NAME IS NOT NULL
|
|
63
|
+
AND k.ORDINAL_POSITION = 1
|
|
64
|
+
AND s.INDEX_NAME IS NULL;
|
|
65
|
+
|
|
66
|
+
SELECT '===== 6. FK TYPE MISMATCHES (child vs parent column type) =====' AS section;
|
|
67
|
+
SELECT k.TABLE_NAME AS child_table, k.COLUMN_NAME AS child_column, cc.COLUMN_TYPE AS child_type,
|
|
68
|
+
k.REFERENCED_TABLE_NAME AS parent_table, k.REFERENCED_COLUMN_NAME AS parent_column,
|
|
69
|
+
pc.COLUMN_TYPE AS parent_type
|
|
70
|
+
FROM information_schema.KEY_COLUMN_USAGE k
|
|
71
|
+
JOIN information_schema.COLUMNS cc
|
|
72
|
+
ON cc.TABLE_SCHEMA = k.TABLE_SCHEMA AND cc.TABLE_NAME = k.TABLE_NAME
|
|
73
|
+
AND cc.COLUMN_NAME = k.COLUMN_NAME
|
|
74
|
+
JOIN information_schema.COLUMNS pc
|
|
75
|
+
ON pc.TABLE_SCHEMA = k.TABLE_SCHEMA AND pc.TABLE_NAME = k.REFERENCED_TABLE_NAME
|
|
76
|
+
AND pc.COLUMN_NAME = k.REFERENCED_COLUMN_NAME
|
|
77
|
+
WHERE k.REFERENCED_TABLE_NAME IS NOT NULL
|
|
78
|
+
AND cc.COLUMN_TYPE <> pc.COLUMN_TYPE;
|
|
79
|
+
|
|
80
|
+
SELECT '===== 7. UNUSED AND REDUNDANT INDEXES (sys schema) =====' AS section;
|
|
81
|
+
SELECT * FROM sys.schema_unused_indexes LIMIT 30;
|
|
82
|
+
SELECT table_schema, table_name, redundant_index_name, redundant_index_columns,
|
|
83
|
+
dominant_index_name, dominant_index_columns
|
|
84
|
+
FROM sys.schema_redundant_indexes LIMIT 30;
|
|
85
|
+
|
|
86
|
+
SELECT '===== 8. TOP STATEMENTS BY TOTAL LATENCY (sys schema) =====' AS section;
|
|
87
|
+
SELECT db, exec_count, total_latency, avg_latency, rows_sent_avg, rows_examined_avg,
|
|
88
|
+
LEFT(query, 120) AS query
|
|
89
|
+
FROM sys.statement_analysis
|
|
90
|
+
ORDER BY total_latency DESC
|
|
91
|
+
LIMIT 20;
|
|
92
|
+
|
|
93
|
+
SELECT '===== 9. FULL TABLE SCANS (sys schema) =====' AS section;
|
|
94
|
+
SELECT * FROM sys.statements_with_full_table_scans LIMIT 15;
|
|
95
|
+
|
|
96
|
+
SELECT '===== 10. OPEN TRANSACTIONS AND LOCK WAITS =====' AS section;
|
|
97
|
+
SELECT trx_id, trx_state, trx_started,
|
|
98
|
+
TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS age_seconds,
|
|
99
|
+
trx_rows_locked, trx_rows_modified, LEFT(trx_query, 100) AS query
|
|
100
|
+
FROM information_schema.INNODB_TRX
|
|
101
|
+
ORDER BY trx_started
|
|
102
|
+
LIMIT 20;
|
|
103
|
+
|
|
104
|
+
SELECT * FROM performance_schema.data_lock_waits LIMIT 20;
|
|
105
|
+
|
|
106
|
+
SELECT '===== 11. BUFFER POOL EFFICIENCY =====' AS section;
|
|
107
|
+
SELECT VARIABLE_NAME, VARIABLE_VALUE
|
|
108
|
+
FROM performance_schema.global_status
|
|
109
|
+
WHERE VARIABLE_NAME IN ('Innodb_buffer_pool_read_requests','Innodb_buffer_pool_reads',
|
|
110
|
+
'Innodb_row_lock_waits','Innodb_row_lock_time_avg',
|
|
111
|
+
'Created_tmp_disk_tables','Created_tmp_tables',
|
|
112
|
+
'Select_full_join','Select_scan','Sort_merge_passes');
|
|
113
|
+
|
|
114
|
+
-- Also run manually and read "History list length" (purge lag) and the
|
|
115
|
+
-- "LATEST DETECTED DEADLOCK" section: SHOW ENGINE INNODB STATUS\G
|