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/sqlinfo.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
"""SQL analysis shared by every language: statement kind, tables, engine guess,
|
|
2
|
+
cheap heuristic flags and the stable fingerprint. No LLM, no database."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import hashlib
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
import sqlglot
|
|
12
|
+
from sqlglot import exp
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
logging.getLogger("sqlglot").setLevel(logging.ERROR)
|
|
16
|
+
|
|
17
|
+
PLACEHOLDER = re.compile(r"«[^»]*»") # a run-time part of a SQL template (same marker as discover.base)
|
|
18
|
+
|
|
19
|
+
CLICKHOUSE = re.compile(
|
|
20
|
+
r"\bFINAL\b|\bPREWHERE\b|\{\w+\s*:\s*[A-Z][\w() ,]*\}|\bENGINE\s*=|\btoStartOf\w+\(|\btoYYYYMM|\barrayJoin\(|"
|
|
21
|
+
r"\buniq(?:Exact|Combined)?\(|\bSETTINGS\s+\w+\s*=|\bcountIf\(|\bsumIf\(|\bargMax\(|\bargMin\(|\bsystem\.\w+|"
|
|
22
|
+
r"\bFORMAT\s+(?:JSON|TSV|CSV|Vertical)|\bLowCardinality\(|\btoDate(?:Time)?(?:64)?\(|\bALTER\s+TABLE\s+\S+\s+(?:UPDATE|DELETE)\b|"
|
|
23
|
+
r"\bOPTIMIZE\s+TABLE\b|\bquantile\w*\(|\bJSONExtract\w*\(|\bgroupArray\(|\bARRAY\s+JOIN\b|\bLIMIT\s+\d+\s+BY\b|"
|
|
24
|
+
r"\bGLOBAL\s+(?:(?:ANY|ALL|ASOF|SEMI|ANTI|INNER|LEFT|RIGHT|FULL|OUTER|CROSS)\s+)*JOIN\b|\bGLOBAL\s+(?:NOT\s+)?IN\b|"
|
|
25
|
+
r"\bWITH\s+TOTALS\b|\bcurrentDatabase\(\)|\bON\s+CLUSTER\b|\bNullable\(|"
|
|
26
|
+
# functions only ClickHouse has (a statement in a project with ClickHouse and another store, no other evidence)
|
|
27
|
+
r"\bformatDateTime\(|\btoString\(|\bto(?:U?Int(?:8|16|32|64)|Float(?:32|64)|UUID|Decimal\d+|UnixTimestamp)\(|"
|
|
28
|
+
r"\bfromUnixTimestamp\w*\(|\banyLast\(|\bgroupUniqArray\(|\barray(?:Map|Filter|Exists|Sort|Distinct|StringConcat)\(|"
|
|
29
|
+
r"\bsumMap\(|\bmapKeys\(|\btupleElement\(|\buniqHLL12\(|\btoIntervalDay\(|\bmultiIf\(|\bsimpleJSONExtract\w*\(",
|
|
30
|
+
re.I,
|
|
31
|
+
)
|
|
32
|
+
POSTGRES = re.compile(r"\$\d+\b|::\w+|\bRETURNING\b|\bILIKE\b|\bON\s+CONFLICT\b|\bpg_\w+|\bFOR\s+UPDATE\b|\bjsonb\w*\b|\bNOW\(\)\s*-\s*INTERVAL\s+'", re.I)
|
|
33
|
+
# A cast to a type only ClickHouse has (`x::Nullable(String)`, `n::UInt32`): ClickHouse evidence, and not the
|
|
34
|
+
# Postgres evidence a `::` cast otherwise is. Case-sensitive: Postgres writes `::int8`, ClickHouse `::Int8`.
|
|
35
|
+
CLICKHOUSE_CAST = re.compile(r"::(?:Nullable|LowCardinality|UInt(?:8|16|32|64|128|256)|Int(?:8|16|32|64|128|256)|Float(?:32|64)|"
|
|
36
|
+
r"String|FixedString|DateTime(?:64)?|Date32|Array|Map|Tuple)\b")
|
|
37
|
+
# MySQL and MariaDB only: full-text MATCH ... AGAINST, upserts, index hints, storage engines.
|
|
38
|
+
MYSQL = re.compile(
|
|
39
|
+
r"\bMATCH\s*\((?:[^()]|\([^()]*\))*\)\s*AGAINST\s*\(|\bON\s+DUPLICATE\s+KEY\s+UPDATE\b|\bSTRAIGHT_JOIN\b|\bINSERT\s+IGNORE\b|"
|
|
40
|
+
r"\bLOCK\s+IN\s+SHARE\s+MODE\b|\bSQL_CALC_FOUND_ROWS\b|\b(?:FORCE|USE|IGNORE)\s+INDEX\s*\(|"
|
|
41
|
+
r"\bENGINE\s*=\s*(?:InnoDB|MyISAM|Aria)\b|\bAUTO_INCREMENT\b|\bCHARACTER\s+SET\s+utf8", re.I)
|
|
42
|
+
MYSQL_STORAGE = re.compile(r"\bENGINE\s*=\s*(?:InnoDB|MyISAM|Aria)\b", re.I)
|
|
43
|
+
# Postgres-looking syntax that the named engine accepts too: not evidence against a call that is known to go
|
|
44
|
+
# to that engine (SQLite has RETURNING and ON CONFLICT; MySQL has FOR UPDATE; ClickHouse has `::` casts).
|
|
45
|
+
SHARED_WITH_POSTGRES = {
|
|
46
|
+
"clickhouse": re.compile(r"::\w+", re.I),
|
|
47
|
+
"sqlite": re.compile(r"\$\d+\b|\bRETURNING\b|\bON\s+CONFLICT\b", re.I),
|
|
48
|
+
"mysql": re.compile(r"\bFOR\s+UPDATE\b|\bNOW\(\)\s*-\s*INTERVAL\s+'", re.I),
|
|
49
|
+
}
|
|
50
|
+
# More of the same for ClickHouse, counted only when the call's own receiver names ClickHouse
|
|
51
|
+
# (`chConn.Select`): clickhouse-go binds `$1`, but a file that imports the ClickHouse driver may
|
|
52
|
+
# still send `$1` to Postgres through another client, so the file's imports alone do not excuse it.
|
|
53
|
+
SHARED_WITH_POSTGRES_BY_RECEIVER = {
|
|
54
|
+
"clickhouse": re.compile(r"\$\d+\b|::\w+|\bILIKE\b|\bNOW\(\)\s*-\s*INTERVAL\s+'", re.I),
|
|
55
|
+
}
|
|
56
|
+
# Syntax ClickHouse does not have: a statement written with it does not run there, whatever table it names.
|
|
57
|
+
NOT_CLICKHOUSE = re.compile(r"\bON\s+CONFLICT\b|\bRETURNING\b|\bFOR\s+UPDATE\b|\bPRAGMA\b|\bAUTOINCREMENT\b|"
|
|
58
|
+
r"\bINSERT\s+OR\s+(?:REPLACE|IGNORE)\b|\bON\s+DUPLICATE\s+KEY\b|\bSERIAL\b", re.I)
|
|
59
|
+
SQLITE = re.compile(r"\bPRAGMA\b|\bsqlite_master\b|\bAUTOINCREMENT\b|\bINSERT\s+OR\s+(?:REPLACE|IGNORE)\b|\bWITHOUT\s+ROWID\b|\bstrftime\(", re.I)
|
|
60
|
+
|
|
61
|
+
KIND_RE = re.compile(r"^\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(\w+)(?:\s+(\w+))?", re.S)
|
|
62
|
+
FROM_RE = re.compile(r"\b(?:FROM|JOIN|INTO|UPDATE|TABLE(?:\s+IF\s+(?:NOT\s+)?EXISTS)?)\s+((?:[\w`\"]+|«[^»]*»)(?:\.(?:[\w`\"]+|«[^»]*»))?)", re.I)
|
|
63
|
+
NOT_TABLES = {"select", "set", "values", "if", "final", "where", "lateral", "unnest", "exists", "only", "numbers", "as", "function"}
|
|
64
|
+
CTE_RE = re.compile(r"(?:\bWITH\s+(?:RECURSIVE\s+)?|,\s*)([A-Za-z_]\w*)\s*(?:\([\w\s,]*\)\s*)?AS\s+(?:(?:NOT\s+)?MATERIALIZED\s+)?\(", re.I)
|
|
65
|
+
# `x IS DISTINCT FROM y` and `extract(epoch FROM col)` use FROM without naming a table
|
|
66
|
+
FROM_NOISE = re.compile(r"\bDISTINCT\s+FROM\b|\b(?:extract|substring|trim|overlay|position)\s*\([^()]*?\bFROM\b", re.I)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _strip_text(sql: str) -> str:
|
|
70
|
+
"""Comments and string literals removed: prose in them is not SQL."""
|
|
71
|
+
s = re.sub(r"--[^\n]*", " ", sql)
|
|
72
|
+
s = re.sub(r"/\*.*?\*/", " ", s, flags=re.S)
|
|
73
|
+
held: list[str] = []
|
|
74
|
+
|
|
75
|
+
def hold(m: re.Match) -> str: # a run-time part may contain quotes of its own
|
|
76
|
+
held.append(m.group(0))
|
|
77
|
+
return f"\x00{len(held) - 1}\x00"
|
|
78
|
+
|
|
79
|
+
s = re.sub(r"'(?:[^'\\]|\\.|'')*'", "''", PLACEHOLDER.sub(hold, s))
|
|
80
|
+
return re.sub(r"\x00(\d+)\x00", lambda m: held[int(m.group(1))], s)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def fallback_tables(sql: str) -> tuple[list[str], list[str]]:
|
|
84
|
+
"""(tables, CTE names) by pattern, for a statement no parser accepts."""
|
|
85
|
+
text = FROM_NOISE.sub(" ", _strip_text(sql))
|
|
86
|
+
ctes = [m.group(1) for m in CTE_RE.finditer(text)]
|
|
87
|
+
lowered = {c.lower() for c in ctes}
|
|
88
|
+
seen: list[str] = []
|
|
89
|
+
for m in FROM_RE.finditer(text):
|
|
90
|
+
reads = m.group(0).split(None, 1)[0].upper() in ("FROM", "JOIN")
|
|
91
|
+
if reads and text[m.end():].lstrip().startswith("("): # FROM jsonb_to_recordset(...): a function, not a table
|
|
92
|
+
continue
|
|
93
|
+
name = m.group(1).replace("`", "").replace('"', "")
|
|
94
|
+
if name.lower() in NOT_TABLES or name.lower() in lowered or name in seen:
|
|
95
|
+
continue
|
|
96
|
+
seen.append(name)
|
|
97
|
+
return seen, ctes
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass
|
|
101
|
+
class SqlInfo:
|
|
102
|
+
kind: str = "other" # select | insert | update | delete | ddl | other
|
|
103
|
+
tables: list[str] = field(default_factory=list)
|
|
104
|
+
ctes: list[str] = field(default_factory=list) # names this statement defines with WITH: never tables
|
|
105
|
+
flags: list[str] = field(default_factory=list)
|
|
106
|
+
engine: str = "" # clickhouse | postgres | sqlite | mysql | "" (unknown); cypher, jpql are not SQL
|
|
107
|
+
# How the engine was decided. Per statement: sql (dialect syntax) | hint (sink rule or the file's driver
|
|
108
|
+
# imports) | receiver (the callee's receiver names the engine) | path (a directory names it) | table (the
|
|
109
|
+
# tables it reads are defined for that engine). Project-wide, never a per-statement guess: default (set in
|
|
110
|
+
# codecop.toml or --default-engine) | inferred (the project's drivers, migrations and config agree on one engine).
|
|
111
|
+
engine_basis: str = ""
|
|
112
|
+
parse_ok: bool = False
|
|
113
|
+
normalized: str = ""
|
|
114
|
+
sql_hash: str = "" # fingerprint of the SQL alone: matches query logs across call sites
|
|
115
|
+
# The same, from the text alone (comments out, literals and numbers replaced, whitespace collapsed): it does
|
|
116
|
+
# not depend on the engine label, so correcting a label later does not change it. `sql_hash` is written in
|
|
117
|
+
# the engine's dialect and does.
|
|
118
|
+
text_hash: str = ""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
NON_SQL = ("cypher", "jpql")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def guess_engine(sql: str, hint: str, by_receiver: bool = False) -> tuple[str, str]:
|
|
125
|
+
"""SQL features beat the sink or import hint, because one file often talks to two stores.
|
|
126
|
+
|
|
127
|
+
Only features that tell the engines apart count: syntax the hinted engine shares with Postgres does not
|
|
128
|
+
turn a ClickHouse, SQLite or MySQL call into a Postgres one. `by_receiver`: the hint is the receiver of
|
|
129
|
+
this very call, which excuses more than a hint about the whole file."""
|
|
130
|
+
if hint in NON_SQL:
|
|
131
|
+
return hint, "hint" # Cypher and JPQL are not SQL: the sink decides, never the text
|
|
132
|
+
ch, pg, lite = len(CLICKHOUSE.findall(sql)), len(POSTGRES.findall(sql)), len(SQLITE.findall(sql))
|
|
133
|
+
my = len(MYSQL.findall(sql))
|
|
134
|
+
ch -= len(MYSQL_STORAGE.findall(sql)) # ENGINE = InnoDB is not a ClickHouse table engine
|
|
135
|
+
casts = len(CLICKHOUSE_CAST.findall(sql))
|
|
136
|
+
ch, pg = ch + casts, pg - casts
|
|
137
|
+
shared = (SHARED_WITH_POSTGRES_BY_RECEIVER.get(hint) if by_receiver else None) or SHARED_WITH_POSTGRES.get(hint)
|
|
138
|
+
if shared is not None:
|
|
139
|
+
pg -= len(shared.findall(sql))
|
|
140
|
+
best = max(ch, pg, lite, my)
|
|
141
|
+
if best > 0:
|
|
142
|
+
top = [name for name, n in (("clickhouse", ch), ("postgres", pg), ("sqlite", lite), ("mysql", my)) if n == best]
|
|
143
|
+
if len(top) == 1:
|
|
144
|
+
return top[0], "sql"
|
|
145
|
+
return (hint, "hint") if hint else ("", "")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# A table name that a template fills in at run time, in a form no extractor can evaluate: `@@table_logs@@`
|
|
149
|
+
# (replaced by the program), `{{.Table}}` / `{{ table }}` (Go templates, Jinja), `${table}` (shells, Kotlin, JS).
|
|
150
|
+
TEMPLATE_TOKEN = re.compile(r"@@(\w+)@@|\{\{-?\s*\.?([\w.]+)\s*-?\}\}|\$\{([\w.]+)\}")
|
|
151
|
+
# `{table}` (str.format) only where a table is named: single braces are also ClickHouse parameters and JSON.
|
|
152
|
+
BRACE_TABLE = re.compile(r"(\b(?:FROM|JOIN|INTO|UPDATE|TABLE(?:\s+IF\s+(?:NOT\s+)?EXISTS)?)\s+(?:[\w`\"]+\.)?)\{(\w+)\}", re.I)
|
|
153
|
+
_AFFIX = re.compile(r"^(?:table|tbl|tb)_|_(?:table|tbl|table_name|tablename|tbl_name)$", re.I)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def template_name_candidates(inner: str) -> list[str]:
|
|
157
|
+
"""Names a template token may stand for: `table_otel_logs` -> otel_logs, `.LogsTable` -> logs."""
|
|
158
|
+
last = inner.split(".")[-1]
|
|
159
|
+
snake = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", last).lower()
|
|
160
|
+
out: list[str] = []
|
|
161
|
+
for name in (inner, last, snake):
|
|
162
|
+
for cand in (name, _AFFIX.sub("", name), _AFFIX.sub("", _AFFIX.sub("", name))):
|
|
163
|
+
if cand and cand not in out:
|
|
164
|
+
out.append(cand)
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def has_template_tokens(sql: str) -> bool:
|
|
169
|
+
return bool(TEMPLATE_TOKEN.search(sql) or BRACE_TABLE.search(sql))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
_TABLE_POSITION = re.compile(r"\b(?:FROM|JOIN|INTO|UPDATE|TABLE(?:\s+IF\s+(?:NOT\s+)?EXISTS)?)\s+(?:[\w`\"]+\.)?$", re.I)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def resolve_template_tokens(sql: str, lookup) -> tuple[str, dict[str, str]]:
|
|
176
|
+
"""Rewrite template tokens. Where a table is named (after FROM, JOIN, INTO, UPDATE, TABLE) the token becomes
|
|
177
|
+
the table name when `lookup(candidates)` knows it; every other token becomes a run-time part «token».
|
|
178
|
+
Returns the rewritten SQL and {token: table name} for the ones that were resolved."""
|
|
179
|
+
resolved: dict[str, str] = {}
|
|
180
|
+
|
|
181
|
+
def swap(token: str, inner: str, before: str) -> str:
|
|
182
|
+
name = lookup(template_name_candidates(inner)) if _TABLE_POSITION.search(before[-80:]) else None
|
|
183
|
+
if name:
|
|
184
|
+
resolved[token] = name
|
|
185
|
+
return name
|
|
186
|
+
return "«" + token.replace("»", ">") + "»"
|
|
187
|
+
|
|
188
|
+
out = BRACE_TABLE.sub(lambda m: m.group(1) + swap("{" + m.group(2) + "}", m.group(2), m.group(1)), sql)
|
|
189
|
+
out = TEMPLATE_TOKEN.sub(lambda m: swap(m.group(0), next(g for g in m.groups() if g), m.string[:m.start()]), out)
|
|
190
|
+
return out, resolved
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def to_parsable(sql: str) -> tuple[str, list[str]]:
|
|
194
|
+
"""Swap run-time parts for identifiers so a parser accepts the template."""
|
|
195
|
+
holes: list[str] = []
|
|
196
|
+
|
|
197
|
+
def hole(m: re.Match) -> str:
|
|
198
|
+
holes.append(m.group(0))
|
|
199
|
+
return f"__qp{len(holes) - 1}__"
|
|
200
|
+
|
|
201
|
+
out = PLACEHOLDER.sub(hole, sql)
|
|
202
|
+
out = re.sub(r"%\((\w+)\)s", r"__p_\1__", out) # pyformat driver params
|
|
203
|
+
out = re.sub(r"(?<![%\w])%s\b", "?", out)
|
|
204
|
+
out = re.sub(r"(?<![\w?])\?(\d+)\b", r"$\1", out) # SQLite numbered parameters (`?1`): sqlglot reads them as `$1`
|
|
205
|
+
out = re.sub(r"(\$\d+),(?=\$)", r"\1, ", out) # sqlglot cannot tokenize "$1,$2" without a space
|
|
206
|
+
return out, holes
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _kind_regex(sql: str) -> str:
|
|
210
|
+
m = KIND_RE.match(sql)
|
|
211
|
+
first = (m.group(1) if m else "").upper()
|
|
212
|
+
second = (m.group(2) or "").upper() if m else ""
|
|
213
|
+
if first in ("SELECT", "WITH"):
|
|
214
|
+
return "select"
|
|
215
|
+
if first == "INSERT":
|
|
216
|
+
return "insert"
|
|
217
|
+
if first == "UPDATE":
|
|
218
|
+
return "update"
|
|
219
|
+
if first == "DELETE":
|
|
220
|
+
return "delete"
|
|
221
|
+
if first == "ALTER" and re.search(r"\b(UPDATE|DELETE)\b", sql, re.I):
|
|
222
|
+
return "update" if re.search(r"\bUPDATE\b", sql, re.I) else "delete"
|
|
223
|
+
if first in ("CREATE", "ALTER", "DROP", "TRUNCATE", "RENAME") or (first, second) == ("OPTIMIZE", "TABLE"):
|
|
224
|
+
return "ddl"
|
|
225
|
+
return "other"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _restore(name: str, holes: list[str]) -> str:
|
|
229
|
+
return re.sub(r"__qp(\d+)__", lambda m: holes[int(m.group(1))] if int(m.group(1)) < len(holes) else m.group(0), name)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _normalize_text(sql: str) -> str:
|
|
233
|
+
s = re.sub(r"--[^\n]*", " ", sql)
|
|
234
|
+
s = re.sub(r"/\*.*?\*/", " ", s, flags=re.S)
|
|
235
|
+
s = re.sub(r"'(?:[^'\\]|\\.|'')*'", "?", s)
|
|
236
|
+
s = re.sub(r"\b\d+(?:\.\d+)?\b", "?", s)
|
|
237
|
+
s = re.sub(r"\s+", " ", s).strip().rstrip(";")
|
|
238
|
+
return s
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def parse_tree(sql: str, engine: str = "") -> tuple[exp.Expression | None, list[str]]:
|
|
242
|
+
"""The parsed statement, as `analyze` parses it (run-time parts held as `__qpN__` identifiers, a whole optional
|
|
243
|
+
clause dropped when that is what makes it parse), and the held parts. (None, holes) when no attempt parses."""
|
|
244
|
+
if engine in NON_SQL:
|
|
245
|
+
return None, []
|
|
246
|
+
parsable, holes = to_parsable(sql)
|
|
247
|
+
dialects = [engine] if engine in ("clickhouse", "postgres", "sqlite", "mysql") else ["clickhouse", "postgres"]
|
|
248
|
+
attempts = [(d, parsable) for d in dialects]
|
|
249
|
+
if holes:
|
|
250
|
+
optional = [i for i, h in enumerate(holes) if h.startswith(("«if(", "«or:"))]
|
|
251
|
+
if optional and len(optional) < len(holes):
|
|
252
|
+
attempts += [(d, re.sub(r"__qp(?:%s)__" % "|".join(map(str, optional)), " ", parsable)) for d in dialects]
|
|
253
|
+
attempts += [(d, re.sub(r"(?<=\s)__qp\d+__(?=\s|$)", " ", parsable)) for d in dialects]
|
|
254
|
+
for dialect, text in attempts:
|
|
255
|
+
try:
|
|
256
|
+
tree = next((p for p in sqlglot.parse(text, read=dialect) if p is not None), None)
|
|
257
|
+
except Exception: # any parser failure: try the next attempt
|
|
258
|
+
continue
|
|
259
|
+
if tree is not None and not isinstance(tree, exp.Command):
|
|
260
|
+
# run-time parts this attempt left out of the tree: nothing in it says where they were
|
|
261
|
+
tree.meta["dropped_holes"] = len(holes) - len(set(re.findall(r"__qp(\d+)__", text)))
|
|
262
|
+
return tree, holes
|
|
263
|
+
return None, holes
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def restore(name: str, holes: list[str]) -> str:
|
|
267
|
+
"""Put the held run-time parts back into text a parsed tree printed."""
|
|
268
|
+
return _restore(name, holes)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def analyze(sql: str, engine_hint: str = "", in_loop: bool = False) -> SqlInfo:
|
|
272
|
+
info = SqlInfo()
|
|
273
|
+
info.engine, info.engine_basis = guess_engine(sql, engine_hint)
|
|
274
|
+
parsable, holes = to_parsable(sql)
|
|
275
|
+
tree = None
|
|
276
|
+
dialects = [info.engine] if info.engine in ("clickhouse", "postgres", "sqlite", "mysql") else ["clickhouse", "postgres"]
|
|
277
|
+
# A run-time part that stands for a whole optional clause ("... = true «filters» GROUP BY") does not
|
|
278
|
+
# parse as an identifier, so the second attempt drops the run-time parts that follow whitespace.
|
|
279
|
+
attempts = [] if info.engine in NON_SQL else [(d, parsable) for d in dialects]
|
|
280
|
+
if holes and info.engine not in NON_SQL:
|
|
281
|
+
# A conditional part («if(c): AND x = :x», «or: ...») is a whole optional clause: the statement stands
|
|
282
|
+
# without it, while the other run-time parts (a column list, a value) must stay to keep it a statement.
|
|
283
|
+
optional = [i for i, h in enumerate(holes) if h.startswith(("«if(", "«or:"))]
|
|
284
|
+
if optional and len(optional) < len(holes):
|
|
285
|
+
attempts += [(d, re.sub(r"__qp(?:%s)__" % "|".join(map(str, optional)), " ", parsable)) for d in dialects]
|
|
286
|
+
attempts += [(d, re.sub(r"(?<=\s)__qp\d+__(?=\s|$)", " ", parsable)) for d in dialects]
|
|
287
|
+
for dialect, text in attempts:
|
|
288
|
+
try:
|
|
289
|
+
parsed = sqlglot.parse(text, read=dialect)
|
|
290
|
+
tree = next((p for p in parsed if p is not None), None)
|
|
291
|
+
if tree is not None and not isinstance(tree, exp.Command):
|
|
292
|
+
info.parse_ok = True
|
|
293
|
+
parsable = text
|
|
294
|
+
break
|
|
295
|
+
except Exception: # sqlglot raises several error types; any failure means "use the fallback"
|
|
296
|
+
tree = None
|
|
297
|
+
|
|
298
|
+
flags: set[str] = set()
|
|
299
|
+
if info.parse_ok and tree is not None:
|
|
300
|
+
root = tree.this if isinstance(tree, exp.With) else tree
|
|
301
|
+
if isinstance(tree, (exp.Select, exp.Union, exp.Subquery)) or isinstance(root, (exp.Select, exp.Union)):
|
|
302
|
+
info.kind = "select"
|
|
303
|
+
elif isinstance(tree, exp.Insert):
|
|
304
|
+
info.kind = "insert"
|
|
305
|
+
elif isinstance(tree, exp.Update):
|
|
306
|
+
info.kind = "update"
|
|
307
|
+
elif isinstance(tree, exp.Delete):
|
|
308
|
+
info.kind = "delete"
|
|
309
|
+
elif isinstance(tree, (exp.Create, exp.Alter, exp.Drop, exp.TruncateTable)):
|
|
310
|
+
info.kind = _kind_regex(sql) if isinstance(tree, exp.Alter) else "ddl"
|
|
311
|
+
else:
|
|
312
|
+
info.kind = _kind_regex(sql)
|
|
313
|
+
ctes = {c.alias_or_name for c in tree.find_all(exp.CTE)}
|
|
314
|
+
info.ctes = sorted(ctes)
|
|
315
|
+
seen: list[str] = []
|
|
316
|
+
for t in tree.find_all(exp.Table):
|
|
317
|
+
if not t.name or (t.name in ctes and not t.db):
|
|
318
|
+
continue
|
|
319
|
+
name = _restore(".".join(p for p in (t.db, t.name) if p), holes)
|
|
320
|
+
if name not in seen:
|
|
321
|
+
seen.append(name)
|
|
322
|
+
info.tables = seen
|
|
323
|
+
if info.kind == "select":
|
|
324
|
+
for sel in tree.find_all(exp.Select):
|
|
325
|
+
source = sel.args.get("from") or sel.args.get("from_")
|
|
326
|
+
src_table = source.this if source is not None else None
|
|
327
|
+
if isinstance(src_table, exp.Final):
|
|
328
|
+
src_table = src_table.this
|
|
329
|
+
reads_table = isinstance(src_table, exp.Table) and bool(src_table.name) and src_table.name not in ctes
|
|
330
|
+
if reads_table and any(isinstance(e, exp.Star) for e in sel.expressions):
|
|
331
|
+
flags.add("select_star")
|
|
332
|
+
bounded = sel.args.get("where") or sel.args.get("prewhere") or sel.args.get("limit")
|
|
333
|
+
table_name = src_table.name if reads_table else ""
|
|
334
|
+
hidden_clause = any(f"__qp{i}__" in parsable.split(table_name, 1)[-1] for i in range(len(holes))) if table_name else False
|
|
335
|
+
is_system = reads_table and (src_table.db or "").lower() in ("system", "information_schema")
|
|
336
|
+
if reads_table and not bounded and not hidden_clause and not is_system and not sel.args.get("joins"):
|
|
337
|
+
flags.add("no_filter")
|
|
338
|
+
if tree.find(exp.Offset):
|
|
339
|
+
flags.add("offset_paging")
|
|
340
|
+
for like in list(tree.find_all(exp.Like)) + list(tree.find_all(exp.ILike)):
|
|
341
|
+
pat = like.expression
|
|
342
|
+
first = pat
|
|
343
|
+
while isinstance(first, (exp.DPipe, exp.Concat)):
|
|
344
|
+
first = first.this if isinstance(first, exp.DPipe) else (first.expressions[0] if first.expressions else None)
|
|
345
|
+
if isinstance(first, exp.Literal) and first.is_string and first.this.startswith("%"):
|
|
346
|
+
flags.add("leading_wildcard_like")
|
|
347
|
+
try:
|
|
348
|
+
norm = tree.copy()
|
|
349
|
+
for lit in norm.find_all(exp.Literal):
|
|
350
|
+
lit.replace(exp.Placeholder())
|
|
351
|
+
info.normalized = _restore(norm.sql(dialect=info.engine or None, normalize=True, comments=False), holes)
|
|
352
|
+
except Exception:
|
|
353
|
+
info.normalized = _normalize_text(sql)
|
|
354
|
+
else:
|
|
355
|
+
info.kind = _kind_regex(sql)
|
|
356
|
+
info.tables, info.ctes = fallback_tables(sql)
|
|
357
|
+
info.normalized = _normalize_text(sql)
|
|
358
|
+
if info.kind == "select":
|
|
359
|
+
if re.search(r"\bSELECT\s+(?:DISTINCT\s+)?\*\s+FROM\s+[\w«]", sql, re.I):
|
|
360
|
+
flags.add("select_star")
|
|
361
|
+
if re.search(r"\bOFFSET\b", sql, re.I):
|
|
362
|
+
flags.add("offset_paging")
|
|
363
|
+
if re.search(r"\bI?LIKE\s+(?:'%|concat\('%)", sql, re.I):
|
|
364
|
+
flags.add("leading_wildcard_like")
|
|
365
|
+
if info.kind == "select" and re.search(r"\bFINAL\b", sql):
|
|
366
|
+
flags.add("final")
|
|
367
|
+
if in_loop:
|
|
368
|
+
flags.add("in_loop")
|
|
369
|
+
info.flags = sorted(flags)
|
|
370
|
+
info.sql_hash = hashlib.sha1(info.normalized.lower().encode()).hexdigest()[:12]
|
|
371
|
+
info.text_hash = hashlib.sha1(_normalize_text(sql).lower().encode()).hexdigest()[:12]
|
|
372
|
+
return info
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.Like, exp.ILike, exp.In, exp.Between)
|
|
376
|
+
EQUALITIES = (exp.EQ, exp.In)
|
|
377
|
+
PARAM_NAME = re.compile(r"^__(?:p_\w+|qp\d+)__$")
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _parse_tree(sql: str, engine: str = ""):
|
|
381
|
+
"""(tree, dialect) for a statement, or (None, ""): the same attempts as `analyze`, for a template or a normalized log
|
|
382
|
+
text (`?..` is a list the server collapsed)."""
|
|
383
|
+
# `{{name::uuid}}` (a template's value) becomes a named parameter, so two of them with other names stay apart
|
|
384
|
+
text = re.sub(r"\{\{\s*(\w+)[^{}]*\}\}", lambda m: f"__p_{m.group(1)}__", re.sub(r"\?\s*\.\.", "?", sql or ""))
|
|
385
|
+
if engine != "clickhouse":
|
|
386
|
+
# CodeCop's own `{name:type}` parameters (a benchmark candidate on PostgreSQL): only ClickHouse parses them
|
|
387
|
+
text = re.sub(r"\{(\w+)\s*:\s*[^{}]+\}", lambda m: f"__p_{m.group(1)}__", text)
|
|
388
|
+
text, _ = to_parsable(text)
|
|
389
|
+
dialects = [engine] if engine in ("clickhouse", "postgres", "sqlite", "mysql") else ["clickhouse", "postgres"]
|
|
390
|
+
# a run-time part right after another one (`ORDER BY «column» «direction»`) is a keyword or a clause: dropped first;
|
|
391
|
+
# then every run-time part that stands alone between spaces (a whole optional clause)
|
|
392
|
+
attempts = [text, re.sub(r"(?<=__)\s+__qp\d+__", " ", text), re.sub(r"(?<=\s)__qp\d+__(?=\s|$)", " ", text)]
|
|
393
|
+
for dialect in dialects:
|
|
394
|
+
for attempt in attempts:
|
|
395
|
+
try:
|
|
396
|
+
tree = next((p for p in sqlglot.parse(attempt, read=dialect) if p is not None), None)
|
|
397
|
+
except Exception: # any parser error: try the next form
|
|
398
|
+
tree = None
|
|
399
|
+
if tree is not None and not isinstance(tree, exp.Command):
|
|
400
|
+
return tree, dialect
|
|
401
|
+
return None, ""
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _is_param(node) -> bool:
|
|
405
|
+
return isinstance(node, (exp.Placeholder, exp.Parameter, exp.Literal, exp.Null, exp.Boolean)) or \
|
|
406
|
+
(isinstance(node, exp.Column) and bool(PARAM_NAME.match(node.name or "")))
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def normalized_predicate(node, dialect: str = "") -> str:
|
|
410
|
+
"""A predicate as text with every value (literal, parameter, run-time part) as `?` and columns unqualified: two
|
|
411
|
+
statements that filter the same columns the same way give the same text, whatever values they are run with."""
|
|
412
|
+
c = node.copy()
|
|
413
|
+
for n in list(c.find_all(exp.Literal, exp.Placeholder, exp.Parameter, exp.Column, exp.Null, exp.Boolean)):
|
|
414
|
+
if _is_param(n):
|
|
415
|
+
n.replace(exp.Var(this="?"))
|
|
416
|
+
elif isinstance(n, exp.Column):
|
|
417
|
+
n.replace(exp.column(n.name))
|
|
418
|
+
try:
|
|
419
|
+
text = c.sql(dialect=dialect or None, normalize=True, comments=False)
|
|
420
|
+
except Exception: # a node the generator can not write: its plain form
|
|
421
|
+
text = str(c)
|
|
422
|
+
return re.sub(r"\?(?:\s*,\s*\?)+", "?", text) # a list of values is one value: its length is a parameter too
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def conjuncts(node) -> list:
|
|
426
|
+
"""The terms of a WHERE (or PREWHERE) condition joined by AND, parentheses removed."""
|
|
427
|
+
if node is None:
|
|
428
|
+
return []
|
|
429
|
+
node = node.this if isinstance(node, (exp.Where, exp.PreWhere)) else node
|
|
430
|
+
while isinstance(node, exp.Paren):
|
|
431
|
+
node = node.this
|
|
432
|
+
if isinstance(node, exp.And):
|
|
433
|
+
return conjuncts(node.this) + conjuncts(node.expression)
|
|
434
|
+
return [node]
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _predicate(term, dialect: str) -> dict | None:
|
|
438
|
+
"""{column, op, text, equality, wrapped} for a comparison of one column with values; None for anything else."""
|
|
439
|
+
node = term
|
|
440
|
+
negated = False
|
|
441
|
+
if isinstance(node, exp.Not):
|
|
442
|
+
node, negated = node.this, True
|
|
443
|
+
if not isinstance(node, COMPARISONS):
|
|
444
|
+
return None
|
|
445
|
+
left, right = node.this, node.args.get("expression")
|
|
446
|
+
cols = [c for c in left.find_all(exp.Column) if not _is_param(c)] if left is not None else []
|
|
447
|
+
if len({c.name.lower() for c in cols}) != 1:
|
|
448
|
+
return None
|
|
449
|
+
others = [right] if right is not None else []
|
|
450
|
+
others += list(node.args.get("expressions") or []) + [node.args.get(k) for k in ("low", "high") if node.args.get(k) is not None]
|
|
451
|
+
if node.args.get("query") is not None:
|
|
452
|
+
return None # IN (SELECT ...): a subquery, not a value
|
|
453
|
+
if any(any(not _is_param(c) for c in o.find_all(exp.Column)) for o in others if o is not None):
|
|
454
|
+
return None # a comparison of two columns
|
|
455
|
+
values = [n for o in others if o is not None for n in o.find_all(exp.Placeholder, exp.Parameter, exp.Literal, exp.Column)]
|
|
456
|
+
return {"column": cols[0].name.lower(), "op": ("not " if negated else "") + type(node).__name__.lower(),
|
|
457
|
+
"text": normalized_predicate(term, dialect), "equality": isinstance(node, EQUALITIES) and not negated,
|
|
458
|
+
"wrapped": not isinstance(left, exp.Column), "qualifier": (cols[0].table or "").lower(),
|
|
459
|
+
# bound to a parameter (a tenant, a window) rather than only to literals the code wrote
|
|
460
|
+
"parameter": any(not isinstance(n, exp.Literal) for n in values)}
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _sources(sel, ctes) -> list[tuple[str, str, bool]]:
|
|
464
|
+
"""(table, alias, final) of every table a SELECT reads in its FROM and JOINs (a CTE's name is not a table, unless
|
|
465
|
+
it is qualified with a database)."""
|
|
466
|
+
out = []
|
|
467
|
+
source = sel.args.get("from") or sel.args.get("from_")
|
|
468
|
+
nodes = [source.this] if source is not None else []
|
|
469
|
+
nodes += [j.this for j in sel.args.get("joins") or []]
|
|
470
|
+
for t in nodes:
|
|
471
|
+
final = isinstance(t, exp.Final)
|
|
472
|
+
if final:
|
|
473
|
+
t = t.this
|
|
474
|
+
if isinstance(t, exp.Table) and t.name and (t.db or t.name not in ctes):
|
|
475
|
+
out.append((t.name.lower(), (t.alias or "").lower(), final))
|
|
476
|
+
return out
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def scan_filters(sql: str, engine: str = "") -> dict:
|
|
480
|
+
"""What each scan of a table filters on, read from the parsed statement (never from its text): the predicates of the
|
|
481
|
+
WHERE and PREWHERE of every SELECT whose FROM is a table, how often each CTE is read, and subqueries written twice.
|
|
482
|
+
|
|
483
|
+
{parse_ok, dialect, aggregate, grouped, limit, scans: [{table, final, predicates: [{column, op, text, equality,
|
|
484
|
+
wrapped}]}], cte_reads: {name: {reads, tables}}, repeated_subqueries: [{text, reads, tables}]}. Table names are
|
|
485
|
+
without their database. Templates (`«...»`) and normalized log texts (`?`, `?..`) parse."""
|
|
486
|
+
tree, dialect = _parse_tree(sql, engine)
|
|
487
|
+
out = {"parse_ok": tree is not None, "dialect": dialect, "aggregate": False, "grouped": False, "limit": False,
|
|
488
|
+
"scans": [], "cte_reads": {}, "repeated_subqueries": []}
|
|
489
|
+
if tree is None:
|
|
490
|
+
return out
|
|
491
|
+
ctes = {c.alias_or_name: c for c in tree.find_all(exp.CTE)}
|
|
492
|
+
for sel in tree.find_all(exp.Select):
|
|
493
|
+
sources = _sources(sel, ctes)
|
|
494
|
+
if not sources:
|
|
495
|
+
continue
|
|
496
|
+
preds = [p for p in (_predicate(t, dialect) for t in conjuncts(sel.args.get("prewhere")) + conjuncts(sel.args.get("where"))) if p]
|
|
497
|
+
first = (sel.args.get("from") or sel.args.get("from_"))
|
|
498
|
+
for i, (table, alias, final) in enumerate(sources):
|
|
499
|
+
# a predicate belongs to the table its column is qualified with; an unqualified one to the FROM table
|
|
500
|
+
mine = [p for p in preds if (p["qualifier"] in (table, alias) if p["qualifier"] else i == 0 and first is not None)]
|
|
501
|
+
out["scans"].append({"table": table, "final": final, "predicates": mine})
|
|
502
|
+
root = tree.this if isinstance(tree, exp.With) else tree
|
|
503
|
+
if isinstance(root, exp.Select):
|
|
504
|
+
out["aggregate"] = bool(root.args.get("group")) or any(e.find(exp.AggFunc) for e in root.expressions)
|
|
505
|
+
out["grouped"] = bool(root.args.get("group"))
|
|
506
|
+
out["limit"] = bool(root.args.get("limit"))
|
|
507
|
+
reads: dict[str, int] = {}
|
|
508
|
+
for t in tree.find_all(exp.Table):
|
|
509
|
+
if t.name in ctes and not t.db:
|
|
510
|
+
reads[t.name] = reads.get(t.name, 0) + 1
|
|
511
|
+
for name, n in reads.items():
|
|
512
|
+
inner = sorted({t.name.lower() for t in ctes[name].find_all(exp.Table) if t.name and (t.db or t.name not in ctes)})
|
|
513
|
+
# MATERIALIZED: True, NOT MATERIALIZED: False, neither: None (the engine decides)
|
|
514
|
+
out["cte_reads"][name] = {"reads": n, "tables": inner, "materialized": ctes[name].args.get("materialized")}
|
|
515
|
+
seen: dict[str, list] = {}
|
|
516
|
+
for sq in tree.find_all(exp.Subquery):
|
|
517
|
+
body = sq.this
|
|
518
|
+
if not isinstance(body, (exp.Select, exp.Union)) or not body.find(exp.Table):
|
|
519
|
+
continue
|
|
520
|
+
# the same text with the same values (literals and parameter names kept): written twice, the same rows twice.
|
|
521
|
+
# The same shape with other values (two periods) is two scans, not one read twice.
|
|
522
|
+
try:
|
|
523
|
+
exact = body.sql(dialect=dialect or None, comments=False)
|
|
524
|
+
except Exception: # a node the generator can not write
|
|
525
|
+
exact = str(body)
|
|
526
|
+
seen.setdefault(exact, []).append(body)
|
|
527
|
+
for _, nodes in seen.items():
|
|
528
|
+
text = normalized_predicate(nodes[0], dialect)
|
|
529
|
+
if len(nodes) >= 2:
|
|
530
|
+
tables = sorted({t.name.lower() for t in nodes[0].find_all(exp.Table) if t.name and t.name not in ctes})
|
|
531
|
+
if tables:
|
|
532
|
+
out["repeated_subqueries"].append({"text": text, "reads": len(nodes), "tables": tables})
|
|
533
|
+
return out
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def fingerprint(sql_hash: str, file: str, symbol: str) -> str:
|
|
537
|
+
"""Call-site identity: normalized SQL plus enclosing symbol, never the line number."""
|
|
538
|
+
return hashlib.sha1(f"{sql_hash}|{file}|{symbol}".encode()).hexdigest()[:12]
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
_NAME = r"((?:[\w`\"]+|«[^»]*»)(?:\.(?:[\w`\"]+|«[^»]*»))?)"
|
|
542
|
+
WRITE_RE = re.compile(
|
|
543
|
+
rf"\bINSERT\s+(?:OR\s+\w+\s+)?INTO\s+(?:TABLE\s+)?{_NAME}|\bUPDATE\s+(?:ONLY\s+)?{_NAME}\s+SET\b|\bDELETE\s+FROM\s+{_NAME}|"
|
|
544
|
+
rf"\bALTER\s+TABLE\s+{_NAME}\s+(?:ON\s+CLUSTER\s+\S+\s+)?(?:UPDATE|DELETE)\b|\bTRUNCATE\s+(?:TABLE\s+)?{_NAME}|"
|
|
545
|
+
rf"\bMATERIALIZED\s+VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?\S+\s+(?:ON\s+CLUSTER\s+\S+\s+)?TO\s+{_NAME}|\bMERGE\s+INTO\s+{_NAME}", re.I)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def write_targets(sql: str | None) -> list[str]:
|
|
549
|
+
"""Tables a statement changes (INSERT, UPDATE, DELETE, mutations, a materialized view's target).
|
|
550
|
+
|
|
551
|
+
Every other table the statement names is read. A statement with a write target and other
|
|
552
|
+
tables (INSERT ... SELECT, a materialized view) moves data from those tables into the target."""
|
|
553
|
+
out: list[str] = []
|
|
554
|
+
for m in WRITE_RE.finditer(sql or ""):
|
|
555
|
+
name = next(g for g in m.groups() if g).replace("`", "").replace('"', "")
|
|
556
|
+
if name.lower() not in NOT_TABLES and name not in out:
|
|
557
|
+
out.append(name)
|
|
558
|
+
return out
|