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/typedparams.py
ADDED
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
"""Typed parameters for any statement from code: every placeholder becomes `{pN:Type}`, typed from the column it is
|
|
2
|
+
compared with (the pulled catalog's type, or the repository's own definition), with a value of that type.
|
|
3
|
+
|
|
4
|
+
Code binds its values in many spellings (`$1`, `?`, `:name`, `%(name)s`, `%s`, `@name`, `@{name}`, ClickHouse's own
|
|
5
|
+
`{name:Type}`). A statement planned or run with untyped stand-ins fails for reasons of the stand-in, not of the
|
|
6
|
+
statement (ClickHouse: `NULL` compared with a UUID key, `''` given to a DateTime: a common cause of plan
|
|
7
|
+
failures). Here each placeholder is read with what is around it:
|
|
8
|
+
|
|
9
|
+
col = ?, ? = col, col <> ?, col LIKE ?, col IN (?, ?), col IN ?, col BETWEEN ? AND ?, has(col, ?), f(col) = ?
|
|
10
|
+
LIMIT ? / OFFSET ? an unsigned count (100 / 0)
|
|
11
|
+
INTERVAL ? DAY, toIntervalDay(?) a count (1)
|
|
12
|
+
toDateTime(?), parseDateTime64BestEffort(?), toDate(?) a time as text
|
|
13
|
+
$1::uuid, CAST(? AS Int32) the code's own cast is the type
|
|
14
|
+
|
|
15
|
+
and typed with the column's type in the tables the statement reads. A placeholder no rule types keeps a neutral value
|
|
16
|
+
and is listed in `untyped`, so a caller can say the value was not typed.
|
|
17
|
+
|
|
18
|
+
Values: `values(table, column, type)` (a caller's lookup: a value present in the sandbox's generated rows, or one of the
|
|
19
|
+
pulled distribution's common values) comes first, so the statement selects rows; otherwise a neutral value of the type.
|
|
20
|
+
Nothing here needs a database."""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import re
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
|
|
27
|
+
from .engines.base import QUOTED
|
|
28
|
+
|
|
29
|
+
# one placeholder, any spelling; group names say which
|
|
30
|
+
PLACEHOLDER = re.compile(
|
|
31
|
+
r"\{\s*(?P<chname>\w+)\s*:\s*(?P<chtype>[^{}]+?)\s*\}" # ClickHouse {name:Type}, `{ name: Type }` too (CodeCop's own form)
|
|
32
|
+
r"|@\{(?P<atb>\w+)\}" # @{name}
|
|
33
|
+
r"|\$\{(?P<dollarb>\w+)\}" # ${name}
|
|
34
|
+
r"|\$(?P<num>\d+)" # $1
|
|
35
|
+
r"|%\((?P<pyname>\w+)\)s" # %(name)s
|
|
36
|
+
r"|(?P<pys>%s)" # %s
|
|
37
|
+
r"|(?<![:\w]):(?P<colon>[A-Za-z_]\w*)\b(?!:)" # :name (not ::cast)
|
|
38
|
+
r"|(?<![\w@])@(?P<at>[A-Za-z_]\w*)\b" # @name
|
|
39
|
+
r"|(?P<q>(?<![\w?])\?(?![?|&\w-]))" # ? (not ?| ?& ?? jsonb operators)
|
|
40
|
+
)
|
|
41
|
+
IDENT = r"(?:`[^`]+`|\"[^\"]+\"|[A-Za-z_][\w$]*)"
|
|
42
|
+
QUALIFIED = rf"{IDENT}(?:\s*\.\s*{IDENT}){{0,2}}"
|
|
43
|
+
COMPARE_OPS = r"(?:=|==|<>|!=|<=|>=|<|>|\bNOT\s+LIKE\b|\bNOT\s+ILIKE\b|\bLIKE\b|\bILIKE\b|\bIS\s+DISTINCT\s+FROM\b)"
|
|
44
|
+
# `col <op> PH` ; `f(col) <op> PH` ; `col IN (PH` ; `col IN PH` ; `col BETWEEN PH` / `... AND PH` (handled apart)
|
|
45
|
+
LEFT_COMPARE = re.compile(rf"(?P<col>{QUALIFIED})\s*(?:\)\s*)*{COMPARE_OPS}\s*(?:\(\s*)*$", re.I)
|
|
46
|
+
LEFT_FUNC_COMPARE = re.compile(rf"(?P<fn>\w+)\s*\(\s*(?P<col>{QUALIFIED})\s*(?:,[^()]*)?\)\s*{COMPARE_OPS}\s*$", re.I)
|
|
47
|
+
LEFT_IN = re.compile(rf"(?P<col>{QUALIFIED})\s*(?:\)\s*)?(?:NOT\s+)?(?:GLOBAL\s+)?IN\s*\(?(?:\s*[^()]*,)?\s*$", re.I)
|
|
48
|
+
LEFT_ANY = re.compile(rf"(?P<col>{QUALIFIED})\s*{COMPARE_OPS}\s*(?:ANY|ALL)\s*\(\s*$", re.I)
|
|
49
|
+
LEFT_BETWEEN = re.compile(rf"(?P<col>{QUALIFIED})\s+(?:NOT\s+)?BETWEEN\s+(?:(?:[^()]|\([^()]*\))+?\s+AND\s+)?$", re.I)
|
|
50
|
+
LEFT_HAS = re.compile(rf"\b(?P<fn>has|hasAny|hasAll|indexOf|arrayExists)\s*\(\s*(?P<col>{QUALIFIED})\s*,\s*$", re.I)
|
|
51
|
+
RIGHT_COMPARE = re.compile(rf"^\s*(?:\)\s*)*{COMPARE_OPS}\s*(?P<col>{QUALIFIED})", re.I)
|
|
52
|
+
RIGHT_COMPARE_OP = re.compile(rf"^\s*(?:\)\s*)*(?P<op>{COMPARE_OPS})", re.I)
|
|
53
|
+
LEFT_LIMIT = re.compile(r"\b(?P<kw>LIMIT|OFFSET|TOP|FETCH\s+FIRST|FETCH\s+NEXT)\s*(?:\(\s*)?(?:\S+\s*,\s*)?$", re.I)
|
|
54
|
+
LEFT_INTERVAL = re.compile(r"\b(?:INTERVAL\s*|to(?:Interval)\w*\s*\(\s*|\w*(?:add|sub|subtract)\w*\s*\(\s*[^,()]+,\s*)$", re.I)
|
|
55
|
+
LEFT_TIME_FN = re.compile(r"\b(?P<fn>to(?:DateTime|DateTime64|Date|Date32|StartOf\w+|UnixTimestamp\w*)|parseDateTime\w*|fromUnixTimestamp\w*|"
|
|
56
|
+
r"to_timestamp|to_date|date_trunc\s*\(\s*'[^']*'\s*,)\s*\(?\s*$", re.I)
|
|
57
|
+
CAST_AFTER = re.compile(r"^\s*::\s*(?P<t>[A-Za-z_][\w ]*?(?:\(\s*\d+(?:\s*,\s*\d+)?\s*\))?(?:\[\])?)(?=[\s),;]|$)", re.I)
|
|
58
|
+
ALIAS_AFTER = re.compile(r"^\s*AS\s+(?P<a>[A-Za-z_]\w*)\s*,?", re.I)
|
|
59
|
+
CH_CAST_PAIR = re.compile(r"^\s*,\s*'(?P<t>[^']+)'\s*\)")
|
|
60
|
+
CH_TO_TYPE = re.compile(r"\b(?P<fn>toUUID|toUUIDOrNull|toUInt8|toUInt16|toUInt32|toUInt64|toInt8|toInt16|toInt32|toInt64|toFloat64|"
|
|
61
|
+
r"toDateTime64|toDateTime|toDate|toString|fromUnixTimestamp64Milli|fromUnixTimestamp64Micro|fromUnixTimestamp64Nano|"
|
|
62
|
+
r"fromUnixTimestamp)\s*\(\s*$", re.I)
|
|
63
|
+
CH_TO_TYPES = {"touuid": "String", "touuidornull": "String", "touint8": "UInt8", "touint16": "UInt16", "touint32": "UInt32",
|
|
64
|
+
"touint64": "UInt64", "toint8": "Int8", "toint16": "Int16", "toint32": "Int32", "toint64": "Int64", "tofloat64": "Float64",
|
|
65
|
+
"todatetime64": "String", "todatetime": "String", "todate": "String", "tostring": "String",
|
|
66
|
+
"fromunixtimestamp64milli": "Int64", "fromunixtimestamp64micro": "Int64", "fromunixtimestamp64nano": "Int64",
|
|
67
|
+
"fromunixtimestamp": "UInt32"}
|
|
68
|
+
ARRAY_ANY_ARG = re.compile(r"\b(?:arrayZip|arrayConcat|arrayIntersect|hasAll|hasAny)\s*\((?:[^()]|\([^()]*\))*$", re.I)
|
|
69
|
+
FROM_EPOCH = re.compile(r"\b(?P<fn>fromUnixTimestamp\w*)\s*\(\s*$", re.I)
|
|
70
|
+
ARRAY_FIRST = re.compile(r"\b(?:has|hasAny|hasAll|indexOf|arrayJoin|arrayZip|length|empty|notEmpty)\s*\(\s*$", re.I)
|
|
71
|
+
RIGHT_ARG = re.compile(rf"^\s*,\s*(?P<col>{QUALIFIED})\s*\)", re.I)
|
|
72
|
+
CAST_AROUND = re.compile(r"\bCAST\s*\(\s*$", re.I)
|
|
73
|
+
CAST_AS = re.compile(r"^\s*AS\s+(?P<t>[A-Za-z_][\w]*(?:\([^()]*(?:\([^()]*\)[^()]*)*\))?(?:\[\])?)\s*\)", re.I)
|
|
74
|
+
TABLE_REF = re.compile(rf"\b(?:FROM|JOIN|UPDATE|INTO|TABLE)\s+(?P<t>{QUALIFIED})(?:\s+(?:AS\s+)?(?!(?:WHERE|JOIN|LEFT|RIGHT|INNER|OUTER|"
|
|
75
|
+
rf"CROSS|FULL|ANY|ALL|SEMI|ANTI|ARRAY|GLOBAL|ASOF|PASTE|ON|USING|GROUP|ORDER|LIMIT|UNION|NATURAL|FINAL|PREWHERE|"
|
|
76
|
+
rf"SAMPLE|SET|VALUES|SELECT|WITH|SETTINGS|FORMAT|HAVING|WINDOW|RETURNING|OFFSET|FOR|LATERAL)\b)(?P<a>{IDENT}))?", re.I)
|
|
77
|
+
INSERT_COLUMNS = re.compile(rf"\bINSERT\s+INTO\s+(?:TABLE\s+)?(?P<t>{QUALIFIED})\s*\((?P<cols>[^()]*)\)\s*(?:SETTINGS\s+[^()]*?)?VALUES\s*\(", re.I)
|
|
78
|
+
SET_ASSIGN = re.compile(rf"(?P<col>{IDENT})\s*=\s*$", re.I)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _bare(name: str) -> str:
|
|
82
|
+
return re.sub(r'[`"\s]', "", name or "").split(".")[-1].lower()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _base(t: str) -> str:
|
|
86
|
+
"""ClickHouse Nullable(X) / LowCardinality(X) -> X; PostgreSQL types lower-cased."""
|
|
87
|
+
t = (t or "").strip()
|
|
88
|
+
while True:
|
|
89
|
+
m = re.fullmatch(r"(?:Nullable|LowCardinality|SimpleAggregateFunction\(\w+,)\s*\((.*)\)", t) or \
|
|
90
|
+
re.fullmatch(r"(?:Nullable|LowCardinality)\((.*)\)", t)
|
|
91
|
+
if not m:
|
|
92
|
+
return t
|
|
93
|
+
t = m.group(1).strip()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass
|
|
97
|
+
class Bound:
|
|
98
|
+
"""A statement with every placeholder written `{name:Type}`, the values, and what typed each."""
|
|
99
|
+
sql: str
|
|
100
|
+
params: dict
|
|
101
|
+
types: dict = field(default_factory=dict) # name -> type
|
|
102
|
+
basis: dict = field(default_factory=dict) # name -> "column table.col" | "cast" | "limit" | ... | "untyped"
|
|
103
|
+
untyped: list = field(default_factory=list) # names no rule typed
|
|
104
|
+
columns: dict = field(default_factory=dict) # name -> (table, column) it is compared with
|
|
105
|
+
# name -> how the value is used: = <> < <= > >= like in "not in" lower upper (BETWEEN) limit offset interval set value
|
|
106
|
+
# stand_in (nothing typed it); `through` names the function the value goes through (`col >= fromUnixTimestamp(?)`)
|
|
107
|
+
ops: dict = field(default_factory=dict)
|
|
108
|
+
through: dict = field(default_factory=dict)
|
|
109
|
+
|
|
110
|
+
def to_dict(self) -> dict:
|
|
111
|
+
return {"sql": self.sql, "params": self.params, "types": self.types, "basis": self.basis, "untyped": self.untyped,
|
|
112
|
+
"columns": {k: list(v) for k, v in self.columns.items()}, "ops": self.ops}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _spans_outside_quotes(sql: str) -> list[tuple[int, int]]:
|
|
116
|
+
"""(start, end) of every stretch of `sql` outside strings, quoted names and comments."""
|
|
117
|
+
out, pos = [], 0
|
|
118
|
+
for m in QUOTED.finditer(sql):
|
|
119
|
+
if m.group(0).startswith(('"', "`")):
|
|
120
|
+
continue # a quoted name: placeholders never sit inside one, but its text is the statement's
|
|
121
|
+
out.append((pos, m.start()))
|
|
122
|
+
pos = m.end()
|
|
123
|
+
out.append((pos, len(sql)))
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def placeholders(sql: str) -> list[re.Match]:
|
|
128
|
+
"""Every placeholder outside strings and comments, in order. `?` is left out when the statement also uses `$n` or
|
|
129
|
+
named binds (it is then PostgreSQL's jsonb operator); `:name` when it follows `::`."""
|
|
130
|
+
found: list[re.Match] = []
|
|
131
|
+
for a, b in _spans_outside_quotes(sql):
|
|
132
|
+
for m in PLACEHOLDER.finditer(sql, a, b):
|
|
133
|
+
found.append(m)
|
|
134
|
+
styles = {_kind(m) for m in found}
|
|
135
|
+
# (`?` beside ClickHouse's own `{name:Type}` is a placeholder too: ClickHouse has no `?` operator)
|
|
136
|
+
if styles & {"num", "pyname", "atb", "colon"} and "q" in styles:
|
|
137
|
+
found = [m for m in found if _kind(m) != "q"]
|
|
138
|
+
if "pys" in styles and "q" in styles:
|
|
139
|
+
found = [m for m in found if _kind(m) != "q"]
|
|
140
|
+
return found
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _kind(m: re.Match) -> str:
|
|
144
|
+
"""Which spelling a placeholder match is (its first group that matched)."""
|
|
145
|
+
return next(k for k, v in m.groupdict().items() if v is not None)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def tables_of(sql: str) -> dict[str, str]:
|
|
149
|
+
"""alias (or table) -> table, both bare and lower case."""
|
|
150
|
+
out: dict[str, str] = {}
|
|
151
|
+
for m in TABLE_REF.finditer(sql):
|
|
152
|
+
t = _bare(m.group("t"))
|
|
153
|
+
if not t or t in ("select", "("):
|
|
154
|
+
continue
|
|
155
|
+
out.setdefault(t, t)
|
|
156
|
+
if m.group("a"):
|
|
157
|
+
out[_bare(m.group("a"))] = t
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _column_type(named: str, aliases: dict[str, str], columns: dict[str, dict[str, str]]) -> tuple[str, str, str] | None:
|
|
162
|
+
"""(table, column, type) for a column reference as the statement writes it, or None when no table it reads has it."""
|
|
163
|
+
parts = [p for p in re.split(r"\s*\.\s*", re.sub(r'[`"]', "", named)) if p]
|
|
164
|
+
if not parts:
|
|
165
|
+
return None
|
|
166
|
+
col = parts[-1].lower()
|
|
167
|
+
tables = list(dict.fromkeys(aliases.values()))
|
|
168
|
+
if len(parts) > 1:
|
|
169
|
+
q = parts[-2].lower()
|
|
170
|
+
t = aliases.get(q, q)
|
|
171
|
+
typ = (columns.get(t) or {}).get(col)
|
|
172
|
+
if typ:
|
|
173
|
+
return t, col, typ
|
|
174
|
+
found = [(t, col, (columns.get(t) or {})[col]) for t in tables if col in (columns.get(t) or {})]
|
|
175
|
+
if not found:
|
|
176
|
+
# a table the statement reads that no lookup has by its alias: any table with the column, one type only
|
|
177
|
+
found = [(t, col, cols[col]) for t, cols in columns.items() if col in cols and t in tables]
|
|
178
|
+
types = {_base(f[2]) for f in found}
|
|
179
|
+
if len(types) == 1 and found:
|
|
180
|
+
return found[0]
|
|
181
|
+
return None # the same name with different types in two tables and no qualifier says which: not typed
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _element(t: str) -> str:
|
|
185
|
+
m = re.fullmatch(r"Array\((.*)\)", _base(t))
|
|
186
|
+
if m:
|
|
187
|
+
return m.group(1)
|
|
188
|
+
if t.endswith("[]"):
|
|
189
|
+
return t[:-2]
|
|
190
|
+
return t
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _neutral(typ: str, engine: str, column: str = "", n: int = 1):
|
|
194
|
+
"""A value of the type that generated data can hold."""
|
|
195
|
+
t = _base(typ)
|
|
196
|
+
low = t.lower()
|
|
197
|
+
if engine == "clickhouse":
|
|
198
|
+
if low.startswith("array("):
|
|
199
|
+
one = _neutral(_element(t), engine, column, n)
|
|
200
|
+
return [] if one is None or _element(t).lower().startswith(("tuple(", "map(", "array(")) else [one]
|
|
201
|
+
if low.startswith(("map(", "tuple(")):
|
|
202
|
+
return None
|
|
203
|
+
if low.startswith("uuid"):
|
|
204
|
+
return f"00000000-0000-4000-8000-{n:012d}"
|
|
205
|
+
if re.match(r"u?int\d*|float|decimal", low):
|
|
206
|
+
return n
|
|
207
|
+
if low.startswith("bool"):
|
|
208
|
+
return True
|
|
209
|
+
if low.startswith("datetime64") or low.startswith("datetime"):
|
|
210
|
+
return "2026-01-01 00:00:00"
|
|
211
|
+
if low.startswith("date"):
|
|
212
|
+
return "2026-01-01"
|
|
213
|
+
if low.startswith("enum"):
|
|
214
|
+
m = re.search(r"'((?:[^'\\]|\\.)*)'", t)
|
|
215
|
+
return m.group(1) if m else ""
|
|
216
|
+
if low.startswith(("ipv4",)):
|
|
217
|
+
return "10.0.0.1"
|
|
218
|
+
if low.startswith(("ipv6",)):
|
|
219
|
+
return "::1"
|
|
220
|
+
if re.search(r"(?:^|_)(?:id|uuid|tenant|subscriber|org|organization|user|account|owner)(?:_id)?$", column or "", re.I):
|
|
221
|
+
return f"00000000-0000-4000-8000-{n:012d}"
|
|
222
|
+
return f"{column or 'v'}_{n}"
|
|
223
|
+
if low.endswith("[]"):
|
|
224
|
+
return "{" + str(_neutral(low[:-2], engine, column, n)) + "}"
|
|
225
|
+
if low == "uuid":
|
|
226
|
+
return f"00000000-0000-4000-8000-{n:012d}"
|
|
227
|
+
if re.match(r"(?:small|big)?int|integer|numeric|decimal|real|double|float|serial", low):
|
|
228
|
+
return n
|
|
229
|
+
if low.startswith("bool"):
|
|
230
|
+
return True
|
|
231
|
+
if re.match(r"timestamp|date", low):
|
|
232
|
+
return "2026-01-01 00:00:00" if low.startswith("timestamp") else "2026-01-01"
|
|
233
|
+
if low.startswith("time"):
|
|
234
|
+
return "00:00:00"
|
|
235
|
+
if low.startswith("interval"):
|
|
236
|
+
return "1 day"
|
|
237
|
+
if low in ("json", "jsonb"):
|
|
238
|
+
return "{}"
|
|
239
|
+
if low == "inet" or low == "cidr":
|
|
240
|
+
return "10.0.0.1"
|
|
241
|
+
return f"{column or 'v'}_{n}"
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _count_type(engine: str) -> str:
|
|
245
|
+
return "UInt64" if engine == "clickhouse" else "bigint"
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _time_type(engine: str) -> str:
|
|
249
|
+
return "String" if engine == "clickhouse" else "text"
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _array_of(t: str, engine: str) -> str:
|
|
253
|
+
return f"Array({_base(t)})" if engine == "clickhouse" else (t if t.endswith("[]") else f"{t}[]")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _ch_param_type(t: str) -> str:
|
|
257
|
+
"""A type ClickHouse accepts for a query parameter: the column's own, LowCardinality left out."""
|
|
258
|
+
t = re.sub(r"LowCardinality\((.*?)\)", r"\1", t)
|
|
259
|
+
t = re.sub(r"SimpleAggregateFunction\(\w+,\s*(.*)\)", r"\1", t)
|
|
260
|
+
return t.strip()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
FLIP = {"<": ">", ">": "<", "<=": ">=", ">=": "<="}
|
|
264
|
+
# `col <op> fn(` : the value goes through a function (toUUID, fromUnixTimestamp64Milli, toDateTime) before the comparison
|
|
265
|
+
LEFT_COMPARE_THROUGH = re.compile(rf"(?P<col>{QUALIFIED})\s*(?:\)\s*)*(?P<op>{COMPARE_OPS})\s*(?P<fn>\w+)\s*\(\s*(?:\(\s*)*$", re.I)
|
|
266
|
+
OP_ONLY = re.compile(rf"(?P<op>{COMPARE_OPS})\s*(?:\w+\s*\(\s*)*(?:\(\s*)*$", re.I)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _op_word(text: str) -> str:
|
|
270
|
+
w = " ".join((text or "").lower().split())
|
|
271
|
+
return {"==": "=", "is distinct from": "<>", "!=": "<>"}.get(w, w)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def bind(sql: str, engine: str, columns: dict[str, dict[str, str]], values=None, prefix: str = "p") -> Bound:
|
|
275
|
+
"""The statement with every placeholder typed (see the module text). `columns`: table -> {column: type}, bare lower-case
|
|
276
|
+
names. `values(table, column, type) -> value | None`: a value the rows hold (optional)."""
|
|
277
|
+
found = placeholders(sql)
|
|
278
|
+
aliases = tables_of(sql)
|
|
279
|
+
insert = INSERT_COLUMNS.search(sql)
|
|
280
|
+
insert_cols = [_bare(c) for c in insert.group("cols").split(",")] if insert else []
|
|
281
|
+
insert_table = _bare(insert.group("t")) if insert else ""
|
|
282
|
+
out: list[str] = []
|
|
283
|
+
params: dict = {}
|
|
284
|
+
b = Bound(sql="", params=params)
|
|
285
|
+
last = 0
|
|
286
|
+
named: dict[str, str] = {} # the code's own name -> our name: one value per name
|
|
287
|
+
positional = 0
|
|
288
|
+
for i, m in enumerate(found):
|
|
289
|
+
kind = _kind(m)
|
|
290
|
+
own = m.group(kind) if kind not in ("q", "pys") else None
|
|
291
|
+
before = sql[max(0, m.start() - 400):m.start()]
|
|
292
|
+
after = sql[m.end():m.end() + 200]
|
|
293
|
+
end = m.end()
|
|
294
|
+
typ, basis, col_ref, as_list, op, through = "", "", None, False, "", ""
|
|
295
|
+
if kind == "chname":
|
|
296
|
+
# written back as `{name:Type}`, a type argument in double quotes (`DateTime(3, "UTC")`) in single ones
|
|
297
|
+
own, typ, basis = m.group("chname"), m.group("chtype").strip().replace('"', "'"), "declared"
|
|
298
|
+
if typ and (c := CH_TO_TYPE.search(before) or LEFT_TIME_FN.search(before)):
|
|
299
|
+
through = c.group("fn").lower() # a declared value the code turns into a time: its function, for its value
|
|
300
|
+
cast = CAST_AFTER.match(after) if engine == "postgres" else None
|
|
301
|
+
if not typ and cast:
|
|
302
|
+
typ, basis = cast.group("t").strip(), "cast"
|
|
303
|
+
end = m.end() + cast.end()
|
|
304
|
+
if not typ and CAST_AROUND.search(before):
|
|
305
|
+
c = CAST_AS.match(after)
|
|
306
|
+
if c:
|
|
307
|
+
typ, basis = c.group("t").strip(), "cast"
|
|
308
|
+
if not typ and engine == "clickhouse" and (c := CH_CAST_PAIR.match(after)) and re.search(r"\bCAST\s*\(\s*$", before, re.I):
|
|
309
|
+
typ, basis = c.group("t").strip(), "cast" # CAST(?, 'Array(String)')
|
|
310
|
+
if not typ and engine == "clickhouse" and (c := CH_TO_TYPE.search(before)):
|
|
311
|
+
typ, basis = CH_TO_TYPES.get(c.group("fn").lower(), ""), "cast"
|
|
312
|
+
if c.group("fn").lower().startswith("todate"):
|
|
313
|
+
basis = "time_text"
|
|
314
|
+
if c.group("fn").lower().startswith("touuid"):
|
|
315
|
+
col_ref = ("", "uuid")
|
|
316
|
+
through = c.group("fn").lower()
|
|
317
|
+
if (lc := LEFT_COMPARE_THROUGH.search(before)) and (got := _column_type(lc.group("col"), aliases, columns)):
|
|
318
|
+
col_ref, op = (got[0], got[1]), _op_word(lc.group("op")) # `tenant = toUUID(?)`: the value is a tenant
|
|
319
|
+
if not typ and engine == "clickhouse" and (c := ARRAY_FIRST.search(before)) and (r := RIGHT_ARG.match(after)):
|
|
320
|
+
got = _column_type(r.group("col"), aliases, columns)
|
|
321
|
+
if got:
|
|
322
|
+
typ, basis, col_ref, as_list = _array_of(got[2], engine), f"column {got[0]}.{got[1]}", (got[0], got[1]), False
|
|
323
|
+
if not typ and engine == "clickhouse" and (al := ALIAS_AFTER.match(after)):
|
|
324
|
+
used = sql[m.end():]
|
|
325
|
+
name_rx = re.escape(al.group("a"))
|
|
326
|
+
if re.search(rf"(?:\bIN\s*\(?|\b(?:has|hasAny|hasAll|arrayZip|indexOf|arrayJoin|length|arrayMap|arrayFilter|arrayExists)\s*\([^()]*?)\s*\b{name_rx}\b", used, re.I):
|
|
327
|
+
typ, basis = "Array(String)", "alias_use"
|
|
328
|
+
else:
|
|
329
|
+
u = re.search(rf"(?P<col>{QUALIFIED})\s*{COMPARE_OPS}\s*{name_rx}\b|\b{name_rx}\s*{COMPARE_OPS}\s*(?P<col2>{QUALIFIED})", used, re.I)
|
|
330
|
+
if u:
|
|
331
|
+
got = _column_type(u.group("col") or u.group("col2"), aliases, columns)
|
|
332
|
+
if got:
|
|
333
|
+
typ, basis, col_ref = got[2], f"column {got[0]}.{got[1]}", (got[0], got[1])
|
|
334
|
+
if not typ and (mm := LEFT_LIMIT.search(before)):
|
|
335
|
+
typ, basis = _count_type(engine), "limit"
|
|
336
|
+
op = "offset" if mm.group("kw").upper() == "OFFSET" else "limit"
|
|
337
|
+
if not typ and LEFT_INTERVAL.search(before):
|
|
338
|
+
typ, basis, op = ("UInt32" if engine == "clickhouse" else "integer"), "interval", "interval"
|
|
339
|
+
if not typ and insert and insert.end() <= m.start():
|
|
340
|
+
# INSERT INTO t (a, b) VALUES (?, ?): the n-th value goes to the n-th column
|
|
341
|
+
idx = len([x for x in found if insert.end() <= x.start() < m.start()])
|
|
342
|
+
if idx < len(insert_cols):
|
|
343
|
+
got = (columns.get(insert_table) or {}).get(insert_cols[idx])
|
|
344
|
+
if got:
|
|
345
|
+
typ, basis, col_ref, op = got, f"column {insert_table}.{insert_cols[idx]}", (insert_table, insert_cols[idx]), "set"
|
|
346
|
+
if not typ:
|
|
347
|
+
hit = None
|
|
348
|
+
for rx, lst in ((LEFT_HAS, "element"), (LEFT_ANY, "element_any"), (LEFT_IN, "in"), (LEFT_BETWEEN, ""),
|
|
349
|
+
(LEFT_FUNC_COMPARE, "func"), (LEFT_COMPARE, "")):
|
|
350
|
+
mm = rx.search(before)
|
|
351
|
+
if mm and not re.fullmatch(r"(?i)and|or|not|where|on|when|then|else|select|null|true|false|case|having|prewhere|is",
|
|
352
|
+
_bare(mm.group("col"))):
|
|
353
|
+
hit = (mm, lst)
|
|
354
|
+
break
|
|
355
|
+
if hit is None and (mm := RIGHT_COMPARE.match(after)):
|
|
356
|
+
hit = (mm, "right")
|
|
357
|
+
if hit is None and (mm := SET_ASSIGN.search(before)) and re.search(r"\bSET\b", before, re.I):
|
|
358
|
+
hit = (mm, "set")
|
|
359
|
+
if hit:
|
|
360
|
+
mm, lst = hit
|
|
361
|
+
if lst in ("element", "element_any", "in"):
|
|
362
|
+
op = "not in" if lst == "in" and re.search(r"\bNOT\s+(?:GLOBAL\s+)?IN\s*\(?(?:\s*[^()]*,)?\s*$", before, re.I) else "in"
|
|
363
|
+
elif lst == "set":
|
|
364
|
+
op = "set"
|
|
365
|
+
elif lst == "right":
|
|
366
|
+
op = FLIP.get(_op_word(RIGHT_COMPARE_OP.match(after).group("op")), _op_word(RIGHT_COMPARE_OP.match(after).group("op")))
|
|
367
|
+
elif mm.re is LEFT_BETWEEN:
|
|
368
|
+
op = "upper" if re.search(r"\bAND\s*$", before, re.I) else "lower"
|
|
369
|
+
else:
|
|
370
|
+
op = _op_word((OP_ONLY.search(before) or re.match("(?P<op>)", "")).group("op")) or "="
|
|
371
|
+
got = _column_type(mm.group("col"), aliases, columns)
|
|
372
|
+
if got:
|
|
373
|
+
t, c, ct = got
|
|
374
|
+
col_ref = (t, c)
|
|
375
|
+
if lst == "func":
|
|
376
|
+
fn = mm.group("fn").lower()
|
|
377
|
+
if fn in ("tostring", "hex", "lowerutf8", "upperutf8") or (fn in ("lower", "upper") and engine == "clickhouse"
|
|
378
|
+
and not re.match(r"(?:Nullable\()?(?:LowCardinality\()?(?:String|FixedString)", ct)):
|
|
379
|
+
typ = "String" if engine == "clickhouse" else "text" # toString(uuid_col) = ?: the value is text
|
|
380
|
+
elif fn in ("lower", "upper", "trim", "trimboth", "coalesce", "ifnull"):
|
|
381
|
+
typ = ct
|
|
382
|
+
elif fn in ("length", "count", "lengthutf8", "char_length"):
|
|
383
|
+
typ = _count_type(engine)
|
|
384
|
+
elif fn.startswith(("todate", "tostartof", "date_trunc", "date")):
|
|
385
|
+
typ = ("Date" if fn == "todate" else ct) if engine == "clickhouse" else ct
|
|
386
|
+
else:
|
|
387
|
+
typ = ct
|
|
388
|
+
elif lst == "element":
|
|
389
|
+
el = _element(ct)
|
|
390
|
+
typ = el if mm.group("fn").lower() in ("has", "indexof", "arrayexists") else ct
|
|
391
|
+
elif lst == "element_any":
|
|
392
|
+
typ = _array_of(ct, engine)
|
|
393
|
+
else:
|
|
394
|
+
typ = ct
|
|
395
|
+
basis = f"column {t}.{c}"
|
|
396
|
+
if lst == "in" and kind != "chname":
|
|
397
|
+
# `col IN ?` (ClickHouse binds a whole list) or `col IN (?)` / `col IN (?, ?)` (one value each)
|
|
398
|
+
as_list = engine == "clickhouse" and not re.search(r"\(\s*(?:[^()]*,)?\s*$", before)
|
|
399
|
+
if not typ and engine == "clickhouse" and (ARRAY_ANY_ARG.search(before) or (ARRAY_FIRST.search(before) and not
|
|
400
|
+
re.match(r"\s*\)", after))):
|
|
401
|
+
typ, basis = "Array(String)", "array_argument" # arrayZip(?, ?), has(?, x), arrayJoin(?): a list
|
|
402
|
+
if not typ and engine == "clickhouse" and (c := FROM_EPOCH.search(before)):
|
|
403
|
+
typ, basis, through = "Int64", "cast", c.group("fn").lower() # fromUnixTimestamp64Second(?): a number
|
|
404
|
+
if not typ and (tf := LEFT_TIME_FN.search(before)):
|
|
405
|
+
typ, basis = _time_type(engine), "time_text"
|
|
406
|
+
through = through or tf.group("fn").lower()
|
|
407
|
+
if not typ:
|
|
408
|
+
basis = "untyped"
|
|
409
|
+
if not op:
|
|
410
|
+
# typed by a declaration or a cast: how it is used, and the column it is used with, still matter for its value
|
|
411
|
+
for rx, kind_of_use in ((LEFT_BETWEEN, "between"), (LEFT_IN, "in"), (LEFT_COMPARE, "cmp"), (RIGHT_COMPARE, "right")):
|
|
412
|
+
mm = rx.match(after) if kind_of_use == "right" else rx.search(before)
|
|
413
|
+
if not mm or re.fullmatch(r"(?i)and|or|not|where|on|when|then|else|select|null|true|false|case|having|prewhere|is",
|
|
414
|
+
_bare(mm.group("col"))):
|
|
415
|
+
continue
|
|
416
|
+
if kind_of_use == "between":
|
|
417
|
+
op = "upper" if re.search(r"\bAND\s*$", before, re.I) else "lower"
|
|
418
|
+
elif kind_of_use == "in":
|
|
419
|
+
op = "not in" if re.search(r"\bNOT\s+(?:GLOBAL\s+)?IN\b[^()]*\(?[^()]*$", before, re.I) else "in"
|
|
420
|
+
elif kind_of_use == "right":
|
|
421
|
+
w = _op_word(RIGHT_COMPARE_OP.match(after).group("op"))
|
|
422
|
+
op = FLIP.get(w, w)
|
|
423
|
+
else:
|
|
424
|
+
op = _op_word((OP_ONLY.search(before) or re.match("(?P<op>)", "")).group("op")) or "="
|
|
425
|
+
if col_ref is None and (got := _column_type(mm.group("col"), aliases, columns)):
|
|
426
|
+
col_ref = (got[0], got[1])
|
|
427
|
+
break
|
|
428
|
+
if not op and (oo := OP_ONLY.search(before)):
|
|
429
|
+
op = _op_word(oo.group("op"))
|
|
430
|
+
if not op:
|
|
431
|
+
op = "stand_in" if basis == "untyped" else "value"
|
|
432
|
+
# the name: the code's own name keeps one value for every use of it; positional ones get their index
|
|
433
|
+
if kind in ("num",):
|
|
434
|
+
key = f"${own}"
|
|
435
|
+
elif kind in ("q", "pys"):
|
|
436
|
+
positional += 1
|
|
437
|
+
key = f"#{positional}"
|
|
438
|
+
else:
|
|
439
|
+
key = own or f"#{i}"
|
|
440
|
+
name = named.get(key)
|
|
441
|
+
if name is None:
|
|
442
|
+
name = re.sub(r"\W", "_", own) if kind in ("chname", "pyname", "colon", "at", "atb", "dollarb") and own else f"{prefix}{len(named) + 1}"
|
|
443
|
+
if name in params and key not in named:
|
|
444
|
+
name = f"{name}_{len(named) + 1}"
|
|
445
|
+
named[key] = name
|
|
446
|
+
if typ:
|
|
447
|
+
typ = _ch_param_type(typ) if engine == "clickhouse" else typ
|
|
448
|
+
if as_list:
|
|
449
|
+
typ = _array_of(typ, engine)
|
|
450
|
+
else:
|
|
451
|
+
typ = "String" if engine == "clickhouse" else "text"
|
|
452
|
+
if name not in b.untyped:
|
|
453
|
+
b.untyped.append(name)
|
|
454
|
+
if name not in params:
|
|
455
|
+
value = None
|
|
456
|
+
# a row's value only for an equality, IN or membership test: a range bound (`< $1` cutoff, BETWEEN) given the
|
|
457
|
+
# middle row's value would select half the table or skew a retention delete
|
|
458
|
+
ranged = bool(re.search(r"(?:<|>|<=|>=|\bBETWEEN\b(?:(?!\bAND\b).)*|\bBETWEEN\b.*\bAND)\s*(?:\(\s*)*$", before, re.I | re.S)) \
|
|
459
|
+
and not re.search(r"(?:<>|!=)\s*$", before)
|
|
460
|
+
if values is not None and col_ref is not None and not ranged:
|
|
461
|
+
value = values(col_ref[0], col_ref[1], typ)
|
|
462
|
+
if value is not None and as_list:
|
|
463
|
+
value = [value]
|
|
464
|
+
if value is None:
|
|
465
|
+
if basis == "limit":
|
|
466
|
+
value = 0 if re.search(r"OFFSET\s*$", before, re.I) else 100
|
|
467
|
+
elif basis == "interval":
|
|
468
|
+
value = 1
|
|
469
|
+
elif basis == "time_text":
|
|
470
|
+
value = "2026-01-01 00:00:00"
|
|
471
|
+
else:
|
|
472
|
+
value = _neutral(typ, engine, "uuid" if through.startswith("touuid") else col_ref[1] if col_ref else name)
|
|
473
|
+
params[name] = value
|
|
474
|
+
b.types[name] = typ
|
|
475
|
+
b.basis[name] = basis
|
|
476
|
+
b.ops[name] = op
|
|
477
|
+
if through:
|
|
478
|
+
b.through[name] = through
|
|
479
|
+
if col_ref:
|
|
480
|
+
b.columns[name] = col_ref
|
|
481
|
+
out.append(sql[last:m.start()] + "{" + f"{name}:{b.types.get(name, typ)}" + "}")
|
|
482
|
+
last = end
|
|
483
|
+
out.append(sql[last:])
|
|
484
|
+
b.sql = "".join(out)
|
|
485
|
+
return b
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def columns_from_definitions(definitions: list[dict]) -> dict[str, dict[str, str]]:
|
|
489
|
+
"""table -> {column: type} from CREATE TABLE texts (the sandbox's definitions)."""
|
|
490
|
+
from .rank import _columns
|
|
491
|
+
out: dict[str, dict[str, str]] = {}
|
|
492
|
+
for d in definitions:
|
|
493
|
+
got = _columns(d.get("create_sql") or "", d["name"])
|
|
494
|
+
cols: dict[str, str] = {}
|
|
495
|
+
for c, text in (got[1] if got else {}).items():
|
|
496
|
+
words = text.split(None, 1)
|
|
497
|
+
if len(words) < 2:
|
|
498
|
+
continue
|
|
499
|
+
t = re.split(r"\s+(?:NOT\s+NULL|NULL|DEFAULT|PRIMARY|REFERENCES|CODEC|COMMENT|MATERIALIZED|ALIAS|EPHEMERAL|TTL|"
|
|
500
|
+
r"CONSTRAINT|UNIQUE|CHECK|GENERATED|COLLATE)\b", words[1].rstrip(","), maxsplit=1, flags=re.I)[0].strip()
|
|
501
|
+
cols[c.replace('"', "").replace("`", "").lower()] = t
|
|
502
|
+
out.setdefault(_bare(d["name"]), {}).update(cols)
|
|
503
|
+
return out
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def columns_from_catalog(catalog: dict | None, engine: str) -> dict[str, dict[str, str]]:
|
|
507
|
+
"""table -> {column: type} from every pulled connection of the engine (db_catalog.json): every database counts."""
|
|
508
|
+
out: dict[str, dict[str, str]] = {}
|
|
509
|
+
for conn in ((catalog or {}).get("connections") or {}).values():
|
|
510
|
+
if conn.get("engine") != engine:
|
|
511
|
+
continue
|
|
512
|
+
for t in conn.get("tables") or []:
|
|
513
|
+
cols = {c["name"].lower(): c.get("type") or "" for c in t.get("columns") or [] if c.get("name")}
|
|
514
|
+
out.setdefault(t["name"].lower(), {}).update({k: v for k, v in cols.items() if k not in out.get(t["name"].lower(), {})})
|
|
515
|
+
return out
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def columns_from_inventory(inventory: dict | None, engine: str) -> dict[str, dict[str, str]]:
|
|
519
|
+
"""table -> {column: type} from the repository's own definitions (migrations, DDL files, models)."""
|
|
520
|
+
out: dict[str, dict[str, str]] = {}
|
|
521
|
+
for t in (inventory or {}).get("tables") or []:
|
|
522
|
+
name = _bare(t.get("name") or "")
|
|
523
|
+
if not name or t.get("test_only"):
|
|
524
|
+
continue
|
|
525
|
+
is_ch = bool(t.get("engine"))
|
|
526
|
+
if (engine == "clickhouse") != is_ch:
|
|
527
|
+
continue
|
|
528
|
+
for c in t.get("columns") or []:
|
|
529
|
+
if c.get("name") and c.get("type"):
|
|
530
|
+
out.setdefault(name, {}).setdefault(c["name"].lower(), c["type"])
|
|
531
|
+
return out
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def merged_columns(*sources: dict[str, dict[str, str]]) -> dict[str, dict[str, str]]:
|
|
535
|
+
"""The first source that knows a table's column wins (pass the real catalog first)."""
|
|
536
|
+
out: dict[str, dict[str, str]] = {}
|
|
537
|
+
for src in sources:
|
|
538
|
+
for t, cols in src.items():
|
|
539
|
+
have = out.setdefault(t, {})
|
|
540
|
+
for c, typ in cols.items():
|
|
541
|
+
have.setdefault(c, typ)
|
|
542
|
+
return out
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def sandbox_values(sb, engine: str, cache: dict | None = None):
|
|
546
|
+
"""A `values` lookup for `bind` that reads a value the sandbox's generated rows hold: the column's value in the
|
|
547
|
+
table's middle row, so an equality on it selects rows (never a real value: the sandbox holds generated data only).
|
|
548
|
+
None when the table is empty or not built."""
|
|
549
|
+
cache = {} if cache is None else cache
|
|
550
|
+
|
|
551
|
+
def look(table: str, column: str, typ: str):
|
|
552
|
+
key = (table, column)
|
|
553
|
+
if key not in cache:
|
|
554
|
+
try:
|
|
555
|
+
if engine == "clickhouse":
|
|
556
|
+
q = ".".join(f"`{p}`" for p in table.split("."))
|
|
557
|
+
n = int((sb.rows(f"SELECT count() AS n FROM {q}") or [{"n": 0}])[0]["n"])
|
|
558
|
+
got = sb.rows(f"SELECT toString(`{column}`) AS v FROM {q} LIMIT 1 OFFSET {max(n // 2, 0)}") if n else []
|
|
559
|
+
else:
|
|
560
|
+
q = ".".join(f'"{p}"' for p in table.split("."))
|
|
561
|
+
n = int((sb.rows(f"SELECT count(*) AS n FROM {q}") or [{"n": 0}])[0]["n"])
|
|
562
|
+
got = sb.rows(f'SELECT ("{column}")::text AS v FROM {q} WHERE "{column}" IS NOT NULL '
|
|
563
|
+
f"OFFSET {max(n // 2, 0)} LIMIT 1") if n else []
|
|
564
|
+
cache[key] = got[0]["v"] if got else None
|
|
565
|
+
except Exception: # noqa: BLE001 - no value: the neutral one is used
|
|
566
|
+
cache[key] = None
|
|
567
|
+
v = cache[key]
|
|
568
|
+
if v is None:
|
|
569
|
+
return None
|
|
570
|
+
base = _base(typ).lower()
|
|
571
|
+
if base.startswith("array(") or base.endswith("[]"):
|
|
572
|
+
return None
|
|
573
|
+
if re.match(r"u?int|float|decimal|(?:small|big)?int|integer|numeric|real|double", base) and re.fullmatch(r"-?\d+(\.\d+)?", str(v)):
|
|
574
|
+
return float(v) if "." in str(v) else int(v)
|
|
575
|
+
return v
|
|
576
|
+
return look
|