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/__init__.py
ADDED
codecop/access.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""How a query's filters line up with each table's sorting key.
|
|
2
|
+
|
|
3
|
+
Computed from the table definition and the benchmarked SQL, without the agent, so
|
|
4
|
+
the report can draw it: the ORDER BY columns in order, and for every filtered
|
|
5
|
+
column whether the filter can narrow the read.
|
|
6
|
+
|
|
7
|
+
A filter is `used` when its column is in the sorting key and every earlier key
|
|
8
|
+
column has an equality (or IN) filter, `skipped` when it is in the key but an
|
|
9
|
+
earlier key column is not pinned, `partition` when it only prunes partitions,
|
|
10
|
+
and `none` when the key does not contain it. This is the prefix rule: ClickHouse
|
|
11
|
+
can sometimes do a little better on a skipped column, never worse.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
import sqlglot
|
|
19
|
+
from sqlglot import exp
|
|
20
|
+
|
|
21
|
+
from .discover.schema import _split_top, find_tables
|
|
22
|
+
|
|
23
|
+
WORD = re.compile(r"[A-Za-z_]\w*")
|
|
24
|
+
OP_STRENGTH = {"eq": 0, "in": 1, "range": 2, "like": 3, "other": 4}
|
|
25
|
+
OPS = (
|
|
26
|
+
(exp.EQ, "eq"), (exp.In, "in"), (exp.Between, "range"), (exp.GT, "range"), (exp.GTE, "range"), (exp.LT, "range"),
|
|
27
|
+
(exp.LTE, "range"), (exp.Like, "like"), (exp.ILike, "like"), (exp.NEQ, "other"),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _strip_outer(text: str) -> str:
|
|
32
|
+
text = text.strip()
|
|
33
|
+
while text.startswith("(") and text.endswith(")"):
|
|
34
|
+
depth = 0
|
|
35
|
+
for i, c in enumerate(text):
|
|
36
|
+
depth += c == "("
|
|
37
|
+
depth -= c == ")"
|
|
38
|
+
if depth == 0 and i < len(text) - 1:
|
|
39
|
+
return text
|
|
40
|
+
text = text[1:-1].strip()
|
|
41
|
+
return text
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def key_parts(order_by: str) -> list[str]:
|
|
45
|
+
inner = _strip_outer(order_by or "")
|
|
46
|
+
if not inner or inner.lower() == "tuple()":
|
|
47
|
+
return []
|
|
48
|
+
return [p.strip() for p in _split_top(inner) if p.strip()]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def query_filters(sql: str, table: str, columns: set[str], keyed: set[str] = frozenset()) -> dict[str, str]:
|
|
52
|
+
"""Column -> strongest filter operator, for WHERE and PREWHERE of every SELECT that reads `table`."""
|
|
53
|
+
try:
|
|
54
|
+
tree = sqlglot.parse_one(sql, read="clickhouse")
|
|
55
|
+
except Exception:
|
|
56
|
+
return {}
|
|
57
|
+
short = table.split(".")[-1]
|
|
58
|
+
found: dict[str, str] = {}
|
|
59
|
+
for select in tree.find_all(exp.Select):
|
|
60
|
+
tables = [t for t in select.find_all(exp.Table) if t.find_ancestor(exp.Select) is select]
|
|
61
|
+
sources = [t.name for t in tables]
|
|
62
|
+
if short not in sources and not any(s.startswith(short + "__") for s in sources):
|
|
63
|
+
continue
|
|
64
|
+
# the names this SELECT gives the table (its alias, or its own name), and every name it gives other sources: a
|
|
65
|
+
# column qualified with another source's name (`t.scan_id` where t is the joined table) is not a filter on it
|
|
66
|
+
mine = {(t.alias_or_name or "").lower() for t in tables if t.name == short or t.name.startswith(short + "__")}
|
|
67
|
+
mine |= {t.name.lower() for t in tables if t.name == short or t.name.startswith(short + "__")}
|
|
68
|
+
others = {(t.alias_or_name or "").lower() for t in tables} - mine
|
|
69
|
+
others |= {(s.alias or "").lower() for s in select.find_all(exp.Subquery) if s.find_ancestor(exp.Select) is select and s.alias}
|
|
70
|
+
|
|
71
|
+
def ours(col: exp.Column) -> bool:
|
|
72
|
+
q = (col.table or "").lower()
|
|
73
|
+
return not q or q in mine or q not in others
|
|
74
|
+
for clause in (select.args.get("where"), select.args.get("prewhere")):
|
|
75
|
+
if clause is None:
|
|
76
|
+
continue
|
|
77
|
+
for node in clause.walk():
|
|
78
|
+
op = next((name for cls, name in OPS if isinstance(node, cls)), None)
|
|
79
|
+
if op is None or node.find_ancestor(exp.Select) is not select:
|
|
80
|
+
continue
|
|
81
|
+
if node.find_ancestor(exp.Or, exp.Not) is not None and op != "other":
|
|
82
|
+
op = "other" # an OR or NOT branch cannot narrow a key range on its own
|
|
83
|
+
# the filtered side is `this`; a column wrapped in a function still counts, weaker
|
|
84
|
+
target = node.this
|
|
85
|
+
names = [c.name for c in target.find_all(exp.Column) if ours(c)] if target is not None else []
|
|
86
|
+
wrapped = not isinstance(target, exp.Column)
|
|
87
|
+
for name in names:
|
|
88
|
+
if columns and name not in columns:
|
|
89
|
+
continue
|
|
90
|
+
# f(col) = x cannot use the key; f(col) >= x can when col is a key or partition column
|
|
91
|
+
kind = "other" if wrapped and (op in ("eq", "in") or name not in keyed) else op
|
|
92
|
+
if name not in found or OP_STRENGTH[kind] < OP_STRENGTH[found[name]]:
|
|
93
|
+
found[name] = kind
|
|
94
|
+
return found
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def table_access(create_sql: str, name: str, baseline_sql: str, rows_estimate: int | None = None) -> dict:
|
|
98
|
+
tables = find_tables("", create_sql)
|
|
99
|
+
t = tables[0] if tables else None
|
|
100
|
+
columns = {c if isinstance(c, str) else c.get("name", "") for c in (t.columns if t else [])}
|
|
101
|
+
order = key_parts(t.order_by if t else "")
|
|
102
|
+
partition = (t.partition_by if t else "") or ""
|
|
103
|
+
key_cols = [[w for w in WORD.findall(part) if not columns or w in columns] for part in order]
|
|
104
|
+
partition_cols = {w for w in WORD.findall(partition) if not columns or w in columns}
|
|
105
|
+
filters = query_filters(baseline_sql, name, columns, partition_cols | {c for cols in key_cols for c in cols})
|
|
106
|
+
out, pinned = [], True
|
|
107
|
+
state = {}
|
|
108
|
+
for cols in key_cols: # walk the key left to right; the usable prefix ends at the first unpinned column
|
|
109
|
+
ops = [filters[c] for c in cols if c in filters]
|
|
110
|
+
for c in cols:
|
|
111
|
+
if c in filters:
|
|
112
|
+
state.setdefault(c, "used" if pinned and filters[c] != "other" else "skipped")
|
|
113
|
+
pinned = pinned and bool(ops) and all(o in ("eq", "in") for o in ops)
|
|
114
|
+
for column, op in sorted(filters.items(), key=lambda kv: OP_STRENGTH[kv[1]]):
|
|
115
|
+
key = state.get(column) or "none"
|
|
116
|
+
if key != "used" and column in partition_cols and op != "other":
|
|
117
|
+
key = "partition"
|
|
118
|
+
out.append({"column": column, "op": op, "key": key})
|
|
119
|
+
rank = {"used": 0, "partition": 1, "skipped": 2, "none": 3}
|
|
120
|
+
out.sort(key=lambda f: rank[f["key"]])
|
|
121
|
+
return {
|
|
122
|
+
"table": name, "engine": (t.engine if t else "") or "", "order_by": order, "partition_by": partition,
|
|
123
|
+
"rows_estimate": rows_estimate, "filters": out,
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def new_order_by(setup_sql: list[str]) -> list[str]:
|
|
128
|
+
"""The sorting key a variant introduces: a re-keyed copy's ORDER BY, or a projection's."""
|
|
129
|
+
for stmt in setup_sql or []:
|
|
130
|
+
if re.match(r"\s*CREATE\s+TABLE", stmt, re.I):
|
|
131
|
+
tables = find_tables("", stmt)
|
|
132
|
+
if tables and tables[0].order_by:
|
|
133
|
+
return key_parts(tables[0].order_by)
|
|
134
|
+
m = re.search(r"\bORDER\s+BY\s+(\(.*?\)|[\w.]+)\s*(?:SETTINGS\b.*|PRIMARY\s+KEY\b.*|TTL\b.*|AS\s+SELECT\b.*)?$", stmt.strip().rstrip(";"), re.I | re.S)
|
|
135
|
+
if m: # CREATE TABLE copy AS original ... ORDER BY (...)
|
|
136
|
+
return key_parts(m.group(1))
|
|
137
|
+
m = re.search(r"ADD\s+PROJECTION\b.*?\bORDER\s+BY\s+(.+?)\)\s*$", stmt, re.I | re.S)
|
|
138
|
+
if m:
|
|
139
|
+
return key_parts(m.group(1))
|
|
140
|
+
return []
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""How a query's filters line up with each Postgres table's indexes.
|
|
2
|
+
|
|
3
|
+
The Postgres counterpart of access.py. A ClickHouse table has one sorting key; a
|
|
4
|
+
Postgres table has any number of indexes, so the output keeps the same `filters`
|
|
5
|
+
list and adds `indexes`: every index of the table, its columns in order, and
|
|
6
|
+
whether this query can use it.
|
|
7
|
+
|
|
8
|
+
Computed from the table definition (CREATE TABLE plus CREATE INDEX statements)
|
|
9
|
+
and the benchmarked SQL, without the agent and without a server.
|
|
10
|
+
|
|
11
|
+
Rules, per index:
|
|
12
|
+
btree walk the columns left to right. A column is usable while every column
|
|
13
|
+
before it has an equality filter (=, IN, = ANY, IS NULL, or a join key).
|
|
14
|
+
A range filter is usable too and ends the prefix. This is the prefix rule;
|
|
15
|
+
the planner can still apply a later column as an in-index filter, which
|
|
16
|
+
narrows nothing.
|
|
17
|
+
hash the single column, equality only.
|
|
18
|
+
brin any column with an equality or range filter (no prefix rule).
|
|
19
|
+
gin, gist, spgist any column with a containment, full-text or LIKE filter
|
|
20
|
+
(LIKE only with a trigram operator class).
|
|
21
|
+
A partial index (`where`) is listed with its predicate; it is counted usable only
|
|
22
|
+
when the query filters every column the predicate names.
|
|
23
|
+
|
|
24
|
+
Per filter, `key` says what the best index can do with it:
|
|
25
|
+
used an index can narrow the scan with this filter
|
|
26
|
+
skipped the column is in an index, but behind a column the query does not pin
|
|
27
|
+
partition the column only prunes partitions
|
|
28
|
+
none no index contains the column (or it is wrapped in a function no index matches)
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import re
|
|
34
|
+
|
|
35
|
+
import sqlglot
|
|
36
|
+
from sqlglot import exp
|
|
37
|
+
|
|
38
|
+
from .engines.pg_ddl import Index, parse_definition, parse_index, split_statements, statement_kind
|
|
39
|
+
|
|
40
|
+
PARAM = re.compile(r"\{(\w+)(?::([^{}]+))?\}")
|
|
41
|
+
WORD = re.compile(r"[A-Za-z_]\w*")
|
|
42
|
+
OP_STRENGTH = {"eq": 0, "in": 1, "join": 2, "range": 3, "contains": 4, "fts": 5, "like": 6, "other": 7}
|
|
43
|
+
EQUALITY = ("eq", "in", "join")
|
|
44
|
+
KEY_RANK = {"used": 0, "partition": 1, "skipped": 2, "none": 3}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _cls(*names):
|
|
48
|
+
return tuple(c for c in (getattr(exp, n, None) for n in names) if c is not None)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
OPS = (
|
|
52
|
+
(_cls("EQ", "NullSafeEQ"), "eq"), (_cls("In"), "in"), (_cls("Is"), "eq"),
|
|
53
|
+
(_cls("Between", "GT", "GTE", "LT", "LTE"), "range"),
|
|
54
|
+
(_cls("Like", "ILike", "SimilarTo", "RegexpLike", "RegexpILike"), "like"),
|
|
55
|
+
(_cls("ArrayContainsAll", "ArrayOverlaps", "JSONBContains", "JSONBExists", "ArrayContains", "JSONBContainsAnyTopKeys",
|
|
56
|
+
"JSONBContainsAllTopKeys"), "contains"),
|
|
57
|
+
(_cls("MatchAgainst"), "fts"),
|
|
58
|
+
(_cls("NEQ"), "other"),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def plain_sql(sql: str) -> str:
|
|
63
|
+
"""Replace {name:type} parameters with a literal, so the text parses as ordinary SQL."""
|
|
64
|
+
return PARAM.sub(lambda m: f"CAST('?' AS {m.group(2)})" if m.group(2) else "'?'", sql)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _norm(text: str) -> str:
|
|
68
|
+
return re.sub(r"[\s\"()]+", "", text).lower()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _op_of(node) -> str | None:
|
|
72
|
+
for classes, name in OPS:
|
|
73
|
+
if classes and isinstance(node, classes):
|
|
74
|
+
return name
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def query_shape(sql: str, table: str, columns: set[str], expressions: dict[str, str] | None = None) -> tuple[dict[str, str], list[dict]]:
|
|
79
|
+
"""(filters, sort) for `table`: column or indexed expression -> strongest operator, and the ORDER BY columns.
|
|
80
|
+
|
|
81
|
+
`expressions` maps a normalised index expression to its text, so `lower(email) = $1` matches an index on lower(email)."""
|
|
82
|
+
try:
|
|
83
|
+
tree = sqlglot.parse_one(plain_sql(sql), read="postgres")
|
|
84
|
+
except Exception:
|
|
85
|
+
return {}, []
|
|
86
|
+
short = table.split(".")[-1].lower()
|
|
87
|
+
expressions = expressions or {}
|
|
88
|
+
found: dict[str, str] = {}
|
|
89
|
+
sort: list[dict] = []
|
|
90
|
+
|
|
91
|
+
def note(name: str, kind: str) -> None:
|
|
92
|
+
if name not in found or OP_STRENGTH[kind] < OP_STRENGTH[found[name]]:
|
|
93
|
+
found[name] = kind
|
|
94
|
+
|
|
95
|
+
for select in tree.find_all(exp.Select):
|
|
96
|
+
sources = {}
|
|
97
|
+
for t in select.find_all(exp.Table):
|
|
98
|
+
if t.find_ancestor(exp.Select) is select:
|
|
99
|
+
sources[t.alias_or_name.lower()] = t.name.lower()
|
|
100
|
+
mine = {alias for alias, name in sources.items() if name == short or name.startswith(short + "__")}
|
|
101
|
+
if not mine:
|
|
102
|
+
continue
|
|
103
|
+
alone = len(sources) == 1
|
|
104
|
+
|
|
105
|
+
def ours(col: exp.Column) -> bool:
|
|
106
|
+
if col.table:
|
|
107
|
+
return col.table.lower() in mine
|
|
108
|
+
return alone or (not columns or col.name in columns)
|
|
109
|
+
|
|
110
|
+
clauses = [select.args.get("where")] + [j.args.get("on") for j in select.args.get("joins") or []]
|
|
111
|
+
for clause in clauses:
|
|
112
|
+
if clause is None:
|
|
113
|
+
continue
|
|
114
|
+
for node in clause.walk():
|
|
115
|
+
op = _op_of(node)
|
|
116
|
+
if op is None or node.find_ancestor(exp.Select) is not select:
|
|
117
|
+
continue
|
|
118
|
+
if node.find_ancestor(exp.Or, exp.Not) is not None:
|
|
119
|
+
op = "other" # one branch of an OR, or a negation, cannot narrow an index range on its own
|
|
120
|
+
left, right = node.this, node.args.get("expression")
|
|
121
|
+
if isinstance(node, exp.Is) and not isinstance(right, exp.Null):
|
|
122
|
+
op = "other"
|
|
123
|
+
sides = [(left, right)]
|
|
124
|
+
if isinstance(node, _cls("EQ")) and isinstance(right, exp.Column) and isinstance(left, exp.Column):
|
|
125
|
+
sides.append((right, left)) # a = b joins both ways
|
|
126
|
+
elif (isinstance(node, _cls("EQ")) and isinstance(left, exp.Tuple) and isinstance(right, exp.Tuple)
|
|
127
|
+
and len(left.expressions) == len(right.expressions)):
|
|
128
|
+
# (t.tenant_id, t.id, t.inserted_at) = (lt.tenant_id, dt.task_id, dt.task_inserted_at): the server
|
|
129
|
+
# reads a row comparison as one equality per position, and so does an index
|
|
130
|
+
sides = []
|
|
131
|
+
for a, b in zip(left.expressions, right.expressions):
|
|
132
|
+
sides.append((a, b))
|
|
133
|
+
if isinstance(a, exp.Column) and isinstance(b, exp.Column):
|
|
134
|
+
sides.append((b, a))
|
|
135
|
+
for target, other in sides:
|
|
136
|
+
if target is None:
|
|
137
|
+
continue
|
|
138
|
+
kind = op
|
|
139
|
+
if isinstance(node, _cls("EQ")) and isinstance(other, exp.Any):
|
|
140
|
+
kind = "in" if op != "other" else op
|
|
141
|
+
cols = [c for c in target.find_all(exp.Column) if ours(c)]
|
|
142
|
+
if not cols:
|
|
143
|
+
continue
|
|
144
|
+
if isinstance(other, exp.Column) and not ours(other) and kind == "eq":
|
|
145
|
+
kind = "join"
|
|
146
|
+
elif isinstance(other, exp.Column) and ours(other) and isinstance(target, exp.Column):
|
|
147
|
+
kind = "other" # two columns of the same table compared: not an index condition
|
|
148
|
+
wrapped = not isinstance(target, exp.Column)
|
|
149
|
+
if wrapped:
|
|
150
|
+
text = _norm(target.sql(dialect="postgres"))
|
|
151
|
+
text = re.sub(r"\b(" + "|".join(re.escape(a) for a in mine) + r")\.", "", text)
|
|
152
|
+
if text in expressions:
|
|
153
|
+
note(expressions[text], kind)
|
|
154
|
+
continue
|
|
155
|
+
# a cast or function around the column: a plain index on it cannot be used for this filter
|
|
156
|
+
kind = "other"
|
|
157
|
+
for c in cols:
|
|
158
|
+
if columns and c.name not in columns:
|
|
159
|
+
continue
|
|
160
|
+
note(c.name, kind)
|
|
161
|
+
order = select.args.get("order")
|
|
162
|
+
if order is not None and not sort:
|
|
163
|
+
for o in order.expressions:
|
|
164
|
+
target = o.this
|
|
165
|
+
if isinstance(target, exp.Column) and ours(target) and (not columns or target.name in columns):
|
|
166
|
+
sort.append({"column": target.name, "desc": bool(o.args.get("desc"))})
|
|
167
|
+
else:
|
|
168
|
+
sort = []
|
|
169
|
+
break
|
|
170
|
+
return found, sort
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _index_use(ix: Index, filters: dict[str, str]) -> tuple[int, dict[str, str]]:
|
|
174
|
+
"""(usable column count, state per filter name) for one index."""
|
|
175
|
+
state: dict[str, str] = {}
|
|
176
|
+
names = [c.column or c.text for c in ix.columns]
|
|
177
|
+
used = 0
|
|
178
|
+
if ix.method == "btree":
|
|
179
|
+
pinned = True
|
|
180
|
+
for name in names:
|
|
181
|
+
op = filters.get(name)
|
|
182
|
+
if op is None:
|
|
183
|
+
pinned = False
|
|
184
|
+
continue
|
|
185
|
+
if pinned and op in EQUALITY + ("range",):
|
|
186
|
+
state[name] = "used"
|
|
187
|
+
used += 1
|
|
188
|
+
else:
|
|
189
|
+
state[name] = "skipped"
|
|
190
|
+
pinned = pinned and op in EQUALITY
|
|
191
|
+
elif ix.method == "hash":
|
|
192
|
+
if len(names) == 1 and filters.get(names[0]) in EQUALITY:
|
|
193
|
+
state[names[0]], used = "used", 1
|
|
194
|
+
elif ix.method == "brin":
|
|
195
|
+
for name in names:
|
|
196
|
+
if filters.get(name) in EQUALITY + ("range",):
|
|
197
|
+
state[name] = "used"
|
|
198
|
+
used += 1
|
|
199
|
+
else: # gin, gist, spgist, and anything an extension adds
|
|
200
|
+
for c in ix.columns:
|
|
201
|
+
name = c.column or c.text
|
|
202
|
+
op = filters.get(name)
|
|
203
|
+
trigram = "trgm" in c.opclass.lower()
|
|
204
|
+
if op in ("contains", "fts") or (op == "like" and trigram) or (op in EQUALITY and ix.method == "gist"):
|
|
205
|
+
state[name] = "used"
|
|
206
|
+
used += 1
|
|
207
|
+
elif op is not None:
|
|
208
|
+
state[name] = "skipped"
|
|
209
|
+
return used, state
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _serves_sort(ix: Index, filters: dict[str, str], sort: list[dict]) -> bool:
|
|
213
|
+
"""True when the index returns rows already in the query's ORDER BY: equality prefix, then the sort columns in order."""
|
|
214
|
+
if ix.method != "btree" or not sort:
|
|
215
|
+
return False
|
|
216
|
+
cols = list(ix.columns)
|
|
217
|
+
while cols and filters.get(cols[0].column or cols[0].text) in EQUALITY and (cols[0].column or cols[0].text) != sort[0]["column"]:
|
|
218
|
+
cols.pop(0)
|
|
219
|
+
if len(cols) < len(sort):
|
|
220
|
+
return False
|
|
221
|
+
pairs = list(zip(cols, sort))
|
|
222
|
+
if any(c.column != s["column"] for c, s in pairs):
|
|
223
|
+
return False
|
|
224
|
+
flips = {c.desc != s["desc"] for c, s in pairs}
|
|
225
|
+
return len(flips) == 1 # all the same direction, or all reversed (a backward scan)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def table_access(create_sql: str, name: str, baseline_sql: str, rows_estimate: int | None = None) -> dict:
|
|
229
|
+
t = parse_definition(create_sql, name)
|
|
230
|
+
columns = set(t.columns)
|
|
231
|
+
expressions = {_norm(c.text): c.text for ix in t.indexes for c in ix.columns if not c.column}
|
|
232
|
+
filters, sort = query_shape(baseline_sql, name, columns, expressions)
|
|
233
|
+
partition_cols = {w for w in WORD.findall(t.partition_by.split("(", 1)[-1]) if w in columns} if t.partition_by else set()
|
|
234
|
+
best: dict[str, str] = {}
|
|
235
|
+
serving: dict[str, list[str]] = {}
|
|
236
|
+
indexes = []
|
|
237
|
+
for ix in t.indexes:
|
|
238
|
+
used, state = _index_use(ix, filters)
|
|
239
|
+
predicate_cols = {w for w in WORD.findall(ix.where) if w in columns}
|
|
240
|
+
if ix.where and not predicate_cols <= set(filters):
|
|
241
|
+
used, state = 0, {k: "skipped" for k in state} # the query does not imply the partial index's predicate
|
|
242
|
+
for col, s in state.items():
|
|
243
|
+
if col not in best or KEY_RANK[s] < KEY_RANK[best[col]]:
|
|
244
|
+
best[col] = s
|
|
245
|
+
if s == "used":
|
|
246
|
+
serving.setdefault(col, []).append(ix.name)
|
|
247
|
+
sorted_by = _serves_sort(ix, filters, sort) and not (ix.where and not predicate_cols <= set(filters))
|
|
248
|
+
indexes.append({
|
|
249
|
+
"name": ix.name, "method": ix.method, "unique": ix.unique, "primary": ix.primary,
|
|
250
|
+
"columns": [c.text + (" DESC" if c.desc else "") for c in ix.columns], "include": ix.include, "where": ix.where,
|
|
251
|
+
"state": "used" if used else ("sort" if sorted_by else "unused"), "used_columns": used, "serves_sort": sorted_by,
|
|
252
|
+
})
|
|
253
|
+
out = []
|
|
254
|
+
for column, op in sorted(filters.items(), key=lambda kv: OP_STRENGTH[kv[1]]):
|
|
255
|
+
key = best.get(column) or "none"
|
|
256
|
+
if key != "used" and column in partition_cols and op != "other":
|
|
257
|
+
key = "partition"
|
|
258
|
+
out.append({"column": column, "op": op, "key": key, "indexes": serving.get(column, [])})
|
|
259
|
+
out.sort(key=lambda f: KEY_RANK[f["key"]])
|
|
260
|
+
indexes.sort(key=lambda i: ({"used": 0, "sort": 1, "unused": 2}[i["state"]], -i["used_columns"]))
|
|
261
|
+
return {
|
|
262
|
+
"table": name, "engine": "postgres", "order_by": [], "partition_by": t.partition_by,
|
|
263
|
+
"rows_estimate": rows_estimate, "filters": out, "indexes": indexes, "sort": sort,
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def new_index(setup_sql: list[str]) -> dict | None:
|
|
268
|
+
"""The first index a variant's setup creates: {name, table, method, unique, columns, include, where}."""
|
|
269
|
+
for script in setup_sql or []:
|
|
270
|
+
for stmt in split_statements(script):
|
|
271
|
+
if statement_kind(stmt) in ("index", "unique_index"):
|
|
272
|
+
ix = parse_index(stmt)
|
|
273
|
+
if ix:
|
|
274
|
+
return {"name": ix.name, "table": ix.table, "method": ix.method, "unique": ix.unique,
|
|
275
|
+
"columns": [c.text + (" DESC" if c.desc else "") for c in ix.columns], "include": ix.include, "where": ix.where}
|
|
276
|
+
return None
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def new_partition_by(setup_sql: list[str]) -> str:
|
|
280
|
+
for script in setup_sql or []:
|
|
281
|
+
m = re.search(r"\bPARTITION\s+BY\s+(\w+\s*\([^)]*\))", script, re.I)
|
|
282
|
+
if m:
|
|
283
|
+
return re.sub(r"\s+", " ", m.group(1))
|
|
284
|
+
return ""
|