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
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
"""Collect table definitions and engine-version evidence from any text file.
|
|
2
|
+
|
|
3
|
+
Language-agnostic on purpose: CREATE TABLE statements live in Python strings,
|
|
4
|
+
Rust raw strings, .sql files and test fixtures alike, so this scans raw text
|
|
5
|
+
instead of going through a language parser.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import asdict, dataclass, field
|
|
12
|
+
|
|
13
|
+
from .base import is_test_path
|
|
14
|
+
|
|
15
|
+
# A template token between the name and the column list (`CREATE TABLE logs @on_cluster (`,
|
|
16
|
+
# `CREATE TABLE logs {{ .OnCluster }} (`, `CREATE TABLE logs %s (`): the statement is still a definition.
|
|
17
|
+
_TEMPLATE_GAP = r"(?:@\w+|\{\{[^{}]*\}\}|\$\{[^{}]*\}|\{\w*\}|%s|«[^»]*»)"
|
|
18
|
+
CREATE = re.compile(
|
|
19
|
+
r"CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?"
|
|
20
|
+
r"((?:[\w`\"{}.$]|«[^»]*»|\{\{[^{}]*\}\})+)\s*(?:ON\s+CLUSTER\s+\S+\s*|" + _TEMPLATE_GAP + r"\s*)?(?:UUID\s+'[^']*'\s*)?\(",
|
|
21
|
+
re.I,
|
|
22
|
+
)
|
|
23
|
+
_IDENT = r"((?:[\w`\"]+\.)?[\w`\"]+)"
|
|
24
|
+
# `ALTER TABLE a RENAME TO b` (Postgres, SQLite, MySQL), `RENAME TABLE a TO b` (ClickHouse, MySQL)
|
|
25
|
+
RENAME_TABLE = re.compile(
|
|
26
|
+
rf"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{_IDENT}\s+RENAME\s+TO\s+{_IDENT}|"
|
|
27
|
+
rf"RENAME\s+TABLE\s+{_IDENT}\s+TO\s+{_IDENT}", re.I)
|
|
28
|
+
RENAME_COLUMN = re.compile(
|
|
29
|
+
rf"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{_IDENT}\s+RENAME\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?"
|
|
30
|
+
r"[`\"]?(\w+)[`\"]?\s+TO\s+[`\"]?(\w+)[`\"]?", re.I)
|
|
31
|
+
# The longest column list read as one definition, in characters. A setting: `[discover] max_table_chars`.
|
|
32
|
+
DEFAULT_MAX_TABLE_CHARS = 2_000_000
|
|
33
|
+
MAX_TABLE_CHARS = DEFAULT_MAX_TABLE_CHARS
|
|
34
|
+
# How far past the column list the ENGINE, ORDER BY and PARTITION BY clauses are looked for, in characters.
|
|
35
|
+
# A setting: `[discover] max_table_tail_chars`.
|
|
36
|
+
DEFAULT_MAX_TABLE_TAIL_CHARS = 2500
|
|
37
|
+
MAX_TABLE_TAIL_CHARS = DEFAULT_MAX_TABLE_TAIL_CHARS
|
|
38
|
+
STRING_END = re.compile(r'"""|\'\'\'|"#|`\s*[;,)]|"\s*[;,)]\s*$|;\s*$', re.M)
|
|
39
|
+
# the engine name, or the template token that stands for it (`ENGINE @merge_tree`, `ENGINE = {{ .Engine }}`)
|
|
40
|
+
ENGINE = re.compile(r"\bENGINE\s*=?\s*(\w+|@\w+|\{\{[^{}]*\}\}|\$\{[^{}]*\}|«[^»]*»)\s*(\([^)]*\))?", re.I)
|
|
41
|
+
CLAUSE = r"\b{kw}\s+(.+?)(?=\s+(?:PARTITION\s+BY|PRIMARY\s+KEY|ORDER\s+BY|SAMPLE\s+BY|TTL|SETTINGS|COMMENT)\b|$)"
|
|
42
|
+
COLUMN = re.compile(r"^\s*[`\"]?(\w+)[`\"]?\s+((?:\w+)(?:\s*\((?:[^()]|\([^()]*\))*\))?)", re.S)
|
|
43
|
+
NOT_COLUMNS = {"index", "projection", "constraint", "primary", "foreign", "unique", "check", "key"}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Table:
|
|
48
|
+
name: str
|
|
49
|
+
engine: str = "" # MergeTree family name, or "" for a plain SQL table (Postgres, SQLite)
|
|
50
|
+
engine_args: str = ""
|
|
51
|
+
order_by: str = ""
|
|
52
|
+
partition_by: str = ""
|
|
53
|
+
primary_key: str = ""
|
|
54
|
+
ttl: str = ""
|
|
55
|
+
columns: list[dict] = field(default_factory=list)
|
|
56
|
+
defined_at: list[str] = field(default_factory=list) # file:line, every place a definition was seen
|
|
57
|
+
name_basis: str = "sql" # sql | constant | file_name | unresolved (the name is built at run time)
|
|
58
|
+
test_only: bool = False # every definition seen lives in test code or fixtures: never preferred
|
|
59
|
+
renamed_from: list[str] = field(default_factory=list) # earlier names, when a later statement renamed it
|
|
60
|
+
# secondary indexes the repository creates: {name, columns, unique, where?, include?, method?, at?}. Columns are
|
|
61
|
+
# names; an index on an expression keeps its text in `expr` and no columns.
|
|
62
|
+
indexes: list[dict] = field(default_factory=list)
|
|
63
|
+
# the dialect the column types are written for when they were translated (ent's schema.go: postgres), else ""
|
|
64
|
+
types_for: str = ""
|
|
65
|
+
added_columns: list[str] = field(default_factory=list) # file:line of each ALTER TABLE ... ADD COLUMN applied
|
|
66
|
+
# "test_fixtures": the application never defines this table (it creates it at run time, from migrations run in code), so
|
|
67
|
+
# the definition is the one its test fixtures hold: schema from the repository's test fixtures
|
|
68
|
+
schema_source: str = ""
|
|
69
|
+
|
|
70
|
+
def to_dict(self) -> dict:
|
|
71
|
+
out = asdict(self)
|
|
72
|
+
for key in ("indexes", "types_for", "added_columns", "schema_source"): # only when there is something to say
|
|
73
|
+
if not out[key]:
|
|
74
|
+
out.pop(key)
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _balanced(text: str, start: int) -> int:
|
|
79
|
+
"""Index just past the parenthesis that closes the one at `start`, or -1."""
|
|
80
|
+
depth, i, n, quote = 0, start, len(text), ""
|
|
81
|
+
while i < n:
|
|
82
|
+
c = text[i]
|
|
83
|
+
if quote:
|
|
84
|
+
if c == "\\":
|
|
85
|
+
i += 1
|
|
86
|
+
elif c == quote:
|
|
87
|
+
quote = ""
|
|
88
|
+
elif c == "'":
|
|
89
|
+
quote = c
|
|
90
|
+
elif c == "(":
|
|
91
|
+
depth += 1
|
|
92
|
+
elif c == ")":
|
|
93
|
+
depth -= 1
|
|
94
|
+
if depth == 0:
|
|
95
|
+
return i + 1
|
|
96
|
+
i += 1
|
|
97
|
+
return -1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _split_top(text: str) -> list[str]:
|
|
101
|
+
parts, depth, cur, quote = [], 0, [], ""
|
|
102
|
+
for c in text:
|
|
103
|
+
if quote:
|
|
104
|
+
cur.append(c)
|
|
105
|
+
if c == quote:
|
|
106
|
+
quote = ""
|
|
107
|
+
continue
|
|
108
|
+
if c == "'":
|
|
109
|
+
quote = c
|
|
110
|
+
elif c == "(":
|
|
111
|
+
depth += 1
|
|
112
|
+
elif c == ")":
|
|
113
|
+
depth -= 1
|
|
114
|
+
if c == "," and depth == 0:
|
|
115
|
+
parts.append("".join(cur))
|
|
116
|
+
cur = []
|
|
117
|
+
else:
|
|
118
|
+
cur.append(c)
|
|
119
|
+
if cur:
|
|
120
|
+
parts.append("".join(cur))
|
|
121
|
+
return parts
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _clause(tail: str, kw: str) -> str:
|
|
125
|
+
m = re.search(CLAUSE.format(kw=kw), tail, re.I | re.S)
|
|
126
|
+
return " ".join(m.group(1).split()).rstrip(";") if m else ""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def find_tables(rel: str, text: str, consts: dict[str, set[str]] | None = None) -> list[Table]:
|
|
130
|
+
out: list[Table] = []
|
|
131
|
+
local = find_name_constants(text) if "CREATE" in text.upper() else {}
|
|
132
|
+
for m in CREATE.finditer(text):
|
|
133
|
+
open_paren = m.end() - 1
|
|
134
|
+
close = _balanced(text, open_paren)
|
|
135
|
+
if close < 0 or close - open_paren > MAX_TABLE_CHARS:
|
|
136
|
+
continue
|
|
137
|
+
name = m.group(1).strip("`\"")
|
|
138
|
+
basis = "sql"
|
|
139
|
+
# `{db}.events` / `«DB».events`: a run-time database prefix does not hide the table name
|
|
140
|
+
prefixed = re.fullmatch(r"(?:\{\{[^{}]*\}\}|\{\w*\}|«[^»]*»|\$\{?\w+\}?)\.([A-Za-z_]\w*)", name)
|
|
141
|
+
if prefixed:
|
|
142
|
+
name = prefixed.group(1)
|
|
143
|
+
const = re.fullmatch(r"\{(\w+)\}|«(\w+)»|\$\{?(\w+)\}?", name)
|
|
144
|
+
if const:
|
|
145
|
+
key = next(g for g in const.groups() if g)
|
|
146
|
+
# the constant defined in this file wins over same-named constants elsewhere
|
|
147
|
+
values = {local[key]} if key in local else (consts or {}).get(key, set())
|
|
148
|
+
if len(values) == 1:
|
|
149
|
+
name, basis = next(iter(values)), "constant"
|
|
150
|
+
if not re.fullmatch(r"[A-Za-z_][\w.]*", name):
|
|
151
|
+
basis = "unresolved"
|
|
152
|
+
tail = text[close: close + MAX_TABLE_TAIL_CHARS]
|
|
153
|
+
end = STRING_END.search(tail)
|
|
154
|
+
if end:
|
|
155
|
+
tail = tail[: end.start()]
|
|
156
|
+
tail = re.sub(r"--[^\n]*", " ", tail)
|
|
157
|
+
table = Table(name=name, name_basis=basis, defined_at=[f"{rel}:{text.count(chr(10), 0, m.start()) + 1}"])
|
|
158
|
+
eng = ENGINE.search(tail)
|
|
159
|
+
if eng:
|
|
160
|
+
table.engine = eng.group(1)
|
|
161
|
+
table.engine_args = (eng.group(2) or "").strip("()")
|
|
162
|
+
table.order_by = _clause(tail, r"ORDER\s+BY")
|
|
163
|
+
table.partition_by = _clause(tail, r"PARTITION\s+BY")
|
|
164
|
+
table.primary_key = _clause(tail, r"PRIMARY\s+KEY")
|
|
165
|
+
table.ttl = _clause(tail, "TTL")
|
|
166
|
+
body = re.sub(r"--[^\n]*", "", text[open_paren + 1: close - 1])
|
|
167
|
+
for part in _split_top(body):
|
|
168
|
+
cm = COLUMN.match(part)
|
|
169
|
+
# a quoted name is a column even when it is a keyword (`index` UInt64)
|
|
170
|
+
if cm and (cm.group(1).lower() not in NOT_COLUMNS or part.lstrip()[:1] in "`\""):
|
|
171
|
+
ctype = cm.group(2)
|
|
172
|
+
op =part.find("(", cm.start(2))
|
|
173
|
+
if op >= 0 and part[cm.start(2):op].strip().isidentifier():
|
|
174
|
+
end = _balanced(part, op) # nested types: SimpleAggregateFunction(f, Array(Enum8('a' = 1)))
|
|
175
|
+
if end > 0:
|
|
176
|
+
ctype = part[cm.start(2):end]
|
|
177
|
+
table.columns.append({"name": cm.group(1), "type": " ".join(ctype.split())})
|
|
178
|
+
if table.columns:
|
|
179
|
+
out.append(table)
|
|
180
|
+
return out
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
CONST_DEF = re.compile(
|
|
184
|
+
r"^[ \t]*(?:pub(?:\([a-z]+\))?\s+)?(?:const|static|final|var|let)?\s*([A-Z_][A-Z0-9_]{2,})\s*(?::\s*&?\s*(?:'static\s+)?[sS]tr(?:ing)?)?"
|
|
185
|
+
r"\s*:?=\s*[rfb]?#?\"([A-Za-z_][\w.]{1,80})\"",
|
|
186
|
+
re.M,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# CONST_DEF from the name on, without the line start and the keywords before it: every match of CONST_DEF holds
|
|
191
|
+
# a match of this, and this one is quick to rule out (CONST_DEF retries each indented line once per space).
|
|
192
|
+
CONST_DEF_TAIL = re.compile(CONST_DEF.pattern[CONST_DEF.pattern.index("([A-Z_]"):])
|
|
193
|
+
CONST_DEF_VALUE = re.compile(r"=\s*[rfb]?#?\"[A-Za-z_]") # and the end of that: `= "name`, the cheapest to look for
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def find_name_constants(text: str) -> dict[str, str]:
|
|
197
|
+
"""NAME = "identifier_like_value" in any language: enough to resolve table-name constants."""
|
|
198
|
+
if not CONST_DEF_VALUE.search(text) or not CONST_DEF_TAIL.search(text):
|
|
199
|
+
return {}
|
|
200
|
+
return {m.group(1): m.group(2) for m in CONST_DEF.finditer(text)}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _source_rank(location: str) -> int:
|
|
204
|
+
"""Application code beats tests, tests beat docs and fixtures."""
|
|
205
|
+
path = location.rsplit(":", 1)[0]
|
|
206
|
+
if path.endswith((".md", ".json", ".txt")):
|
|
207
|
+
return 0
|
|
208
|
+
return 1 if _in_tests(path) else 2
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
TEST_HINT = re.compile(r"(^|/)(tests?|testdata|fixtures|page_tests)(/|$)|(^|/)test_|_test\.")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _in_tests(path: str) -> bool:
|
|
215
|
+
return bool(TEST_HINT.search(path)) or is_test_path(path)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _order_key(location: str) -> tuple:
|
|
219
|
+
"""Migrations run in name order: 0002_x before 0010_y, and a statement before the ones below it."""
|
|
220
|
+
path, _, line = location.rpartition(":")
|
|
221
|
+
return tuple(int(p) if p.isdigit() else p for p in re.split(r"(\d+)", path)), int(line or 0)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _bare(name: str) -> str:
|
|
225
|
+
return name.replace("`", "").replace('"', "")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def find_renames(rel: str, text: str) -> list[dict]:
|
|
229
|
+
"""Table and column renames in any text, in file order."""
|
|
230
|
+
out: list[dict] = []
|
|
231
|
+
if "RENAME" not in text and "rename" not in text:
|
|
232
|
+
return out
|
|
233
|
+
for m in RENAME_TABLE.finditer(text):
|
|
234
|
+
old, new = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), m.group(4))
|
|
235
|
+
out.append({"kind": "table", "table": _bare(old), "to": _bare(new),
|
|
236
|
+
"at": f"{rel}:{text.count(chr(10), 0, m.start()) + 1}"})
|
|
237
|
+
for m in RENAME_COLUMN.finditer(text):
|
|
238
|
+
if m.group(2).upper() in ("TO", "COLUMN", "CONSTRAINT", "INDEX"):
|
|
239
|
+
continue
|
|
240
|
+
out.append({"kind": "column", "table": _bare(m.group(1)), "column": m.group(2), "to": m.group(3),
|
|
241
|
+
"at": f"{rel}:{text.count(chr(10), 0, m.start()) + 1}"})
|
|
242
|
+
return out
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
CREATE_INDEX = re.compile(
|
|
246
|
+
r"\bCREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?([`\"\w.]+\s+)?ON\s+(?:ONLY\s+)?([`\"\w.]+)\s*"
|
|
247
|
+
r"(?:USING\s+(\w+)\s*)?\(", re.I)
|
|
248
|
+
ALTER_TABLE = re.compile(rf"\bALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?{_IDENT}\s+(?=ADD\b)", re.I)
|
|
249
|
+
ADD_COLUMN = re.compile(
|
|
250
|
+
r"(?:^|,)\s*ADD\s+(?!CONSTRAINT\b|INDEX\b|PRIMARY\b|UNIQUE\b|FOREIGN\b|CHECK\b|PROJECTION\b|PARTITION\b|STATISTICS\b|KEY\b)"
|
|
251
|
+
r"(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?[`\"]?(\w+)[`\"]?\s+((?:\w+)(?:\s+(?:precision|varying|with(?:out)?\s+time\s+zone))?"
|
|
252
|
+
r"(?:\s*\((?:[^()]|\([^()]*\))*\))?(?:\s*\[\])?)", re.I)
|
|
253
|
+
PLAIN_COLUMN = re.compile(r"^[`\"]?(\w+)[`\"]?(?:\s+\w+_ops)?(?:\s+(?:ASC|DESC))?(?:\s+NULLS\s+(?:FIRST|LAST))?$", re.I)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _statement_end(text: str, start: int, sql_file: bool = False) -> int:
|
|
257
|
+
"""Where the statement that starts at `start` ends: its `;`, or the end of the string literal holding it. In a .sql
|
|
258
|
+
file there is no host string: only the `;` ends it (a quoted identifier before it, `"live_revision";`, is not
|
|
259
|
+
the end of a string literal: cutting there leaves an unclosed quote, and psql waits for more input)."""
|
|
260
|
+
if sql_file:
|
|
261
|
+
semi = text.find(";", start)
|
|
262
|
+
return semi if semi >= 0 else len(text)
|
|
263
|
+
end = STRING_END.search(text, start)
|
|
264
|
+
semi = text.find(";", start)
|
|
265
|
+
candidates = [p for p in (end.start() if end else -1, semi) if p >= 0]
|
|
266
|
+
return min(candidates) if candidates else len(text)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
CREATE_FUNCTION = re.compile(r"\bCREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+((?:\"?\w+\"?\.)?\"?\w+\"?)\s*\(", re.I)
|
|
270
|
+
DOLLAR = re.compile(r"\$(\w*)\$")
|
|
271
|
+
MAX_FUNCTION_CHARS = 20_000
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def find_sql_functions(rel: str, text: str) -> list[dict]:
|
|
275
|
+
"""`CREATE [OR REPLACE] FUNCTION name(...) ... LANGUAGE sql ... AS $tag$ body $tag$;` in a .sql file: {name, sql,
|
|
276
|
+
defined_at}. Only LANGUAGE sql functions that return no trigger: a plpgsql body or a trigger function is not what
|
|
277
|
+
a read calls, and the sandbox should not run procedural code it does not need. The statement ends at the `;` after
|
|
278
|
+
the closing dollar quote."""
|
|
279
|
+
out = []
|
|
280
|
+
for m in CREATE_FUNCTION.finditer(text):
|
|
281
|
+
start = m.start()
|
|
282
|
+
q = DOLLAR.search(text, m.end())
|
|
283
|
+
if not q:
|
|
284
|
+
continue
|
|
285
|
+
close = text.find(q.group(0), q.end())
|
|
286
|
+
if close < 0:
|
|
287
|
+
continue
|
|
288
|
+
semi = text.find(";", close + len(q.group(0)))
|
|
289
|
+
end = semi if semi >= 0 else len(text)
|
|
290
|
+
stmt = text[start:end].strip()
|
|
291
|
+
head = (text[m.end():q.start()] + " " + text[close + len(q.group(0)):end]).lower()
|
|
292
|
+
if len(stmt) > MAX_FUNCTION_CHARS or "returns trigger" in head or not re.search(r"\blanguage\s+'?sql'?\b", head):
|
|
293
|
+
continue
|
|
294
|
+
out.append({"name": m.group(1).replace('"', "").lower(), "sql": stmt,
|
|
295
|
+
"defined_at": f"{rel}:{text.count(chr(10), 0, start) + 1}"})
|
|
296
|
+
return out
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def last_functions(found: list[dict]) -> list[dict]:
|
|
300
|
+
"""One definition per function name: the last one found (migrations are read in file order)."""
|
|
301
|
+
by_name: dict[str, dict] = {}
|
|
302
|
+
for f in sorted(found, key=lambda f: _order_key(f["defined_at"])):
|
|
303
|
+
by_name[f["name"]] = f
|
|
304
|
+
return list(by_name.values())
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def find_indexes(rel: str, text: str) -> list[dict]:
|
|
308
|
+
"""`CREATE [UNIQUE] INDEX name ON table [USING m] (columns) [INCLUDE (...)] [WHERE ...]` in any text, in file order:
|
|
309
|
+
{table, name, columns | expr, unique, where?, include?, method?, at}."""
|
|
310
|
+
out = []
|
|
311
|
+
if "INDEX" not in text.upper():
|
|
312
|
+
return out
|
|
313
|
+
for m in CREATE_INDEX.finditer(text):
|
|
314
|
+
close = _balanced(text, m.end() - 1)
|
|
315
|
+
if close < 0:
|
|
316
|
+
continue
|
|
317
|
+
parts = [" ".join(p.split()) for p in _split_top(text[m.end(): close - 1])]
|
|
318
|
+
plain = [PLAIN_COLUMN.match(p) for p in parts]
|
|
319
|
+
rec = {"table": _bare(m.group(3)), "name": _bare((m.group(2) or "").strip()), "unique": bool(m.group(1))}
|
|
320
|
+
if all(plain) and parts:
|
|
321
|
+
rec["columns"] = [p.group(1) for p in plain]
|
|
322
|
+
else:
|
|
323
|
+
rec["expr"] = ", ".join(parts)
|
|
324
|
+
if m.group(4) and m.group(4).lower() != "btree":
|
|
325
|
+
rec["method"] = m.group(4).lower()
|
|
326
|
+
tail = text[close: _statement_end(text, close, rel.lower().endswith(".sql"))]
|
|
327
|
+
inc = re.match(r"\s*INCLUDE\s*\(([^)]*)\)", tail, re.I)
|
|
328
|
+
if inc:
|
|
329
|
+
rec["include"] = [_bare(c.strip()) for c in inc.group(1).split(",") if c.strip()]
|
|
330
|
+
where = re.search(r"\bWHERE\s+(.+)$", tail, re.I | re.S)
|
|
331
|
+
if where:
|
|
332
|
+
rec["where"] = " ".join(where.group(1).split())
|
|
333
|
+
if rec["where"].count('"') % 2:
|
|
334
|
+
# a quoted identifier cut at the string-literal heuristic: the predicate is not kept half-quoted
|
|
335
|
+
stop = close + len(tail)
|
|
336
|
+
if text[stop:stop + 1] == '"':
|
|
337
|
+
rec["where"] += '"'
|
|
338
|
+
else:
|
|
339
|
+
rec.pop("where")
|
|
340
|
+
rec["at"] = f"{rel}:{text.count(chr(10), 0, m.start()) + 1}"
|
|
341
|
+
out.append(rec)
|
|
342
|
+
return out
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def find_added_columns(rel: str, text: str) -> list[dict]:
|
|
346
|
+
"""`ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] c type` in any text, in file order: {table, column, type, at}."""
|
|
347
|
+
out = []
|
|
348
|
+
if "ADD" not in text.upper():
|
|
349
|
+
return out
|
|
350
|
+
for m in ALTER_TABLE.finditer(text):
|
|
351
|
+
body = text[m.end(): _statement_end(text, m.end())]
|
|
352
|
+
at = f"{rel}:{text.count(chr(10), 0, m.start()) + 1}"
|
|
353
|
+
for a in ADD_COLUMN.finditer(body):
|
|
354
|
+
out.append({"table": _bare(m.group(1)), "column": a.group(1), "type": " ".join(a.group(2).split()), "at": at})
|
|
355
|
+
return out
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _top_dir(location: str) -> str:
|
|
359
|
+
path = location.rsplit(":", 1)[0]
|
|
360
|
+
return path.split("/", 1)[0] if "/" in path else ""
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def apply_alters(found: list[Table], indexes: list[dict], added: list[dict], several: dict[str, set[str]]) -> None:
|
|
364
|
+
"""Columns that later migrations add, then the secondary indexes the repository creates, onto the merged tables.
|
|
365
|
+
|
|
366
|
+
A table name defined in several top-level directories (two services, each with its own database) takes a
|
|
367
|
+
statement only from the directory of the definition that was kept. An index is kept only when every column it
|
|
368
|
+
names is a column of the table."""
|
|
369
|
+
by_name: dict[str, Table] = {}
|
|
370
|
+
for t in found:
|
|
371
|
+
if t.name_basis != "unresolved":
|
|
372
|
+
by_name.setdefault(t.name.split(".")[-1].lower(), t)
|
|
373
|
+
|
|
374
|
+
def target(table: str, at: str) -> Table | None:
|
|
375
|
+
t = by_name.get(table.split(".")[-1].lower())
|
|
376
|
+
if t is None or t.engine: # a ClickHouse table's skip indexes are part of its definition
|
|
377
|
+
return None
|
|
378
|
+
if len(several.get(t.name.split(".")[-1].lower(), ())) > 1 and _top_dir(at) != _top_dir(t.defined_at[0]):
|
|
379
|
+
return None
|
|
380
|
+
if _in_tests(at.rsplit(":", 1)[0]) and not t.test_only:
|
|
381
|
+
return None
|
|
382
|
+
return t
|
|
383
|
+
for a in sorted(added, key=lambda r: _order_key(r["at"])):
|
|
384
|
+
t = target(a["table"], a["at"])
|
|
385
|
+
if t is not None and not any(c["name"].lower() == a["column"].lower() for c in t.columns):
|
|
386
|
+
t.columns.append({"name": a["column"], "type": a["type"]})
|
|
387
|
+
t.added_columns.append(a["at"])
|
|
388
|
+
for ix in indexes:
|
|
389
|
+
t = target(ix["table"], ix["at"])
|
|
390
|
+
if t is None:
|
|
391
|
+
continue
|
|
392
|
+
have = {c["name"].lower() for c in t.columns}
|
|
393
|
+
if ix.get("columns") and not all(c.lower() in have for c in ix["columns"]):
|
|
394
|
+
continue
|
|
395
|
+
rec = {k: v for k, v in ix.items() if k != "table"}
|
|
396
|
+
same = [i for i in t.indexes if (i.get("name") and i.get("name") == rec.get("name"))
|
|
397
|
+
or (i.get("columns") and i.get("columns") == rec.get("columns") and i.get("where") == rec.get("where"))]
|
|
398
|
+
if not same:
|
|
399
|
+
t.indexes.append(rec)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def apply_renames(found: list[Table], renames: list[dict]) -> list[Table]:
|
|
403
|
+
"""Follow renames in migration order: a table created as `job` and renamed to `v2_job` is `v2_job`.
|
|
404
|
+
|
|
405
|
+
A rename applies to the definitions that come before it in the same directory: migration files run in
|
|
406
|
+
name order, and a statement after the ones above it. The same name created again later is a new table, and
|
|
407
|
+
a rename in one module says nothing about a definition in another (two services that each migrate their
|
|
408
|
+
own copy). The schema part of a name is kept from the new name, or from the old one when the new has none."""
|
|
409
|
+
if not renames:
|
|
410
|
+
return found
|
|
411
|
+
events = sorted(renames, key=lambda r: _order_key(r["at"]))
|
|
412
|
+
for r in events:
|
|
413
|
+
at = _order_key(r["at"])
|
|
414
|
+
r_dir = r["at"].rsplit(":", 1)[0].rpartition("/")[0]
|
|
415
|
+
r_test = _in_tests(r["at"].rsplit(":", 1)[0])
|
|
416
|
+
old = r["table"].split(".")[-1]
|
|
417
|
+
for t in found:
|
|
418
|
+
if t.name_basis == "unresolved" or t.name.split(".")[-1] != old or _order_key(t.defined_at[0]) >= at:
|
|
419
|
+
continue
|
|
420
|
+
if "." in r["table"] and "." in t.name and r["table"] != t.name:
|
|
421
|
+
continue
|
|
422
|
+
if t.defined_at[0].rsplit(":", 1)[0].rpartition("/")[0] != r_dir:
|
|
423
|
+
continue
|
|
424
|
+
if r_test and not _in_tests(t.defined_at[0].rsplit(":", 1)[0]):
|
|
425
|
+
continue # a test that renames a table does not rename the application's
|
|
426
|
+
if r["kind"] == "table":
|
|
427
|
+
new = r["to"]
|
|
428
|
+
if "." not in new and "." in t.name:
|
|
429
|
+
new = t.name.rsplit(".", 1)[0] + "." + new
|
|
430
|
+
if new != t.name:
|
|
431
|
+
t.renamed_from.append(t.name)
|
|
432
|
+
t.name = new
|
|
433
|
+
else:
|
|
434
|
+
for c in t.columns:
|
|
435
|
+
if c["name"] == r["column"]:
|
|
436
|
+
c["name"] = r["to"]
|
|
437
|
+
return found
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _is_ch(t: "Table") -> bool:
|
|
441
|
+
return bool(t.engine) and t.engine.lower() not in ("innodb", "myisam", "aria", "ndb", "ndbcluster", "tokudb")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def merge_tables(found: list[Table], referenced: set[str] | None = None, renames: list[dict] | None = None,
|
|
445
|
+
indexes: list[dict] | None = None, added: list[dict] | None = None, app_reads: set[str] | None = None) -> list[Table]:
|
|
446
|
+
"""One entry per table name: prefer application code, then the fullest
|
|
447
|
+
definition, and remember every location. A definition whose name is built at
|
|
448
|
+
run time stays separate; it takes its file's name when that is a table the
|
|
449
|
+
queries use (events.rs defines events).
|
|
450
|
+
|
|
451
|
+
Renames are followed first, in migration order. A table whose every definition
|
|
452
|
+
is in test code or fixtures is marked `test_only`: it never beats a definition
|
|
453
|
+
from application code, and callers must not treat it as the real schema."""
|
|
454
|
+
found = apply_renames(found, renames or [])
|
|
455
|
+
several: dict[str, set[str]] = {} # bare name -> the top-level directories that define it
|
|
456
|
+
for t in found:
|
|
457
|
+
if t.name_basis != "unresolved":
|
|
458
|
+
several.setdefault(t.name.split(".")[-1].lower(), set()).add(_top_dir(t.defined_at[0]))
|
|
459
|
+
by_name: dict[str, Table] = {}
|
|
460
|
+
for t in found:
|
|
461
|
+
if t.name_basis == "unresolved":
|
|
462
|
+
stem = t.defined_at[0].rsplit(":", 1)[0].rsplit("/", 1)[-1].rsplit(".", 1)[0]
|
|
463
|
+
if referenced and stem in referenced:
|
|
464
|
+
t.name, t.name_basis = stem, "file_name"
|
|
465
|
+
else:
|
|
466
|
+
by_name[f"?{t.defined_at[0]}"] = t
|
|
467
|
+
t.name = f"?{t.defined_at[0]}"
|
|
468
|
+
continue
|
|
469
|
+
# a ClickHouse table and a plain SQL table of the same name are two tables (two stores), not two definitions
|
|
470
|
+
key = t.name + ("\x00ch" if _is_ch(t) else "")
|
|
471
|
+
cur = by_name.get(key)
|
|
472
|
+
if cur is None:
|
|
473
|
+
by_name[key] = t
|
|
474
|
+
continue
|
|
475
|
+
locations = cur.defined_at + [d for d in t.defined_at if d not in cur.defined_at]
|
|
476
|
+
locations.sort(key=lambda d: -_source_rank(d))
|
|
477
|
+
better = (_source_rank(t.defined_at[0]), bool(t.engine), len(t.columns)) > (
|
|
478
|
+
_source_rank(cur.defined_at[0]), bool(cur.engine), len(cur.columns))
|
|
479
|
+
keep = t if better else cur
|
|
480
|
+
other = cur if better else t
|
|
481
|
+
keep.defined_at = [keep.defined_at[0]] + [d for d in locations if d != keep.defined_at[0]]
|
|
482
|
+
keep.renamed_from = keep.renamed_from + [n for n in other.renamed_from if n not in keep.renamed_from]
|
|
483
|
+
if other.indexes and _top_dir(other.defined_at[0]) == _top_dir(keep.defined_at[0]):
|
|
484
|
+
known = {i.get("name") for i in keep.indexes}
|
|
485
|
+
keep.indexes = keep.indexes + [i for i in other.indexes if i.get("name") not in known]
|
|
486
|
+
by_name[key] = keep
|
|
487
|
+
for t in by_name.values():
|
|
488
|
+
t.test_only = all(_source_rank(d) < 2 for d in t.defined_at)
|
|
489
|
+
# the application reads it and defines it nowhere (created at run time by migrations run in code): the test fixture's
|
|
490
|
+
# DDL is the best schema there is, and it says so
|
|
491
|
+
if t.test_only and app_reads and t.name.split(".")[-1] in app_reads and \
|
|
492
|
+
any(_source_rank(d) == 1 for d in t.defined_at):
|
|
493
|
+
t.test_only, t.schema_source = False, "test_fixtures"
|
|
494
|
+
merged = sorted(by_name.values(), key=lambda t: t.name)
|
|
495
|
+
if indexes or added:
|
|
496
|
+
apply_alters(merged, indexes or [], added or [], several)
|
|
497
|
+
return merged
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
VERSION_PATTERNS = [
|
|
501
|
+
("clickhouse", "strong", re.compile(r"clickhouse(?:/clickhouse)?-server:v?(\d+\.\d+(?:\.\d+)*)")),
|
|
502
|
+
("clickhouse", "medium", re.compile(r"\bClickHouse\s+(?:server\s+)?(?:version\s+)?v?(\d{2}\.\d+(?:\.\d+)*)", re.I)),
|
|
503
|
+
("postgres", "strong", re.compile(r"(?:image:\s*|FROM\s+|docker\.io/library/)postgres:v?(\d+(?:\.\d+)?)")),
|
|
504
|
+
("valkey", "strong", re.compile(r"valkey/valkey:v?(\d+(?:\.\d+)*)")),
|
|
505
|
+
("redis", "strong", re.compile(r"(?:image:\s*|FROM\s+)redis:v?(\d+(?:\.\d+)*)")),
|
|
506
|
+
]
|
|
507
|
+
INFRA_FILE = re.compile(r"(docker-compose[^/]*\.ya?ml|compose[^/]*\.ya?ml|Dockerfile[^/]*|\.github/workflows/[^/]+\.ya?ml|Jenkinsfile|\.tf|values[^/]*\.ya?ml|k8s/[^/]+\.ya?ml)$")
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def find_versions(rel: str, text: str) -> list[dict]:
|
|
511
|
+
out = []
|
|
512
|
+
infra = bool(INFRA_FILE.search(rel))
|
|
513
|
+
for engine, strength, pattern in VERSION_PATTERNS:
|
|
514
|
+
for m in pattern.finditer(text):
|
|
515
|
+
out.append({
|
|
516
|
+
"engine": engine, "version": m.group(1),
|
|
517
|
+
"strength": strength if infra or strength == "medium" else "medium",
|
|
518
|
+
"source": f"{rel}:{text.count(chr(10), 0, m.start()) + 1}",
|
|
519
|
+
})
|
|
520
|
+
return out
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Tables from ent's generated migration schema (`ent/migrate/schema.go`).
|
|
2
|
+
|
|
3
|
+
ent writes the whole schema it creates as Go values: a `[]*schema.Column` per table and a `*schema.Table` that names
|
|
4
|
+
the table, its primary key and its indexes by position in that column list. No CREATE TABLE text exists anywhere in
|
|
5
|
+
such a repository (ent's `client.Schema.Create` builds the tables at start-up), so without this file the tables of an
|
|
6
|
+
ent project are known only from the statements that read them.
|
|
7
|
+
|
|
8
|
+
Column types are given as ent's PostgreSQL dialect creates them (entgo.io/ent/dialect/sql/schema/postgres.go); a
|
|
9
|
+
column's own `SchemaType` for postgres wins."""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
from .schema import Table
|
|
16
|
+
|
|
17
|
+
COLUMNS = re.compile(r"^\s*(\w+)Columns\s*=\s*\[\]\*schema\.Column\{\s*$", re.M)
|
|
18
|
+
TABLE = re.compile(r"^\s*(\w+)Table\s*=\s*&schema\.Table\{\s*$", re.M)
|
|
19
|
+
FIELD = re.compile(r"(\w+):\s*(\"(?:[^\"\\]|\\.)*\"|[^,{}]+(?:\{[^{}]*\})?)")
|
|
20
|
+
COLUMN_REF = re.compile(r"(\w+)Columns\[(\d+)\]")
|
|
21
|
+
# ent's PostgreSQL types for its field types (the ones ent's postgres driver writes)
|
|
22
|
+
PG_TYPES = {"TypeBool": "boolean", "TypeTime": "timestamptz", "TypeJSON": "jsonb", "TypeUUID": "uuid", "TypeBytes": "bytea",
|
|
23
|
+
"TypeEnum": "varchar", "TypeString": "varchar", "TypeOther": "text", "TypeInt8": "smallint", "TypeInt16": "smallint",
|
|
24
|
+
"TypeInt32": "integer", "TypeInt": "bigint", "TypeInt64": "bigint", "TypeUint8": "smallint", "TypeUint16": "integer",
|
|
25
|
+
"TypeUint32": "bigint", "TypeUint": "bigint", "TypeUint64": "bigint", "TypeFloat32": "real", "TypeFloat64": "double precision"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_ent_schema(rel: str, text: str) -> bool:
|
|
29
|
+
return rel.endswith(".go") and "entgo.io/ent/dialect/sql/schema" in text and "[]*schema.Column{" in text
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _block(text: str, start: int) -> str:
|
|
33
|
+
"""The text between the brace that opens at or after `start` and the one that closes it."""
|
|
34
|
+
i = text.index("{", start)
|
|
35
|
+
depth, j, quote = 0, i, ""
|
|
36
|
+
while j < len(text):
|
|
37
|
+
c = text[j]
|
|
38
|
+
if quote:
|
|
39
|
+
if c == "\\":
|
|
40
|
+
j += 1
|
|
41
|
+
elif c == quote:
|
|
42
|
+
quote = ""
|
|
43
|
+
elif c in "\"`":
|
|
44
|
+
quote = c
|
|
45
|
+
elif c == "{":
|
|
46
|
+
depth += 1
|
|
47
|
+
elif c == "}":
|
|
48
|
+
depth -= 1
|
|
49
|
+
if depth == 0:
|
|
50
|
+
return text[i + 1:j]
|
|
51
|
+
j += 1
|
|
52
|
+
return text[i + 1:]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _items(body: str) -> list[str]:
|
|
56
|
+
"""The top-level `{...}` elements of a composite literal's body."""
|
|
57
|
+
out, depth, start, quote = [], 0, -1, ""
|
|
58
|
+
for i, c in enumerate(body):
|
|
59
|
+
if quote:
|
|
60
|
+
if c == quote and body[i - 1] != "\\":
|
|
61
|
+
quote = ""
|
|
62
|
+
continue
|
|
63
|
+
if c in "\"`":
|
|
64
|
+
quote = c
|
|
65
|
+
elif c == "{":
|
|
66
|
+
if depth == 0:
|
|
67
|
+
start = i + 1
|
|
68
|
+
depth += 1
|
|
69
|
+
elif c == "}":
|
|
70
|
+
depth -= 1
|
|
71
|
+
if depth == 0 and start >= 0:
|
|
72
|
+
out.append(body[start:i])
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _string(value: str) -> str:
|
|
77
|
+
value = value.strip()
|
|
78
|
+
if value.startswith('"') and value.endswith('"'):
|
|
79
|
+
return bytes(value[1:-1], "utf-8").decode("unicode_escape")
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _pg_type(fields: dict[str, str]) -> str:
|
|
84
|
+
schema_type = re.search(r"dialect\.Postgres:\s*\"([^\"]+)\"", fields.get("SchemaType", ""))
|
|
85
|
+
if schema_type:
|
|
86
|
+
return schema_type.group(1)
|
|
87
|
+
kind = fields.get("Type", "").strip().rsplit(".", 1)[-1]
|
|
88
|
+
out = PG_TYPES.get(kind, "text")
|
|
89
|
+
size = fields.get("Size", "").strip()
|
|
90
|
+
if kind == "TypeString" and size.isdigit() and int(size) < 2147483647 and int(size) != 65535 and int(size) <= 10485760:
|
|
91
|
+
out = f"varchar({size})"
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def find_tables(rel: str, text: str) -> list[Table]:
|
|
96
|
+
columns: dict[str, list[dict]] = {}
|
|
97
|
+
for m in COLUMNS.finditer(text):
|
|
98
|
+
cols = []
|
|
99
|
+
for item in _items(_block(text, m.end() - 1)):
|
|
100
|
+
fields = {k: v for k, v in FIELD.findall(item)}
|
|
101
|
+
if "Name" not in fields:
|
|
102
|
+
continue
|
|
103
|
+
col = {"name": _string(fields["Name"]), "type": _pg_type(fields)}
|
|
104
|
+
if fields.get("Nullable", "").strip() == "true":
|
|
105
|
+
col["nullable"] = True
|
|
106
|
+
if fields.get("Unique", "").strip() == "true":
|
|
107
|
+
col["unique"] = True
|
|
108
|
+
cols.append(col)
|
|
109
|
+
columns[m.group(1)] = cols
|
|
110
|
+
out = []
|
|
111
|
+
for m in TABLE.finditer(text):
|
|
112
|
+
body = _block(text, m.end() - 1)
|
|
113
|
+
name = re.search(r"\bName:\s*\"([^\"]+)\"", body)
|
|
114
|
+
cols_of = re.search(r"\bColumns:\s*(\w+)Columns\b", body)
|
|
115
|
+
if not name or not cols_of or cols_of.group(1) not in columns:
|
|
116
|
+
continue
|
|
117
|
+
cols = columns[cols_of.group(1)]
|
|
118
|
+
|
|
119
|
+
def names(refs: str) -> list[str]:
|
|
120
|
+
got = []
|
|
121
|
+
for prefix, n in COLUMN_REF.findall(refs):
|
|
122
|
+
if prefix == cols_of.group(1) and int(n) < len(cols):
|
|
123
|
+
got.append(cols[int(n)]["name"])
|
|
124
|
+
return got
|
|
125
|
+
pk = re.search(r"\bPrimaryKey:\s*\[\]\*schema\.Column\{([^}]*)\}", body)
|
|
126
|
+
indexes = []
|
|
127
|
+
at = body.find("Indexes:")
|
|
128
|
+
if at >= 0:
|
|
129
|
+
for item in _items(_block(body, at)):
|
|
130
|
+
iname = re.search(r"\bName:\s*\"([^\"]+)\"", item)
|
|
131
|
+
icols = re.search(r"\bColumns:\s*\[\]\*schema\.Column\{([^}]*)\}", item)
|
|
132
|
+
if not iname or not icols:
|
|
133
|
+
continue
|
|
134
|
+
where = re.search(r"\bWhere:\s*(\"(?:[^\"\\]|\\.)*\")", item)
|
|
135
|
+
indexes.append({"name": iname.group(1), "columns": names(icols.group(1)),
|
|
136
|
+
"unique": bool(re.search(r"\bUnique:\s*true", item)),
|
|
137
|
+
**({"where": _string(where.group(1))} if where else {})})
|
|
138
|
+
for c in cols:
|
|
139
|
+
if c.pop("unique", False):
|
|
140
|
+
indexes.append({"name": f"{name.group(1)}_{c['name']}_key", "columns": [c["name"]], "unique": True})
|
|
141
|
+
c.pop("nullable", None)
|
|
142
|
+
line = text.count("\n", 0, m.start()) + 1
|
|
143
|
+
out.append(Table(name=name.group(1), columns=[dict(c) for c in cols], defined_at=[f"{rel}:{line}"],
|
|
144
|
+
primary_key=", ".join(names(pk.group(1))) if pk else "", indexes=indexes, types_for="postgres"))
|
|
145
|
+
return out
|