codecop 0.1.0__py3-none-any.whl
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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/apply/html.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""The plan inside report.html: ordered steps with their reversibility, locks, estimates and sandbox results. No prose.
|
|
2
|
+
|
|
3
|
+
report.py renders a finding as `<section class=finding id='Q-001'>...</section>`. A plan is drawn as one more block at
|
|
4
|
+
the end of that section, so this module adds to the page report.py produced instead of changing how it is produced.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import html
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
from .common import human_bytes, human_duration
|
|
14
|
+
|
|
15
|
+
MARK = "<div class=plan "
|
|
16
|
+
CSS = """
|
|
17
|
+
.plan{border-top:1px solid var(--line);margin-top:18px;padding-top:16px}
|
|
18
|
+
.plan>header{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
|
19
|
+
.steps{list-style:none;margin:10px 0 0;padding:0}
|
|
20
|
+
.steps>li{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;padding:9px 0;border-top:1px dashed var(--line)}
|
|
21
|
+
.steps>li:first-child{border-top:0}
|
|
22
|
+
.stepn{width:24px;height:24px;border-radius:50%;border:1px solid var(--line);display:grid;place-items:center;font:600 12px/1 ui-monospace,Menlo,monospace;background:var(--bg)}
|
|
23
|
+
.steps>li.irr .stepn,.node.irr{border-color:var(--bad);color:var(--bad)}
|
|
24
|
+
.steps>li.read .stepn{border-style:dashed}
|
|
25
|
+
.steprow{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
|
|
26
|
+
.steprow b{font-size:14px}
|
|
27
|
+
.phase{font-size:10.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--accent)}
|
|
28
|
+
.hint{font-size:12px;color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:1px 7px;background:var(--bg)}
|
|
29
|
+
.node .n{font:600 11px/1 ui-monospace,Menlo,monospace;color:var(--muted);margin-right:5px}
|
|
30
|
+
.diff{white-space:pre;overflow-x:auto;word-break:normal}
|
|
31
|
+
.diff .add{color:var(--good);background:var(--good-bg);display:block}.diff .del{color:var(--bad);background:var(--bad-bg);display:block}
|
|
32
|
+
.diff .hunk{color:var(--accent);display:block}
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def e(text) -> str:
|
|
37
|
+
return html.escape(str(text if text is not None else ""))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def tag(text, cls="", title="") -> str:
|
|
41
|
+
return f"<span class='tag {e(cls)}'{' title=' + chr(39) + e(title) + chr(39) if title else ''}>{e(text)}</span>"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def fingerprint(plan: dict) -> str:
|
|
45
|
+
"""Identifies a plan's statements, so a sandbox result is only shown next to the plan it was run for."""
|
|
46
|
+
text = json.dumps([[s["id"], s["sql"], (s.get("per_partition") or {}).get("template")] for s in plan.get("steps") or []], sort_keys=True)
|
|
47
|
+
return hashlib.sha1(text.encode()).hexdigest()[:12]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _bar(label, part, whole, value, cls="") -> str:
|
|
51
|
+
width = min(100.0 * float(part or 0) / float(whole), 100) if whole else 0
|
|
52
|
+
return (f"<span class=l>{e(label)}</span><div class=track><div class='fill {e(cls)}' style='width:{width:.1f}%'></div></div>"
|
|
53
|
+
f"<span class=v>{e(value)}</span>")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _estimate_tags(est: dict | None) -> list[str]:
|
|
57
|
+
if not est:
|
|
58
|
+
return []
|
|
59
|
+
basis = " · ".join(est.get("basis") or [])
|
|
60
|
+
out = []
|
|
61
|
+
if est.get("duration_s"):
|
|
62
|
+
out.append(tag(f"estimate: {human_duration(est['duration_s']['low'])} to {human_duration(est['duration_s']['high'])}", "unverified", basis))
|
|
63
|
+
if est.get("extra_disk_bytes"):
|
|
64
|
+
out.append(tag(f"estimate: +{human_bytes(est['extra_disk_bytes'])} disk", "unverified", basis))
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _partitions(pp: dict) -> str:
|
|
69
|
+
parts = pp.get("partitions") or []
|
|
70
|
+
if not parts:
|
|
71
|
+
return f"<div class=chips>{tag('the newest partition, found when the plan runs' if pp.get('scope') == 'newest' else 'partitions are listed when the plan runs: one statement each')}</div>"
|
|
72
|
+
if pp.get("scope") == "newest":
|
|
73
|
+
return f"<div class=chips>{tag('partition ' + parts[-1]['id'])}{tag('~' + human_bytes(parts[-1]['bytes']) + ' rewritten (estimate)', 'unverified') if parts[-1].get('bytes') else ''}</div>"
|
|
74
|
+
whole = max((p.get("bytes") or 0 for p in parts), default=0)
|
|
75
|
+
shown = parts if len(parts) <= 14 else parts[:6] + parts[-6:]
|
|
76
|
+
rows = "".join(_bar(p["id"] + (" · newest" if p["id"] == pp.get("newest") else ""), p.get("bytes"), whole,
|
|
77
|
+
f"~{human_bytes(p['bytes'])}" if p.get("bytes") else "-", "warn" if p["id"] == pp.get("newest") else "") for p in shown)
|
|
78
|
+
more = tag(f"{len(parts) - len(shown)} more partitions not drawn") if len(shown) < len(parts) else ""
|
|
79
|
+
return (f"<div class=chips>{tag(f'{len(parts)} partitions from the real catalog', 'verified')}"
|
|
80
|
+
f"{tag('sizes: table total divided evenly (estimate)', 'unverified')}{more}</div><div class=bars style='margin-top:6px'>{rows}</div>")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _step(s: dict, plan: dict, checked: dict | None) -> str:
|
|
84
|
+
cls = "read" if s["effect"] == "read" else ("" if s["reversible"] else "irr")
|
|
85
|
+
tags = [tag("reads only") if s["effect"] == "read" else tag("reversible", "verified", "; ".join(s["undo_sql"])) if s["reversible"]
|
|
86
|
+
else tag("not reversible", "rejected")]
|
|
87
|
+
if s.get("locks"):
|
|
88
|
+
tags.append(tag(f"locks: {s['locks']}"))
|
|
89
|
+
tags += _estimate_tags(s.get("estimate"))
|
|
90
|
+
if checked:
|
|
91
|
+
tags.append(tag(f"sandbox: passed · {checked['ms'] / 1000:.1f} s", "verified", checked.get("detail", "")) if checked["ok"]
|
|
92
|
+
else tag("sandbox: not run" if checked.get("skipped") else "sandbox: failed", "rejected", checked.get("detail", "")))
|
|
93
|
+
if checked.get("detail") and (not checked["ok"] or s["phase"] in ("backfill", "confirm")):
|
|
94
|
+
tags.append(f"<span class=hint>{e(checked['detail'][:160])}</span>")
|
|
95
|
+
hints = "".join(f"<span class=hint>{e(c)}</span>" for c in s.get("chips") or [])
|
|
96
|
+
pp = s.get("per_partition")
|
|
97
|
+
statements = list(s["sql"]) + ([pp["template"]] if pp else [])
|
|
98
|
+
sql = "".join(f"<pre>{e(x)}</pre>" for x in statements)
|
|
99
|
+
alt = "".join(f"<pre>{e(x)}</pre>" for x in s.get("alternative_sql") or [])
|
|
100
|
+
return (f"<li class='{cls}'><span class=stepn>{s['n']}</span><div><div class=steprow><b>{e(s['title'])}</b><span class=phase>{e(s['phase'].replace('_', ' '))}</span>"
|
|
101
|
+
f"{''.join(tags)}</div>"
|
|
102
|
+
+ (f"<div class=chips>{hints}</div>" if hints else "") + (_partitions(pp) if pp else "")
|
|
103
|
+
+ f"<details><summary>SQL · {e(s['file'])}</summary>{sql}{'<b>Alternative</b>' + alt if alt else ''}</details></div></li>")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _overview(plan: dict) -> str:
|
|
107
|
+
"""The steps as one strip, in order: number, phase, and a red border where there is no way back."""
|
|
108
|
+
arrow = "<span class=arrow>→</span>"
|
|
109
|
+
nodes = [f"<div class='node {'' if s['reversible'] else 'irr'}'><span class=n>{s['n']}</span>{e(s['phase'].replace('_', ' '))}</div>" for s in plan["steps"]]
|
|
110
|
+
return f"<div class=flow>{arrow.join(nodes)}</div>"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _rollback(plan: dict) -> str:
|
|
114
|
+
rows = []
|
|
115
|
+
for r in plan.get("rollback") or []:
|
|
116
|
+
sql = "".join(f"<pre>{e(x)}</pre>" for x in r["sql"])
|
|
117
|
+
rows.append(f"<div class=keyrow><span class=lbl style='min-width:190px'>{e(r['when'])}</span>"
|
|
118
|
+
f"{tag('can go back', 'verified') if r['possible'] else tag('no way back', 'rejected')}{tag('loses ' + r['loses'])}"
|
|
119
|
+
+ (f"<details style='margin:0'><summary>SQL · {e(r.get('file', ''))}</summary>{sql}</details>" if sql else "") + "</div>")
|
|
120
|
+
return "<h4>Going back</h4>" + "".join(rows) if rows else ""
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _where(x: dict) -> str:
|
|
124
|
+
return (f"<div class=node><span class=mono>{e(x.get('symbol') or str(x['file']).split('/')[-1])}</span>"
|
|
125
|
+
f"<small>{e(str(x['file']).split('/')[-1])}:{e(x['line'])}</small></div>")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _code(plan: dict) -> str:
|
|
129
|
+
code = plan.get("code")
|
|
130
|
+
if not code:
|
|
131
|
+
return ""
|
|
132
|
+
out = ["<h4>Code at the same time</h4>"]
|
|
133
|
+
for site in code["call_sites"]:
|
|
134
|
+
out.append(f"<div class=keyrow>{_where(site)}{tag(site['change'], 'verified' if site['change'].startswith('none') else 'unverified')}</div>")
|
|
135
|
+
counts = code.get("reader_counts") or {}
|
|
136
|
+
chips = []
|
|
137
|
+
if counts.get("better"):
|
|
138
|
+
chips.append(tag(f"{counts['better']} other queries line up better with the new key", "verified"))
|
|
139
|
+
if counts.get("same"):
|
|
140
|
+
chips.append(tag(f"{counts['same']} unchanged"))
|
|
141
|
+
if counts.get("worse"):
|
|
142
|
+
chips.append(tag(f"{counts['worse']} use fewer key columns afterwards: review", "rejected"))
|
|
143
|
+
if counts.get("unknown"):
|
|
144
|
+
chips.append(tag(f"{counts['unknown']} could not be judged", "unverified"))
|
|
145
|
+
if code.get("writers"):
|
|
146
|
+
chips.append(tag(f"{len(code['writers'])} writers: covered by the forwarding view"))
|
|
147
|
+
if plan.get("dependent_views"):
|
|
148
|
+
chips.append(tag(f"{len(plan['dependent_views'])} dependent view(s) in the database"))
|
|
149
|
+
if chips:
|
|
150
|
+
out.append(f"<div class=chips>{''.join(chips)}</div>")
|
|
151
|
+
worse = [r for r in code.get("other_readers") or [] if r["effect"] == "worse"]
|
|
152
|
+
if worse:
|
|
153
|
+
out.append(f"<details><summary>Queries to review ({len(worse)})</summary><div class=flow>{''.join(_where(r) for r in worse)}</div></details>")
|
|
154
|
+
return "".join(out)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
PATCH_LABEL = {"exact": ("diff: SQL literal located exactly", "verified"), "needs_argument_change": ("diff, plus the bound arguments must be reordered", "unverified"),
|
|
158
|
+
"not_located": ("no diff", "rejected")}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _diff(text: str) -> str:
|
|
162
|
+
lines = []
|
|
163
|
+
for line in text.splitlines():
|
|
164
|
+
cls = "hunk" if line.startswith("@@") else "add" if line.startswith("+") and not line.startswith("+++") else \
|
|
165
|
+
"del" if line.startswith("-") and not line.startswith("---") else ""
|
|
166
|
+
lines.append(f"<span class={cls}>{e(line)}</span>" if cls else e(line) + "\n")
|
|
167
|
+
return f"<pre class=diff>{''.join(lines)}</pre>"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _patch(plan: dict) -> str:
|
|
171
|
+
p = plan.get("patch")
|
|
172
|
+
if not p:
|
|
173
|
+
return ""
|
|
174
|
+
label, cls = PATCH_LABEL[p["status"]]
|
|
175
|
+
chips = [tag(label, cls)]
|
|
176
|
+
if p["reason"]:
|
|
177
|
+
chips.append(f"<span class=hint>{e(p['reason'])}</span>")
|
|
178
|
+
if p["file"]:
|
|
179
|
+
chips.append(tag(f"{p['file'].split('/')[-1]}:{p['line']}", "", p["file"]))
|
|
180
|
+
chips.append(tag(f"inside {p['literal']}"))
|
|
181
|
+
if p.get("bind_order"):
|
|
182
|
+
chips.append(tag("new argument order: " + ", ".join(p["bind_order"]), "unverified"))
|
|
183
|
+
chips.append(tag("written to the out dir, not applied"))
|
|
184
|
+
body = (f"<details><summary>Diff · {e(p.get('diff_file', ''))}</summary>{_diff(p['diff'])}</details>" if p["diff"] else
|
|
185
|
+
f"<details><summary>Rewritten query · {e(p.get('sql_file', ''))}</summary><pre>{e(p['new_sql'])}</pre></details>" if p["new_sql"] else "")
|
|
186
|
+
return f"<h4>Code change</h4><div class=chips>{''.join(chips)}</div>{body}"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _check(result: dict | None) -> str:
|
|
190
|
+
if not result:
|
|
191
|
+
return ""
|
|
192
|
+
probes = "".join(tag(p["label"], "verified" if p["ok"] else "unverified" if p["ok"] is None else "rejected", p["detail"]) for p in result.get("probes") or [])
|
|
193
|
+
rb = result.get("rollback")
|
|
194
|
+
if rb:
|
|
195
|
+
probes += tag("rollback ran on the sandbox" if rb["ok"] else "rollback failed on the sandbox", "verified" if rb["ok"] else "rejected", rb["detail"])
|
|
196
|
+
m = result.get("measure")
|
|
197
|
+
bars = ""
|
|
198
|
+
if m and m.get("after", {}).get("read_rows") is not None:
|
|
199
|
+
bench = m.get("bench") or {}
|
|
200
|
+
whole = max(m["before"].get("read_rows") or 0, m["after"]["read_rows"] or 0, bench.get("read_rows") or 0)
|
|
201
|
+
bars = ("<div class=bars style='margin-top:8px'>" + _bar("before", m["before"].get("read_rows"), whole, f"{m['before'].get('read_rows') or 0:,} rows")
|
|
202
|
+
+ (_bar("benchmark said", bench["read_rows"], whole, f"{bench['read_rows']:,} rows", "out") if bench.get("read_rows") is not None else "")
|
|
203
|
+
+ _bar("after the plan", m["after"]["read_rows"], whole, f"{m['after']['read_rows']:,} rows", "win" if m["ok"] else "bad") + "</div>")
|
|
204
|
+
if m.get("same_results") is not None:
|
|
205
|
+
probes += tag("same result as before the migration" if m["same_results"] else "result differs from before", "verified" if m["same_results"] else "rejected")
|
|
206
|
+
error = f"<span class=hint>{e(result['error'][:200])}</span>" if result.get("error") else ""
|
|
207
|
+
return f"<h4>Run on the sandbox</h4><div class=chips>{probes}{error}</div>{bars}"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def plan_html(plan: dict, result: dict | None = None) -> str:
|
|
211
|
+
"""One plan as a block for its finding's section."""
|
|
212
|
+
if result and result.get("fingerprint") != fingerprint(plan):
|
|
213
|
+
result = None # a sandbox result for other statements says nothing about these
|
|
214
|
+
checked = {s["id"]: s for s in (result or {}).get("steps") or []}
|
|
215
|
+
v = plan["variant"]
|
|
216
|
+
head = [tag("sandbox check passed", "verified") if result and result["ok"] else tag("sandbox check failed", "rejected") if result else
|
|
217
|
+
tag("not run anywhere", "unverified", "codecop apply --check runs it on the sandbox")] if plan.get("steps") else []
|
|
218
|
+
sizes = plan.get("sizes") or {}
|
|
219
|
+
size_tags = []
|
|
220
|
+
if plan.get("steps") and sizes.get("rows"):
|
|
221
|
+
size_tags.append(tag(f"{sizes['source']}: {sizes['rows']:,} rows" + (f", {human_bytes(sizes['bytes_on_disk'])}" if sizes.get("bytes_on_disk") else "")
|
|
222
|
+
+ (f", {sizes['partitions']} partitions" if sizes.get("partitions") else ""),
|
|
223
|
+
"verified" if sizes["source"] == "real catalog" else "unverified"))
|
|
224
|
+
size_tags += _estimate_tags(plan.get("estimates"))
|
|
225
|
+
warnings = "".join(tag(w["detail"][:140], "rejected" if w["code"] in ("dedup_key_changes", "duplicates_possible") else "unverified") for w in plan.get("warnings") or [])
|
|
226
|
+
if plan["status"] != "planned":
|
|
227
|
+
return (f"{MARK}id='plan-{e(plan['finding'])}'><header>{tag('no plan', 'rejected')}<h3>{e(v['change'])}</h3></header>"
|
|
228
|
+
f"<div class=chips><span class=hint>{e(plan['reason'])}</span></div></div>")
|
|
229
|
+
title = "Migration plan" if plan.get("steps") else "Code change"
|
|
230
|
+
steps = ("<h4>Steps, in order</h4>" + _overview(plan) + f"<ol class=steps>{''.join(_step(s, plan, checked.get(s['id'])) for s in plan['steps'])}</ol>"
|
|
231
|
+
if plan.get("steps") else "")
|
|
232
|
+
return (f"{MARK}id='plan-{e(plan['finding'])}'><header>{tag(plan['delivery'])}<h3>{title}: {e(v['change'])}</h3>{''.join(head)}"
|
|
233
|
+
f"{tag('files written; nothing was run on a real database')}</header>"
|
|
234
|
+
+ (f"<div class=chips>{''.join(size_tags)}{warnings}</div>" if size_tags or warnings else "")
|
|
235
|
+
+ steps + (_check(result) if plan.get("steps") else "") + (_rollback(plan) if plan.get("steps") else "")
|
|
236
|
+
+ (_code(plan) if plan.get("steps") else "") + _patch(plan) + "</div>")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def inject(page: str, plan_doc: dict | None, check_doc: dict | None = None, finding_ids: dict[str, str] | None = None) -> tuple[str, int]:
|
|
240
|
+
"""Add each plan to its finding's section of a rendered report. Returns the page and how many plans were placed.
|
|
241
|
+
|
|
242
|
+
`finding_ids`: finding label -> the finding's stable id in the findings the page was rendered from; a plan made for
|
|
243
|
+
another finding that now carries the same label is left out."""
|
|
244
|
+
if not plan_doc or not plan_doc.get("plans") or MARK in page:
|
|
245
|
+
return page, 0
|
|
246
|
+
results = {r["finding"]: r for r in (check_doc or {}).get("results") or []}
|
|
247
|
+
placed = 0
|
|
248
|
+
for plan in plan_doc["plans"]:
|
|
249
|
+
if finding_ids is not None and finding_ids.get(plan["finding"]) != plan["id"]:
|
|
250
|
+
continue
|
|
251
|
+
start = page.find(f"<section class=finding id='{html.escape(plan['finding'])}'>")
|
|
252
|
+
end = page.find("</section>", start) if start >= 0 else -1
|
|
253
|
+
if end < 0:
|
|
254
|
+
# a table suggestion of an advisor: its row in "Access paths, per table" holds a place for its plan
|
|
255
|
+
mark = f"<!--codecop-plan:{html.escape(plan['finding'])}-->"
|
|
256
|
+
at = page.find(mark)
|
|
257
|
+
if at < 0:
|
|
258
|
+
continue
|
|
259
|
+
end = at + len(mark)
|
|
260
|
+
page = page[:end] + plan_html(plan, results.get(plan["finding"])) + page[end:]
|
|
261
|
+
placed += 1
|
|
262
|
+
if placed and "</style>" in page:
|
|
263
|
+
page = page.replace("</style>", CSS + "</style>", 1)
|
|
264
|
+
return page, placed
|
codecop/apply/patch.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""A query rewrite as a unified diff against the repository file. The repository is only read; the diff goes to the out dir.
|
|
2
|
+
|
|
3
|
+
A diff is written only when every link is exact:
|
|
4
|
+
|
|
5
|
+
1. the benchmarked baseline is the code's SQL with nothing changed but its parameters (so the rewrite, which was
|
|
6
|
+
written against the baseline, can be carried back to the code's own placeholder style);
|
|
7
|
+
2. the code's SQL is found as one literal: in the call site's file, or in exactly one other file of that language;
|
|
8
|
+
3. the new text fits inside that literal without escaping.
|
|
9
|
+
|
|
10
|
+
Otherwise the plan says which link broke and carries the rewritten SQL as text. Nothing is guessed.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import difflib
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from .. import formerly
|
|
21
|
+
|
|
22
|
+
PARAM = re.compile(r"\{(\w+):[^{}]+\}")
|
|
23
|
+
POSITIONAL = ("?", "%s")
|
|
24
|
+
SKIP_DIRS = {".git", "node_modules", "target", "vendor", "build", "dist", ".venv", "venv", "__pycache__", ".codecop", formerly.OLD_OUT_DIR, ".idea", ".gradle"}
|
|
25
|
+
MAX_FILE_BYTES = 2_000_000
|
|
26
|
+
MAX_FILES = 8000
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _flex(text: str) -> str:
|
|
30
|
+
"""A regex for `text` that accepts any run of whitespace where `text` has one (and none at its ends)."""
|
|
31
|
+
return r"\s+".join(re.escape(t) for t in text.split())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def placeholder_map(baseline: str, original: str) -> tuple[dict[str, str], list[str]] | None:
|
|
35
|
+
"""What each `{name:Type}` of the benchmarked SQL stands for in the code's SQL, and the names in order.
|
|
36
|
+
|
|
37
|
+
None when the two differ in anything but those parameters."""
|
|
38
|
+
names = PARAM.findall(baseline)
|
|
39
|
+
pieces = PARAM.split(baseline)[::2] # the text between the parameters
|
|
40
|
+
pattern = r"\s*"
|
|
41
|
+
for i, piece in enumerate(pieces):
|
|
42
|
+
tokens = piece.split()
|
|
43
|
+
lead = r"\s*" if piece[:1].isspace() else ""
|
|
44
|
+
trail = r"\s*" if piece[-1:].isspace() else ""
|
|
45
|
+
pattern += lead + r"\s+".join(re.escape(t) for t in tokens) + trail
|
|
46
|
+
if i < len(names):
|
|
47
|
+
pattern += r"(%\(\w+\)s|[^\s,()]{1,80}|'[^'\n]{0,200}')"
|
|
48
|
+
m = re.fullmatch(pattern + r"\s*;?\s*", original, re.S)
|
|
49
|
+
if not m:
|
|
50
|
+
return None
|
|
51
|
+
mapping: dict[str, str] = {}
|
|
52
|
+
for name, text in zip(names, m.groups()):
|
|
53
|
+
if mapping.setdefault(name, text) != text and text not in POSITIONAL:
|
|
54
|
+
return None # one parameter, two different spellings in the code: not a plain substitution
|
|
55
|
+
return mapping, names
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def to_code_sql(new_sql: str, mapping: dict[str, str]) -> tuple[str, list[str]] | tuple[None, str]:
|
|
59
|
+
"""The rewrite in the code's placeholder style, with the parameter names in the order they now appear."""
|
|
60
|
+
order = PARAM.findall(new_sql)
|
|
61
|
+
missing = sorted({n for n in order if n not in mapping})
|
|
62
|
+
if missing:
|
|
63
|
+
return None, f"the rewrite uses a parameter the code does not bind: {', '.join(missing)}"
|
|
64
|
+
return PARAM.sub(lambda m: mapping[m.group(1)], new_sql), order
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _candidates(root: Path, site_file: str, anchor: str) -> list[Path]:
|
|
68
|
+
"""The call site's file first, then other files of the same language that contain the anchor text."""
|
|
69
|
+
first = root / site_file
|
|
70
|
+
out = [first] if first.is_file() else []
|
|
71
|
+
suffix = first.suffix
|
|
72
|
+
if not suffix or not anchor:
|
|
73
|
+
return out
|
|
74
|
+
seen = 0
|
|
75
|
+
for base, dirs, files in os.walk(root):
|
|
76
|
+
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")]
|
|
77
|
+
for name in files:
|
|
78
|
+
if not name.endswith(suffix):
|
|
79
|
+
continue
|
|
80
|
+
path = Path(base) / name
|
|
81
|
+
seen += 1
|
|
82
|
+
if seen > MAX_FILES:
|
|
83
|
+
return out
|
|
84
|
+
if path == first:
|
|
85
|
+
continue
|
|
86
|
+
try:
|
|
87
|
+
if path.stat().st_size <= MAX_FILE_BYTES and anchor in path.read_text(errors="replace"):
|
|
88
|
+
out.append(path)
|
|
89
|
+
except OSError:
|
|
90
|
+
continue
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _delimiter(text: str, start: int, suffix: str) -> tuple[str, tuple[str, ...]]:
|
|
95
|
+
"""Which kind of literal the SQL sits in, and which characters cannot be added to it as they are."""
|
|
96
|
+
before = text[:start].rstrip()
|
|
97
|
+
if suffix == ".sql":
|
|
98
|
+
return "a .sql file", ()
|
|
99
|
+
if before.endswith('"""'):
|
|
100
|
+
return 'a """ text block', ('"""', "\\")
|
|
101
|
+
if before.endswith("'''"):
|
|
102
|
+
return "a ''' string", ("'''", "\\")
|
|
103
|
+
if before.endswith("`"):
|
|
104
|
+
return "a raw string", ("`",)
|
|
105
|
+
if before.endswith('"'):
|
|
106
|
+
return "a string literal", ('"', "\\", "\n")
|
|
107
|
+
if before.endswith("'"):
|
|
108
|
+
return "a string literal", ("'", "\\", "\n")
|
|
109
|
+
return "a literal that starts before the SQL", ('"', "`", "\\")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _edit(text: str, start: int, end: int, new_sql: str) -> tuple[str, list[str]]:
|
|
113
|
+
"""Replace the SQL in text[start:end] by `new_sql`, touching only the tokens that differ so the file keeps its layout."""
|
|
114
|
+
old = [(m.group(0), start + m.start(), start + m.end()) for m in re.finditer(r"\S+", text[start:end])]
|
|
115
|
+
new = new_sql.split()
|
|
116
|
+
ops = difflib.SequenceMatcher(a=[t for t, _, _ in old], b=new, autojunk=False).get_opcodes()
|
|
117
|
+
out, inserted, cursor = [], [], start
|
|
118
|
+
for tag, i1, i2, j1, j2 in ops:
|
|
119
|
+
if tag == "equal":
|
|
120
|
+
continue
|
|
121
|
+
piece = " ".join(new[j1:j2])
|
|
122
|
+
if tag == "insert":
|
|
123
|
+
at = old[i1][1] if i1 < len(old) else old[-1][2]
|
|
124
|
+
out.append(text[cursor:at] + (piece + " " if i1 < len(old) else " " + piece))
|
|
125
|
+
cursor = at
|
|
126
|
+
elif tag == "delete":
|
|
127
|
+
a = old[i1 - 1][2] if i1 > 0 else old[i1][1] # take the whitespace before the removed tokens with them
|
|
128
|
+
b = old[i2 - 1][2] if i1 > 0 else (old[i2][1] if i2 < len(old) else old[i2 - 1][2])
|
|
129
|
+
out.append(text[cursor:a])
|
|
130
|
+
cursor = b
|
|
131
|
+
else:
|
|
132
|
+
out.append(text[cursor:old[i1][1]] + piece)
|
|
133
|
+
cursor = old[i2 - 1][2]
|
|
134
|
+
if piece:
|
|
135
|
+
inserted.append(piece)
|
|
136
|
+
return text[:start] + "".join(out) + text[cursor:], inserted
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _unified(old: str, new: str, rel: str) -> str:
|
|
140
|
+
lines = []
|
|
141
|
+
for line in difflib.unified_diff(old.splitlines(keepends=True), new.splitlines(keepends=True), fromfile=f"a/{rel}", tofile=f"b/{rel}", n=3):
|
|
142
|
+
lines.append(line if line.endswith("\n") else line + "\n\\n")
|
|
143
|
+
return "".join(lines)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def build(root: Path | None, finding: dict, variant: dict) -> dict:
|
|
147
|
+
"""The patch for one rewrite, or why there is none. `root`: the repository, read-only."""
|
|
148
|
+
site = finding["site"]
|
|
149
|
+
out = {"status": "not_located", "reason": "", "site": {"file": site["file"], "line": site["line"]}, "file": "", "line": 0, "diff": "",
|
|
150
|
+
"new_sql": "", "bind_order": [], "literal": ""}
|
|
151
|
+
original, baseline, new = finding.get("original_sql") or "", finding["baseline_sql"], variant.get("sql") or ""
|
|
152
|
+
if "«" in original or site.get("resolution") == "template":
|
|
153
|
+
out["reason"] = "the query is assembled from pieces at run time: there is no single literal to change"
|
|
154
|
+
out["new_sql"] = new
|
|
155
|
+
return out
|
|
156
|
+
mapped = placeholder_map(baseline, original)
|
|
157
|
+
if mapped is None:
|
|
158
|
+
out["reason"] = "the benchmarked query differs from the code's SQL in more than its parameters"
|
|
159
|
+
out["new_sql"] = new
|
|
160
|
+
return out
|
|
161
|
+
mapping, old_order = mapped
|
|
162
|
+
code_sql, new_order = to_code_sql(new, mapping)
|
|
163
|
+
if code_sql is None:
|
|
164
|
+
out["reason"], out["new_sql"] = new_order, new
|
|
165
|
+
return out
|
|
166
|
+
out["new_sql"] = code_sql
|
|
167
|
+
positional = any(v in POSITIONAL for v in mapping.values())
|
|
168
|
+
if root is None or not Path(root).is_dir():
|
|
169
|
+
out["reason"] = "the repository is not on this machine"
|
|
170
|
+
return out
|
|
171
|
+
root = Path(root)
|
|
172
|
+
tokens = original.split()
|
|
173
|
+
anchor = max(tokens[:40], key=len, default="") if tokens else ""
|
|
174
|
+
pattern = re.compile(_flex(original.rstrip().rstrip(";")))
|
|
175
|
+
hits = []
|
|
176
|
+
for path in _candidates(root, site["file"], anchor if len(anchor) >= 8 else ""):
|
|
177
|
+
try:
|
|
178
|
+
text = path.read_text()
|
|
179
|
+
except (OSError, UnicodeDecodeError):
|
|
180
|
+
continue
|
|
181
|
+
found = [(path, text, m.start(), m.end()) for m in pattern.finditer(text)]
|
|
182
|
+
if found and path == root / site["file"]:
|
|
183
|
+
# the call site's own file: the occurrence nearest the call wins
|
|
184
|
+
hits = [min(found, key=lambda h: abs(h[1].count("\n", 0, h[2]) + 1 - site["line"]))]
|
|
185
|
+
break
|
|
186
|
+
hits += found
|
|
187
|
+
if not hits:
|
|
188
|
+
out["reason"] = "the SQL was not found as one literal (it may be concatenated, escaped or formatted in the source)"
|
|
189
|
+
return out
|
|
190
|
+
if len(hits) > 1:
|
|
191
|
+
out["reason"] = f"the same SQL appears {len(hits)} times outside the call site's file: which one the call uses is not certain"
|
|
192
|
+
return out
|
|
193
|
+
path, text, start, end = hits[0]
|
|
194
|
+
rel = path.relative_to(root).as_posix()
|
|
195
|
+
kind, forbidden = _delimiter(text, start, path.suffix)
|
|
196
|
+
new_text, inserted = _edit(text, start, end, code_sql.rstrip().rstrip(";"))
|
|
197
|
+
bad = next((c for c in forbidden for piece in inserted if c in piece), None)
|
|
198
|
+
if bad is not None:
|
|
199
|
+
out["reason"] = f"the new SQL has a character ({bad!r}) that must be escaped inside {kind}"
|
|
200
|
+
return out
|
|
201
|
+
if any("%" in v for v in mapping.values()) and any("%" in re.sub(r"%\(\w+\)s|%s", "", piece) for piece in inserted):
|
|
202
|
+
out["reason"] = "the SQL is a % format string and the new text adds a % sign"
|
|
203
|
+
return out
|
|
204
|
+
if new_text == text:
|
|
205
|
+
out["reason"] = "the rewrite is the same text as the code's SQL"
|
|
206
|
+
return out
|
|
207
|
+
out.update(file=rel, line=text.count("\n", 0, start) + 1, diff=_unified(text, new_text, rel), literal=kind)
|
|
208
|
+
if positional and new_order != old_order:
|
|
209
|
+
out.update(status="needs_argument_change", bind_order=new_order,
|
|
210
|
+
reason="the placeholders are positional and their order changes: the bound arguments must follow")
|
|
211
|
+
else:
|
|
212
|
+
out.update(status="exact", reason="")
|
|
213
|
+
return out
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""PostgreSQL plans: an index, built without blocking writes.
|
|
2
|
+
|
|
3
|
+
The sandbox ran `CREATE INDEX`; production gets `CREATE INDEX CONCURRENTLY`, which takes a SHARE UPDATE EXCLUSIVE
|
|
4
|
+
lock (reads and writes go on), scans the table twice, and cannot run inside a transaction. If it fails it leaves an
|
|
5
|
+
INVALID index behind, so the plan checks `indisvalid` and says how to start over.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
from ..engines.pg_ddl import parse_index, split_statements, statement_kind
|
|
13
|
+
from .clickhouse import PlanError, expected_read
|
|
14
|
+
from .common import estimate_label, estimates, normalize_sql, step
|
|
15
|
+
|
|
16
|
+
PARAM = re.compile(r"\{(\w+)(?::([^{}]+))?\}")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def concurrently(stmt: str) -> str:
|
|
20
|
+
"""`CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] name ...` in its online, re-runnable form."""
|
|
21
|
+
m = re.match(r"\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(CONCURRENTLY\s+)?(IF\s+NOT\s+EXISTS\s+)?", stmt, re.I)
|
|
22
|
+
return f"CREATE {'UNIQUE ' if m.group(1) else ''}INDEX CONCURRENTLY IF NOT EXISTS " + stmt[m.end():]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def qualified(index_name: str, table: str) -> str:
|
|
26
|
+
"""An index lives in its table's schema; DROP INDEX needs that schema when it is not on the search path."""
|
|
27
|
+
schema = table.replace('"', "").rpartition(".")[0]
|
|
28
|
+
return f"{schema}.{index_name}" if schema and "." not in index_name else index_name
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def explain_sql(sql: str, params: dict) -> str:
|
|
32
|
+
from ..engines.postgres import render_params
|
|
33
|
+
return "EXPLAIN (ANALYZE, BUFFERS) " + render_params(normalize_sql(sql), params)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def index_plan(findings: dict, finding: dict, variant: dict, catalog_sizes, setup_seconds: float | None) -> dict:
|
|
37
|
+
statements = [s.strip().rstrip(";") for script in variant.get("setup_sql") or [] for s in split_statements(script)]
|
|
38
|
+
indexes = [(s, parse_index(s)) for s in statements if statement_kind(s) in ("index", "unique_index")]
|
|
39
|
+
indexes = [(s, ix) for s, ix in indexes if ix]
|
|
40
|
+
if not indexes:
|
|
41
|
+
raise PlanError("the variant's setup has no CREATE INDEX")
|
|
42
|
+
steps, warnings, rollback_sql, first_sizes = [], [], [], None
|
|
43
|
+
names = [qualified(ix.name, ix.table) for _, ix in indexes]
|
|
44
|
+
tables = list(dict.fromkeys(ix.table for _, ix in indexes))
|
|
45
|
+
steps.append(step("precheck", "Look for long transactions and leftovers", "prepare", [
|
|
46
|
+
"SELECT count(*) AS long_transactions FROM pg_stat_activity WHERE xact_start < now() - interval '5 minutes' AND pid <> pg_backend_pid()",
|
|
47
|
+
"SELECT c.relname AS invalid_index FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid WHERE NOT i.indisvalid AND c.relname IN ("
|
|
48
|
+
+ ", ".join("'" + ix.name.split(".")[-1].replace("'", "''") + "'" for _, ix in indexes) + ")",
|
|
49
|
+
], effect="read", expect={"statement": 1, "max_rows": 0},
|
|
50
|
+
chips=["the build waits for every transaction older than itself: a long one stalls it", "an invalid index of this name is a failed earlier build: drop it first"]))
|
|
51
|
+
total = {"extra_disk_bytes": 0, "low": 0, "high": 0}
|
|
52
|
+
for stmt, ix in indexes:
|
|
53
|
+
table = next((t for t in finding["tables"] if t.replace('"', "") == ix.table.replace('"', "")), ix.table)
|
|
54
|
+
sizes = catalog_sizes(table)
|
|
55
|
+
first_sizes = first_sizes or sizes
|
|
56
|
+
est = estimates(findings, finding, {**variant, "storage_delta_bytes": int((variant.get("storage_delta_bytes") or 0) / len(indexes))}, table, sizes,
|
|
57
|
+
setup_seconds / len(indexes) if setup_seconds else None, slower=3.0)
|
|
58
|
+
if est["duration_s"]:
|
|
59
|
+
est["basis"].append("time: CONCURRENTLY scans the table twice and waits for open transactions; counted as 3x a plain build")
|
|
60
|
+
est["label"] = estimate_label(est)
|
|
61
|
+
for k, v in (("extra_disk_bytes", est["extra_disk_bytes"] or 0), ("low", (est["duration_s"] or {}).get("low", 0)),
|
|
62
|
+
("high", (est["duration_s"] or {}).get("high", 0))):
|
|
63
|
+
total[k] += v
|
|
64
|
+
total.setdefault("basis", []).extend(b for b in est["basis"] if b not in total.get("basis", []))
|
|
65
|
+
name = qualified(ix.name, ix.table)
|
|
66
|
+
drop = f"DROP INDEX CONCURRENTLY IF EXISTS {name}"
|
|
67
|
+
rollback_sql.insert(0, drop)
|
|
68
|
+
chips = ["reads and writes continue", "cannot run inside a transaction block", "other schema changes and VACUUM on the table wait until it ends"]
|
|
69
|
+
if sizes.get("kind") == "partitioned table":
|
|
70
|
+
chips.append("the table is partitioned: CONCURRENTLY is not allowed on the parent; build it on each partition, then on the parent")
|
|
71
|
+
warnings.append({"code": "partitioned", "detail": f"{table} is partitioned: build the index on each partition first"})
|
|
72
|
+
steps.append(step(f"create_{ix.name.split('.')[-1]}", f"Build {ix.name.split('.')[-1]} without blocking writes", "build", [concurrently(stmt)],
|
|
73
|
+
undo=[drop], locks="SHARE UPDATE EXCLUSIVE on " + ix.table,
|
|
74
|
+
estimate={k: est[k] for k in ("is_estimate", "duration_s", "extra_disk_bytes", "basis", "label", "sizes_from")}, chips=chips))
|
|
75
|
+
steps.append(step(f"verify_{ix.name.split('.')[-1]}", "Check the index is valid", "verify", [
|
|
76
|
+
f"SELECT i.indisvalid AS valid, i.indisready AS ready, pg_relation_size(i.indexrelid) AS bytes FROM pg_index i "
|
|
77
|
+
f"WHERE i.indexrelid = '{name}'::regclass"], effect="read", expect={"min_rows": 1, "every": {"valid": True, "ready": True}},
|
|
78
|
+
chips=[f"not valid: {drop}, then build again"]))
|
|
79
|
+
for stmt in statements:
|
|
80
|
+
if statement_kind(stmt) not in ("index", "unique_index"):
|
|
81
|
+
steps.insert(1, step("setup_other", " ".join(stmt.split()[:3])[:60], "build", [stmt], reversible=False, chips=["as the sandbox ran it; no automatic undo"]))
|
|
82
|
+
warnings.append({"code": "manual", "detail": "one setup statement is not a CREATE INDEX: it is run as written"})
|
|
83
|
+
steps.append(step("analyze", "Refresh planner statistics", "build", [f"ANALYZE {t}" for t in tables], locks="SHARE UPDATE EXCLUSIVE, brief",
|
|
84
|
+
chips=["an index on an expression has no statistics until the table is analyzed", "changes statistics only"]))
|
|
85
|
+
first = indexes[0][1]
|
|
86
|
+
steps.append(step("confirm", "Confirm the query uses the index", "confirm", [explain_sql(variant["sql"], finding.get("params") or {})], effect="read",
|
|
87
|
+
chips=["parameter values are the sandbox's: use real ones", f"the plan should show an index scan on {first.name.split('.')[-1]}",
|
|
88
|
+
"EXPLAIN ANALYZE runs the query"],
|
|
89
|
+
expect={"measure": {"sql": variant["sql"], "params": finding.get("params") or {}, **(expected_read(variant) or {})}}))
|
|
90
|
+
est_all = {"is_estimate": True, "extra_disk_bytes": total["extra_disk_bytes"] or None,
|
|
91
|
+
"duration_s": {"low": total["low"], "high": total["high"]} if total["high"] else None, "sizes_from": first_sizes["source"], "basis": total.get("basis", [])}
|
|
92
|
+
est_all["label"] = estimate_label(est_all)
|
|
93
|
+
same_query = normalize_sql(variant.get("sql", "")) == normalize_sql(finding["baseline_sql"])
|
|
94
|
+
return {
|
|
95
|
+
"recipe": "index", "table": tables[0], "tables": tables, "indexes": names, "sizes": first_sizes, "estimates": est_all, "warnings": warnings,
|
|
96
|
+
"steps": steps,
|
|
97
|
+
"rollback": [{"when": "at any point", "possible": True, "loses": "nothing: the table's data is not touched", "sql": rollback_sql}],
|
|
98
|
+
"code": {"needs_patch": not same_query, "call_sites": [{
|
|
99
|
+
"file": finding["site"]["file"], "line": finding["site"]["line"], "symbol": finding["site"].get("symbol") or "",
|
|
100
|
+
"change": "none: the query is unchanged" if same_query else "the query changes too: see the patch"}],
|
|
101
|
+
"other_readers": [], "reader_counts": {}, "writers": []},
|
|
102
|
+
}
|