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,444 @@
|
|
|
1
|
+
"""Reading Postgres DDL as text: split a script, parse a table and its indexes, strip what a sandbox cannot honour.
|
|
2
|
+
|
|
3
|
+
No server needed. The sandbox uses it to build tables, access_postgres.py to line
|
|
4
|
+
indexes up with a query's filters.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from ..discover.schema import _balanced, _split_top
|
|
13
|
+
|
|
14
|
+
IDENT = r'(?:"[^"]+"|[A-Za-z_][\w$]*)'
|
|
15
|
+
QNAME = rf"(?:{IDENT}\.)?{IDENT}"
|
|
16
|
+
CREATE_TABLE = re.compile(
|
|
17
|
+
rf"^\s*CREATE\s+(?:(?:GLOBAL\s+|LOCAL\s+)?(?:TEMP|TEMPORARY)\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?({QNAME})", re.I)
|
|
18
|
+
CREATE_INDEX = re.compile(
|
|
19
|
+
rf"^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:({IDENT})\s+)?ON\s+(?:ONLY\s+)?({QNAME})"
|
|
20
|
+
r"\s*(?:USING\s+(\w+)\s*)?\(", re.I)
|
|
21
|
+
CONSTRAINT_HEAD = re.compile(rf"^\s*(?:CONSTRAINT\s+({IDENT})\s+)?(PRIMARY\s+KEY|UNIQUE|FOREIGN\s+KEY|CHECK|EXCLUDE)\b", re.I)
|
|
22
|
+
INLINE_REFERENCES = re.compile(
|
|
23
|
+
rf"\s+REFERENCES\s+{QNAME}(?:\s*\([^)]*\))?"
|
|
24
|
+
r"(?:\s+MATCH\s+\w+|\s+ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|RESTRICT|NO\s+ACTION|SET\s+(?:NULL|DEFAULT)(?:\s*\([^)]*\))?)"
|
|
25
|
+
r"|\s+(?:NOT\s+)?DEFERRABLE|\s+INITIALLY\s+(?:DEFERRED|IMMEDIATE))*", re.I)
|
|
26
|
+
TYPE_END = re.compile(
|
|
27
|
+
r"\s+(?:NOT\s+NULL|NULL|DEFAULT|PRIMARY\s+KEY|UNIQUE|REFERENCES|CHECK|CONSTRAINT|GENERATED|COLLATE|STORAGE|COMPRESSION)\b", re.I)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def unquote(name: str) -> str:
|
|
31
|
+
"""public."Users" -> public.Users; unquoted names fold to lower case, as the server does."""
|
|
32
|
+
return ".".join(p[1:-1] if p.startswith('"') else p.lower() for p in re.findall(IDENT, name))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def short(name: str) -> str:
|
|
36
|
+
return unquote(name).split(".")[-1]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def split_statements(script: str) -> list[str]:
|
|
40
|
+
"""Split on top-level semicolons. Strings, quoted names, dollar quotes and comments are respected; comments are dropped."""
|
|
41
|
+
out, cur, i, n = [], [], 0, len(script)
|
|
42
|
+
while i < n:
|
|
43
|
+
c = script[i]
|
|
44
|
+
two = script[i:i + 2]
|
|
45
|
+
if two == "--":
|
|
46
|
+
j = script.find("\n", i)
|
|
47
|
+
i = n if j < 0 else j
|
|
48
|
+
continue
|
|
49
|
+
if two == "/*":
|
|
50
|
+
j = script.find("*/", i + 2)
|
|
51
|
+
i = n if j < 0 else j + 2
|
|
52
|
+
cur.append(" ")
|
|
53
|
+
continue
|
|
54
|
+
if c in "'\"":
|
|
55
|
+
j = i + 1
|
|
56
|
+
while j < n:
|
|
57
|
+
if script[j] == c:
|
|
58
|
+
if script[j:j + 2] == c * 2:
|
|
59
|
+
j += 2
|
|
60
|
+
continue
|
|
61
|
+
break
|
|
62
|
+
j += 1
|
|
63
|
+
cur.append(script[i:j + 1])
|
|
64
|
+
i = j + 1
|
|
65
|
+
continue
|
|
66
|
+
if c == "$":
|
|
67
|
+
m = re.match(r"\$\w*\$", script[i:])
|
|
68
|
+
if m:
|
|
69
|
+
j = script.find(m.group(0), i + len(m.group(0)))
|
|
70
|
+
j = n if j < 0 else j + len(m.group(0))
|
|
71
|
+
cur.append(script[i:j])
|
|
72
|
+
i = j
|
|
73
|
+
continue
|
|
74
|
+
if c == ";":
|
|
75
|
+
stmt = "".join(cur).strip()
|
|
76
|
+
if stmt:
|
|
77
|
+
out.append(stmt)
|
|
78
|
+
cur = []
|
|
79
|
+
else:
|
|
80
|
+
cur.append(c)
|
|
81
|
+
i += 1
|
|
82
|
+
stmt = "".join(cur).strip()
|
|
83
|
+
if stmt:
|
|
84
|
+
out.append(stmt)
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def statement_kind(stmt: str) -> str:
|
|
89
|
+
"""table | index | unique_index | type | schema | function | extension | sequence | alter | comment | other."""
|
|
90
|
+
head = re.sub(r"\s+", " ", stmt.strip()[:160]).upper()
|
|
91
|
+
if CREATE_TABLE.match(stmt):
|
|
92
|
+
return "table"
|
|
93
|
+
if re.match(r"CREATE UNIQUE INDEX\b", head):
|
|
94
|
+
return "unique_index"
|
|
95
|
+
if re.match(r"CREATE INDEX\b", head):
|
|
96
|
+
return "index"
|
|
97
|
+
if re.match(r"CREATE (TYPE|DOMAIN)\b", head):
|
|
98
|
+
return "type"
|
|
99
|
+
if re.match(r"CREATE SCHEMA\b", head):
|
|
100
|
+
return "schema"
|
|
101
|
+
if re.match(r"CREATE (OR REPLACE )?FUNCTION\b", head):
|
|
102
|
+
return "function"
|
|
103
|
+
if re.match(r"CREATE EXTENSION\b", head):
|
|
104
|
+
return "extension"
|
|
105
|
+
if re.match(r"CREATE SEQUENCE\b", head):
|
|
106
|
+
return "sequence"
|
|
107
|
+
if re.match(r"ALTER TABLE\b", head):
|
|
108
|
+
return "alter"
|
|
109
|
+
if re.match(r"(COMMENT ON|SET |RESET |BEGIN|COMMIT|START TRANSACTION)", head):
|
|
110
|
+
return "comment"
|
|
111
|
+
return "other"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _body(stmt: str) -> tuple[int, int]:
|
|
115
|
+
"""(start, end) of the parenthesised column list of a CREATE TABLE, or (-1, -1) (PARTITION OF without one, CREATE TABLE AS)."""
|
|
116
|
+
m = CREATE_TABLE.match(stmt)
|
|
117
|
+
if not m:
|
|
118
|
+
return -1, -1
|
|
119
|
+
rest = stmt[m.end():]
|
|
120
|
+
if not rest.lstrip().startswith("("):
|
|
121
|
+
return -1, -1
|
|
122
|
+
start = m.end() + rest.index("(")
|
|
123
|
+
end = _balanced(stmt, start)
|
|
124
|
+
return (start, end) if end > 0 else (-1, -1)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def strip_constraints(stmt: str) -> tuple[str, list[str]]:
|
|
128
|
+
"""Remove foreign keys, CHECK and EXCLUDE constraints from a CREATE TABLE.
|
|
129
|
+
|
|
130
|
+
Generated data does not honour them and they never make a read cheaper. Returns the
|
|
131
|
+
statement and one note per kind removed."""
|
|
132
|
+
start, end = _body(stmt)
|
|
133
|
+
if start < 0:
|
|
134
|
+
return stmt, []
|
|
135
|
+
kept, counts = [], {"foreign key": 0, "check": 0, "exclude": 0}
|
|
136
|
+
for part in _split_top(stmt[start + 1:end - 1]):
|
|
137
|
+
m = CONSTRAINT_HEAD.match(part)
|
|
138
|
+
kind = re.sub(r"\s+", " ", m.group(2)).lower() if m else ""
|
|
139
|
+
if kind in counts:
|
|
140
|
+
counts[kind] += 1
|
|
141
|
+
continue
|
|
142
|
+
part, n = INLINE_REFERENCES.subn("", part)
|
|
143
|
+
counts["foreign key"] += n
|
|
144
|
+
while True:
|
|
145
|
+
c = re.search(r"\s+(?:CONSTRAINT\s+" + IDENT + r"\s+)?CHECK\s*\(", part, re.I)
|
|
146
|
+
if not c or CONSTRAINT_HEAD.match(part):
|
|
147
|
+
break
|
|
148
|
+
close = _balanced(part, c.end() - 1)
|
|
149
|
+
if close < 0:
|
|
150
|
+
break
|
|
151
|
+
tail = re.sub(r"^\s+NO\s+INHERIT\b", "", part[close:], flags=re.I)
|
|
152
|
+
part = part[:c.start()] + tail
|
|
153
|
+
counts["check"] += 1
|
|
154
|
+
kept.append(part)
|
|
155
|
+
notes = [f"{n} {kind} constraint{'s' if n > 1 else ''} left out" for kind, n in counts.items() if n]
|
|
156
|
+
return stmt[:start + 1] + ",".join(kept) + stmt[end - 1:], notes
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass
|
|
160
|
+
class IndexColumn:
|
|
161
|
+
text: str # as written, without direction or operator class
|
|
162
|
+
column: str = "" # the plain column name, "" for an expression
|
|
163
|
+
desc: bool = False
|
|
164
|
+
opclass: str = ""
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass
|
|
168
|
+
class Index:
|
|
169
|
+
name: str
|
|
170
|
+
table: str
|
|
171
|
+
method: str = "btree"
|
|
172
|
+
unique: bool = False
|
|
173
|
+
primary: bool = False
|
|
174
|
+
columns: list[IndexColumn] = field(default_factory=list)
|
|
175
|
+
include: list[str] = field(default_factory=list)
|
|
176
|
+
where: str = ""
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass
|
|
180
|
+
class PgTable:
|
|
181
|
+
name: str
|
|
182
|
+
columns: dict[str, str] = field(default_factory=dict) # name -> type as written
|
|
183
|
+
partition_by: str = ""
|
|
184
|
+
partition_of: str = ""
|
|
185
|
+
indexes: list[Index] = field(default_factory=list)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _index_column(text: str) -> IndexColumn:
|
|
189
|
+
text = text.strip()
|
|
190
|
+
desc = bool(re.search(r"\bDESC\b", text, re.I))
|
|
191
|
+
core = re.sub(r"\s+(?:ASC|DESC)\b|\s+NULLS\s+(?:FIRST|LAST)\b", "", text, flags=re.I).strip()
|
|
192
|
+
core = re.sub(r"\s+COLLATE\s+\S+", "", core, flags=re.I).strip()
|
|
193
|
+
opclass = ""
|
|
194
|
+
if not core.startswith("("):
|
|
195
|
+
m = re.match(rf"^({IDENT})\s+([A-Za-z_][\w.]*)$", core)
|
|
196
|
+
if m:
|
|
197
|
+
core, opclass = m.group(1), m.group(2)
|
|
198
|
+
else:
|
|
199
|
+
m = re.match(r"^(\(.*\))\s+([A-Za-z_][\w.]*)$", core, re.S)
|
|
200
|
+
if m and _balanced(core, 0) == len(m.group(1)):
|
|
201
|
+
core, opclass = m.group(1), m.group(2)
|
|
202
|
+
plain = re.fullmatch(IDENT, core)
|
|
203
|
+
return IndexColumn(text=core, column=unquote(core) if plain else "", desc=desc, opclass=opclass)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def parse_index(stmt: str) -> Index | None:
|
|
207
|
+
m = CREATE_INDEX.match(stmt)
|
|
208
|
+
if not m:
|
|
209
|
+
return None
|
|
210
|
+
start = m.end() - 1
|
|
211
|
+
end = _balanced(stmt, start)
|
|
212
|
+
if end < 0:
|
|
213
|
+
return None
|
|
214
|
+
cols = [_index_column(p) for p in _split_top(stmt[start + 1:end - 1]) if p.strip()]
|
|
215
|
+
rest = stmt[end:]
|
|
216
|
+
include: list[str] = []
|
|
217
|
+
inc = re.search(r"\bINCLUDE\s*\(", rest, re.I)
|
|
218
|
+
if inc:
|
|
219
|
+
close = _balanced(rest, inc.end() - 1)
|
|
220
|
+
if close > 0:
|
|
221
|
+
include = [unquote(p.strip()) for p in _split_top(rest[inc.end():close - 1]) if p.strip()]
|
|
222
|
+
rest = rest[close:]
|
|
223
|
+
where = re.search(r"\bWHERE\s+(.+)$", rest, re.I | re.S)
|
|
224
|
+
table = unquote(m.group(3))
|
|
225
|
+
name = unquote(m.group(2)) if m.group(2) else f"{table.split('.')[-1]}_{'_'.join(c.column or 'expr' for c in cols)}_idx"
|
|
226
|
+
return Index(name=name, table=table, method=(m.group(4) or "btree").lower(), unique=bool(m.group(1)), columns=cols,
|
|
227
|
+
include=include, where=re.sub(r"\s+", " ", where.group(1)).strip().rstrip(";") if where else "")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _paren_list(text: str) -> list[str]:
|
|
231
|
+
start = text.find("(")
|
|
232
|
+
end = _balanced(text, start) if start >= 0 else -1
|
|
233
|
+
return [p.strip() for p in _split_top(text[start + 1:end - 1])] if end > 0 else []
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def parse_table(stmt: str) -> PgTable | None:
|
|
237
|
+
m = CREATE_TABLE.match(stmt)
|
|
238
|
+
if not m:
|
|
239
|
+
return None
|
|
240
|
+
t = PgTable(name=unquote(m.group(1)))
|
|
241
|
+
start, end = _body(stmt)
|
|
242
|
+
tail = stmt[end:] if end > 0 else stmt[m.end():]
|
|
243
|
+
of = re.search(rf"\bPARTITION\s+OF\s+({QNAME})", stmt[m.end():(start if start > 0 else None)] or "", re.I)
|
|
244
|
+
if of:
|
|
245
|
+
t.partition_of = unquote(of.group(1))
|
|
246
|
+
part = re.search(r"\bPARTITION\s+BY\s+(\w+\s*\(.*)$", tail, re.I | re.S)
|
|
247
|
+
if part:
|
|
248
|
+
text = part.group(1)
|
|
249
|
+
close = _balanced(text, text.index("("))
|
|
250
|
+
t.partition_by = re.sub(r"\s+", " ", text[:close] if close > 0 else text).strip()
|
|
251
|
+
if start < 0:
|
|
252
|
+
return t
|
|
253
|
+
short_name = t.name.split(".")[-1]
|
|
254
|
+
for part_text in _split_top(stmt[start + 1:end - 1]):
|
|
255
|
+
part_text = part_text.strip()
|
|
256
|
+
if not part_text or re.match(r"LIKE\b", part_text, re.I):
|
|
257
|
+
continue
|
|
258
|
+
head = CONSTRAINT_HEAD.match(part_text)
|
|
259
|
+
if head:
|
|
260
|
+
kind = re.sub(r"\s+", " ", head.group(2)).upper()
|
|
261
|
+
if kind in ("PRIMARY KEY", "UNIQUE"):
|
|
262
|
+
inc = re.search(r"\bINCLUDE\s*\((.*?)\)", part_text[head.end():], re.I | re.S)
|
|
263
|
+
first = part_text[head.end():]
|
|
264
|
+
first = first[:_balanced(first, first.index("("))] if "(" in first else ""
|
|
265
|
+
cols = [unquote(c) for c in _paren_list(first)]
|
|
266
|
+
name = unquote(head.group(1)) if head.group(1) else (
|
|
267
|
+
f"{short_name}_pkey" if kind == "PRIMARY KEY" else f"{short_name}_{'_'.join(cols)}_key")
|
|
268
|
+
t.indexes.append(Index(name=name, table=t.name, unique=True, primary=kind == "PRIMARY KEY",
|
|
269
|
+
columns=[IndexColumn(text=c, column=c) for c in cols],
|
|
270
|
+
include=[unquote(c.strip()) for c in inc.group(1).split(",")] if inc else []))
|
|
271
|
+
continue
|
|
272
|
+
cm = re.match(rf"^({IDENT})\s+(.*)$", part_text, re.S)
|
|
273
|
+
if not cm:
|
|
274
|
+
continue
|
|
275
|
+
col, rest = unquote(cm.group(1)), cm.group(2)
|
|
276
|
+
stop = TYPE_END.search(" " + rest)
|
|
277
|
+
t.columns[col] = re.sub(r"\s+", " ", rest[:stop.start() - 1] if stop else rest).strip()
|
|
278
|
+
if re.search(r"\bPRIMARY\s+KEY\b", rest, re.I):
|
|
279
|
+
t.indexes.append(Index(name=f"{short_name}_pkey", table=t.name, unique=True, primary=True,
|
|
280
|
+
columns=[IndexColumn(text=col, column=col)]))
|
|
281
|
+
elif re.search(r"\bUNIQUE\b", rest, re.I):
|
|
282
|
+
t.indexes.append(Index(name=f"{short_name}_{col}_key", table=t.name, unique=True,
|
|
283
|
+
columns=[IndexColumn(text=col, column=col)]))
|
|
284
|
+
return t
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
REFERENCES = re.compile(rf"\bREFERENCES\s+({QNAME})\s*(\([^)]*\))?", re.I)
|
|
288
|
+
ALTER_ADD = re.compile(rf"\s*ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?({QNAME})\s+ADD\s+(.*)$", re.I | re.S)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _names(text: str) -> list[str]:
|
|
292
|
+
return [unquote(p) for p in _paren_list(text) if re.fullmatch(IDENT, p.strip())]
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def foreign_keys(create_sql: str) -> list[dict]:
|
|
296
|
+
"""Every foreign key a definition script declares: [{table, columns, parent, parent_columns}].
|
|
297
|
+
|
|
298
|
+
Inline `col type REFERENCES p (id)`, table-level `FOREIGN KEY (a, b) REFERENCES p (x, y)` and
|
|
299
|
+
`ALTER TABLE t ADD [CONSTRAINT n] FOREIGN KEY ...`. A reference without a column list points at the parent's
|
|
300
|
+
primary key: `parent_columns` is then empty and the caller fills it from the parent's definition."""
|
|
301
|
+
out: list[dict] = []
|
|
302
|
+
|
|
303
|
+
def add(table: str, columns: list[str], text: str) -> None:
|
|
304
|
+
m = REFERENCES.search(text)
|
|
305
|
+
if m and columns:
|
|
306
|
+
out.append({"table": table, "columns": columns, "parent": unquote(m.group(1)),
|
|
307
|
+
"parent_columns": _names(m.group(2)) if m.group(2) else []})
|
|
308
|
+
|
|
309
|
+
for stmt in split_statements(create_sql):
|
|
310
|
+
kind = statement_kind(stmt)
|
|
311
|
+
if kind == "table":
|
|
312
|
+
m = CREATE_TABLE.match(stmt)
|
|
313
|
+
start, end = _body(stmt)
|
|
314
|
+
if start < 0:
|
|
315
|
+
continue
|
|
316
|
+
table = unquote(m.group(1))
|
|
317
|
+
for part in _split_top(stmt[start + 1:end - 1]):
|
|
318
|
+
part = part.strip()
|
|
319
|
+
head = CONSTRAINT_HEAD.match(part)
|
|
320
|
+
if head:
|
|
321
|
+
if re.sub(r"\s+", " ", head.group(2)).upper() == "FOREIGN KEY":
|
|
322
|
+
add(table, _names(part[head.end():]), part)
|
|
323
|
+
continue
|
|
324
|
+
cm = re.match(rf"^({IDENT})\s+", part)
|
|
325
|
+
if cm and not re.match(r"LIKE\b", part, re.I):
|
|
326
|
+
add(table, [unquote(cm.group(1))], part)
|
|
327
|
+
elif kind == "alter":
|
|
328
|
+
m = ALTER_ADD.match(stmt)
|
|
329
|
+
head = CONSTRAINT_HEAD.match(m.group(2)) if m else None
|
|
330
|
+
if head and re.sub(r"\s+", " ", head.group(2)).upper() == "FOREIGN KEY":
|
|
331
|
+
add(unquote(m.group(1)), _names(m.group(2)[head.end():]), m.group(2))
|
|
332
|
+
return out
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def check_constraints(create_sql: str) -> list[dict]:
|
|
336
|
+
"""Every CHECK a definition script declares: [{table, expr}], the expression as written, without its parentheses."""
|
|
337
|
+
out: list[dict] = []
|
|
338
|
+
|
|
339
|
+
def collect(table: str, text: str) -> None:
|
|
340
|
+
pos = 0
|
|
341
|
+
while True:
|
|
342
|
+
c = re.compile(r"\bCHECK\s*\(", re.I).search(text, pos)
|
|
343
|
+
if not c:
|
|
344
|
+
return
|
|
345
|
+
close = _balanced(text, c.end() - 1)
|
|
346
|
+
if close < 0:
|
|
347
|
+
return
|
|
348
|
+
out.append({"table": table, "expr": " ".join(text[c.end():close - 1].split())})
|
|
349
|
+
pos = close
|
|
350
|
+
|
|
351
|
+
for stmt in split_statements(create_sql):
|
|
352
|
+
kind = statement_kind(stmt)
|
|
353
|
+
if kind == "table":
|
|
354
|
+
start, end = _body(stmt)
|
|
355
|
+
if start >= 0:
|
|
356
|
+
table = unquote(CREATE_TABLE.match(stmt).group(1))
|
|
357
|
+
for part in _split_top(stmt[start + 1:end - 1]):
|
|
358
|
+
collect(table, part)
|
|
359
|
+
elif kind == "alter":
|
|
360
|
+
m = ALTER_ADD.match(stmt)
|
|
361
|
+
if m and re.search(r"\bCHECK\s*\(", m.group(2), re.I):
|
|
362
|
+
collect(unquote(m.group(1)), m.group(2))
|
|
363
|
+
return out
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
NUMBER = r"-?\d+(?:\.\d+)?"
|
|
367
|
+
_COL = rf"\(*\s*({IDENT})\s*\)*(?:::[\w ]+?)?\)*"
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def check_domain(expr: str) -> dict | None:
|
|
371
|
+
"""What a simple CHECK allows for one column: {column, values} | {column, min, max, min_open, max_open} |
|
|
372
|
+
{column, max_length}; None for anything else (it is then verified after the load, not generated for).
|
|
373
|
+
|
|
374
|
+
Reads the shapes migrations write and the ones pg_get_constraintdef prints: `c IN ('a', 'b')`,
|
|
375
|
+
`c = ANY (ARRAY['a', 'b'])`, `c >= 0`, `c > 0 AND c <= 10`, `c BETWEEN 1 AND 5`, `length(c) <= 40`."""
|
|
376
|
+
text = " ".join(expr.split())
|
|
377
|
+
while text.startswith("(") and _balanced(text, 0) == len(text):
|
|
378
|
+
text = text[1:-1].strip()
|
|
379
|
+
m = re.fullmatch(rf"{_COL}\s+IN\s*\((.*)\)", text, re.I | re.S) or \
|
|
380
|
+
re.fullmatch(rf"{_COL}\s*=\s*ANY\s*\(\s*\(?\s*ARRAY\s*\[(.*?)\]\s*\)?(?:::[\w \[\]]+)?\s*\)", text, re.I | re.S)
|
|
381
|
+
if m:
|
|
382
|
+
values = []
|
|
383
|
+
for part in _split_top(m.group(2)):
|
|
384
|
+
v = re.fullmatch(rf"\s*\(?\s*(?:'((?:[^']|'')*)'|({NUMBER}))\s*\)?(?:::[\w \[\]]+)?\s*\)?", part)
|
|
385
|
+
if not v:
|
|
386
|
+
return None
|
|
387
|
+
values.append(v.group(1).replace("''", "'") if v.group(1) is not None else v.group(2))
|
|
388
|
+
return {"column": unquote(m.group(1)), "values": values} if values else None
|
|
389
|
+
m = re.fullmatch(rf"(?:char_|character_)?length\s*\(\s*({IDENT})\s*\)\s*(<=|<)\s*(\d+)", text, re.I)
|
|
390
|
+
if m:
|
|
391
|
+
return {"column": unquote(m.group(1)), "max_length": int(m.group(3)) - (1 if m.group(2) == "<" else 0)}
|
|
392
|
+
m = re.fullmatch(rf"{_COL}\s+BETWEEN\s+\(?({NUMBER})\)?\s+AND\s+\(?({NUMBER})\)?", text, re.I)
|
|
393
|
+
if m:
|
|
394
|
+
return {"column": unquote(m.group(1)), "min": float(m.group(2)), "max": float(m.group(3)), "min_open": False, "max_open": False}
|
|
395
|
+
out: dict = {}
|
|
396
|
+
for piece in re.split(r"\s+AND\s+", text, flags=re.I):
|
|
397
|
+
piece = piece.strip()
|
|
398
|
+
while piece.startswith("(") and _balanced(piece, 0) == len(piece):
|
|
399
|
+
piece = piece[1:-1].strip()
|
|
400
|
+
m = re.fullmatch(rf"{_COL}\s*(>=|>|<=|<)\s*\(?({NUMBER})\)?(?:::[\w ]+)?", piece)
|
|
401
|
+
if not m or out.get("column", unquote(m.group(1))) != unquote(m.group(1)):
|
|
402
|
+
return None
|
|
403
|
+
out["column"] = unquote(m.group(1))
|
|
404
|
+
side = "min" if m.group(2).startswith(">") else "max"
|
|
405
|
+
out[side], out[side + "_open"] = float(m.group(3)), len(m.group(2)) == 1
|
|
406
|
+
return out or None
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def parse_definition(create_sql: str, name: str = "") -> PgTable:
|
|
410
|
+
"""The table called `name` (or the first one) with every index the script gives it.
|
|
411
|
+
|
|
412
|
+
Indexes declared on a partition parent or by ALTER TABLE ... ADD PRIMARY KEY / UNIQUE count too."""
|
|
413
|
+
tables: list[PgTable] = []
|
|
414
|
+
indexes: list[Index] = []
|
|
415
|
+
for stmt in split_statements(create_sql):
|
|
416
|
+
kind = statement_kind(stmt)
|
|
417
|
+
if kind == "table":
|
|
418
|
+
t = parse_table(stmt)
|
|
419
|
+
if t:
|
|
420
|
+
tables.append(t)
|
|
421
|
+
elif kind in ("index", "unique_index"):
|
|
422
|
+
ix = parse_index(stmt)
|
|
423
|
+
if ix:
|
|
424
|
+
indexes.append(ix)
|
|
425
|
+
elif kind == "alter":
|
|
426
|
+
m = re.match(rf"\s*ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?({QNAME})\s+ADD\s+(.*)$", stmt, re.I | re.S)
|
|
427
|
+
head = CONSTRAINT_HEAD.match(m.group(2)) if m else None
|
|
428
|
+
if head and re.sub(r"\s+", " ", head.group(2)).upper() in ("PRIMARY KEY", "UNIQUE"):
|
|
429
|
+
table = unquote(m.group(1))
|
|
430
|
+
cols = [unquote(c) for c in _paren_list(m.group(2)[head.end():])]
|
|
431
|
+
primary = "PRIMARY" in head.group(2).upper()
|
|
432
|
+
iname = unquote(head.group(1)) if head.group(1) else f"{table.split('.')[-1]}_{'pkey' if primary else '_'.join(cols) + '_key'}"
|
|
433
|
+
indexes.append(Index(name=iname, table=table, unique=True, primary=primary,
|
|
434
|
+
columns=[IndexColumn(text=c, column=c) for c in cols]))
|
|
435
|
+
# `name` may have lost its quotes on the way here ("Event" arrives as Event): compare without regard to case
|
|
436
|
+
want = name.replace('"', "").split(".")[-1].lower() if name else ""
|
|
437
|
+
main = next((t for t in tables if t.name.split(".")[-1].lower() == want and not t.partition_of), None) or \
|
|
438
|
+
next((t for t in tables if not t.partition_of), None) or (tables[0] if tables else PgTable(name=unquote(name) if name else ""))
|
|
439
|
+
seen = {ix.name for ix in main.indexes}
|
|
440
|
+
for ix in indexes:
|
|
441
|
+
if ix.table.split(".")[-1] == main.name.split(".")[-1] and ix.name not in seen:
|
|
442
|
+
main.indexes.append(ix)
|
|
443
|
+
seen.add(ix.name)
|
|
444
|
+
return main
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Index statements for the shortlisted tables, found by a text search of the repository.
|
|
2
|
+
|
|
3
|
+
A Postgres table's indexes rarely sit next to its CREATE TABLE: they are spread
|
|
4
|
+
over later migrations. Missing one makes the agent propose an index that already
|
|
5
|
+
exists, and the benchmark would then "verify" a win that production already has.
|
|
6
|
+
This search is cheap and gives the agent a list to start from; it is told to
|
|
7
|
+
verify it, because a migration can also drop or replace an index.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .. import formerly
|
|
17
|
+
from ..discover.schema import _balanced
|
|
18
|
+
|
|
19
|
+
SKIP_DIRS = {".git", "node_modules", "target", "vendor", "dist", "build", ".venv", "venv", "__pycache__", ".codecop", formerly.OLD_OUT_DIR, ".next", "bin", "obj"}
|
|
20
|
+
SOURCE = (".sql", ".go", ".rs", ".py", ".java", ".kt", ".ts", ".js", ".rb", ".ex", ".cs", ".php", ".yaml", ".yml", ".tmpl", ".tpl")
|
|
21
|
+
TESTISH = re.compile(r"(^|/)(tests?|testdata|fixtures)/|(^|/)test_|_test\.|\.test\.|\.spec\.")
|
|
22
|
+
INDEX = re.compile(
|
|
23
|
+
r"CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:[\w\"]+\s+)?ON\s+(?:ONLY\s+)?([\w\".]+)\s*(?:USING\s+\w+\s*)?\(",
|
|
24
|
+
re.I)
|
|
25
|
+
VIEW = re.compile(r"CREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w\".]+)", re.I)
|
|
26
|
+
DROP = re.compile(r"DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?([\w\".]+)", re.I)
|
|
27
|
+
TAIL = re.compile(r"\s*(?:INCLUDE\s*\([^)]*\)\s*)?(?:WITH\s*\([^)]*\)\s*)?(?:WHERE\s+[^;`]+?)?(?=;|`|\"\"\"|\"#|$)", re.I | re.S)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def index_statements(root: str, names: set[str], max_bytes: int = 2_000_000, views: set[str] | None = None) -> tuple[dict[str, list[dict]], dict[str, tuple]]:
|
|
31
|
+
"""The CREATE INDEX statements on `names` found by text search, structured: ({table: [{sql, file, line, test}]},
|
|
32
|
+
{dropped index name (lower case): (file, line) of its last DROP INDEX outside test code}). Read only.
|
|
33
|
+
`views`, when given, receives the names (lower case, without schema) of the views and materialized views created."""
|
|
34
|
+
wanted = {n.lower() for n in names}
|
|
35
|
+
found: dict[str, list[dict]] = {}
|
|
36
|
+
dropped: dict[str, tuple] = {}
|
|
37
|
+
seen: set[str] = set()
|
|
38
|
+
base = Path(root)
|
|
39
|
+
if not base.is_dir():
|
|
40
|
+
return found, dropped
|
|
41
|
+
for folder, dirs, files in os.walk(base):
|
|
42
|
+
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.startswith("."))
|
|
43
|
+
for fname in sorted(files):
|
|
44
|
+
if not fname.endswith(SOURCE):
|
|
45
|
+
continue
|
|
46
|
+
path = Path(folder) / fname
|
|
47
|
+
try:
|
|
48
|
+
if path.stat().st_size > max_bytes:
|
|
49
|
+
continue
|
|
50
|
+
text = path.read_text(errors="replace")
|
|
51
|
+
except OSError:
|
|
52
|
+
continue
|
|
53
|
+
upper = text.upper()
|
|
54
|
+
if views is not None and "VIEW" in upper and not TESTISH.search(str(path.relative_to(base))):
|
|
55
|
+
views.update(m.group(1).replace('"', "").split(".")[-1].lower() for m in VIEW.finditer(text))
|
|
56
|
+
if "INDEX" not in upper:
|
|
57
|
+
continue
|
|
58
|
+
rel = str(path.relative_to(base))
|
|
59
|
+
for m in INDEX.finditer(text):
|
|
60
|
+
table = m.group(1).replace('"', "").split(".")[-1].lower()
|
|
61
|
+
if table not in wanted:
|
|
62
|
+
continue
|
|
63
|
+
end = _balanced(text, m.end() - 1)
|
|
64
|
+
if end < 0:
|
|
65
|
+
continue
|
|
66
|
+
tail = TAIL.match(text, end)
|
|
67
|
+
stmt = re.sub(r"\s+", " ", text[m.start():tail.end() if tail else end]).strip()
|
|
68
|
+
key = re.sub(r"\s+|CONCURRENTLY|IF NOT EXISTS", "", stmt.upper())
|
|
69
|
+
if key in seen or len(stmt) > 600:
|
|
70
|
+
continue
|
|
71
|
+
seen.add(key)
|
|
72
|
+
found.setdefault(table, []).append({"sql": stmt, "file": rel, "line": text.count("\n", 0, m.start()) + 1,
|
|
73
|
+
"test": bool(TESTISH.search(rel))})
|
|
74
|
+
for m in DROP.finditer(text):
|
|
75
|
+
if not TESTISH.search(rel):
|
|
76
|
+
at = (rel, text.count("\n", 0, m.start()) + 1)
|
|
77
|
+
name = m.group(1).replace('"', "").split(".")[-1].lower()
|
|
78
|
+
dropped[name] = max(dropped.get(name, at), at)
|
|
79
|
+
return found, dropped
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def index_hints(root: str, names: set[str], limit: int = 160, max_bytes: int = 2_000_000) -> str:
|
|
83
|
+
wanted = {n.lower() for n in names}
|
|
84
|
+
found: dict[str, list[str]] = {}
|
|
85
|
+
seen: set[str] = set()
|
|
86
|
+
dropped: list[str] = []
|
|
87
|
+
base = Path(root)
|
|
88
|
+
if not base.is_dir():
|
|
89
|
+
return "(repository not readable: search for CREATE INDEX yourself)"
|
|
90
|
+
for folder, dirs, files in os.walk(base):
|
|
91
|
+
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.startswith("."))
|
|
92
|
+
for fname in sorted(files):
|
|
93
|
+
if not fname.endswith(SOURCE):
|
|
94
|
+
continue
|
|
95
|
+
path = Path(folder) / fname
|
|
96
|
+
try:
|
|
97
|
+
if path.stat().st_size > max_bytes:
|
|
98
|
+
continue
|
|
99
|
+
text = path.read_text(errors="replace")
|
|
100
|
+
except OSError:
|
|
101
|
+
continue
|
|
102
|
+
if "INDEX" not in text.upper():
|
|
103
|
+
continue
|
|
104
|
+
rel = str(path.relative_to(base))
|
|
105
|
+
for m in INDEX.finditer(text):
|
|
106
|
+
table = m.group(1).replace('"', "").split(".")[-1].lower()
|
|
107
|
+
if table not in wanted:
|
|
108
|
+
continue
|
|
109
|
+
end = _balanced(text, m.end() - 1)
|
|
110
|
+
if end < 0:
|
|
111
|
+
continue
|
|
112
|
+
tail = TAIL.match(text, end)
|
|
113
|
+
stmt = re.sub(r"\s+", " ", text[m.start():tail.end() if tail else end]).strip()
|
|
114
|
+
key = re.sub(r"\s+|CONCURRENTLY|IF NOT EXISTS", "", stmt.upper())
|
|
115
|
+
if key in seen or len(stmt) > 600:
|
|
116
|
+
continue
|
|
117
|
+
seen.add(key)
|
|
118
|
+
line = text.count("\n", 0, m.start()) + 1
|
|
119
|
+
found.setdefault(table, []).append(f" {stmt} [{rel}:{line}{', test code' if TESTISH.search(rel) else ''}]")
|
|
120
|
+
for m in DROP.finditer(text):
|
|
121
|
+
if not TESTISH.search(rel):
|
|
122
|
+
dropped.append(f"{m.group(1).replace(chr(34), '')} [{rel}:{text.count(chr(10), 0, m.start()) + 1}]")
|
|
123
|
+
if not found:
|
|
124
|
+
return "(no CREATE INDEX statement found for these tables by text search: check migrations and ORM models yourself)"
|
|
125
|
+
lines, count = [], 0
|
|
126
|
+
for table in sorted(found):
|
|
127
|
+
lines.append(f"- {table}")
|
|
128
|
+
for entry in found[table]:
|
|
129
|
+
if count >= limit:
|
|
130
|
+
break
|
|
131
|
+
lines.append(entry)
|
|
132
|
+
count += 1
|
|
133
|
+
if count >= limit:
|
|
134
|
+
lines.append(f"(list cut at {limit} statements)")
|
|
135
|
+
if dropped:
|
|
136
|
+
lines.append("Indexes dropped somewhere in the repository (an index above may be gone): " + "; ".join(sorted(set(dropped))[:40]))
|
|
137
|
+
return "\n".join(lines)
|