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/baseline.py
ADDED
|
@@ -0,0 +1,1043 @@
|
|
|
1
|
+
"""The whole-repository baseline pass: one measured baseline for every valid SELECT of an engine, with no agent.
|
|
2
|
+
|
|
3
|
+
Until now the sandbox measured only what the agent ranked (the top statements of a run), so most statements ended
|
|
4
|
+
"nothing to gain" on the agent's word or were never asked about. This pass makes a bench candidate of every SELECT of
|
|
5
|
+
the engine whose text the code holds (literal, constant, SQL file, an ORM call discover translated), one per distinct
|
|
6
|
+
statement (sql_hash), labelled `B-<hash>`:
|
|
7
|
+
|
|
8
|
+
text the code's statement as loopbench.member_text reads it (driver placeholders become `$n`; an ORM's
|
|
9
|
+
«value» slots become parameters; any other run-time part leaves the statement out, with the reason)
|
|
10
|
+
parameters each placeholder typed by what it stands beside (typed_sql): a column it is compared with (its type from
|
|
11
|
+
the table's definition), a list (`IN (?)`, `= ANY($1)`), LIMIT / OFFSET, a pattern (LIKE), the code's
|
|
12
|
+
own cast (`$1::uuid`). The values are chosen so the statement returns rows: an equality's value is put on
|
|
13
|
+
a few rows of the table it filters (a fixture), a time range spans the generated data
|
|
14
|
+
definitions the real catalog's (when a database was pulled), else the repository's own (loopschema.definition)
|
|
15
|
+
data profile the agent's (profile.json) where it describes the table, else the catalog's (catalog_profile, when
|
|
16
|
+
pulled), else one from the columns alone (loopschema.schema_profile); every one labelled with its basis
|
|
17
|
+
|
|
18
|
+
Every statement first goes through the plan gate (plangate.py): planned, not run, against the sandbox schema. One that
|
|
19
|
+
does not plan is not measured and keeps a typed reason. The bench then measures the rest at the small scale with the
|
|
20
|
+
rules' and advisors' variants (bench.py), and blockers.py gives each its outcome as for any candidate: at the engine's
|
|
21
|
+
floor -> "nothing to gain, measured"; a variant verified -> "fixed"; measured with no variant that reads less -> "needs
|
|
22
|
+
another fix". The agent is asked afterwards, by heat and inside the budget, only about statements the pass left open.
|
|
23
|
+
|
|
24
|
+
Settings under `[baseline]` in codecop.toml (DEFAULTS). Nothing here starts a sandbox, calls an agent or reads the network.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import copy
|
|
30
|
+
import hashlib
|
|
31
|
+
import json
|
|
32
|
+
import re
|
|
33
|
+
from collections import Counter
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
FILE = "baseline.json"
|
|
37
|
+
SCHEMA_VERSION = 1
|
|
38
|
+
PREFIX = "B-"
|
|
39
|
+
DEFAULTS = {
|
|
40
|
+
"enabled": True, # the pass runs in every scan (false: the agent's ranked statements only, as before)
|
|
41
|
+
"scales": "0.1", # fractions of max_rows the pass measures at (the small scale)
|
|
42
|
+
"max_rows": 500_000, # the largest table the pass builds is scales x this (the proofs after it keep --max-rows)
|
|
43
|
+
"runs": 1, # timed runs per statement after the warm-up (verdicts are taken on rows and bytes read)
|
|
44
|
+
"fit_rounds": 1, # with a pull: corrections of the data towards production (bench --fit-rounds)
|
|
45
|
+
"max_statements": 0, # 0: every statement; else at most this many, hottest first (a setting, never a silent cap)
|
|
46
|
+
"limit_value": 100, # the value a LIMIT placeholder is run with
|
|
47
|
+
"offset_value": 0, # ... and an OFFSET placeholder
|
|
48
|
+
"include_tooling": True, # scripts and tooling are in the denominator: measured too
|
|
49
|
+
"family_variants": 3,
|
|
50
|
+
"advisor_measured_per_suggestion": 10, # ... and the statements measured with each of them (served first)
|
|
51
|
+
"advisor_seconds": 600, # the PostgreSQL advisor's bench time in the pass, at most ([advisor] max_bench_seconds wins)
|
|
52
|
+
"advisor_indexes_per_table": 2, # the PostgreSQL advisor's indexes per table in the pass (each is built and measured
|
|
53
|
+
# with its insert side); [advisor] max_indexes_per_table, when set, wins # variants of a statement family (families.json) baselined per run-time-built site, best first
|
|
54
|
+
"time_low": "2000-01-01 00:00:00", # a lower time bound: every generated row is after it
|
|
55
|
+
"time_high": "2099-01-01 00:00:00", # an upper time bound: every generated row is before it
|
|
56
|
+
}
|
|
57
|
+
# The reasons a statement of the engine is not measured by the pass, in the report's wording (the shared list in
|
|
58
|
+
# blockers.py has the outcome codes; these say which stage stopped it). One per statement.
|
|
59
|
+
SKIP_REASONS = ("no_statement_text", "does_not_parse", "run_time_parts_in_text", "parameter_not_typed", "no_table_definition",
|
|
60
|
+
"covered_by_agent")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def settings_of(config: dict | None) -> dict:
|
|
64
|
+
out = dict(DEFAULTS)
|
|
65
|
+
for k, v in (config or {}).items():
|
|
66
|
+
if k not in DEFAULTS:
|
|
67
|
+
continue
|
|
68
|
+
want = type(DEFAULTS[k])
|
|
69
|
+
if want is bool and isinstance(v, bool):
|
|
70
|
+
out[k] = v
|
|
71
|
+
elif want is int and isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0:
|
|
72
|
+
out[k] = int(v)
|
|
73
|
+
elif want is str and isinstance(v, (str, int, float)) and not isinstance(v, bool):
|
|
74
|
+
out[k] = str(v)
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def label(sql_hash: str) -> str:
|
|
79
|
+
return PREFIX + str(sql_hash or "")[:10]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def is_baseline(finding: str | None) -> bool:
|
|
83
|
+
return str(finding or "").startswith(PREFIX)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _bare(name: str) -> str:
|
|
87
|
+
return re.sub(r"[`\"\[\]]", "", name or "").split(".")[-1].lower()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _role(site: dict) -> str:
|
|
91
|
+
from .rank import site_role # the path decides for migrations, seeds and backfills (they run once)
|
|
92
|
+
r = site_role(site)
|
|
93
|
+
return "" if r == "unknown" and not site.get("role") else r
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _is_test(site: dict) -> bool:
|
|
97
|
+
return bool(site.get("is_test")) or _role(site) == "test"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# ---------------------------------------------------------------------------- which statements
|
|
101
|
+
|
|
102
|
+
def family_sites(inventory: dict, families: dict | None, engine: str, cfg: dict) -> list[dict]:
|
|
103
|
+
"""The variants of the statement families (families/) of this engine's run-time-built sites, as call
|
|
104
|
+
sites of their own: the family's site with one variant's text (best first, at most `family_variants` a site), so
|
|
105
|
+
the pass baselines them like any statement. Each keeps `family_variant` (the variant's id)."""
|
|
106
|
+
if not families:
|
|
107
|
+
return []
|
|
108
|
+
from .sqlinfo import analyze
|
|
109
|
+
by_id = {str(s.get("id")): s for s in (inventory or {}).get("call_sites") or []}
|
|
110
|
+
out = []
|
|
111
|
+
for sid, fam in families.items():
|
|
112
|
+
site = by_id.get(str(sid))
|
|
113
|
+
if site is None or _is_test(site) or (site.get("engine") or (fam.get("site") or {}).get("engine") or "") != engine:
|
|
114
|
+
continue
|
|
115
|
+
n = 0
|
|
116
|
+
for v in fam.get("variants") or []:
|
|
117
|
+
if n >= int(cfg["family_variants"]):
|
|
118
|
+
break
|
|
119
|
+
sql = v.get("sql") or ""
|
|
120
|
+
if not sql.strip() or "«" in sql:
|
|
121
|
+
continue
|
|
122
|
+
info = analyze(sql, engine, bool(site.get("in_loop")))
|
|
123
|
+
if info.kind != "select":
|
|
124
|
+
continue
|
|
125
|
+
n += 1
|
|
126
|
+
out.append({**site, "sql": sql, "resolution": "literal", "parse_ok": bool(info.parse_ok) or True, "statement": "select",
|
|
127
|
+
"engine": engine, "tables": list(info.tables or site.get("tables") or []),
|
|
128
|
+
"sql_hash": "f" + str(v.get("id") or info.sql_hash), "family_variant": v.get("id")})
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def statements(inventory: dict, engine: str, cfg: dict, families: dict | None = None) -> tuple[list[dict], dict[str, str]]:
|
|
133
|
+
"""(groups, skipped): every distinct SELECT text of the engine as {sql_hash, site, site_ids}, the call site with the
|
|
134
|
+
most evidence first; and the call-site id -> reason of each SELECT site of the engine that is not a group. The
|
|
135
|
+
variants of statement families count as statements of their sites (family_sites)."""
|
|
136
|
+
groups: dict[str, dict] = {}
|
|
137
|
+
skipped: dict[str, str] = {}
|
|
138
|
+
fam = family_sites(inventory, families, engine, cfg)
|
|
139
|
+
fam_ids = {str(s.get("id")) for s in fam}
|
|
140
|
+
for s in ((inventory or {}).get("call_sites") or []) + fam:
|
|
141
|
+
if not s.get("family_variant") and str(s.get("id")) in fam_ids:
|
|
142
|
+
continue # its family's variants stand for it
|
|
143
|
+
if _is_test(s) or (s.get("engine") or "") != engine or s.get("statement") != "select":
|
|
144
|
+
continue
|
|
145
|
+
if _role(s) == "migration" or not cfg.get("include_tooling") and _role(s) in ("tooling", "script"):
|
|
146
|
+
continue
|
|
147
|
+
sid = str(s.get("id") or "")
|
|
148
|
+
if not (s.get("sql") or "").strip():
|
|
149
|
+
skipped[sid] = "no_statement_text"
|
|
150
|
+
continue
|
|
151
|
+
if not s.get("parse_ok"):
|
|
152
|
+
skipped[sid] = "does_not_parse"
|
|
153
|
+
continue
|
|
154
|
+
h = s.get("sql_hash") or hashlib.sha1((s.get("sql") or "").encode()).hexdigest()[:16]
|
|
155
|
+
g = groups.get(h)
|
|
156
|
+
if g is None:
|
|
157
|
+
groups[h] = {"sql_hash": h, "site": s, "site_ids": [sid]}
|
|
158
|
+
else:
|
|
159
|
+
g["site_ids"].append(sid)
|
|
160
|
+
if _rank_site(s) > _rank_site(g["site"]):
|
|
161
|
+
g["site"] = s
|
|
162
|
+
return list(groups.values()), skipped
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
CTE_NAME = re.compile(r"(?:\bWITH\s+(?:RECURSIVE\s+)?|,\s*)[`\"]?([A-Za-z_]\w*)[`\"]?\s*(?:\([^()]*\)\s*)?AS\s+(?:NOT\s+)?(?:MATERIALIZED\s+)?\(", re.I)
|
|
166
|
+
SYSTEM_READ = re.compile(r"\b(?:system\.\w+|information_schema\.\w+|pg_catalog\.\w+|pg_\w+|sqlite_master|sqlite_schema)\b", re.I)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def system_table(name: str, engine: str) -> bool:
|
|
170
|
+
"""A table of the server's own catalog: it exists in every sandbox, no definition is built for it."""
|
|
171
|
+
n = re.sub(r"[`\"\[\]]", "", name or "").lower()
|
|
172
|
+
return n.startswith(("system.", "information_schema.", "pg_catalog.")) or n.split(".")[-1].startswith("pg_") \
|
|
173
|
+
or n in ("sqlite_master", "sqlite_schema") or (engine == "clickhouse" and n in ("numbers", "one", "zeros"))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _rank_site(s: dict) -> tuple:
|
|
177
|
+
"""Which of the sites sending one statement stands for it: app code on a request path first."""
|
|
178
|
+
return (_role(s) in ("app", "job"), bool(s.get("origins")), -len(str(s.get("file") or "")))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ---------------------------------------------------------------------------- the statement's text and parameters
|
|
182
|
+
|
|
183
|
+
EPOCH_FN = re.compile(r"unixtimestamp|fromunix|to_timestamp", re.I)
|
|
184
|
+
TIME_TYPE = re.compile(r"time|date", re.I)
|
|
185
|
+
NUM_TYPE = re.compile(r"^(?:u?int\d*|integer|bigint|smallint|serial\w*|numeric|decimal\w*|real|double|float\w*|bigserial|smallserial)",
|
|
186
|
+
re.I)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def text_of(site: dict, engine: str, cfg: dict) -> tuple[str | None, list[str], str]:
|
|
190
|
+
"""The statement as the sandbox runs it, with placeholders as the code writes them (`$n`, `?`, `{name:Type}`):
|
|
191
|
+
(sql, notes, why_not). A statement read from a SQL file is fixed text like a literal."""
|
|
192
|
+
from .loopbench import member_text
|
|
193
|
+
s = dict(site)
|
|
194
|
+
if s.get("resolution") in ("file", "unresolved", None, "") and (s.get("sql") or "").strip():
|
|
195
|
+
s["resolution"] = "literal"
|
|
196
|
+
sql, notes, why = member_text(s, engine, int(cfg["limit_value"]))
|
|
197
|
+
if sql is None:
|
|
198
|
+
return None, notes, why
|
|
199
|
+
if re.search(r"\{\{|\{%|\$\{", sql):
|
|
200
|
+
return None, notes, "template text in the statement (a part only known when it is rendered)"
|
|
201
|
+
return sql.strip().rstrip(";").strip(), notes, ""
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def column_types(definition: dict, engine: str, facts=None) -> dict[str, str]:
|
|
205
|
+
"""column (lower case) -> its type as the engine spells it, from the definition (the real catalog's columns first)."""
|
|
206
|
+
out: dict[str, str] = {}
|
|
207
|
+
if facts is not None and definition.get("source") == "real catalog":
|
|
208
|
+
t = facts.tables(engine).get(definition["name"].split(".")[-1] if engine == "clickhouse" else definition["name"]) or {}
|
|
209
|
+
for c in t.get("columns") or []:
|
|
210
|
+
out[c["name"].lower()] = c.get("type") or ""
|
|
211
|
+
if out:
|
|
212
|
+
return out
|
|
213
|
+
from .rank import _columns
|
|
214
|
+
got = _columns(definition.get("create_sql") or "", definition.get("name") or "")
|
|
215
|
+
for col, text in (got[1] if got else {}).items():
|
|
216
|
+
rest = text.split(" ", 1)[1] if " " in text else ""
|
|
217
|
+
out[col.strip('`"').lower()] = _type_words(rest, engine)
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
STOP_WORDS = re.compile(r"\s+(?:NOT\s+NULL|NULL|DEFAULT|PRIMARY|REFERENCES|UNIQUE|CHECK|COLLATE|GENERATED|CONSTRAINT|MATERIALIZED|ALIAS|"
|
|
222
|
+
r"EPHEMERAL|CODEC|COMMENT|TTL|AS)\b.*$", re.I)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _type_words(rest: str, engine: str) -> str:
|
|
226
|
+
"""The type at the start of a column's text (`timestamp with time zone NOT NULL` -> `timestamp with time zone`)."""
|
|
227
|
+
if engine == "clickhouse":
|
|
228
|
+
depth, end = 0, len(rest)
|
|
229
|
+
for i, ch in enumerate(rest):
|
|
230
|
+
if ch == "(":
|
|
231
|
+
depth += 1
|
|
232
|
+
elif ch == ")":
|
|
233
|
+
depth -= 1
|
|
234
|
+
elif ch == " " and depth == 0:
|
|
235
|
+
end = i
|
|
236
|
+
break
|
|
237
|
+
return rest[:end].strip()
|
|
238
|
+
return STOP_WORDS.sub("", " " + rest).strip()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _ch_param_type(t: str) -> str:
|
|
242
|
+
"""A ClickHouse parameter's type for a column of type `t`: LowCardinality left out (a parameter is a plain value)."""
|
|
243
|
+
t = t.strip()
|
|
244
|
+
m = re.fullmatch(r"LowCardinality\((.*)\)", t)
|
|
245
|
+
if m:
|
|
246
|
+
return _ch_param_type(m.group(1))
|
|
247
|
+
m = re.fullmatch(r"Nullable\((.*)\)", t)
|
|
248
|
+
if m:
|
|
249
|
+
return f"Nullable({_ch_param_type(m.group(1))})"
|
|
250
|
+
return t
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _pg_param_type(t: str) -> str:
|
|
254
|
+
from .observed import pg_one_word
|
|
255
|
+
t = re.sub(r"\(.*?\)", "", t or "").strip().lower()
|
|
256
|
+
t = {"serial": "integer", "serial4": "integer", "bigserial": "bigint", "serial8": "bigint", "smallserial": "smallint"}.get(t, t)
|
|
257
|
+
return pg_one_word(t) if t else "text"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _scalar(t: str) -> str:
|
|
261
|
+
"""The element type of an array type, the type itself otherwise."""
|
|
262
|
+
m = re.fullmatch(r"Array\((.*)\)", t.strip())
|
|
263
|
+
if m:
|
|
264
|
+
return m.group(1)
|
|
265
|
+
return t[:-2] if t.endswith("[]") else t
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _value(engine: str, typ: str, column: str, op: str, cfg: dict, n: int):
|
|
269
|
+
"""A value of `typ` for a placeholder: an equality's is one the fixture puts on rows; a range spans every generated row."""
|
|
270
|
+
base = re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", typ.strip())
|
|
271
|
+
low = base.lower()
|
|
272
|
+
if op in (">", ">=", "lower"):
|
|
273
|
+
if TIME_TYPE.search(low):
|
|
274
|
+
return cfg["time_low"][:10] if low == "date" or low.startswith("date") and "time" not in low else cfg["time_low"]
|
|
275
|
+
return -1_000_000_000 if not low.startswith("uint") else 0
|
|
276
|
+
if op in ("<", "<=", "upper"):
|
|
277
|
+
if TIME_TYPE.search(low):
|
|
278
|
+
return cfg["time_high"][:10] if low == "date" or low.startswith("date") and "time" not in low else cfg["time_high"]
|
|
279
|
+
return 2_000_000_000
|
|
280
|
+
if op in ("like", "ilike"):
|
|
281
|
+
return "%"
|
|
282
|
+
if op in ("not like", "not ilike", "!=", "<>"):
|
|
283
|
+
return "codecop-none" if not NUM_TYPE.match(low) and low not in ("uuid",) else (
|
|
284
|
+
"ffffffff-ffff-4fff-8fff-ffffffffffff" if low == "uuid" else -1)
|
|
285
|
+
if low == "uuid":
|
|
286
|
+
return f"00000000-0000-4000-8000-{n:012d}"
|
|
287
|
+
if NUM_TYPE.match(low):
|
|
288
|
+
return n
|
|
289
|
+
if low.startswith("bool"):
|
|
290
|
+
return "true" if engine != "clickhouse" else 1
|
|
291
|
+
if TIME_TYPE.search(low):
|
|
292
|
+
return cfg["time_low"] if "time" in low else cfg["time_low"][:10]
|
|
293
|
+
if low.startswith("json"):
|
|
294
|
+
return "{}"
|
|
295
|
+
if low.startswith(("map", "tuple", "array")) or low.endswith("[]"):
|
|
296
|
+
return None
|
|
297
|
+
return f"{column}_{n}"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def typed_sql(sql: str, tables: list[str], types_by_table: dict[str, dict[str, str]], engine: str, cfg: dict) -> tuple[str | None, dict, str]:
|
|
301
|
+
"""The statement with every placeholder written `{pN:type}` and what each stands for:
|
|
302
|
+
(sql, {pN: {type, column, table, op, value}}, why_not). The typing is typedparams.bind's (one typing path for the
|
|
303
|
+
schema check, the plan gate and the pass): the column a value is compared with, a cast, a function the value goes
|
|
304
|
+
through (`toUUID(?)`, `fromUnixTimestamp64Milli(?)`), LIMIT / OFFSET, an INSERT's column; more spellings (`:name`,
|
|
305
|
+
`%(name)s`, `@name`). The values are the pass's: an equality's is one the fixture puts on rows, a range spans every
|
|
306
|
+
generated row. A placeholder nothing types is a stand-in of text; the plan gate tells whether the statement plans
|
|
307
|
+
with it (`stand_in_type` when not) and tries other types."""
|
|
308
|
+
from . import typedparams as TP
|
|
309
|
+
if engine == "sqlite":
|
|
310
|
+
return _typed_sql_sqlite(sql, tables, types_by_table, cfg)
|
|
311
|
+
cols = {t: dict(types_by_table.get(t) or {}) for t in tables}
|
|
312
|
+
b = TP.bind(sql, engine, cols)
|
|
313
|
+
params: dict[str, dict] = {}
|
|
314
|
+
final_type: dict[str, str] = {}
|
|
315
|
+
for name, raw in b.params.items():
|
|
316
|
+
typ = b.types.get(name) or ""
|
|
317
|
+
op = b.ops.get(name) or "value"
|
|
318
|
+
table, column = b.columns.get(name) or ("", "")
|
|
319
|
+
through = b.through.get(name, "")
|
|
320
|
+
listed = typ.startswith("Array(") or typ.endswith("[]")
|
|
321
|
+
scalar_t = _scalar(typ)
|
|
322
|
+
if engine == "postgres":
|
|
323
|
+
ptype = _pg_param_type(scalar_t) + ("[]" if listed else "")
|
|
324
|
+
else:
|
|
325
|
+
ptype = typ if b.basis.get(name) == "declared" else _ch_param_type(typ)
|
|
326
|
+
rng = op in (">", ">=", "<", "<=", "lower", "upper")
|
|
327
|
+
tok = re.search(r"\{" + re.escape(name) + r"\s*:", b.sql)
|
|
328
|
+
left = b.sql[:tok.start()] if tok else ""
|
|
329
|
+
numeric = bool(NUM_TYPE.match(re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", scalar_t.strip())))
|
|
330
|
+
if op == "limit":
|
|
331
|
+
value = int(cfg["limit_value"])
|
|
332
|
+
elif op == "offset":
|
|
333
|
+
value = int(cfg["offset_value"])
|
|
334
|
+
elif op == "interval" or scalar_t.lower().startswith("interval"):
|
|
335
|
+
value = "3650 days" if scalar_t.lower().startswith("interval") else 3650
|
|
336
|
+
elif not numeric and (TZ_LEFT.search(left) or re.search(r"time_?zone|(?:^|_)tz$", name, re.I)):
|
|
337
|
+
value = "UTC" # a time zone argument: toTimeZone(t, {tz:String}), toStartOfDay(t, {tz:String})
|
|
338
|
+
elif not numeric and UNIT_LEFT.search(left):
|
|
339
|
+
value = "day" # an interval's unit: toInterval(1, {unit:String}), date_trunc({unit}, ...), INTERVAL 1 {unit}
|
|
340
|
+
elif numeric and through and (EPOCH_FN.search(through) or TIME_TYPE.search(through)):
|
|
341
|
+
# a number the code turns into a time (fromUnixTimestamp({start:Int64})): the type wins, never a time's text
|
|
342
|
+
scale = 1000 if "milli" in through else 1_000_000 if "micro" in through else 1_000_000_000 if "nano" in through else 1
|
|
343
|
+
value = (0 if op in (">", ">=", "lower") else 4_102_444_800 * scale) if rng else 1_767_225_600 * scale
|
|
344
|
+
elif through and EPOCH_FN.search(through) and rng:
|
|
345
|
+
scale = 1000 if "milli" in through else 1_000_000 if "micro" in through else 1_000_000_000 if "nano" in through else 1
|
|
346
|
+
value = 0 if op in (">", ">=", "lower") else 4_102_444_800 * scale # every generated time is inside [1970, 2100)
|
|
347
|
+
elif through.startswith("touuid"):
|
|
348
|
+
value = "00000000-0000-4000-8000-000000000001"
|
|
349
|
+
elif (b.basis.get(name) == "time_text" or (through and TIME_TYPE.search(through))) and (rng or not column):
|
|
350
|
+
value = _value(engine, "DateTime", column or name, op if rng else ">=", cfg, 1)
|
|
351
|
+
elif table or b.basis.get(name) in ("cast", "declared"):
|
|
352
|
+
col_t = (types_by_table.get(table) or {}).get(column) or ""
|
|
353
|
+
if re.search(r"\buuid\b", col_t, re.I) and not re.search(r"\buuid\b", scalar_t, re.I):
|
|
354
|
+
scalar_t = "UUID" # toString(uuid_col) = ?: text that is one of the column's values
|
|
355
|
+
value = _value(engine, scalar_t, column or name,
|
|
356
|
+
op if op not in ("in", "not in", "set", "value") else ("!=" if op == "not in" else "="), cfg, 1)
|
|
357
|
+
else:
|
|
358
|
+
value = raw # typedparams' neutral value of the type
|
|
359
|
+
if isinstance(value, bool):
|
|
360
|
+
value = 1 if engine == "clickhouse" else "true"
|
|
361
|
+
elif isinstance(value, list):
|
|
362
|
+
value = value[0] if value else None
|
|
363
|
+
if value is None:
|
|
364
|
+
if op == "stand_in" or not table:
|
|
365
|
+
# "qopt": a neutral text value, kept from before the rename (formerly qopt) so the data stays the same
|
|
366
|
+
value = "qopt"
|
|
367
|
+
else:
|
|
368
|
+
return None, {}, f"parameter_not_typed: no value of type {ptype} for parameter {name}"
|
|
369
|
+
if listed:
|
|
370
|
+
if engine == "clickhouse":
|
|
371
|
+
value = "[" + (repr(value) if isinstance(value, str) else str(value)).replace('"', "'") + "]"
|
|
372
|
+
else:
|
|
373
|
+
value = "{" + str(value) + "}"
|
|
374
|
+
final_type[name] = ptype
|
|
375
|
+
params[name] = {"type": ptype, "column": column, "table": table, "op": op, "value": value}
|
|
376
|
+
text = PARAM_TOKEN.sub(lambda m: "{" + f"{m.group(1)}:{final_type[m.group(1)]}" + "}" if m.group(1) in final_type else m.group(0), b.sql)
|
|
377
|
+
if engine == "postgres":
|
|
378
|
+
# `INTERVAL $1`: a parameter is no interval literal (`INTERVAL CAST(...)` is a syntax error); written as a cast
|
|
379
|
+
def interval(m: re.Match) -> str:
|
|
380
|
+
n = m.group(1)
|
|
381
|
+
if n in params:
|
|
382
|
+
params[n].update(type="interval", value="3650 days" if params[n]["op"] != "interval" else "3650 days")
|
|
383
|
+
return "CAST({" + n + ":interval} AS interval)"
|
|
384
|
+
text = re.sub(r"\bINTERVAL\s+\{(\w+)\s*:[^{}]+\}", interval, text, flags=re.I)
|
|
385
|
+
return text, params, ""
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
PARAM_TOKEN = re.compile(r"\{(\w+)\s*:\s*[^{}]+\}")
|
|
389
|
+
TZ_LEFT = re.compile(r"\b(?:toTimeZone|toDateTime64|toDateTime|toDate32|toDate|toStartOf\w+|toUnixTimestamp|toYYYYMMDD|toYYYYMM|toHour|"
|
|
390
|
+
r"toMonday|toDayOfWeek|toRelative\w+|now64|now|today|parseDateTime\w*)\s*\((?:[^()]|\([^()]*\))*,\s*$", re.I)
|
|
391
|
+
UNIT_LEFT = re.compile(r"(?:\btoInterval\s*\(\s*[^,()]+,|\bINTERVAL\s+[^\s,()]+|\b(?:date_?trunc|dateTrunc|date_?diff|dateDiff|date_?add|dateAdd|"
|
|
392
|
+
r"date_?sub|dateSub|timestamp_?add|timestamp_?sub|age)\s*\()\s*$", re.I)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _typed_sql_sqlite(sql: str, tables: list[str], types_by_table: dict[str, dict[str, str]], cfg: dict) -> tuple[str | None, dict, str]:
|
|
396
|
+
"""SQLite: the same typing; every parameter is TEXT or INTEGER."""
|
|
397
|
+
text, params, why = typed_sql(sql, tables, types_by_table, "postgres", cfg)
|
|
398
|
+
if text is None:
|
|
399
|
+
return text, params, why
|
|
400
|
+
for v in params.values():
|
|
401
|
+
v["type"] = "INTEGER" if NUM_TYPE.match(_scalar(v["type"])) else "TEXT"
|
|
402
|
+
if isinstance(v["value"], str) and v["value"] == "true":
|
|
403
|
+
v["value"] = 1
|
|
404
|
+
return PARAM_TOKEN.sub(lambda m: "{" + f"{m.group(1)}:{params[m.group(1)]['type']}" + "}" if m.group(1) in params else m.group(0),
|
|
405
|
+
text), params, why
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
# ---------------------------------------------------------------------------- ORM expressions left in a translation
|
|
409
|
+
|
|
410
|
+
ORM_COL = r"col\(\s*(\w+)\.(\w+)\s*\)|(\w+)\.(\w+)"
|
|
411
|
+
ORM_FORMS = [
|
|
412
|
+
# (pattern over the «…» text, SQL it becomes; {a}/{b} are columns, {v} a parameter)
|
|
413
|
+
(re.compile(r"^(?:" + ORM_COL + r")\s*(==|!=|>=|<=|>|<)\s*(?:" + ORM_COL + r")$"), "cmp_cols"),
|
|
414
|
+
(re.compile(r"^(?:" + ORM_COL + r")\s*(==|!=|>=|<=|>|<)\s*[\w.()\[\]'\"]+$"), "cmp_value"),
|
|
415
|
+
(re.compile(r"^(?:" + ORM_COL + r")\.(in_|not_in)\(.*\)$"), "in"),
|
|
416
|
+
(re.compile(r"^(?:" + ORM_COL + r")\.(desc|asc)\(\)$"), "order"),
|
|
417
|
+
(re.compile(r"^(?:" + ORM_COL + r")\.(is_|is_not|isnot)\(\s*None\s*\)$"), "null"),
|
|
418
|
+
(re.compile(r"^(?:" + ORM_COL + r")\.(startswith|endswith|contains|like|ilike)\(.*\)$"), "like"),
|
|
419
|
+
(re.compile(r"^col\(\s*(\w+)\.(\w+)\s*\)$"), "column"),
|
|
420
|
+
]
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _snake(name: str) -> str:
|
|
424
|
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def orm_parts(site: dict, tables: list[str], types: dict[str, dict[str, str]]) -> dict:
|
|
428
|
+
"""The site with the ORM expressions its translation left as «…» written as SQL where the form is plain: a column
|
|
429
|
+
compared with a column or a value (`col(Trace.flow_id) == col(Flow.id)`, `col(Job.id) == job_id`), `.in_()`, `.desc()`,
|
|
430
|
+
`.is_(None)`, `.startswith()`, and an optional filter (`optional: user.username = username`, run with the filter in).
|
|
431
|
+
A value becomes a parameter; a model's attribute becomes the column of the statement's table that has it. Any other
|
|
432
|
+
«…» is left for member_text, which says it is a run-time part. Copies; the site is not changed."""
|
|
433
|
+
sql = site.get("sql") or ""
|
|
434
|
+
if "«" not in sql or site.get("resolution") not in ("orm", "template"):
|
|
435
|
+
return site
|
|
436
|
+
n = [9000]
|
|
437
|
+
|
|
438
|
+
def column(model: str, field: str) -> str | None:
|
|
439
|
+
f = field.lower()
|
|
440
|
+
owners = [t for t in tables if f in (types.get(t) or {})]
|
|
441
|
+
if not owners:
|
|
442
|
+
return None
|
|
443
|
+
guess = _snake(model)
|
|
444
|
+
guess_b = re.sub(r"_(table|model|record)$", "", guess)
|
|
445
|
+
pick = next((t for t in owners if t in (guess, guess_b, guess + "s", guess_b + "s")), owners[0] if len(owners) == 1 else None)
|
|
446
|
+
if pick is None:
|
|
447
|
+
pick = next((t for t in owners if guess_b.startswith(t) or t.startswith(guess_b)), owners[0])
|
|
448
|
+
return f"{pick}.{field}"
|
|
449
|
+
|
|
450
|
+
def value() -> str:
|
|
451
|
+
n[0] += 1
|
|
452
|
+
return f"${n[0]}"
|
|
453
|
+
|
|
454
|
+
def one(inner: str) -> str | None:
|
|
455
|
+
text = inner.strip()
|
|
456
|
+
if text.startswith("optional:"):
|
|
457
|
+
text = text[len("optional:"):].strip()
|
|
458
|
+
if "…" in text:
|
|
459
|
+
return None
|
|
460
|
+
# SQL with the code's names as values: `a.b = name` -> `a.b = $n`
|
|
461
|
+
sub = re.sub(r"(=|<>|!=|>=|<=|>|<)\s*([A-Za-z_][\w.]*)(?!\s*\()", lambda m: f"{m.group(1)} {value()}"
|
|
462
|
+
if not re.fullmatch(r"\w+\.\w+", m.group(2)) or m.group(2).split(".")[0] not in tables else m.group(0), text)
|
|
463
|
+
return None if "«" in sub or "col(" in sub else sub
|
|
464
|
+
if text.startswith("~"):
|
|
465
|
+
inner_sql = one(text[1:]) # `~col(M.name).startswith(p)`: the condition negated
|
|
466
|
+
return f"NOT ({inner_sql})" if inner_sql else None
|
|
467
|
+
if (lab := re.fullmatch(r"(.+)\.label\(\s*['\"](\w+)['\"]\s*\)", text)):
|
|
468
|
+
inner_sql = one(lab.group(1)) # `col(Flow.name).label('flow_name')`
|
|
469
|
+
return f"{inner_sql} AS {lab.group(2)}" if inner_sql else None
|
|
470
|
+
if (cte := re.fullmatch(r"(\w+)\.c\.(\w+)", text)):
|
|
471
|
+
return f"{cte.group(1)}.{cte.group(2)}" # a subquery's or CTE's column (`cte.c.position`)
|
|
472
|
+
for pat, form in ORM_FORMS:
|
|
473
|
+
m = pat.fullmatch(text)
|
|
474
|
+
if not m:
|
|
475
|
+
continue
|
|
476
|
+
g = m.groups()
|
|
477
|
+
left = column(g[0] or g[2], g[1] or g[3]) if form != "column" else column(g[0], g[1])
|
|
478
|
+
if left is None:
|
|
479
|
+
return None
|
|
480
|
+
if form == "cmp_cols":
|
|
481
|
+
right = column(g[5] or g[7], g[6] or g[8])
|
|
482
|
+
return None if right is None else f"{left} {'=' if g[4] == '==' else g[4]} {right}"
|
|
483
|
+
if form == "cmp_value":
|
|
484
|
+
return f"{left} {'=' if g[4] == '==' else g[4]} {value()}"
|
|
485
|
+
if form == "in":
|
|
486
|
+
return f"{left} {'NOT IN' if g[4] == 'not_in' else 'IN'} ({value()})"
|
|
487
|
+
if form == "order":
|
|
488
|
+
return f"{left} {g[4].upper()}"
|
|
489
|
+
if form == "null":
|
|
490
|
+
return f"{left} IS {'NULL' if g[4] == 'is_' else 'NOT NULL'}"
|
|
491
|
+
if form == "like":
|
|
492
|
+
lit = re.search(r"\(\s*'([^'%\\]*)'\s*\)$", text)
|
|
493
|
+
if lit and g[4] in ("startswith", "endswith", "contains"):
|
|
494
|
+
pat = {"startswith": "{}%", "endswith": "%{}", "contains": "%{}%"}[g[4]].format(lit.group(1))
|
|
495
|
+
return f"{left} LIKE '{pat}'" # the code's own text: the filter keeps its meaning
|
|
496
|
+
return f"{left} {'ILIKE' if g[4] == 'ilike' else 'LIKE'} {value()}"
|
|
497
|
+
return left
|
|
498
|
+
return None
|
|
499
|
+
out, last, changed = [], 0, False
|
|
500
|
+
for m in re.finditer(r"«([^«»]*)»", sql):
|
|
501
|
+
got = one(m.group(1))
|
|
502
|
+
if got is None:
|
|
503
|
+
continue
|
|
504
|
+
out.append(sql[last:m.start()] + got)
|
|
505
|
+
last = m.end()
|
|
506
|
+
changed = True
|
|
507
|
+
if not changed:
|
|
508
|
+
return site
|
|
509
|
+
out.append(sql[last:])
|
|
510
|
+
return {**site, "sql": "".join(out)}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
PG_RESERVED = {"user", "order", "group", "end", "table", "column", "check", "default", "limit", "offset", "window", "analyse",
|
|
514
|
+
"analyze", "select", "where", "from", "to", "with", "when", "grant", "all", "desc", "asc", "case", "do", "only",
|
|
515
|
+
"references", "primary", "foreign", "unique", "constraint", "current_user", "session_user", "user_role"}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def quote_reserved(sql: str, tables: list[str]) -> str:
|
|
519
|
+
"""PostgreSQL: a table whose name is a reserved word (`user`, `order`, `group`) written bare, as an ORM translation
|
|
520
|
+
leaves it (`FROM user WHERE user.id = $1`), quoted the way the ORM sends it (`FROM "user" WHERE "user".id = $1`)."""
|
|
521
|
+
for t in tables:
|
|
522
|
+
if t.lower() not in PG_RESERVED - {"user_role"}:
|
|
523
|
+
continue
|
|
524
|
+
sql = re.sub(rf"(?<![\w\".]){re.escape(t)}(?=\.\w)", f'"{t}"', sql)
|
|
525
|
+
sql = re.sub(rf"\b(FROM|JOIN|UPDATE|INTO)\s+{re.escape(t)}\b(?!\.)", rf'\1 "{t}"', sql, flags=re.I)
|
|
526
|
+
return sql
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
# ---------------------------------------------------------------------------- a table named at run time
|
|
530
|
+
|
|
531
|
+
TABLE_SLOT = re.compile(r"\b(FROM|JOIN)\s+«([^«»]*)»", re.I)
|
|
532
|
+
_WORD = re.compile(r"(?<![\w.'\"`])([A-Za-z_]\w*)\b(?!\s*\()")
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def infer_tables(site: dict, columns: dict[str, dict[str, str]], min_columns: int = 3) -> tuple[dict, list[str]]:
|
|
536
|
+
"""(the site with each `FROM «expr»` / `JOIN «expr»` written as the one table whose columns the statement names, the
|
|
537
|
+
notes). A table name the code computes (`FROM «s.table()»`, `FROM «tableName»`) is taken as the table of the engine
|
|
538
|
+
that holds the most of the statement's column names, at least `min_columns` of them, strictly more than any other;
|
|
539
|
+
else the slot stays (the statement is still not runnable). Only a statement with one such slot is changed."""
|
|
540
|
+
sql = site.get("sql") or ""
|
|
541
|
+
slots = TABLE_SLOT.findall(sql)
|
|
542
|
+
if len(slots) != 1 or not columns:
|
|
543
|
+
return site, []
|
|
544
|
+
from .engines.base import QUOTED
|
|
545
|
+
bare = QUOTED.sub(" ", PH_ANY.sub(" ", sql))
|
|
546
|
+
words = {w.lower() for w in _WORD.findall(bare)}
|
|
547
|
+
scored = sorted(((len(words & set(cols)), t) for t, cols in columns.items()), reverse=True)
|
|
548
|
+
if not scored or scored[0][0] < min_columns or (len(scored) > 1 and scored[1][0] == scored[0][0]):
|
|
549
|
+
return site, []
|
|
550
|
+
hit, table = scored[0]
|
|
551
|
+
expr = slots[0][1]
|
|
552
|
+
new_sql = sql.replace(f"«{expr}»", table, 1)
|
|
553
|
+
tables = [table if t == f"«{expr}»" or "«" in t else t for t in site.get("tables") or []] or [table]
|
|
554
|
+
note = (f"the table `{expr}` names at run time is taken as {table}: the table holding {hit} of the column names the "
|
|
555
|
+
"statement reads (no other holds as many)")
|
|
556
|
+
return {**site, "sql": new_sql, "tables": list(dict.fromkeys(tables))}, [note]
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
PH_ANY = re.compile(r"«[^«»]*»")
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
# ---------------------------------------------------------------------------- the bench input
|
|
563
|
+
|
|
564
|
+
def definition_of(name: str, engine: str, inventory: dict, facts, loaded: dict, readers: list[str]) -> dict | None:
|
|
565
|
+
"""The definition a table of the statement is built from: one the run already loads, the real catalog's, the repository's."""
|
|
566
|
+
from . import loopschema
|
|
567
|
+
key = _bare(name)
|
|
568
|
+
if key in loaded:
|
|
569
|
+
return loaded[key]
|
|
570
|
+
d = None
|
|
571
|
+
if facts is not None:
|
|
572
|
+
bare = re.sub(r'[`"]', "", name)
|
|
573
|
+
d = facts.definition(engine, bare) or (facts.definition(engine, key) if engine != "clickhouse" else None)
|
|
574
|
+
if d is None and engine == "postgres" and "." in bare and bare.split(".")[0] == "public":
|
|
575
|
+
d = facts.definition(engine, bare.split(".", 1)[1])
|
|
576
|
+
if d is None:
|
|
577
|
+
d = loopschema.definition(inventory, re.sub(r'[`"]', "", name), engine, readers)
|
|
578
|
+
return copy.deepcopy(d) if d else None
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def extend(rank: dict | None, profile: dict | None, inventory: dict, engine: str, facts=None, settings: dict | None = None,
|
|
582
|
+
gate: dict | None = None, families: dict | None = None) -> tuple[dict | None, dict | None, dict]:
|
|
583
|
+
"""rank and profile with a candidate for every SELECT of `engine` the run does not already measure (copies; the files
|
|
584
|
+
on disk are not changed), and the pass's document: {statements, skipped, gate, by_reason}. `gate`: finding -> the plan
|
|
585
|
+
gate's earlier result (plangate.py); a statement that did not plan is left out of the candidates and keeps its reason."""
|
|
586
|
+
from . import catalog_profile, loopschema
|
|
587
|
+
cfg = settings_of(settings)
|
|
588
|
+
doc = {"schema_version": SCHEMA_VERSION, "engine": engine, "settings": cfg, "statements": [], "skipped": {},
|
|
589
|
+
"by_reason": {}, "tables": {"catalog": 0, "repository": 0, "agent": 0}}
|
|
590
|
+
if not cfg["enabled"] or engine not in ("postgres", "clickhouse", "sqlite"):
|
|
591
|
+
return rank, profile, doc
|
|
592
|
+
groups, skipped = statements(inventory, engine, cfg, families)
|
|
593
|
+
rank = copy.deepcopy(rank) if rank else {"engine": engine, "engine_version": "", "candidates": [], "table_definitions": [],
|
|
594
|
+
"agent": {"runner": "", "model": "", "cost_usd": 0.0}, "shortlist": [], "rejected": []}
|
|
595
|
+
profile = copy.deepcopy(profile) if profile else {"engine": engine, "tables": []}
|
|
596
|
+
covered_ids = {str(c.get("id")) for c in rank.get("candidates") or [] if c.get("baseline_sql") and c.get("sql_from") != "query_log"}
|
|
597
|
+
by_id = {str(s.get("id")): s for s in inventory.get("call_sites") or []}
|
|
598
|
+
covered_hash = {by_id[i].get("sql_hash") for i in covered_ids if i in by_id}
|
|
599
|
+
loaded = {_bare(d["name"]): d for d in rank.get("table_definitions") or []}
|
|
600
|
+
agent_tables = {_bare(t["name"]) for t in profile.get("tables") or [] if t.get("basis") not in ("catalog, no agent", "schema only, no agent")}
|
|
601
|
+
readers: dict[str, list[str]] = {}
|
|
602
|
+
for g in groups:
|
|
603
|
+
for t in g["site"].get("tables") or []:
|
|
604
|
+
readers.setdefault(_bare(t), []).append(g["site"].get("file") or "")
|
|
605
|
+
added: dict[str, dict] = {}
|
|
606
|
+
types_cache: dict[str, dict[str, str]] = {}
|
|
607
|
+
out: list[dict] = []
|
|
608
|
+
gate = gate or {}
|
|
609
|
+
all_columns = None # every table's columns of the engine, read once a statement needs a table inferred
|
|
610
|
+
groups.sort(key=lambda g: (-len(g["site_ids"]), g["sql_hash"]))
|
|
611
|
+
for g in groups:
|
|
612
|
+
site, h = g["site"], g["sql_hash"]
|
|
613
|
+
entry = {"finding": label(h), "sql_hash": h, "site_ids": g["site_ids"], "site": {"file": site.get("file"), "line": site.get("line")},
|
|
614
|
+
**({"family_variant": site["family_variant"]} if site.get("family_variant") else {})}
|
|
615
|
+
if h in covered_hash or any(i in covered_ids for i in g["site_ids"]):
|
|
616
|
+
entry["state"], entry["reason"] = "covered", "covered_by_agent"
|
|
617
|
+
doc["statements"].append(entry)
|
|
618
|
+
continue
|
|
619
|
+
if cfg["max_statements"] and len(out) >= cfg["max_statements"]:
|
|
620
|
+
entry["state"], entry["reason"] = "not_measured", "over_max_statements"
|
|
621
|
+
doc["statements"].append(entry)
|
|
622
|
+
continue
|
|
623
|
+
inferred_notes: list[str] = []
|
|
624
|
+
if TABLE_SLOT.search(site.get("sql") or ""):
|
|
625
|
+
if all_columns is None:
|
|
626
|
+
from . import sandboxschema
|
|
627
|
+
all_columns = sandboxschema.columns_of(engine, getattr(facts, "catalog", None), inventory)
|
|
628
|
+
site, inferred_notes = infer_tables(site, all_columns)
|
|
629
|
+
raw_tables = [t for t in site.get("tables") or [] if t and not t.startswith("?")]
|
|
630
|
+
if any("«" in t or "»" in t for t in raw_tables):
|
|
631
|
+
entry.update(state="not_measured", reason="run_time_parts_in_text", detail="a table name is only known at run time")
|
|
632
|
+
doc["statements"].append(entry)
|
|
633
|
+
continue
|
|
634
|
+
ctes = {m.lower() for m in CTE_NAME.findall(site.get("sql") or "")}
|
|
635
|
+
raw_tables = [t for t in raw_tables if _bare(t) not in ctes and not system_table(t, engine)]
|
|
636
|
+
tables = list(dict.fromkeys(_bare(t) for t in raw_tables))
|
|
637
|
+
if not tables and SYSTEM_READ.search(site.get("sql") or ""):
|
|
638
|
+
tables = [] # reads only the server's own catalog: runs in the sandbox as it is
|
|
639
|
+
elif not tables:
|
|
640
|
+
entry.update(state="not_measured", reason="no_table_definition", detail="the statement names no table")
|
|
641
|
+
doc["statements"].append(entry)
|
|
642
|
+
continue
|
|
643
|
+
defs: dict[str, dict] = {}
|
|
644
|
+
lacking = []
|
|
645
|
+
for raw in raw_tables:
|
|
646
|
+
t = _bare(raw)
|
|
647
|
+
if t in defs:
|
|
648
|
+
continue
|
|
649
|
+
d = loaded.get(t) or added.get(t) or definition_of(raw, engine, inventory, facts, loaded, readers.get(t) or [])
|
|
650
|
+
if d is None:
|
|
651
|
+
lacking.append(t)
|
|
652
|
+
else:
|
|
653
|
+
defs[t] = d
|
|
654
|
+
if lacking:
|
|
655
|
+
# no definition anywhere: the gate's typed reason, without starting the sandbox for it
|
|
656
|
+
entry.update(state="does_not_plan", reason="table_not_pulled", tables=lacking,
|
|
657
|
+
detail=f"no definition of {', '.join(lacking[:4])} in the pulled catalog or the repository's schema")
|
|
658
|
+
doc["statements"].append(entry)
|
|
659
|
+
continue
|
|
660
|
+
for t, d in defs.items():
|
|
661
|
+
if t not in types_cache:
|
|
662
|
+
types_cache[t] = column_types(d, engine, facts)
|
|
663
|
+
sql, notes, why = text_of(orm_parts(site, tables, types_cache), engine, cfg)
|
|
664
|
+
if sql is not None and engine == "postgres":
|
|
665
|
+
sql = quote_reserved(sql, tables)
|
|
666
|
+
if sql is None:
|
|
667
|
+
entry["state"] = "not_measured"
|
|
668
|
+
entry["reason"] = "run_time_parts_in_text" if "run time" in why or "template" in why or "rendered" in why else "no_statement_text"
|
|
669
|
+
entry["detail"] = why[:300]
|
|
670
|
+
doc["statements"].append(entry)
|
|
671
|
+
continue
|
|
672
|
+
sql_t, params, why = typed_sql(sql, tables, types_cache, engine, cfg)
|
|
673
|
+
if sql_t is None:
|
|
674
|
+
entry.update(state="not_measured", reason="parameter_not_typed", detail=why[:300])
|
|
675
|
+
doc["statements"].append(entry)
|
|
676
|
+
continue
|
|
677
|
+
f = label(h)
|
|
678
|
+
prior = gate.get(f)
|
|
679
|
+
if prior and prior.get("fingerprint") == _fingerprint(sql_t, defs) and not prior.get("ok"):
|
|
680
|
+
entry.update(state="does_not_plan", reason=prior.get("reason") or "does_not_plan", error_class=prior.get("class"),
|
|
681
|
+
detail=prior.get("error", "")[:300])
|
|
682
|
+
doc["statements"].append(entry)
|
|
683
|
+
continue
|
|
684
|
+
for t, d in defs.items():
|
|
685
|
+
if t not in loaded and t not in added:
|
|
686
|
+
added[t] = d
|
|
687
|
+
cand = {"finding": f, "id": str(site.get("id")), "title": f"Baseline of {str(site.get('file', '')).split('/')[-1]}:{site.get('line', 0)}",
|
|
688
|
+
"severity": "low", "confidence": "high", "baseline_sql": sql_t, "original_sql": site.get("sql") or "",
|
|
689
|
+
"params": {k: v["value"] for k, v in params.items()},
|
|
690
|
+
"param_ops": {k: ("stand_in" if v["op"] == "stand_in" or (not v["column"] and v["op"] not in ("limit", "offset", "interval"))
|
|
691
|
+
else v["op"]) for k, v in params.items()},
|
|
692
|
+
"tables": [defs[t]["name"] for t in tables if t in defs], "variants": [], "causes": [],
|
|
693
|
+
"sql_from": "code", "baseline_pass": True, "same_sql_sites": len(g["site_ids"]),
|
|
694
|
+
"gate_fingerprint": _fingerprint(sql_t, defs),
|
|
695
|
+
"site": {"file": site.get("file"), "line": site.get("line")},
|
|
696
|
+
"assumptions": list(notes) + inferred_notes + ["a baseline of the code's own statement, every parameter typed from what it is compared "
|
|
697
|
+
"with; values put on a few rows so it returns rows (no agent)"],
|
|
698
|
+
"baseline_params": params, "_column_types": {t: types_cache.get(t) or {} for t in tables}}
|
|
699
|
+
if site.get("origins"):
|
|
700
|
+
cand["origin"] = {"role": _role(site) or "app", "kind": (site["origins"][0] or {}).get("kind") or "",
|
|
701
|
+
"entry_points": [{k: o.get(k) for k in ("kind", "name", "file", "line")} for o in site["origins"][:3]]}
|
|
702
|
+
out.append(cand)
|
|
703
|
+
entry.update(state="candidate", tables=cand["tables"])
|
|
704
|
+
doc["statements"].append(entry)
|
|
705
|
+
for sid, why in skipped.items():
|
|
706
|
+
doc["skipped"][sid] = why
|
|
707
|
+
doc["by_reason"] = dict(Counter(e.get("reason") or e.get("state") for e in doc["statements"]
|
|
708
|
+
if e.get("state") not in ("candidate",)) + Counter(skipped.values()))
|
|
709
|
+
if not out:
|
|
710
|
+
return rank, profile, doc
|
|
711
|
+
# definitions, then the data: the catalog's description for pulled tables (catalog_profile), the columns alone otherwise
|
|
712
|
+
rank["table_definitions"] = list(rank.get("table_definitions") or []) + [added[t] for t in sorted(added)]
|
|
713
|
+
by_table = {_bare(t["name"]): t for t in profile.get("tables") or []}
|
|
714
|
+
real = facts.tables(engine) if facts is not None else {}
|
|
715
|
+
catalog_cands = [c for c in out if any(_bare(t) not in by_table and (real.get(t if engine != "clickhouse" else _bare(t))
|
|
716
|
+
or real.get(_bare(t))) for t in c["tables"])]
|
|
717
|
+
if catalog_cands and facts is not None:
|
|
718
|
+
shadow = {"candidates": [dict(c) for c in catalog_cands]}
|
|
719
|
+
r2, p2, _notes = catalog_profile.augment({**rank, "candidates": []}, profile, shadow, facts, engine)
|
|
720
|
+
profile = p2
|
|
721
|
+
by_table = {_bare(t["name"]): t for t in profile.get("tables") or []}
|
|
722
|
+
lcfg = loopschema.settings_of(None)
|
|
723
|
+
for t in sorted(added):
|
|
724
|
+
if t not in by_table:
|
|
725
|
+
prof_t = loopschema.schema_profile(added[t], inventory, engine, lcfg)
|
|
726
|
+
profile.setdefault("tables", []).append(prof_t)
|
|
727
|
+
by_table[t] = prof_t
|
|
728
|
+
doc["tables"]["repository"] += 1
|
|
729
|
+
elif t in agent_tables:
|
|
730
|
+
doc["tables"]["agent"] += 1
|
|
731
|
+
else:
|
|
732
|
+
doc["tables"]["catalog"] += 1
|
|
733
|
+
for cand in out:
|
|
734
|
+
_fixtures(cand, by_table, lcfg)
|
|
735
|
+
cand.pop("baseline_params", None)
|
|
736
|
+
cand.pop("_column_types", None)
|
|
737
|
+
rank["candidates"] = list(rank.get("candidates") or []) + out
|
|
738
|
+
return rank, profile, doc
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _fingerprint(sql: str, defs: dict[str, dict]) -> str:
|
|
742
|
+
text = json.dumps([sql, sorted((k, (d.get("create_sql") or "")) for k, d in defs.items())])
|
|
743
|
+
return hashlib.sha1(text.encode()).hexdigest()[:16]
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
_QCOL = r"(?P<col>(?:[`\"]?[A-Za-z_]\w*[`\"]?\s*\.\s*)?[`\"]?[A-Za-z_]\w*[`\"]?)"
|
|
747
|
+
LITERAL_EQ = re.compile(r"(?<![<>!])" + _QCOL + r"\s*(?:=|==)\s*(?:'(?P<s>(?:[^'\\]|''|\\.)*)'|(?P<n>-?\d+)(?![\w.]))", re.I)
|
|
748
|
+
LITERAL_IN = re.compile(_QCOL + r"\s+(?:GLOBAL\s+)?IN\s*\(\s*(?:'(?P<s>(?:[^'\\]|''|\\.)*)'|(?P<n>-?\d+)(?![\w.]))", re.I)
|
|
749
|
+
_NOT_COL = {"and", "or", "not", "where", "on", "when", "then", "else", "select", "null", "true", "false", "case", "having", "is",
|
|
750
|
+
"prewhere", "limit", "offset", "by"}
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
IN_EXTRA_VALUES = 2 # values of a literal IN list put on rows beside the first
|
|
754
|
+
LITERAL_IN_LIST = re.compile(_QCOL + r"\s+(?:GLOBAL\s+)?IN\s*\(\s*(?P<list>(?:'(?:[^'\\]|'')*'|-?\d+)(?:\s*,\s*(?:'(?:[^'\\]|'')*'|-?\d+))+)\s*\)", re.I)
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def literal_in_extras(sql: str, by_table: dict, tables: list[str]) -> list[tuple[str, str, list]]:
|
|
758
|
+
"""(table, column, [second value, third, ...]) of every literal `col IN ('a', 'b', ...)` of the statement."""
|
|
759
|
+
from . import typedparams as TP
|
|
760
|
+
aliases = TP.tables_of(sql)
|
|
761
|
+
out = []
|
|
762
|
+
for m in LITERAL_IN_LIST.finditer(sql):
|
|
763
|
+
if m.group("col").split(".")[-1].strip('`" ').lower() in _NOT_COL:
|
|
764
|
+
continue
|
|
765
|
+
own = _owner(m.group("col"), aliases, by_table, tables)
|
|
766
|
+
if not own:
|
|
767
|
+
continue
|
|
768
|
+
items = [x.group(1).replace("''", "'") if x.group(1) is not None else int(x.group(2))
|
|
769
|
+
for x in re.finditer(r"'((?:[^'\\]|'')*)'|(-?\d+)", m.group("list"))]
|
|
770
|
+
spec = next(c for c in by_table[own[0]]["columns"] if (c.get("name") or "").lower() == own[1].lower())
|
|
771
|
+
if len(items) > 1:
|
|
772
|
+
out.append((own[0], spec["name"], items[1:]))
|
|
773
|
+
return out
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
JOIN_ON = re.compile(_QCOL.replace("?P<col>", "?P<a>") + r"\s*=\s*" + _QCOL.replace("?P<col>", "?P<b>"), re.I)
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def _owner(ref: str, aliases: dict, by_table: dict, tables: list[str]) -> tuple[str, str] | None:
|
|
780
|
+
parts = [p.strip('`" ') for p in ref.split(".")]
|
|
781
|
+
col = parts[-1]
|
|
782
|
+
want = [aliases.get(parts[0].lower(), parts[0].lower())] if len(parts) > 1 else tables
|
|
783
|
+
owners = [_bare(t) for t in want if any((c.get("name") or "").lower() == col.lower()
|
|
784
|
+
for c in (by_table.get(_bare(t)) or {}).get("columns") or [])]
|
|
785
|
+
return (owners[0], col) if len(owners) == 1 else None
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def join_pairs(sql: str, by_table: dict, tables: list[str]) -> list[tuple[tuple[str, str], tuple[str, str]]]:
|
|
789
|
+
"""((table, column), (table, column)) of every `a.x = b.y` between two different tables of the statement (a join
|
|
790
|
+
condition, in ON or WHERE), both qualified."""
|
|
791
|
+
from . import typedparams as TP
|
|
792
|
+
aliases = TP.tables_of(sql)
|
|
793
|
+
out = []
|
|
794
|
+
for m in JOIN_ON.finditer(sql):
|
|
795
|
+
if "." not in m.group("a") or "." not in m.group("b"):
|
|
796
|
+
continue
|
|
797
|
+
a, b = _owner(m.group("a"), aliases, by_table, tables), _owner(m.group("b"), aliases, by_table, tables)
|
|
798
|
+
if a and b and a[0] != b[0]:
|
|
799
|
+
out.append((a, b))
|
|
800
|
+
return out
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
def _join_value(col_type: str):
|
|
804
|
+
"""A key value both sides of a join can hold, and the first generated row of a unique key holds."""
|
|
805
|
+
t = re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", (col_type or "").strip()).lower()
|
|
806
|
+
if t == "uuid":
|
|
807
|
+
return "00000000-0000-4000-8000-000000000001"
|
|
808
|
+
if NUM_TYPE.match(t):
|
|
809
|
+
return 1
|
|
810
|
+
return "codecop-join-1"
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
IS_NULL = re.compile(_QCOL + r"\s+IS\s+NULL\b", re.I)
|
|
814
|
+
SOFT_DELETE = re.compile(r"(?:deleted|archived|removed|discarded|retired|revoked|expired|disabled|terminated)_?(?:at|on|time)$", re.I)
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def null_columns(sql: str, by_table: dict, tables: list[str]) -> list[tuple[str, str]]:
|
|
818
|
+
"""(table, column) of every `col IS NULL` of the statement (not `IS NOT NULL`) whose column one of its tables' profiles has."""
|
|
819
|
+
from . import typedparams as TP
|
|
820
|
+
aliases = TP.tables_of(sql)
|
|
821
|
+
out: list[tuple[str, str]] = []
|
|
822
|
+
for m in IS_NULL.finditer(sql):
|
|
823
|
+
parts = [p.strip('`" ') for p in m.group("col").split(".")]
|
|
824
|
+
col = parts[-1]
|
|
825
|
+
if col.lower() in _NOT_COL:
|
|
826
|
+
continue
|
|
827
|
+
want = [aliases.get(parts[0].lower(), parts[0].lower())] if len(parts) > 1 else tables
|
|
828
|
+
owners = [_bare(t) for t in want if any((c.get("name") or "").lower() == col.lower()
|
|
829
|
+
for c in (by_table.get(_bare(t)) or {}).get("columns") or [])]
|
|
830
|
+
if len(owners) == 1:
|
|
831
|
+
spec = next(c for c in by_table[owners[0]]["columns"] if (c.get("name") or "").lower() == col.lower())
|
|
832
|
+
out.append((owners[0], spec["name"]))
|
|
833
|
+
return list(dict.fromkeys(out))
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def literal_equalities(sql: str, by_table: dict, tables: list[str]) -> list[tuple[str, str, object]]:
|
|
837
|
+
"""(table, column, value) of every `col = 'literal'`, `col = 7` and `col IN ('a', ...)` (its first value) of the
|
|
838
|
+
statement whose column one of its tables' profiles has. `NOT IN` (its column word is `NOT`) and `<>` never match."""
|
|
839
|
+
from . import typedparams as TP
|
|
840
|
+
aliases = TP.tables_of(sql)
|
|
841
|
+
out: list[tuple[str, str, object]] = []
|
|
842
|
+
for rx in (LITERAL_EQ, LITERAL_IN):
|
|
843
|
+
for m in rx.finditer(sql):
|
|
844
|
+
parts = [p.strip('`" ') for p in m.group("col").split(".")]
|
|
845
|
+
col = parts[-1]
|
|
846
|
+
if col.lower() in _NOT_COL:
|
|
847
|
+
continue
|
|
848
|
+
want = [aliases.get(parts[0].lower(), parts[0].lower())] if len(parts) > 1 else tables
|
|
849
|
+
owners = []
|
|
850
|
+
for t in want:
|
|
851
|
+
prof = by_table.get(_bare(t))
|
|
852
|
+
if prof and any((c.get("name") or "").lower() == col.lower() for c in prof.get("columns") or []):
|
|
853
|
+
owners.append(_bare(t))
|
|
854
|
+
if len(owners) != 1:
|
|
855
|
+
continue
|
|
856
|
+
spec = next(c for c in by_table[owners[0]]["columns"] if (c.get("name") or "").lower() == col.lower())
|
|
857
|
+
value: object = m.group("s").replace("''", "'") if m.group("s") is not None else int(m.group("n"))
|
|
858
|
+
out.append((owners[0], spec["name"], value))
|
|
859
|
+
return out
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
UUID_TEXT = re.compile(r"[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}")
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def fits(value, col_type: str) -> bool:
|
|
866
|
+
"""Whether a fixture value is one the column's type holds (unknown type: yes). A value it does not hold (text in an
|
|
867
|
+
integer column, '{}' in a date, '' in json) fails the load of the whole table."""
|
|
868
|
+
t = re.sub(r"^(?:Nullable|LowCardinality)\((.*)\)$", r"\1", (col_type or "").strip()).lower()
|
|
869
|
+
if not t or value is None:
|
|
870
|
+
return True
|
|
871
|
+
text = str(value)
|
|
872
|
+
if NUM_TYPE.match(t):
|
|
873
|
+
return (isinstance(value, (int, float)) and not isinstance(value, bool)) or bool(re.fullmatch(r"-?\d+(?:\.\d+)?", text))
|
|
874
|
+
if t == "uuid":
|
|
875
|
+
return bool(UUID_TEXT.fullmatch(text))
|
|
876
|
+
if t.startswith(("date", "timestamp", "time")):
|
|
877
|
+
return bool(re.match(r"\d{4}-\d{2}-\d{2}", text))
|
|
878
|
+
if t.startswith("json"):
|
|
879
|
+
return text[:1] in "{[" and len(text) > 1
|
|
880
|
+
if t.startswith("bool"):
|
|
881
|
+
return text.lower() in ("true", "false", "1", "0", "t", "f")
|
|
882
|
+
return True
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def _fixtures(cand: dict, by_table: dict, lcfg: dict) -> None:
|
|
886
|
+
"""The equality values of the statement on a few rows of the table each filters, so it selects rows."""
|
|
887
|
+
per: dict[str, list[dict]] = {}
|
|
888
|
+
for name, p in (cand.get("baseline_params") or {}).items():
|
|
889
|
+
if p.get("op") not in ("=", "==", "in") or not p.get("column") or not p.get("table"):
|
|
890
|
+
continue
|
|
891
|
+
t = by_table.get(_bare(p["table"]))
|
|
892
|
+
if t is None:
|
|
893
|
+
continue
|
|
894
|
+
spec = next((c for c in t.get("columns") or [] if c.get("name", "").lower() == p["column"].lower()), None)
|
|
895
|
+
value = cand["params"].get(name)
|
|
896
|
+
if isinstance(value, str) and value.startswith(("{", "[")):
|
|
897
|
+
inner = value[1:-1].strip().strip("'")
|
|
898
|
+
value = int(inner) if re.fullmatch(r"-?\d+", inner) else inner
|
|
899
|
+
if (spec or {}).get("kind") == "unique" and str(p.get("type", "")).lower() in ("uuid",):
|
|
900
|
+
continue # one row per value: the generator writes this one
|
|
901
|
+
if any(v["column"] == (spec or {}).get("name", p["column"]) for v in per.get(_bare(p["table"]), [])):
|
|
902
|
+
continue
|
|
903
|
+
if not fits(value, ((cand.get("_column_types") or {}).get(_bare(p["table"])) or {}).get(p["column"].lower(), "")):
|
|
904
|
+
continue # a value the column's type does not hold would fail the whole table's load
|
|
905
|
+
per.setdefault(_bare(p["table"]), []).append({"column": (spec or {}).get("name") or p["column"], "value": value})
|
|
906
|
+
# the statement's own literals too (`status = 'queued'`, `name IN ('admin', ...)`, `kind = 3`): generated data rarely
|
|
907
|
+
# holds the code's words, so a filter on one would select nothing and the baseline would read no row
|
|
908
|
+
for t, col, value in literal_equalities(cand.get("baseline_sql") or "", by_table, [_bare(x) for x in cand.get("tables") or []]):
|
|
909
|
+
if any(v["column"].lower() == col.lower() for v in per.get(t, [])):
|
|
910
|
+
continue
|
|
911
|
+
if not fits(value, ((cand.get("_column_types") or {}).get(t) or {}).get(col.lower(), "")):
|
|
912
|
+
continue
|
|
913
|
+
per.setdefault(t, []).append({"column": col, "value": value})
|
|
914
|
+
# `JOIN b ON b.a_id = a.id`: the fixture rows of the two tables hold one key value, or the join pairs none of them
|
|
915
|
+
for (t1, c1), (t2, c2) in join_pairs(cand.get("baseline_sql") or "", by_table, [_bare(x) for x in cand.get("tables") or []]):
|
|
916
|
+
types1 = ((cand.get("_column_types") or {}).get(t1) or {}).get(c1.lower(), "")
|
|
917
|
+
have = next((v["value"] for v in per.get(t1, []) if v["column"].lower() == c1.lower()), None)
|
|
918
|
+
have = have if have is not None else next((v["value"] for v in per.get(t2, []) if v["column"].lower() == c2.lower()), None)
|
|
919
|
+
value = have if have is not None else _join_value(types1 or ((cand.get("_column_types") or {}).get(t2) or {}).get(c2.lower(), ""))
|
|
920
|
+
for t, c in ((t1, c1), (t2, c2)):
|
|
921
|
+
spec = next((x for x in by_table[t].get("columns") or [] if (x.get("name") or "").lower() == c.lower()), None)
|
|
922
|
+
if (spec or {}).get("kind") == "unique":
|
|
923
|
+
continue # one row per value: the generator's first row holds it (_join_value takes that value)
|
|
924
|
+
if any(v["column"].lower() == c.lower() for v in per.get(t, [])):
|
|
925
|
+
continue
|
|
926
|
+
if fits(value, ((cand.get("_column_types") or {}).get(t) or {}).get(c.lower(), "")):
|
|
927
|
+
per.setdefault(t, []).append({"column": (spec or {}).get("name") or c, "value": value})
|
|
928
|
+
# `deleted_at IS NULL`, `organization_id IS NULL`: the fixture rows hold NULL there, or they never satisfy the rest of
|
|
929
|
+
# the statement ("parameters match no rows"); a soft-delete column is mostly NULL anyway
|
|
930
|
+
for t, col in null_columns(cand.get("baseline_sql") or "", by_table, [_bare(x) for x in cand.get("tables") or []]):
|
|
931
|
+
typ = ((cand.get("_column_types") or {}).get(t) or {}).get(col.lower(), "")
|
|
932
|
+
if typ.startswith(("UInt", "Int", "String", "DateTime", "Date", "UUID", "LowCardinality(String", "Float", "Bool", "Array", "Map")):
|
|
933
|
+
continue # a ClickHouse column that is not Nullable holds no NULL: the predicate never holds
|
|
934
|
+
if any(v["column"].lower() == col.lower() for v in per.get(t, [])):
|
|
935
|
+
continue
|
|
936
|
+
per.setdefault(t, []).append({"column": col, "value": None})
|
|
937
|
+
spec = next((c for c in by_table[t].get("columns") or [] if (c.get("name") or "").lower() == col.lower()), None)
|
|
938
|
+
if spec is not None and SOFT_DELETE.search(col):
|
|
939
|
+
spec["null_fraction"] = max(float(spec.get("null_fraction") or 0), 0.9)
|
|
940
|
+
for t, values in per.items():
|
|
941
|
+
by_table[t].setdefault("fixtures", []).append({"id": cand["finding"], "values": values, "share": float(lcfg["fixture_share"]),
|
|
942
|
+
"min_rows": int(lcfg["fixture_min_rows"]),
|
|
943
|
+
"basis": "baseline pass: the statement's parameter values on a few rows"})
|
|
944
|
+
# `status IN ('queued', 'running', 'suspended')`: the second and third values too, each on rows of their own with the
|
|
945
|
+
# statement's other values, so the list selects more than one value's rows
|
|
946
|
+
for t, col, more in literal_in_extras(cand.get("baseline_sql") or "", by_table, [_bare(x) for x in cand.get("tables") or []]):
|
|
947
|
+
base_values = per.get(t) or []
|
|
948
|
+
for i, v in enumerate(more[:IN_EXTRA_VALUES], start=2):
|
|
949
|
+
if not fits(v, ((cand.get("_column_types") or {}).get(t) or {}).get(col.lower(), "")):
|
|
950
|
+
continue
|
|
951
|
+
vals = [x for x in base_values if x["column"].lower() != col.lower()] + [{"column": col, "value": v}]
|
|
952
|
+
by_table[t].setdefault("fixtures", []).append({"id": f"{cand['finding']}#{i}", "values": vals,
|
|
953
|
+
"share": float(lcfg["fixture_share"]), "min_rows": int(lcfg["fixture_min_rows"]),
|
|
954
|
+
"basis": "baseline pass: another value of the statement's IN list"})
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
# ---------------------------------------------------------------------------- the stage file
|
|
958
|
+
|
|
959
|
+
def load(out_dir: Path) -> dict | None:
|
|
960
|
+
try:
|
|
961
|
+
return json.loads((Path(out_dir) / FILE).read_text())
|
|
962
|
+
except (OSError, ValueError):
|
|
963
|
+
return None
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def gate_of(out_dir: Path) -> dict:
|
|
967
|
+
"""finding -> the plan gate's last result for it ({ok, class, reason, error, fingerprint})."""
|
|
968
|
+
return ((load(out_dir) or {}).get("gate") or {})
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
def save(out_dir: Path, doc: dict, gate: dict | None = None) -> None:
|
|
972
|
+
"""baseline.json: the pass's statements and, merged over the file's earlier results, the plan gate's."""
|
|
973
|
+
prev = load(out_dir) or {}
|
|
974
|
+
merged = dict(prev.get("gate") or {})
|
|
975
|
+
merged.update(gate or {})
|
|
976
|
+
doc = {**doc, "gate": merged}
|
|
977
|
+
if gate:
|
|
978
|
+
for e in doc.get("statements") or []:
|
|
979
|
+
g = merged.get(e.get("finding"))
|
|
980
|
+
if e.get("state") == "candidate" and g and not g.get("ok"):
|
|
981
|
+
e.update(state="does_not_plan", reason=g.get("reason") or "does_not_plan", error_class=g.get("class"),
|
|
982
|
+
detail=(g.get("error") or "")[:300])
|
|
983
|
+
doc["summary"] = summary(doc)
|
|
984
|
+
(Path(out_dir) / FILE).write_text(json.dumps(doc, indent=1, ensure_ascii=False))
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
def summary(doc: dict) -> dict:
|
|
988
|
+
st = doc.get("statements") or []
|
|
989
|
+
states = Counter(e.get("state") for e in st)
|
|
990
|
+
reasons = Counter(e.get("reason") for e in st if e.get("state") not in ("candidate",)) + Counter((doc.get("skipped") or {}).values())
|
|
991
|
+
classes = Counter(e.get("error_class") for e in st if e.get("state") == "does_not_plan" and e.get("error_class"))
|
|
992
|
+
return {"statements": len(st), "sites": sum(len(e.get("site_ids") or []) for e in st), "states": dict(states),
|
|
993
|
+
"reasons": dict(reasons.most_common()), "does_not_plan": dict(classes.most_common())}
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def plan_marks(doc: dict | None) -> dict[str, dict]:
|
|
997
|
+
"""call-site id -> `plan` for the inventory (coverage.py's plan-gate hook): {ok: True} for a statement that planned,
|
|
998
|
+
{ok: False, reason, class} for one that did not plan or whose parameter nothing types."""
|
|
999
|
+
gate = (doc or {}).get("gate") or {}
|
|
1000
|
+
out: dict[str, dict] = {}
|
|
1001
|
+
for e in (doc or {}).get("statements") or []:
|
|
1002
|
+
mark = None
|
|
1003
|
+
if e.get("state") == "does_not_plan":
|
|
1004
|
+
mark = {"ok": False, "reason": "table_not_pulled" if e.get("reason") == "table_not_pulled" else "does_not_plan",
|
|
1005
|
+
"class": e.get("error_class") or ("table_not_pulled" if e.get("reason") == "table_not_pulled" else "other")}
|
|
1006
|
+
elif e.get("state") == "not_measured" and e.get("reason") == "parameter_not_typed":
|
|
1007
|
+
mark = {"ok": False, "reason": "parameter_not_typed", "class": "stand_in_type"}
|
|
1008
|
+
elif e.get("state") == "candidate" and (gate.get(e.get("finding")) or {}).get("ok"):
|
|
1009
|
+
mark = {"ok": True}
|
|
1010
|
+
if mark is not None:
|
|
1011
|
+
mark["finding"] = e.get("finding")
|
|
1012
|
+
for sid in e.get("site_ids") or []:
|
|
1013
|
+
if not (out.get(str(sid)) or {}).get("ok"): # one variant of a family that plans is enough
|
|
1014
|
+
out[str(sid)] = mark
|
|
1015
|
+
return out
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
# ---------------------------------------------------------------------------- outcomes of what was not measured
|
|
1019
|
+
|
|
1020
|
+
NEXT_STEP = {"table_not_pulled": "pull_its_database", "table_in_other_database": "pull_its_database",
|
|
1021
|
+
"column": "update_definition", "piece": "attach_piece_to_statement", "template_text": "none_codecop_side",
|
|
1022
|
+
"stand_in_type": "typed_parameters", "parameter_not_typed": "typed_parameters", "run_time_parts_in_text": "statement_families",
|
|
1023
|
+
"no_statement_text": "statement_families", "does_not_parse": "none_codecop_side", "no_table_definition": "pull_its_database",
|
|
1024
|
+
"other": "none_codecop_side"}
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def unjudged(doc: dict | None) -> list[dict]:
|
|
1028
|
+
"""One not-judged outcome per call site the pass could not measure, with one reason and one next step:
|
|
1029
|
+
[{id, state, reason, from, evidence: {class, detail, finding, next_step}}]."""
|
|
1030
|
+
out = []
|
|
1031
|
+
for e in (doc or {}).get("statements") or []:
|
|
1032
|
+
if e.get("state") not in ("does_not_plan", "not_measured") or e.get("family_variant"):
|
|
1033
|
+
continue # a family's variant: the family's roll-up says what happened to its site
|
|
1034
|
+
reason = "does_not_plan" if e["state"] == "does_not_plan" and e.get("reason") != "table_not_pulled" else (e.get("reason") or "does_not_plan")
|
|
1035
|
+
# the shared vocabulary's codes (coverage_reasons.py)
|
|
1036
|
+
reason = {"run_time_parts_in_text": "run_time_parts", "no_table_definition": "table_not_pulled"}.get(reason, reason)
|
|
1037
|
+
cls = e.get("error_class") or e.get("reason") or "other"
|
|
1038
|
+
for sid in e.get("site_ids") or []:
|
|
1039
|
+
out.append({"id": sid, "state": "not_judged", "reason": reason, "from": "sandbox" if e["state"] == "does_not_plan" else "run",
|
|
1040
|
+
"file": (e.get("site") or {}).get("file", ""), "line": (e.get("site") or {}).get("line", 0),
|
|
1041
|
+
"evidence": {"class": cls, "finding": e.get("finding"), "detail": (e.get("detail") or "")[:200],
|
|
1042
|
+
"next_step": NEXT_STEP.get(cls, "none_codecop_side")}})
|
|
1043
|
+
return out
|