@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
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Lint migration files for operations that lock, rewrite, or break a running deploy.
|
|
3
|
+
|
|
4
|
+
Works on raw SQL (Flyway, Liquibase formatted SQL, golang-migrate, Atlas) and on
|
|
5
|
+
framework migrations (Alembic, Django, Laravel, Doctrine, TypeORM, Knex, Drizzle,
|
|
6
|
+
Rails) by matching both the SQL and the framework DSL.
|
|
7
|
+
|
|
8
|
+
Usage:
|
|
9
|
+
python3 migration_lint.py <file|dir> [...] [--engine postgres|mysql]
|
|
10
|
+
[--format text|json] [--min-severity info|warn|error]
|
|
11
|
+
|
|
12
|
+
Exit codes: 0 = no ERROR findings, 1 = at least one ERROR, 2 = usage error.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
SEVERITY_ORDER = {"info": 0, "warn": 1, "error": 2}
|
|
23
|
+
SUFFIXES = (".sql", ".py", ".php", ".ts", ".js", ".rb", ".go", ".xml", ".yaml", ".yml", ".json")
|
|
24
|
+
|
|
25
|
+
VOLATILE_DEFAULTS = r"(now\(\)|current_timestamp|clock_timestamp\(\)|random\(\)|gen_random_uuid\(\)|uuid_generate_v4\(\)|uuid\(\))"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Rule:
|
|
29
|
+
def __init__(self, rid, severity, pattern, message, fix, engines=("postgres", "mysql"),
|
|
30
|
+
unless=None, flags=re.I):
|
|
31
|
+
self.id = rid
|
|
32
|
+
self.severity = severity
|
|
33
|
+
self.pattern = re.compile(pattern, flags)
|
|
34
|
+
self.message = message
|
|
35
|
+
self.fix = fix
|
|
36
|
+
self.engines = engines
|
|
37
|
+
self.unless = re.compile(unless, re.I) if unless else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# --- rules that read one logical line/statement -----------------------------
|
|
41
|
+
LINE_RULES = [
|
|
42
|
+
Rule("MIG001", "error",
|
|
43
|
+
r"\bCREATE\s+(UNIQUE\s+)?INDEX\b",
|
|
44
|
+
"CREATE INDEX without CONCURRENTLY locks out writes for the whole build.",
|
|
45
|
+
"PostgreSQL: CREATE INDEX CONCURRENTLY (outside any transaction). "
|
|
46
|
+
"MySQL 8: add ALGORITHM=INPLACE, LOCK=NONE.",
|
|
47
|
+
engines=("postgres",), unless=r"CONCURRENTLY"),
|
|
48
|
+
|
|
49
|
+
Rule("MIG002", "error",
|
|
50
|
+
r"\bCREATE\s+(UNIQUE\s+)?INDEX\b(?![^;]*ALGORITHM\s*=)",
|
|
51
|
+
"CREATE INDEX without an explicit ALGORITHM/LOCK clause.",
|
|
52
|
+
"State the intent so the server errors instead of silently copying the table: "
|
|
53
|
+
"ALTER TABLE t ADD INDEX i (c), ALGORITHM=INPLACE, LOCK=NONE;",
|
|
54
|
+
engines=("mysql",)),
|
|
55
|
+
|
|
56
|
+
Rule("MIG003", "error",
|
|
57
|
+
r"\bALTER\s+TABLE\b[^;]*\bALTER\s+COLUMN\b[^;]*\b(TYPE|SET\s+DATA\s+TYPE)\b",
|
|
58
|
+
"ALTER COLUMN ... TYPE rewrites the whole table and every index under "
|
|
59
|
+
"ACCESS EXCLUSIVE.",
|
|
60
|
+
"Expand/contract instead: add the new column, backfill in batches, dual-write, "
|
|
61
|
+
"swap readers, drop the old column in a later release.",
|
|
62
|
+
engines=("postgres",)),
|
|
63
|
+
|
|
64
|
+
Rule("MIG004", "error",
|
|
65
|
+
r"\bALTER\s+TABLE\b[^;]*\b(CHANGE|MODIFY)\s+(COLUMN\s+)?\w+[^;]*\b(BIGINT|INT|VARCHAR|TEXT|DECIMAL|DATETIME|TIMESTAMP)\b",
|
|
66
|
+
"Changing a column's data type in InnoDB is ALGORITHM=COPY: full rebuild, "
|
|
67
|
+
"no concurrent DML.",
|
|
68
|
+
"Use gh-ost/pt-online-schema-change, or expand/contract with a new column. "
|
|
69
|
+
"Exception: widening VARCHAR within the same length-byte class (<=255 or >=256) "
|
|
70
|
+
"is INPLACE.",
|
|
71
|
+
engines=("mysql",)),
|
|
72
|
+
|
|
73
|
+
Rule("MIG005", "warn",
|
|
74
|
+
r"\bALTER\s+TABLE\b[^;]*\bSET\s+NOT\s+NULL\b",
|
|
75
|
+
"SET NOT NULL scans the whole table while holding ACCESS EXCLUSIVE.",
|
|
76
|
+
"Two steps: ALTER TABLE t ADD CONSTRAINT c CHECK (col IS NOT NULL) NOT VALID; "
|
|
77
|
+
"ALTER TABLE t VALIDATE CONSTRAINT c; then SET NOT NULL skips the scan (PG 12+).",
|
|
78
|
+
engines=("postgres",)),
|
|
79
|
+
|
|
80
|
+
Rule("MIG006", "warn",
|
|
81
|
+
r"\bADD\s+(CONSTRAINT\s+\S+\s+)?(FOREIGN\s+KEY|CHECK)\b",
|
|
82
|
+
"Adding a validated constraint scans the table and blocks writes.",
|
|
83
|
+
"Add it NOT VALID first, then VALIDATE CONSTRAINT in a second statement "
|
|
84
|
+
"(SHARE UPDATE EXCLUSIVE, concurrent writes allowed).",
|
|
85
|
+
engines=("postgres",), unless=r"NOT\s+VALID"),
|
|
86
|
+
|
|
87
|
+
Rule("MIG007", "warn",
|
|
88
|
+
r"\bADD\s+(CONSTRAINT\s+\S+\s+)?FOREIGN\s+KEY\b",
|
|
89
|
+
"Adding a foreign key in InnoDB falls back to ALGORITHM=COPY unless "
|
|
90
|
+
"foreign_key_checks=0.",
|
|
91
|
+
"Create the child index first, then add the FK with foreign_key_checks=0 in a "
|
|
92
|
+
"controlled window, or use an online schema change tool.",
|
|
93
|
+
engines=("mysql",)),
|
|
94
|
+
|
|
95
|
+
Rule("MIG008", "error",
|
|
96
|
+
r"\bADD\s+COLUMN\b[^;]*\bDEFAULT\s+" + VOLATILE_DEFAULTS,
|
|
97
|
+
"ADD COLUMN with a volatile DEFAULT rewrites every row.",
|
|
98
|
+
"A constant default is metadata-only (PG 11+, MySQL 8 INSTANT). For now()/uuid, "
|
|
99
|
+
"add the column nullable, backfill in batches, then set the default.",
|
|
100
|
+
engines=("postgres", "mysql")),
|
|
101
|
+
|
|
102
|
+
Rule("MIG009", "warn",
|
|
103
|
+
r"\b(DROP\s+COLUMN|DROP\s+TABLE|RENAME\s+(COLUMN\s+)?\w+\s+TO|RENAME\s+TO)\b",
|
|
104
|
+
"Destructive or renaming DDL breaks any instance of the old code still running.",
|
|
105
|
+
"Expand/contract: ship the additive change, deploy code that stops using the old "
|
|
106
|
+
"object, drop it in a later release. Never rename in place.",
|
|
107
|
+
engines=("postgres", "mysql")),
|
|
108
|
+
|
|
109
|
+
Rule("MIG010", "warn",
|
|
110
|
+
r"^\s*(UPDATE|DELETE)\s+(?!.*\bWHERE\b)[^;]*;",
|
|
111
|
+
"Unbounded UPDATE/DELETE: one transaction touching every row.",
|
|
112
|
+
"Batch it by primary key (… WHERE id BETWEEN :lo AND :hi, committing each chunk). "
|
|
113
|
+
"PostgreSQL: one huge UPDATE doubles the heap and stalls autovacuum; InnoDB: the "
|
|
114
|
+
"undo log grows until commit.",
|
|
115
|
+
flags=re.I | re.M),
|
|
116
|
+
|
|
117
|
+
Rule("MIG011", "warn",
|
|
118
|
+
r"\bVACUUM\s+FULL\b|\bREINDEX\s+(?!.*CONCURRENTLY)(TABLE|INDEX|DATABASE)\b|\bOPTIMIZE\s+TABLE\b",
|
|
119
|
+
"Blocking maintenance command inside a migration.",
|
|
120
|
+
"VACUUM FULL and plain REINDEX take ACCESS EXCLUSIVE; OPTIMIZE TABLE rebuilds the "
|
|
121
|
+
"InnoDB table. Use REINDEX INDEX CONCURRENTLY, or run it in a maintenance window — "
|
|
122
|
+
"not in a deploy step.",
|
|
123
|
+
flags=re.I),
|
|
124
|
+
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
# --- rules that read the whole file (framework context) ---------------------
|
|
128
|
+
FILE_RULES = [
|
|
129
|
+
("MIG020", "error",
|
|
130
|
+
lambda t, p: p.endswith(".py") and "AddIndexConcurrently" in t and not re.search(r"atomic\s*=\s*False", t),
|
|
131
|
+
"Django AddIndexConcurrently/RemoveIndexConcurrently without `atomic = False`.",
|
|
132
|
+
"CONCURRENTLY cannot run inside a transaction. Add `atomic = False` to the Migration "
|
|
133
|
+
"class or the migration fails at runtime."),
|
|
134
|
+
|
|
135
|
+
("MIG021", "error",
|
|
136
|
+
lambda t, p: p.endswith(".py") and re.search(r"postgresql_concurrently\s*=\s*True", t)
|
|
137
|
+
and "autocommit_block" not in t,
|
|
138
|
+
"Alembic concurrent index build inside the default transactional migration.",
|
|
139
|
+
"Wrap it: `with op.get_context().autocommit_block(): op.create_index(..., "
|
|
140
|
+
"postgresql_concurrently=True)`."),
|
|
141
|
+
|
|
142
|
+
("MIG022", "error",
|
|
143
|
+
lambda t, p: p.endswith(".rb") and re.search(r"\balgorithm:\s*:concurrently", t)
|
|
144
|
+
and "disable_ddl_transaction!" not in t,
|
|
145
|
+
"Rails concurrent index without `disable_ddl_transaction!`.",
|
|
146
|
+
"Add `disable_ddl_transaction!` to the migration class."),
|
|
147
|
+
|
|
148
|
+
("MIG023", "warn",
|
|
149
|
+
lambda t, p: p.endswith(".py") and "RunPython" in t and not re.search(r"reverse_code|noop", t),
|
|
150
|
+
"Django RunPython data migration with no reverse_code.",
|
|
151
|
+
"Supply reverse_code (or migrations.RunPython.noop) so the migration is reversible and "
|
|
152
|
+
"`migrate <app> <previous>` does not dead-end."),
|
|
153
|
+
|
|
154
|
+
("MIG024", "warn",
|
|
155
|
+
lambda t, p: p.endswith(".php") and re.search(r"Schema::(table|create)", t)
|
|
156
|
+
and re.search(r"DB::(table|statement|update)\(", t),
|
|
157
|
+
"Laravel migration mixes schema changes and data backfill in one file.",
|
|
158
|
+
"MySQL commits DDL implicitly, so a later failure cannot roll back the DDL and leaves "
|
|
159
|
+
"a half-applied migration. Split schema and backfill into separate migrations."),
|
|
160
|
+
|
|
161
|
+
("MIG025", "warn",
|
|
162
|
+
lambda t, p: p.endswith(".ts") and re.search(r"\bsynchronize\s*:\s*true", t),
|
|
163
|
+
"TypeORM `synchronize: true`.",
|
|
164
|
+
"It silently drops and recreates columns to match entities. Never enable it outside a "
|
|
165
|
+
"throwaway local database; generate migrations instead."),
|
|
166
|
+
|
|
167
|
+
("MIG026", "warn",
|
|
168
|
+
lambda t, p: p.endswith(".sql") and re.search(r"CREATE\s+INDEX\s+CONCURRENTLY", t, re.I)
|
|
169
|
+
and re.search(r"^\s*BEGIN\s*;", t, re.I | re.M),
|
|
170
|
+
"CREATE INDEX CONCURRENTLY inside an explicit BEGIN block.",
|
|
171
|
+
"PostgreSQL rejects it with 'CREATE INDEX CONCURRENTLY cannot run inside a transaction "
|
|
172
|
+
"block'. Remove the BEGIN/COMMIT, and tell the runner not to wrap this migration "
|
|
173
|
+
"(Flyway: executeInTransaction=false; golang-migrate: -x / no-tx directive)."),
|
|
174
|
+
|
|
175
|
+
("MIG027", "warn",
|
|
176
|
+
lambda t, p: p.endswith(".sql") and not re.search(r"lock_timeout|lock_wait_timeout", t, re.I)
|
|
177
|
+
and re.search(r"ALTER\s+TABLE|CREATE\s+INDEX", t, re.I),
|
|
178
|
+
"No lock_timeout guard in a migration containing ALTER TABLE / CREATE INDEX.",
|
|
179
|
+
"DDL queues behind any long-running query and then blocks every query behind it "
|
|
180
|
+
"(PostgreSQL lock queue / InnoDB metadata lock). Open with `SET lock_timeout = '3s';` "
|
|
181
|
+
"(PostgreSQL) or `SET SESSION lock_wait_timeout = 3;` (MySQL) so a blocked statement "
|
|
182
|
+
"fails fast and is retried instead of freezing the table."),
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def scan_file(path: str, engine: str) -> list[dict]:
|
|
187
|
+
try:
|
|
188
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
189
|
+
text = fh.read()
|
|
190
|
+
except OSError as exc:
|
|
191
|
+
print(f"WARNING: skipping {path}: {exc}", file=sys.stderr)
|
|
192
|
+
return []
|
|
193
|
+
|
|
194
|
+
findings = []
|
|
195
|
+
# Strip -- and # comments so commented-out DDL does not fire rules.
|
|
196
|
+
scrub = re.sub(r"--[^\n]*", "", text)
|
|
197
|
+
scrub = re.sub(r"/\*.*?\*/", "", scrub, flags=re.S)
|
|
198
|
+
|
|
199
|
+
for rule in LINE_RULES:
|
|
200
|
+
if engine not in rule.engines:
|
|
201
|
+
continue
|
|
202
|
+
for m in rule.pattern.finditer(scrub):
|
|
203
|
+
window = scrub[m.start(): m.start() + 400]
|
|
204
|
+
if rule.unless and rule.unless.search(window):
|
|
205
|
+
continue
|
|
206
|
+
findings.append({
|
|
207
|
+
"id": rule.id, "severity": rule.severity, "file": path,
|
|
208
|
+
"line": scrub.count("\n", 0, m.start()) + 1,
|
|
209
|
+
"snippet": " ".join(m.group(0).split())[:120],
|
|
210
|
+
"message": rule.message, "fix": rule.fix,
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
for rid, sev, test, msg, fix in FILE_RULES:
|
|
214
|
+
try:
|
|
215
|
+
hit = test(text, path)
|
|
216
|
+
except Exception: # a malformed file must not kill the lint run
|
|
217
|
+
hit = False
|
|
218
|
+
if hit:
|
|
219
|
+
findings.append({"id": rid, "severity": sev, "file": path, "line": 1,
|
|
220
|
+
"snippet": "", "message": msg, "fix": fix})
|
|
221
|
+
return findings
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def collect(paths: list[str]) -> list[str]:
|
|
225
|
+
files = []
|
|
226
|
+
for p in paths:
|
|
227
|
+
if os.path.isdir(p):
|
|
228
|
+
for root, _dirs, names in os.walk(p):
|
|
229
|
+
if any(part in root for part in (os.sep + "node_modules", os.sep + ".git", os.sep + "vendor")):
|
|
230
|
+
continue
|
|
231
|
+
files.extend(os.path.join(root, n) for n in sorted(names) if n.endswith(SUFFIXES))
|
|
232
|
+
else:
|
|
233
|
+
files.append(p)
|
|
234
|
+
return files
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def main(argv=None) -> int:
|
|
238
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
239
|
+
ap.add_argument("paths", nargs="+", help="migration files or directories")
|
|
240
|
+
ap.add_argument("--engine", choices=["postgres", "mysql"], default="postgres")
|
|
241
|
+
ap.add_argument("--format", choices=["text", "json"], default="text")
|
|
242
|
+
ap.add_argument("--min-severity", choices=["info", "warn", "error"], default="info")
|
|
243
|
+
args = ap.parse_args(argv)
|
|
244
|
+
|
|
245
|
+
files = collect(args.paths)
|
|
246
|
+
if not files:
|
|
247
|
+
print("ERROR: no migration files found with a known suffix "
|
|
248
|
+
f"({', '.join(SUFFIXES)}).", file=sys.stderr)
|
|
249
|
+
return 2
|
|
250
|
+
|
|
251
|
+
findings = []
|
|
252
|
+
for path in files:
|
|
253
|
+
findings.extend(scan_file(path, args.engine))
|
|
254
|
+
findings = [f for f in findings if SEVERITY_ORDER[f["severity"]] >= SEVERITY_ORDER[args.min_severity]]
|
|
255
|
+
findings.sort(key=lambda f: (SEVERITY_ORDER[f["severity"]] * -1, f["file"], f["line"]))
|
|
256
|
+
|
|
257
|
+
if args.format == "json":
|
|
258
|
+
print(json.dumps({"engine": args.engine, "files_scanned": len(files),
|
|
259
|
+
"findings": findings}, indent=2))
|
|
260
|
+
else:
|
|
261
|
+
print(f"Scanned {len(files)} file(s); {len(findings)} finding(s).\n")
|
|
262
|
+
for f in findings:
|
|
263
|
+
print(f"[{f['severity'].upper():5}] {f['id']} {f['file']}:{f['line']}")
|
|
264
|
+
if f["snippet"]:
|
|
265
|
+
print(f" > {f['snippet']}")
|
|
266
|
+
print(f" {f['message']}")
|
|
267
|
+
print(f" FIX: {f['fix']}\n")
|
|
268
|
+
|
|
269
|
+
return 1 if any(f["severity"] == "error" for f in findings) else 0
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
if __name__ == "__main__":
|
|
273
|
+
sys.exit(main())
|