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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,971 @@
1
+ """The parsed-statement side of the scenarios (scenarios.py): what a statement's filters do to each table it reads, and
2
+ the rewrites that rules can write mechanically. No text matching on SQL: every rule here reads the statement parsed by
3
+ sqlglot (text matching on SQL was not useful).
4
+
5
+ A statement is any text CodeCop knows: SQL in code (run-time parts « » become identifiers the parser accepts and are
6
+ remembered), ORM-translated SQL, and the server's normalized text of a pulled shape (every value already `?`).
7
+
8
+ `TableInfo` is what the rules need of a table: its columns and types, sorting key, partition key, time columns of either
9
+ key, rows, real bytes per row of each column, skip indexes, projections, and the materialized views fed from it. From
10
+ the real catalog when a pull exists, else from the inventory's table definitions (no sizes, no rows).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import re
17
+ from dataclasses import dataclass, field
18
+
19
+ import sqlglot
20
+ from sqlglot import exp
21
+
22
+ from .sqlinfo import to_parsable
23
+
24
+ TIME_TYPE = re.compile(r"\b(?:Date|DateTime|DateTime64|Date32|timestamp|timestamptz|date|datetime)\b", re.I)
25
+ HEAVY_NAME = re.compile(r"payload|body|content|message|json|html|input|output|propert|attribute|metadata|raw|response|request|"
26
+ r"argument|stacktrace|blob|document|prompt|completion|^events$|^data$", re.I)
27
+ ID_NAME = re.compile(r"(?:_?id|Id|_ids|_?hash|_at|_time|_ts|_type|_kind|_name|_key)$") # an identifier or a label, never a payload
28
+ WORD = re.compile(r"[A-Za-z_]\w*")
29
+ COMPARE = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.In, exp.Between, exp.Like, exp.ILike, exp.NullSafeEQ)
30
+ AGG_NAMES = {"count", "sum", "avg", "min", "max", "any", "anylast", "argmax", "argmin", "grouparray", "groupuniqarray", "uniq",
31
+ "uniqexact", "uniqcombined", "quantile", "quantiles", "countif", "sumif", "avgif", "maxif", "minif", "topk", "median"}
32
+ HEAVY_AGG = {"argmax", "argmin", "any", "anylast", "grouparray", "groupuniqarray", "max", "min", "anyheavy", "argmaxif", "argminif"}
33
+
34
+
35
+ def dialect_of(engine: str) -> str:
36
+ return {"clickhouse": "clickhouse", "postgres": "postgres", "mysql": "mysql", "sqlite": "sqlite"}.get(engine or "", "clickhouse")
37
+
38
+
39
+ @dataclass
40
+ class Parsed:
41
+ tree: exp.Expression | None
42
+ text: str
43
+ holes: list[str] = field(default_factory=list) # run-time parts, as `__qpN__` identifiers in the tree
44
+ error: str = ""
45
+ dropped: bool = False # a run-time part that stood where a clause would was left out to parse the rest
46
+ cut: list[str] = field(default_factory=list) # the run-time parts left out, as discover wrote them
47
+
48
+ @property
49
+ def only_optional_cut(self) -> bool:
50
+ """Every part left out is an optional clause («if(c): ...», «or: ...»): the statement as parsed is the one sent
51
+ when none of them applies."""
52
+ return bool(self.cut) and all(h.startswith(("«if(", "«or:")) for h in self.cut)
53
+
54
+ @property
55
+ def ok(self) -> bool:
56
+ return self.tree is not None
57
+
58
+
59
+ OPERATOR_WORDS = {"AND", "OR", "ON", "WHERE", "PREWHERE", "HAVING", "BY", "IN", "NOT", "SELECT", "LIMIT", "OFFSET", "THEN", "ELSE",
60
+ "WHEN", "CASE", "BETWEEN", "LIKE", "ILIKE", "IS", "INTERVAL", "AS", "FROM", "JOIN", "WITH", "SETTINGS"}
61
+
62
+
63
+ def parse(sql: str, engine: str) -> Parsed:
64
+ """The statement parsed for its engine. A run-time part («expr» from discover) becomes an identifier `__qpN__`; a
65
+ normalized `?..` (a list the server collapsed) becomes one `?`."""
66
+ text = re.sub(r"\?\s*\.\.", "?", sql or "")
67
+ parsable, holes = to_parsable(text)
68
+ # A run-time part that stands where a whole clause would (`FROM t «optional join» WHERE`) is not an identifier: the
69
+ # second attempt drops the parts that stand alone between two words that are not operators. A part inside a
70
+ # filter (`AND «filters»`) stays, so a rule still sees that the filter has a run-time part.
71
+ attempts = [parsable]
72
+ def drop(m: re.Match) -> str:
73
+ before = re.search(r"(\S+)\s*$", parsable[:m.start()])
74
+ word = (before.group(1) if before else "").upper()
75
+ return m.group(0) if word in OPERATOR_WORDS or word[-1:] in ("=", "<", ">", "(", ",") else " "
76
+
77
+ alone = re.sub(r"(?<=\s)__qp\d+__(?=\s|$)", drop, parsable)
78
+ if alone != parsable:
79
+ attempts.append(alone)
80
+ # a conditional part («if(c): AND x = :x», «or: ...») is a whole optional clause: the statement stands without it
81
+ optional = [i for i, h in enumerate(holes) if h.startswith(("«if(", "«or:"))]
82
+ if optional:
83
+ cut = re.sub(r"__qp(?:%s)__,?" % "|".join(map(str, optional)), " ", parsable)
84
+ attempts += [cut, re.sub(r"(?<=\s)__qp\d+__(?=\s|$)", drop, cut)]
85
+ error = ""
86
+ for n, attempt in enumerate(attempts):
87
+ try:
88
+ trees = sqlglot.parse(attempt, read=dialect_of(engine))
89
+ except Exception as e: # any parser error: the statement is counted as unparsed, never matched by text instead
90
+ error = str(e)[:200]
91
+ continue
92
+ tree = next((t for t in trees if t is not None), None)
93
+ if tree is None or isinstance(tree, exp.Command):
94
+ error = "not a statement the parser reads"
95
+ continue
96
+ cut = [h for i, h in enumerate(holes) if f"__qp{i}__" not in attempt] if n > 0 else []
97
+ return Parsed(tree, sql, holes, dropped=n > 0, cut=cut)
98
+ return Parsed(None, sql, holes, error)
99
+
100
+
101
+ def render(tree: exp.Expression, engine: str) -> str:
102
+ return tree.sql(dialect=dialect_of(engine))
103
+
104
+
105
+ # ---- tables ------------------------------------------------------------------------------------------------------
106
+
107
+ @dataclass
108
+ class TableInfo:
109
+ name: str
110
+ engine: str = "" # the table engine (ReplacingMergeTree, ...)
111
+ columns: dict[str, str] = field(default_factory=dict) # name -> type
112
+ sorting_key: list[str] = field(default_factory=list) # bare columns of the ORDER BY, in order ([] for an expression key)
113
+ sorting_expr: str = ""
114
+ partition_expr: str = ""
115
+ partition_cols: list[str] = field(default_factory=list)
116
+ rows: int | None = None
117
+ row_bytes: dict[str, float] = field(default_factory=dict) # column -> real mean uncompressed bytes per row (catalog)
118
+ skip_indexes: list[dict] = field(default_factory=list)
119
+ projections: list[dict] = field(default_factory=list)
120
+ feeds: list[str] = field(default_factory=list) # materialized views that read this table
121
+ create_sql: str = ""
122
+ source: str = "" # real catalog | inventory
123
+
124
+ @property
125
+ def key_cols(self) -> set[str]:
126
+ return {c for c in self.sorting_key} | {w for w in WORD.findall(self.sorting_expr) if w in self.columns}
127
+
128
+ @property
129
+ def time_cols(self) -> list[str]:
130
+ """Date or time columns that are in the partition key or the sorting key: a read with no bound on them reads
131
+ every partition (or the whole key range)."""
132
+ out = []
133
+ for c in list(self.partition_cols) + sorted(self.key_cols):
134
+ if c in self.columns and TIME_TYPE.search(self.columns[c] or "") and c not in out:
135
+ out.append(c)
136
+ return out
137
+
138
+ @property
139
+ def deduplicating(self) -> bool:
140
+ return bool(re.search(r"(Replacing|Collapsing|VersionedCollapsing|Coalescing|Aggregating|Summing)MergeTree", self.engine or "", re.I))
141
+
142
+ table_row_bytes: float | None = None # real uncompressed bytes per row of the whole table (catalog)
143
+
144
+ def wide(self, column: str, min_bytes: float) -> tuple[bool, str]:
145
+ """Whether a column is heavy: by its real bytes per row when the catalog has them; else, when the whole row is
146
+ narrower than `min_bytes`, no column is; else by its type (JSON, Map, Object, an array of strings) or a String
147
+ whose name says payload (body, content, payload, json, ...)."""
148
+ if column in self.row_bytes and self.row_bytes[column] > 0:
149
+ return self.row_bytes[column] >= min_bytes, "measured"
150
+ if self.table_row_bytes is not None and self.table_row_bytes < min_bytes:
151
+ return False, "measured"
152
+ t = self.columns.get(column, "")
153
+ if not t or re.search(r"LowCardinality|FixedString|UUID", t):
154
+ return False, "by_type"
155
+ if re.search(r"\b(?:JSON|Object|Map|jsonb?)\b|Array\((?:Nullable\()?String", t, re.I):
156
+ return True, "by_type"
157
+ return bool(re.search(r"\bString\b|\btext\b|bytea", t, re.I) and HEAVY_NAME.search(column) and not ID_NAME.search(column)), "by_type"
158
+
159
+
160
+ def _key_columns(expr: str, columns: dict[str, str]) -> list[str]:
161
+ from .access import key_parts
162
+ parts = key_parts(expr or "")
163
+ out = []
164
+ for p in parts:
165
+ p = p.strip().strip("`\"")
166
+ if re.fullmatch(r"\w+", p):
167
+ out.append(p)
168
+ else:
169
+ return out # an expression ends the usable bare prefix
170
+ return out
171
+
172
+
173
+ def tables_from_catalog(facts, engine: str) -> dict[str, TableInfo]:
174
+ out: dict[str, TableInfo] = {}
175
+ for name, t in (facts.tables(engine) if facts else {}).items():
176
+ cols = {c["name"]: c.get("type", "") for c in t.get("columns") or []}
177
+ rows = int(t.get("rows") or 0)
178
+ sizes = {c["name"]: int(c.get("uncompressed_bytes") or 0) / rows for c in t.get("columns") or [] if rows and c.get("uncompressed_bytes")}
179
+ pk = t.get("partition_key") or ""
180
+ out[name] = TableInfo(table_row_bytes=(int(t.get("uncompressed_bytes") or 0) / rows) if rows and t.get("uncompressed_bytes") else None,name=name, engine=t.get("engine", ""), columns=cols, sorting_key=_key_columns(t.get("sorting_key") or "", cols),
181
+ sorting_expr=t.get("sorting_key") or "", partition_expr=pk,
182
+ partition_cols=[w for w in WORD.findall(pk) if w in cols], rows=rows if t.get("rows") is not None else None,
183
+ row_bytes=sizes, skip_indexes=list(t.get("skip_indexes") or []), projections=list(t.get("projections") or []),
184
+ feeds=list(t.get("feeds") or []), create_sql=t.get("create_sql") or "", source="real catalog")
185
+ return out
186
+
187
+
188
+ def tables_from_inventory(inventory: dict) -> dict[str, TableInfo]:
189
+ out: dict[str, TableInfo] = {}
190
+ for t in (inventory or {}).get("tables") or []:
191
+ if t.get("test_only"):
192
+ continue
193
+ name = str(t.get("name") or "").split(".")[-1].strip("`\"")
194
+ if not name:
195
+ continue
196
+ cols = {c["name"]: c.get("type", "") for c in t.get("columns") or [] if isinstance(c, dict) and c.get("name")}
197
+ pk = t.get("partition_by") or ""
198
+ info = TableInfo(name=name, engine=t.get("engine", ""), columns=cols, sorting_key=_key_columns(t.get("order_by") or "", cols),
199
+ sorting_expr=t.get("order_by") or t.get("primary_key") or "", partition_expr=pk,
200
+ partition_cols=[w for w in WORD.findall(pk) if w in cols], source="inventory")
201
+ seen = out.get(name)
202
+ if seen is None or (not seen.sorting_expr and info.sorting_expr) or len(info.columns) > len(seen.columns):
203
+ out[name] = info
204
+ return out
205
+
206
+
207
+ # ---- what a SELECT reads -------------------------------------------------------------------------------------------
208
+
209
+ @dataclass
210
+ class Read:
211
+ """One table read by one SELECT: where it is, under which alias, with FINAL or not."""
212
+ select: exp.Select
213
+ table: str
214
+ alias: str
215
+ final: bool
216
+ node: exp.Expression # the Table node
217
+ joined: bool # read on the right side of a JOIN
218
+ join: exp.Join | None = None
219
+
220
+
221
+ def _table_of(source) -> tuple[exp.Table | None, bool]:
222
+ if isinstance(source, exp.Final):
223
+ return (source.this if isinstance(source.this, exp.Table) else None), True
224
+ if isinstance(source, exp.Table):
225
+ return source, bool(source.args.get("final"))
226
+ return None, False
227
+
228
+
229
+ def cte_reads(tree: exp.Expression) -> list[Read]:
230
+ """Reads of a CTE that is itself a read of one table (`traces_final AS (SELECT ... FROM traces FINAL WHERE ...)`):
231
+ as reads of that table, so a column carried through the CTE is the table's column."""
232
+ base = {}
233
+ for c in tree.find_all(exp.CTE):
234
+ sel = c.this if isinstance(c.this, exp.Select) else None
235
+ if sel is None or sel.args.get("joins"):
236
+ continue
237
+ src = sel.args.get("from") or sel.args.get("from_")
238
+ t, final = _table_of(src.this) if src is not None else (None, False)
239
+ if t is not None and t.name:
240
+ base[c.alias_or_name.lower()] = (t.name, final)
241
+ out = []
242
+ for sel in tree.find_all(exp.Select):
243
+ src = sel.args.get("from") or sel.args.get("from_")
244
+ if src is None:
245
+ continue
246
+ t, _ = _table_of(src.this)
247
+ if t is not None and t.name.lower() in base and not sel.args.get("joins"):
248
+ name, final = base[t.name.lower()]
249
+ out.append(Read(sel, name, t.alias_or_name, final, t, False))
250
+ return out
251
+
252
+
253
+ def reads(tree: exp.Expression) -> list[Read]:
254
+ ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
255
+ out = []
256
+ for sel in tree.find_all(exp.Select):
257
+ src = sel.args.get("from") or sel.args.get("from_")
258
+ if src is not None:
259
+ t, final = _table_of(src.this)
260
+ if t is not None and t.name and t.name.lower() not in ctes:
261
+ out.append(Read(sel, t.name, t.alias_or_name, final, t, False))
262
+ for j in sel.args.get("joins") or []:
263
+ t, final = _table_of(j.this)
264
+ if t is not None and t.name and t.name.lower() not in ctes:
265
+ out.append(Read(sel, t.name, t.alias_or_name, final, t, True, j))
266
+ return out
267
+
268
+
269
+ def conjuncts(node: exp.Expression | None) -> list[exp.Expression]:
270
+ if node is None:
271
+ return []
272
+ if isinstance(node, (exp.Where, exp.PreWhere, exp.Having)):
273
+ node = node.this
274
+ while isinstance(node, exp.Paren):
275
+ node = node.this
276
+ if isinstance(node, exp.And):
277
+ return conjuncts(node.this) + conjuncts(node.expression)
278
+ return [node]
279
+
280
+
281
+ def _own(node: exp.Expression, sel: exp.Select) -> bool:
282
+ return node.find_ancestor(exp.Select) is sel
283
+
284
+
285
+ def column_of(col: exp.Column, rd: Read, info: TableInfo | None, single: bool) -> tuple[str | None, str | None]:
286
+ """(column of `rd.table` this Column names, sub path) or (None, None). `a.b` is the column b of alias a, or (on
287
+ ClickHouse) the JSON/tuple subcolumn b of column a; an unqualified name belongs to the table when it is a column of it
288
+ (or when the SELECT reads one table and its columns are not known)."""
289
+ q = col.table
290
+ name = col.name
291
+ cols = info.columns if info else {}
292
+ if q:
293
+ if q.lower() in (rd.alias.lower(), rd.table.lower()):
294
+ return name, None
295
+ if cols and q in cols and not single:
296
+ return q, name
297
+ if cols and q in cols:
298
+ return q, name
299
+ return None, None
300
+ if not cols:
301
+ return (name, None) if single else (None, None)
302
+ return (name, None) if name in cols else (None, None)
303
+
304
+
305
+ def filter_nodes(rd: Read) -> list[tuple[str, exp.Expression]]:
306
+ """The predicates that decide which rows of this read are kept: (clause, conjunct) of its SELECT's PREWHERE and
307
+ WHERE, and the ON of its own JOIN."""
308
+ out = []
309
+ for clause in ("prewhere", "where"):
310
+ for c in conjuncts(rd.select.args.get(clause)):
311
+ out.append((clause, c))
312
+ if rd.join is not None and rd.join.args.get("on") is not None:
313
+ out += [("on", c) for c in conjuncts(rd.join.args["on"])]
314
+ return out
315
+
316
+
317
+ def columns_in(node: exp.Expression, rd: Read, info: TableInfo | None, single: bool) -> set[str]:
318
+ out = set()
319
+ for col in node.find_all(exp.Column):
320
+ name, _ = column_of(col, rd, info, single)
321
+ if name:
322
+ out.add(name)
323
+ return out
324
+
325
+
326
+ def fname(node: exp.Expression, engine: str) -> str:
327
+ """A function's name as the engine writes it, lower case: `tostring`, `cast`, `lower`, `jsonextractstring`."""
328
+ if isinstance(node, exp.Anonymous):
329
+ return str(node.this).lower()
330
+ if isinstance(node, exp.Cast):
331
+ return "cast"
332
+ try:
333
+ text = node.sql(dialect=dialect_of(engine))
334
+ except Exception:
335
+ return node.key.lower()
336
+ m = re.match(r"\s*([A-Za-z_]\w*)\s*\(", text)
337
+ return m.group(1).lower() if m else node.key.lower()
338
+
339
+
340
+ def _strip(node: exp.Expression) -> exp.Expression:
341
+ while isinstance(node, exp.Paren):
342
+ node = node.this
343
+ return node
344
+
345
+
346
+ def has_hole(node: exp.Expression | None) -> bool:
347
+ if node is None:
348
+ return False
349
+ return any(re.fullmatch(r"__qp\d+__", i.name or "") for i in node.find_all(exp.Identifier)) or \
350
+ any(re.fullmatch(r"__qp\d+__", c.name or "") for c in node.find_all(exp.Column))
351
+
352
+
353
+ # ---- rule checks on one read -------------------------------------------------------------------------------------
354
+
355
+ @dataclass
356
+ class Wrapped:
357
+ column: str
358
+ functions: list[str] # outermost first
359
+ clause: str
360
+ unwrap: bool # the rule can remove the wrapper with the same rows
361
+ why: str
362
+
363
+
364
+ IDENTITY_ON = {"tostring": re.compile(r"^(?:LowCardinality\()?(?:Nullable\()?String\)?\)?$"),
365
+ "assumenotnull": re.compile(r"^(?!Nullable)"), "identity": re.compile(r".*")}
366
+
367
+
368
+ def _side_parts(cmp: exp.Expression) -> list[exp.Expression]:
369
+ if isinstance(cmp, exp.Between):
370
+ return [cmp.this]
371
+ if isinstance(cmp, exp.In):
372
+ return [cmp.this]
373
+ return [cmp.this, cmp.expression]
374
+
375
+
376
+ def _chain(node: exp.Expression, engine: str) -> tuple[list[str], exp.Column | None]:
377
+ """f(g(col)): (['f', 'g'], col) when the expression is a chain of functions over exactly one column (other
378
+ arguments being values), else ([], None)."""
379
+ names: list[str] = []
380
+ node = _strip(node)
381
+ while not isinstance(node, exp.Column):
382
+ cols = list(node.find_all(exp.Column))
383
+ if len(cols) != 1 or isinstance(node, (exp.Select, exp.Subquery, exp.Bracket, exp.Dot)) or node.find(exp.Select):
384
+ return [], None
385
+ if not isinstance(node, (exp.Func, exp.Cast)):
386
+ return [], None
387
+ names.append(fname(node, engine))
388
+ inner = next((a for a in node.iter_expressions() if a.find(exp.Column) is not None), None)
389
+ if inner is None:
390
+ return [], None
391
+ node = _strip(inner)
392
+ return names, node
393
+
394
+
395
+ CLOCK = {"now", "now64", "today", "yesterday", "current_timestamp", "current_date", "currentdate", "currenttimestamp"}
396
+
397
+
398
+ def is_supplied(node: exp.Expression) -> bool:
399
+ """A value the caller supplies at run time: a parameter, a `?` of the server's normalized text, a run-time part, or
400
+ the clock."""
401
+ if node.find(exp.Placeholder, exp.Parameter) is not None:
402
+ return True
403
+ if any(re.fullmatch(r"__qp\d+__|__p_\w+__", i.name or "") for i in node.find_all(exp.Identifier)):
404
+ return True
405
+ for f in node.find_all(exp.Func):
406
+ if fname(f, "clickhouse") in CLOCK or isinstance(f, (exp.CurrentTimestamp, exp.CurrentDate)):
407
+ return True
408
+ return False
409
+
410
+
411
+ def wrapped_key_filters(rd: Read, info: TableInfo, engine: str, safe: set[str], single: bool, needs_parameter: bool = True) -> list[Wrapped]:
412
+ """Comparisons where a sorting-key or partition-key column of the table is inside a function the engine's key
413
+ analysis does not see through, compared with something that is not a column of the table."""
414
+ out = []
415
+ keyed = info.key_cols | set(info.partition_cols)
416
+ for clause, c in filter_nodes(rd):
417
+ c = _strip(c)
418
+ if not isinstance(c, COMPARE) or not _own(c, rd.select):
419
+ continue
420
+ sides = _side_parts(c)
421
+ for side in sides:
422
+ names, col = _chain(side, engine)
423
+ if not names or col is None:
424
+ continue
425
+ name, sub = column_of(col, rd, info, single)
426
+ if not name or sub or name not in keyed:
427
+ continue
428
+ others = [s for s in sides if s is not side] + list(c.args.get("expressions") or []) + \
429
+ [x for x in (c.args.get("low"), c.args.get("high"), c.args.get("query")) if x is not None]
430
+ if any(columns_in(o, rd, info, single) for o in others):
431
+ continue # a join condition between two columns: not a value comparison
432
+ if all(n in safe for n in names):
433
+ continue
434
+ if needs_parameter and not any(is_supplied(o) for o in others):
435
+ continue # `length(key) = 64`: a constant check, not a lookup of a value the caller supplies
436
+ ctype = info.columns.get(name, "")
437
+ unwrap = len(names) == 1 and names[0] in IDENTITY_ON and bool(IDENTITY_ON[names[0]].search(ctype or ""))
438
+ out.append(Wrapped(name, names, clause, unwrap, "identity on the column's type" if unwrap else "changes the value"))
439
+ return out
440
+
441
+
442
+ @dataclass
443
+ class Lookup:
444
+ path: str
445
+ column: str # the typed column of the same name
446
+ in_key: bool
447
+ clause: str
448
+
449
+
450
+ def _norm(s: str) -> str:
451
+ return re.sub(r"[^a-z0-9]", "", (s or "").lower())
452
+
453
+
454
+ def map_lookup_filters(rd: Read, info: TableInfo, engine: str, single: bool, require_key: bool) -> list[Lookup]:
455
+ """A map, JSON or subcolumn lookup compared with a value where the table has a typed column of the same name."""
456
+ out = []
457
+ by_norm = {_norm(c): c for c in info.columns}
458
+ keyed = info.key_cols | set(info.partition_cols) | {str(i.get("expr") or "") for i in info.skip_indexes}
459
+ for clause, c in filter_nodes(rd):
460
+ c = _strip(c)
461
+ if not isinstance(c, COMPARE):
462
+ continue
463
+ for side in _side_parts(c):
464
+ side = _strip(side)
465
+ while isinstance(side, (exp.Cast, exp.TryCast)):
466
+ side = _strip(side.this)
467
+ key = None
468
+ if isinstance(side, exp.Bracket) and isinstance(side.this, exp.Column) and side.expressions:
469
+ lit = side.expressions[0]
470
+ if isinstance(lit, exp.Literal) and lit.is_string:
471
+ key = lit.this
472
+ elif isinstance(side, (exp.JSONExtract, exp.JSONExtractScalar)):
473
+ path = side.expression
474
+ if isinstance(path, exp.JSONPath):
475
+ keys = [p.this for p in path.expressions if isinstance(p, exp.JSONPathKey)]
476
+ key = keys[-1] if keys else None
477
+ elif isinstance(path, exp.Literal):
478
+ key = str(path.this)
479
+ elif isinstance(side, exp.Anonymous) and str(side.this).lower().startswith("jsonextract"):
480
+ args = side.expressions
481
+ if len(args) >= 2 and isinstance(args[-1], exp.Literal) and args[-1].is_string:
482
+ key = args[-1].this
483
+ elif isinstance(side, exp.Column) and side.table and info.columns and side.table in info.columns:
484
+ key = side.name # a JSON subcolumn: payload.tenant_id
485
+ if not key:
486
+ continue
487
+ hit = by_norm.get(_norm(key)) or by_norm.get(_norm(str(key).split(".")[-1]))
488
+ if not hit:
489
+ continue
490
+ in_key = hit in keyed
491
+ if require_key and not in_key:
492
+ continue
493
+ out.append(Lookup(str(key), hit, in_key, clause))
494
+ return out
495
+
496
+
497
+ def _pinned(rd: Read, info: TableInfo, single: bool) -> set[str]:
498
+ """Columns of the table this read compares with or IN (outside OR and NOT)."""
499
+ out = set()
500
+ for _, c in filter_nodes(rd):
501
+ c = _strip(c)
502
+ if isinstance(c, (exp.EQ, exp.In)) and isinstance(_strip(c.this), exp.Column):
503
+ name, sub = column_of(_strip(c.this), rd, info, single)
504
+ if name and not sub:
505
+ out.add(name)
506
+ return out
507
+
508
+
509
+ SCOPE_TAILS = ("id", "ids", "name", "key", "uuid", "slug", "url", "baseurl", "code")
510
+
511
+
512
+ def _is_scope(column: str, scope: list[str]) -> bool:
513
+ n = re.sub(r"[^a-z0-9]", "", column.lower())
514
+ return any(n == w or (n.startswith(w) and n[len(w):] in SCOPE_TAILS) or n.endswith(w + "id") for w in scope)
515
+
516
+
517
+ def time_bound(rd: Read, info: TableInfo, single: bool, scope: list[str] = ()) -> tuple[bool, list[str]]:
518
+ """(bounded, time columns): whether this read bounds the table's time where that matters: a time column of the
519
+ partition key (no bound opens every partition), or a time column of the sorting key that comes right after the
520
+ columns the read pins with equality (no bound reads the whole range under that prefix). A lookup whose equality
521
+ prefix runs past the time column, or where the time column sits deeper in the key, is bounded by the key."""
522
+ tcols = info.time_cols
523
+ if not tcols:
524
+ return True, []
525
+ for _, c in filter_nodes(rd):
526
+ if columns_in(c, rd, info, single) & set(tcols):
527
+ return True, tcols
528
+ part = [c for c in tcols if c in info.partition_cols]
529
+ pinned = _pinned(rd, info, single)
530
+ from .access import key_parts
531
+ parts = [[w for w in WORD.findall(p) if w in info.columns] for p in key_parts(info.sorting_expr or "")]
532
+ nxt = next((cols for cols in parts if cols and not set(cols) <= pinned), [])
533
+ # the range under the pinned prefix is large only when the prefix is a scope (a tenant, a project), not one entity
534
+ scoped = all(_is_scope(c, scope) for c in pinned & {c for cols in parts for c in cols})
535
+ matters = part + ([c for c in nxt if c in tcols and c not in part] if scoped else [])
536
+ return (not matters), matters
537
+
538
+
539
+ def dynamic_filter(rd: Read) -> bool:
540
+ """A run-time part in this read's filters (or in the place of its WHERE): the bound may be in it."""
541
+ for clause in ("where", "prewhere", "having"):
542
+ if has_hole(rd.select.args.get(clause)):
543
+ return True
544
+ if rd.join is not None and has_hole(rd.join.args.get("on")):
545
+ return True
546
+ return False
547
+
548
+
549
+ def selected_columns(sel: exp.Select, rd: Read, info: TableInfo | None, single: bool) -> tuple[set[str], bool]:
550
+ """Columns of the table the SELECT list names, and whether it selects `*`."""
551
+ cols, star = set(), False
552
+ for e_ in sel.expressions:
553
+ if isinstance(e_, exp.Star) or (isinstance(e_, exp.Column) and isinstance(e_.this, exp.Star)):
554
+ star = True
555
+ cols |= columns_in(e_, rd, info, single)
556
+ return cols, star
557
+
558
+
559
+ def is_aggregate(sel: exp.Select, engine: str) -> bool:
560
+ if sel.args.get("group"):
561
+ return True
562
+ for e_ in sel.expressions:
563
+ for f in e_.find_all(exp.AggFunc, exp.Anonymous):
564
+ if f.find_ancestor(exp.Select) is sel and fname(f, engine) in AGG_NAMES and f.find_ancestor(exp.Window) is None:
565
+ return True
566
+ return False
567
+
568
+
569
+ def limit_of(sel: exp.Select) -> exp.Expression | None:
570
+ lim = sel.args.get("limit")
571
+ if lim is None or isinstance(lim, exp.Fetch):
572
+ return lim
573
+ return lim.expression if isinstance(lim, exp.Limit) else None
574
+
575
+
576
+ def real_limit(sel: exp.Select) -> bool:
577
+ """A page: a LIMIT that is not the literal 1, or an OFFSET."""
578
+ lim = limit_of(sel)
579
+ if sel.args.get("offset") is not None:
580
+ return True
581
+ if lim is None:
582
+ return False
583
+ return not (isinstance(lim, exp.Literal) and str(lim.this) == "1")
584
+
585
+
586
+ def heavy_in_aggregate(sel: exp.Select, rd: Read, info: TableInfo, engine: str, min_bytes: float, single: bool) -> list[str]:
587
+ out = []
588
+ for e_ in sel.expressions:
589
+ for f in e_.find_all(exp.AggFunc, exp.Anonymous, exp.Max, exp.Min):
590
+ if fname(f, engine) not in HEAVY_AGG:
591
+ continue
592
+ for col in f.find_all(exp.Column):
593
+ name, _ = column_of(col, rd, info, single)
594
+ if name and info.wide(name, min_bytes)[0] and name not in out:
595
+ out.append(name)
596
+ return out
597
+
598
+
599
+ def count_only(sel: exp.Select, engine: str) -> bool:
600
+ """SELECT count(...) [AS x] and nothing else: one count, no GROUP BY (several counts are a statistics query, not
601
+ the total of a page)."""
602
+ if sel.args.get("group") or len(sel.expressions) != 1:
603
+ return False
604
+ for e_ in sel.expressions:
605
+ e_ = e_.this if isinstance(e_, exp.Alias) else e_
606
+ if not (isinstance(e_, exp.Count) or (isinstance(e_, exp.Anonymous) and str(e_.this).lower() in ("count", "countdistinct"))):
607
+ return False
608
+ return True
609
+
610
+
611
+ def where_columns(sel: exp.Select) -> set[str]:
612
+ out = set()
613
+ for clause in ("where", "prewhere"):
614
+ node = sel.args.get(clause)
615
+ if node is not None:
616
+ out |= {c.name for c in node.find_all(exp.Column) if c.find_ancestor(exp.Select) is sel}
617
+ return out
618
+
619
+
620
+ def outer_select(tree: exp.Expression) -> exp.Select | None:
621
+ t = tree
622
+ if isinstance(t, exp.Select):
623
+ return t
624
+ if isinstance(t, (exp.Union,)):
625
+ return None
626
+ return t.find(exp.Select)
627
+
628
+
629
+ # ---- mechanical rewrites -------------------------------------------------------------------------------------------
630
+
631
+ def _and(parts: list[exp.Expression]) -> exp.Expression | None:
632
+ if not parts:
633
+ return None
634
+ out = parts[0]
635
+ for p in parts[1:]:
636
+ out = exp.And(this=out, expression=p)
637
+ return out
638
+
639
+
640
+ def _key_conjuncts(rd: Read, info: TableInfo, single: bool, allowed: set[str]) -> tuple[list[exp.Expression], list[exp.Expression]]:
641
+ """The WHERE conjuncts of a read that name only `allowed` columns of its table (and values), and the rest."""
642
+ keys, rest = [], []
643
+ for c in conjuncts(rd.select.args.get("where")):
644
+ cols = columns_in(c, rd, info, single)
645
+ others = {x.name for x in c.find_all(exp.Column)} - cols
646
+ if cols and cols <= allowed and not others and c.find(exp.Select) is None and not has_hole(c):
647
+ keys.append(c)
648
+ else:
649
+ rest.append(c)
650
+ return keys, rest
651
+
652
+
653
+ def _locate(tree: exp.Expression, table: str) -> list[Read]:
654
+ return [r for r in reads(tree) if r.table.lower() == table.lower() and not r.joined and not (r.select.args.get("joins"))]
655
+
656
+
657
+ def prewhere_keys(sql: str, engine: str, info: TableInfo) -> tuple[str, str] | None:
658
+ """Move the WHERE conjuncts that name only sorting-key columns of a table read with FINAL into PREWHERE.
659
+
660
+ With FINAL, ClickHouse does not move filters ahead of the column reads by itself (optimize_move_to_prewhere_if_final
661
+ is off by default), so the payload columns of every granule the key selects are read before rows are dropped. A
662
+ predicate on sorting-key columns only is the same for every version of a row, so filtering on it before FINAL keeps
663
+ the same rows. Returns (sql, note) or None when nothing applies."""
664
+ p = parse(sql, engine)
665
+ if not p.ok or p.holes:
666
+ return None
667
+ tree = p.tree
668
+ done = 0
669
+ for rd in _locate(tree, info.name):
670
+ if not rd.final or rd.select.args.get("prewhere") is not None:
671
+ continue
672
+ keys, rest = _key_conjuncts(rd, info, True, set(info.sorting_key))
673
+ if not keys:
674
+ continue
675
+ rd.select.set("prewhere", exp.PreWhere(this=_and([k.copy() for k in keys])))
676
+ rd.select.set("where", exp.Where(this=_and([r.copy() for r in rest])) if rest else None)
677
+ done += 1
678
+ if not done:
679
+ return None
680
+ return render(tree, engine), "sorting-key predicates in PREWHERE (the same for every version of a row, so FINAL keeps the same rows)"
681
+
682
+
683
+ def probe_first(sql: str, engine: str, info: TableInfo) -> tuple[str, str] | None:
684
+ """Add a narrow existence probe in front of the wide read: `AND (SELECT count() FROM (SELECT 1 FROM t WHERE <the key
685
+ predicates> LIMIT 1)) > 0`. The probe reads the table without FINAL, so it sees every row the main read can return:
686
+ when it finds nothing, nothing would have been returned, and the main read is skipped. One statement, the same rows."""
687
+ p = parse(sql, engine)
688
+ if not p.ok or p.holes:
689
+ return None
690
+ tree = p.tree
691
+ allowed = set(info.sorting_key) | set(info.partition_cols)
692
+ done = 0
693
+ for rd in _locate(tree, info.name):
694
+ keys, _ = _key_conjuncts(rd, info, True, allowed)
695
+ if not keys:
696
+ continue
697
+ table = exp.Table(this=exp.to_identifier(rd.table), alias=exp.TableAlias(this=exp.to_identifier(rd.alias))) \
698
+ if rd.alias and rd.alias.lower() != rd.table.lower() else exp.Table(this=exp.to_identifier(rd.table))
699
+ inner = exp.Select(expressions=[exp.Literal.number(1)]).from_(table).where(_and([k.copy() for k in keys])).limit(1)
700
+ probe = exp.GT(this=exp.Subquery(this=exp.Select(expressions=[exp.Count(this=exp.Star())]).from_(exp.Subquery(this=inner))),
701
+ expression=exp.Literal.number(0))
702
+ where = rd.select.args.get("where")
703
+ rd.select.set("where", exp.Where(this=_and(conjuncts(where) + [probe]) if where is not None else probe))
704
+ done += 1
705
+ break
706
+ if not done:
707
+ return None
708
+ return render(tree, engine), "a probe on the key predicates first: when it finds no row the wide read is skipped"
709
+
710
+
711
+ def late_materialize(sql: str, engine: str, info: TableInfo) -> tuple[str, str] | None:
712
+ """Select the rows to keep on narrow columns first, then read the wide columns for those rows only:
713
+ `... WHERE <filters> AND (key) IN (SELECT key FROM t WHERE <filters> ORDER BY <order> LIMIT n) ORDER BY <order> LIMIT n`.
714
+ The rows whose key is among the top n's keys include the top n, so ordering and limiting them gives the same page
715
+ (up to ties, which the benchmark's comparison handles)."""
716
+ p = parse(sql, engine)
717
+ if not p.ok or p.holes or not info.sorting_key:
718
+ return None
719
+ sel = outer_select(p.tree)
720
+ if sel is None or sel.args.get("joins") or not sel.args.get("order") or limit_of(sel) is None or is_aggregate(sel, engine) \
721
+ or sel.args.get("distinct") or sel.find(exp.Window):
722
+ return None
723
+ rds = [r for r in reads(p.tree) if r.select is sel]
724
+ if len(rds) != 1 or rds[0].table.lower() != info.name.lower():
725
+ return None
726
+ rd = rds[0]
727
+ keys = [exp.column(k, table=rd.alias if rd.alias.lower() != rd.table.lower() else None) for k in info.sorting_key]
728
+ inner = sel.copy()
729
+ inner.set("expressions", [k.copy() for k in keys])
730
+ inner.set("with", None)
731
+ member = exp.Tuple(expressions=[k.copy() for k in keys]) if len(keys) > 1 else keys[0].copy()
732
+ cond = exp.In(this=member, query=exp.Subquery(this=inner))
733
+ outer = sel
734
+ where = outer.args.get("where")
735
+ outer.set("where", exp.Where(this=_and(conjuncts(where) + [cond]) if where is not None else cond))
736
+ outer.set("offset", None)
737
+ return render(p.tree, engine), "the page picked on the sorting key first; wide columns read for those rows only"
738
+
739
+
740
+ def unwrap_identity(sql: str, engine: str, info: TableInfo, safe: set[str]) -> tuple[str, str] | None:
741
+ """`toString(col) = toString(?)` on a String column: the function is the identity there, so the comparison is the
742
+ same on the bare column, which the key can use. Only wrappers that are the identity on the column's type."""
743
+ p = parse(sql, engine)
744
+ if not p.ok or p.holes:
745
+ return None
746
+ done = []
747
+ all_reads = reads(p.tree)
748
+ for rd in [r for r in all_reads if r.table.lower() == info.name.lower()]:
749
+ single = len([r for r in all_reads if r.select is rd.select]) == 1
750
+ wanted = {(w.column, tuple(w.functions)) for w in wrapped_key_filters(rd, info, engine, safe, single) if w.unwrap}
751
+ if not wanted:
752
+ continue
753
+ for _, c in filter_nodes(rd):
754
+ c = _strip(c)
755
+ if not isinstance(c, COMPARE):
756
+ continue
757
+ pairs = [("this", "expression")] if isinstance(c, (exp.In, exp.Between)) else [("this", "expression"), ("expression", "this")]
758
+ for mine, theirs in pairs:
759
+ side = c.args.get(mine)
760
+ if side is None:
761
+ continue
762
+ names, col = _chain(side, engine)
763
+ if col is None or (column_of(col, rd, info, single)[0], tuple(names)) not in wanted:
764
+ continue
765
+ c.set(mine, col.copy())
766
+ done.append(f"{names[0]}({col.name})")
767
+ other = c.args.get(theirs)
768
+ o = _strip(other) if other is not None else None
769
+ if o is not None and isinstance(o, (exp.Func, exp.Anonymous)) and fname(o, engine) == names[0] \
770
+ and not list(o.find_all(exp.Column)):
771
+ args = [a for a in o.iter_expressions()]
772
+ if len(args) == 1:
773
+ c.set(theirs, args[0].copy())
774
+ break
775
+ if not done:
776
+ return None
777
+ return render(p.tree, engine), "unwrapped " + ", ".join(sorted(set(done))) + ": the identity on the column's type"
778
+
779
+
780
+ def count_without_inner_order(sql: str, engine: str) -> tuple[str, str] | None:
781
+ """`SELECT count() FROM (SELECT ... ORDER BY ...)`: an ORDER BY inside a counted subquery with no LIMIT changes
782
+ nothing about the count; without it the rows are not sorted first."""
783
+ p = parse(sql, engine)
784
+ if not p.ok or p.holes:
785
+ return None
786
+ sel = outer_select(p.tree)
787
+ if sel is None or not count_only(sel, engine):
788
+ return None
789
+ src = sel.args.get("from") or sel.args.get("from_")
790
+ sub = src.this if src is not None else None
791
+ if not isinstance(sub, exp.Subquery) or not isinstance(sub.this, exp.Select):
792
+ return None
793
+ inner = sub.this
794
+ if not inner.args.get("order") or limit_of(inner) is not None or inner.args.get("offset") is not None or inner.args.get("limit_by"):
795
+ return None
796
+ inner.set("order", None)
797
+ return render(p.tree, engine), "the ORDER BY inside the counted subquery removed (no LIMIT: the count is the same)"
798
+
799
+
800
+ def inner_is_runtime(tree: exp.Expression) -> bool:
801
+ """`SELECT count(*) FROM («query») t`: the counted statement is a run-time part."""
802
+ sel = outer_select(tree)
803
+ src = (sel.args.get("from") or sel.args.get("from_")) if sel is not None else None
804
+ return src is not None and isinstance(src.this, exp.Subquery) and has_hole(src.this) and src.this.find(exp.Select) is None
805
+
806
+
807
+ def wrapped_count(tree: exp.Expression, engine: str) -> bool:
808
+ sel = outer_select(tree)
809
+ if sel is None or not count_only(sel, engine):
810
+ return False
811
+ src = sel.args.get("from") or sel.args.get("from_")
812
+ sub = src.this if src is not None else None
813
+ if isinstance(sub, exp.Subquery) and isinstance(sub.this, (exp.Select, exp.Union)):
814
+ return True
815
+ return isinstance(sub, exp.Subquery) and has_hole(sub)
816
+
817
+
818
+ def inner_order_without_limit(tree: exp.Expression) -> bool:
819
+ sel = outer_select(tree)
820
+ src = (sel.args.get("from") or sel.args.get("from_")) if sel is not None else None
821
+ sub = src.this if src is not None else None
822
+ inner = sub.this if isinstance(sub, exp.Subquery) else None
823
+ return isinstance(inner, exp.Select) and bool(inner.args.get("order")) and limit_of(inner) is None
824
+
825
+
826
+ # ---- table-level variants ------------------------------------------------------------------------------------------
827
+
828
+ def skip_index_setup(table: str, column: str, op: str, column_type: str) -> tuple[list[str], str]:
829
+ kind = "minmax" if op == "range" or TIME_TYPE.search(column_type or "") or re.search(r"Int|Float|Decimal", column_type or "") \
830
+ else "bloom_filter(0.01)"
831
+ name = f"codecop_scn_{re.sub(r'[^A-Za-z0-9_]', '_', column)}"
832
+ return [f"ALTER TABLE {table} ADD INDEX {name} {column} TYPE {kind} GRANULARITY 1",
833
+ f"ALTER TABLE {table} MATERIALIZE INDEX {name}"], kind
834
+
835
+
836
+ def projection_setup(table: str, order: list[str]) -> list[str]:
837
+ return [f"ALTER TABLE {table} ADD PROJECTION codecop_scn_p (SELECT * ORDER BY ({', '.join(order)}))",
838
+ f"ALTER TABLE {table} MATERIALIZE PROJECTION codecop_scn_p"]
839
+
840
+
841
+ ENGINE_CLAUSE = re.compile(r"\bENGINE\s*=\s*(\w+(?:\s*\([^()]*\))?)", re.I)
842
+
843
+
844
+ def rekey_setup(info: TableInfo, create_sql: str, order: list[str]) -> tuple[list[str], str] | None:
845
+ """A copy of the table with a sorting key that starts with `order` and keeps every other column of the old key (a
846
+ deduplicating table keeps the same rows per key). Returns (setup, copy name)."""
847
+ from .engines.clickhouse import plain_engine
848
+ m = ENGINE_CLAUSE.search(plain_engine(create_sql or "")) # the sandbox's engine: Shared/Replicated become plain
849
+ if not m or not info.sorting_key:
850
+ return None
851
+ new = list(order) + [c for c in info.sorting_key if c not in order]
852
+ if new == info.sorting_key:
853
+ return None
854
+ copy_name = f"{info.name}__codecop_rk"
855
+ part = f" PARTITION BY {info.partition_expr}" if info.partition_expr else ""
856
+ return ([f"CREATE TABLE {copy_name} AS {info.name} ENGINE = {m.group(1)}{part} ORDER BY ({', '.join(new)})",
857
+ f"INSERT INTO {copy_name} SELECT * FROM {info.name}"], copy_name)
858
+
859
+
860
+ def rename_table(sql: str, engine: str, old: str, new: str) -> str | None:
861
+ p = parse(sql, engine)
862
+ if not p.ok or p.holes:
863
+ return None
864
+ n = 0
865
+ for t in p.tree.find_all(exp.Table):
866
+ if t.name.lower() == old.lower():
867
+ t.set("this", exp.to_identifier(new))
868
+ t.set("db", None)
869
+ n += 1
870
+ return render(p.tree, engine) if n else None
871
+
872
+
873
+ def copy_of(tree: exp.Expression) -> exp.Expression:
874
+ return copy.deepcopy(tree)
875
+
876
+
877
+ # ---- PostgreSQL: empty reads ----------------------------------------------------------------------------------------
878
+ #
879
+ # A statement that returns nothing on most runs still reads the pages its plan visits. On PostgreSQL the rule-written
880
+ # variants are an index that serves the predicate (table-level: it costs every insert) and a cheap existence probe in
881
+ # front of the read; the third change, polling less or running on the event that writes the rows, is the application's
882
+ # and stays evidence only. `{name:type}` parameters are swapped for identifiers to parse and put back after.
883
+
884
+ PG_PARAM = re.compile(r"\{(\w+)\s*:\s*([^{}]+?)\}")
885
+
886
+
887
+ def _pg_swap(sql: str) -> tuple[str, dict[str, str]]:
888
+ found: dict[str, str] = {}
889
+
890
+ def one(m: re.Match) -> str:
891
+ key = f"codecop_ph_{len(found)}"
892
+ found[key] = m.group(0)
893
+ return key
894
+ return PG_PARAM.sub(one, sql or ""), found
895
+
896
+
897
+ def _pg_back(text: str, found: dict[str, str]) -> str:
898
+ for key in sorted(found, key=len, reverse=True):
899
+ text = re.sub(r'"?\b' + re.escape(key) + r'\b"?', lambda _m, v=found[key]: v, text)
900
+ return text
901
+
902
+
903
+ def _own_conjuncts(rd: Read, info: TableInfo, single: bool, placeholders: set[str]) -> list[exp.Expression]:
904
+ """The WHERE conjuncts of a read whose every column is a column of this read's table (a parameter is a value)."""
905
+ return _own_conjuncts_of(conjuncts(rd.select.args.get("where")), rd, info, single, placeholders)
906
+
907
+
908
+ def _own_conjuncts_of(parts: list[exp.Expression], rd: Read, info: TableInfo, single: bool, placeholders: set[str]) -> list[exp.Expression]:
909
+ out = []
910
+ for c in parts:
911
+ if c.find(exp.Select) is not None or has_hole(c):
912
+ continue
913
+ cols = [x for x in c.find_all(exp.Column) if x.name not in placeholders]
914
+ if cols and all(column_of(x, rd, info, single)[0] for x in cols):
915
+ out.append(c)
916
+ return out
917
+
918
+
919
+ def pg_probe_first(sql: str, info: TableInfo) -> tuple[str, str] | None:
920
+ """`... WHERE <filters> AND EXISTS (SELECT 1 FROM t WHERE <t's own filters> LIMIT 1)`: an uncorrelated probe the
921
+ planner runs once (an InitPlan, a One-Time Filter); when it finds no row the read is skipped. A row the statement
922
+ returns satisfies t's filters, so the probe finds it: the same rows on every run."""
923
+ text, found = _pg_swap(sql)
924
+ p = parse(text, "postgres")
925
+ if not p.ok or p.holes:
926
+ return None
927
+ sel = outer_select(p.tree)
928
+ if sel is None:
929
+ return None
930
+ own = [r for r in reads(p.tree) if r.select is sel]
931
+ single = len(own) == 1
932
+ # the table read in FROM or through an inner join (an outer join's side may be missing from a returned row)
933
+ rd = next((r for r in own if r.table.lower() == info.name.lower()
934
+ and (not r.joined or (r.join is not None and not r.join.args.get("side") and (r.join.args.get("kind") or "").upper() != "CROSS"))), None)
935
+ if rd is None:
936
+ return None
937
+ keys = _own_conjuncts(rd, info, single, set(found))
938
+ if rd.joined and rd.join is not None and rd.join.args.get("on") is not None:
939
+ keys += [k for k in _own_conjuncts_of(conjuncts(rd.join.args["on"]), rd, info, single, set(found)) if k not in keys]
940
+ if not keys or not any(x.name in found for k in keys for x in k.find_all(exp.Column)):
941
+ return None # a probe with no value the caller passes finds the same row on every run: it skips nothing
942
+ table = exp.Table(this=exp.to_identifier(rd.table), db=rd.node.args.get("db"),
943
+ alias=exp.TableAlias(this=exp.to_identifier(rd.alias)) if rd.alias and rd.alias.lower() != rd.table.lower() else None)
944
+ inner = exp.Select(expressions=[exp.Literal.number(1)]).from_(table).where(_and([k.copy() for k in keys])).limit(1)
945
+ probe = exp.Exists(this=inner)
946
+ where = sel.args.get("where")
947
+ sel.set("where", exp.Where(this=_and(conjuncts(where) + [probe]) if where is not None else probe))
948
+ return _pg_back(render(p.tree, "postgres"), found), \
949
+ f"an existence probe on {rd.table}'s own filters first: when it finds no row, the read is skipped (same rows)"
950
+
951
+
952
+ def pg_index_for_filter(sql: str, info: TableInfo, create_sql: str, table_name: str) -> tuple[list[str], str] | None:
953
+ """A btree index that serves the statement's filters on one table: its equality columns, then its first range
954
+ column, when no index of the definition already narrows the scan on all of them. ([CREATE INDEX], note) or None."""
955
+ from .access_postgres import table_access
956
+ from .engines.postgres import quoted
957
+ try:
958
+ a = table_access(create_sql, table_name, sql)
959
+ except Exception: # a definition the access analysis can not read: no variant, never a guess
960
+ return None
961
+ filters = [f for f in a.get("filters") or [] if f.get("op") in ("eq", "in", "range")]
962
+ eq = [f["column"] for f in filters if f["op"] in ("eq", "in")]
963
+ rng = [f["column"] for f in filters if f["op"] == "range"][:1]
964
+ cols = list(dict.fromkeys(eq + rng))
965
+ if not cols:
966
+ return None
967
+ if all(f["key"] == "used" for f in filters if f["column"] in cols):
968
+ return None # an index of the definition already narrows the scan on every one of them
969
+ name = re.sub(r"\W+", "_", f"codecop_scn_{info.name}_{'_'.join(cols)}")[:63]
970
+ stmt = f"CREATE INDEX {quoted(name)} ON {quoted(table_name)} ({', '.join(quoted(c) for c in cols)})"
971
+ return [stmt], f"a btree index on {info.name} ({', '.join(cols)}): the statement's equality columns, then its first range column"