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/sandboxschema.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""The sandbox schema for every statement of a repository, and whether each statement plans against it.
|
|
2
|
+
|
|
3
|
+
Built empty in a throwaway server (the scan's own sandbox image), from:
|
|
4
|
+
1. every pulled database of the engine (db_catalog.json: every connection, every database a pull described), each
|
|
5
|
+
table in its own database or schema, as production has it. ClickHouse: Shared*/Replicated* engines made local,
|
|
6
|
+
TTL and storage settings left out, a materialized view kept as a table of its columns (what a SELECT from it
|
|
7
|
+
reads), a view built after its tables, a dictionary or an engine whose definition the pull does not fetch built as
|
|
8
|
+
a table of its columns. Every table is also reachable by its bare name from the session's database (the one the
|
|
9
|
+
workload reads most, `realdb.facts.Facts.tables`), as the code names it.
|
|
10
|
+
2. the repository's own definitions (migrations, DDL files, models: inventory `tables`) for a table no pull has.
|
|
11
|
+
|
|
12
|
+
A statement is then planned, never run: PostgreSQL `EXPLAIN` (a write too: EXPLAIN plans it without doing it),
|
|
13
|
+
ClickHouse `EXPLAIN PLAN` (an INSERT: its target exists and its SELECT plans). Its placeholders are typed from the
|
|
14
|
+
columns they are compared with (typedparams.bind), so a failure is the statement's, not a stand-in value's.
|
|
15
|
+
|
|
16
|
+
A site whose text is only a piece of a longer statement in the repository (the same text inside another site's
|
|
17
|
+
statement) is planned as that whole statement (`whole_of`): a piece is never sent alone.
|
|
18
|
+
|
|
19
|
+
Reasons a site stops here (coverage_reasons, stage `plans`): does_not_parse, does_not_plan, table_not_pulled (with the
|
|
20
|
+
schema or database a pull would need, named in `next`), piece_whole_not_found.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import re
|
|
27
|
+
from collections import Counter
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
from . import typedparams as TP
|
|
31
|
+
|
|
32
|
+
KINDS = {"postgres": ("select", "insert", "update", "delete"), "clickhouse": ("select", "insert")}
|
|
33
|
+
RUNTIME_PART = re.compile(r"«[^»]*»|(?<![{\w$])\{[A-Za-z_]\w*\}(?!\})")
|
|
34
|
+
# a statement that is a clause, not a whole statement: it is a piece of one
|
|
35
|
+
PIECE_START = re.compile(r"^\s*(?:WHERE|AND|OR|ORDER\s+BY|GROUP\s+BY|LIMIT|OFFSET|HAVING|ON|SET|VALUES|JOIN|LEFT|INNER|UNION|,|\)|FROM)\b",
|
|
36
|
+
re.I)
|
|
37
|
+
MISSING_TABLE = (re.compile(r'relation "([^"]+)" does not exist', re.I),
|
|
38
|
+
re.compile(r"Table ([\w.`]+) does not exist|Unknown table expression identifier '([^']+)'|UNKNOWN_TABLE[^']*'?([\w.`]+)", re.I),
|
|
39
|
+
re.compile(r"Database ([\w`]+) does not exist|UNKNOWN_DATABASE", re.I))
|
|
40
|
+
PARSE_ERROR = re.compile(r"syntax error at or near|syntax error at end|SYNTAX_ERROR|Syntax error: failed|unterminated|Code: 62\.", re.I)
|
|
41
|
+
# a stand-in value of the wrong type: the next stand-in is tried (ClickHouse, untyped placeholders only)
|
|
42
|
+
STAND_IN_ERROR = re.compile(r"Cannot (?:parse|convert|read)|CANNOT_|ILLEGAL_TYPE|TYPE_MISMATCH|Illegal type|NO_COMMON_TYPE|no supertype|"
|
|
43
|
+
r"must be (?:an )?(?:array|integer|number|string)|must be array|Nullable|NULL|Array does not start", re.I)
|
|
44
|
+
STAND_INS = ("NULL", "''", "0", "'2026-01-01 00:00:00'", "[]", "'00000000-0000-4000-8000-000000000001'")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# ---- the tables ----------------------------------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
def _q_ch(name: str) -> str:
|
|
50
|
+
return ".".join(f"`{p}`" for p in name.split("."))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _ch_ddl(create_sql: str) -> str:
|
|
54
|
+
from .engines.clickhouse import plain_engine
|
|
55
|
+
from .realdb.facts import TTL_CLAUSE, SETTINGS_CLAUSE, KEEP_SETTINGS
|
|
56
|
+
sql = plain_engine(create_sql.strip())
|
|
57
|
+
sql = re.sub(r"\s+UUID\s+'[0-9a-f-]+'", "", sql, count=1, flags=re.I)
|
|
58
|
+
sql = TTL_CLAUSE.sub("", sql)
|
|
59
|
+
m = SETTINGS_CLAUSE.search(sql)
|
|
60
|
+
if m:
|
|
61
|
+
kept = [s.strip() for s in re.split(r",\s*(?=\w+\s*=)", m.group(1)) if s.strip().split("=")[0].strip() in KEEP_SETTINGS]
|
|
62
|
+
sql = sql[:m.start()] + (" SETTINGS " + ", ".join(kept) if kept else "")
|
|
63
|
+
return sql
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _ch_columns_table(full: str, columns: list[dict]) -> str:
|
|
67
|
+
cols = ", ".join(f"`{c['name']}` {c['type']}" for c in columns if c.get("name") and c.get("type"))
|
|
68
|
+
return f"CREATE TABLE {_q_ch(full)} ({cols}) ENGINE = MergeTree ORDER BY tuple()" if cols else ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def build_clickhouse(sb, catalog: dict | None, inventory: dict | None, facts=None, names: set[str] | None = None, log=lambda s: None) -> dict:
|
|
72
|
+
"""Every pulled table in its own database, every bare name in the session's database, then the repository's tables
|
|
73
|
+
no pull has. Returns {built, failed: [{table, error}], bare, repository, session_database}."""
|
|
74
|
+
tables = [t for conn in ((catalog or {}).get("connections") or {}).values() if conn.get("engine") == "clickhouse"
|
|
75
|
+
for t in conn.get("tables") or []]
|
|
76
|
+
report: dict = {"built": 0, "failed": [], "bare": 0, "repository": 0, "repository_failed": []}
|
|
77
|
+
for db in sorted({t.get("database") or "default" for t in tables}):
|
|
78
|
+
sb.execute(f"CREATE DATABASE IF NOT EXISTS `{db}`")
|
|
79
|
+
order = {"View": 2, "MaterializedView": 1}
|
|
80
|
+
todo = sorted(tables, key=lambda t: order.get(t.get("engine", ""), 0))
|
|
81
|
+
built: dict[str, dict] = {}
|
|
82
|
+
for rnd in range(3):
|
|
83
|
+
failed = []
|
|
84
|
+
for t in todo:
|
|
85
|
+
full = f"{t.get('database') or 'default'}.{t['name']}"
|
|
86
|
+
eng = t.get("engine") or ""
|
|
87
|
+
if eng == "View" and t.get("create_sql"):
|
|
88
|
+
sql = re.sub(r"^\s*CREATE\s+VIEW\s+\S+", f"CREATE VIEW {_q_ch(full)}", t["create_sql"], count=1, flags=re.I)
|
|
89
|
+
elif eng == "MaterializedView" or not t.get("create_sql") or not re.search(r"MergeTree|Log|Memory|Null|Join|Set|Buffer|Distributed|Merge",
|
|
90
|
+
eng or ""):
|
|
91
|
+
sql = _ch_columns_table(full, t.get("columns") or [])
|
|
92
|
+
else:
|
|
93
|
+
sql = _ch_ddl(t["create_sql"])
|
|
94
|
+
sql = re.sub(r"^(\s*CREATE\s+TABLE\s+)(?:IF\s+NOT\s+EXISTS\s+)?\S+", lambda m: m.group(1) + _q_ch(full), sql, count=1, flags=re.I)
|
|
95
|
+
if re.search(r"ENGINE\s*=\s*(?:Distributed|Merge|Buffer)\b", sql):
|
|
96
|
+
sql = _ch_columns_table(full, t.get("columns") or [])
|
|
97
|
+
try:
|
|
98
|
+
if not sql:
|
|
99
|
+
raise ValueError("no columns")
|
|
100
|
+
sb.execute(sql)
|
|
101
|
+
built[full] = t
|
|
102
|
+
except Exception as e: # noqa: BLE001 - the server's error is the result
|
|
103
|
+
if rnd == 2 and t.get("columns") and eng != "View":
|
|
104
|
+
try:
|
|
105
|
+
sb.execute(_ch_columns_table(full, t["columns"]))
|
|
106
|
+
built[full] = t
|
|
107
|
+
continue
|
|
108
|
+
except Exception as e2: # noqa: BLE001
|
|
109
|
+
e = e2
|
|
110
|
+
failed.append((t, str(e)[:300]))
|
|
111
|
+
todo = [t for t, _ in failed]
|
|
112
|
+
if not todo:
|
|
113
|
+
break
|
|
114
|
+
report["failed"] = [{"table": f"{t.get('database')}.{t['name']}", "error": err} for t, err in failed] if todo else []
|
|
115
|
+
report["built"] = len(built)
|
|
116
|
+
# bare names in the session's database: the one the workload reads (Facts.tables), else the most rows
|
|
117
|
+
chosen = facts.tables("clickhouse") if facts is not None else {}
|
|
118
|
+
session = sb.database
|
|
119
|
+
by_bare: dict[str, str] = {}
|
|
120
|
+
for full, t in built.items():
|
|
121
|
+
bare = t["name"]
|
|
122
|
+
pick = chosen.get(bare)
|
|
123
|
+
if pick is not None and (pick.get("database") or "default") == full.split(".")[0]:
|
|
124
|
+
by_bare[bare] = full
|
|
125
|
+
else:
|
|
126
|
+
by_bare.setdefault(bare, full)
|
|
127
|
+
for bare, full in by_bare.items():
|
|
128
|
+
if full.split(".")[0] == session:
|
|
129
|
+
continue
|
|
130
|
+
kind = built[full].get("engine")
|
|
131
|
+
try:
|
|
132
|
+
if kind == "View":
|
|
133
|
+
sb.execute(f"CREATE VIEW IF NOT EXISTS `{session}`.`{bare}` AS SELECT * FROM {_q_ch(full)}")
|
|
134
|
+
else:
|
|
135
|
+
sb.execute(f"CREATE TABLE IF NOT EXISTS `{session}`.`{bare}` AS {_q_ch(full)}")
|
|
136
|
+
report["bare"] += 1
|
|
137
|
+
except Exception as e: # noqa: BLE001
|
|
138
|
+
report["failed"].append({"table": f"{session}.{bare}", "error": str(e)[:300]})
|
|
139
|
+
# the repository's own tables no pull has
|
|
140
|
+
have = {b.lower() for b in by_bare}
|
|
141
|
+
from .loopschema import definition
|
|
142
|
+
for t in (inventory or {}).get("tables") or []:
|
|
143
|
+
bare = TP._bare(t.get("name") or "")
|
|
144
|
+
if not bare or bare in have or t.get("test_only") or not t.get("engine") or "«" in (t.get("name") or ""):
|
|
145
|
+
continue
|
|
146
|
+
if names is not None and bare not in names:
|
|
147
|
+
continue
|
|
148
|
+
d = definition(inventory, t["name"].replace('"', "").replace("`", "").split(".")[-1], "clickhouse")
|
|
149
|
+
if not d:
|
|
150
|
+
continue
|
|
151
|
+
try:
|
|
152
|
+
sb.create_table(d)
|
|
153
|
+
have.add(bare)
|
|
154
|
+
report["repository"] += 1
|
|
155
|
+
if t.get("schema_source") == "test_fixtures":
|
|
156
|
+
report.setdefault("from_test_fixtures", []).append(bare) # schema from the repository's test fixtures
|
|
157
|
+
except Exception as e: # noqa: BLE001
|
|
158
|
+
report["repository_failed"].append({"table": bare, "error": str(e)[:300]})
|
|
159
|
+
report["session_database"] = session
|
|
160
|
+
return report
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def build_postgres(sb, catalog: dict | None, inventory: dict | None, facts=None, names: set[str] | None = None, log=lambda s: None) -> dict:
|
|
164
|
+
"""Every pulled table (every connection: every database a pull read) in its schema, then the repository's tables no
|
|
165
|
+
pull has. Returns {built, failed, repository, repository_failed}."""
|
|
166
|
+
from .realdb.postgres import quote_created_table
|
|
167
|
+
from .loopschema import postgres_definition
|
|
168
|
+
report: dict = {"built": 0, "failed": [], "repository": 0, "repository_failed": []}
|
|
169
|
+
for ext in ("pg_trgm", "uuid-ossp", "pgcrypto", "citext", "btree_gin", "btree_gist", "hstore", "vector", "ltree"):
|
|
170
|
+
sb._extension(ext)
|
|
171
|
+
have: set[str] = set()
|
|
172
|
+
for conn in ((catalog or {}).get("connections") or {}).values():
|
|
173
|
+
if conn.get("engine") != "postgres":
|
|
174
|
+
continue
|
|
175
|
+
for t in conn.get("tables") or []:
|
|
176
|
+
if not t.get("create_sql") or t.get("is_partition"):
|
|
177
|
+
continue
|
|
178
|
+
schema = t.get("schema") or "public"
|
|
179
|
+
key = f"{schema}.{t['name']}".lower()
|
|
180
|
+
if key in have:
|
|
181
|
+
continue
|
|
182
|
+
sql = quote_created_table(t["create_sql"])
|
|
183
|
+
name = t["name"] if schema == "public" else f"{schema}.{t['name']}"
|
|
184
|
+
if schema != "public" and not re.search(rf"TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?\"?{re.escape(schema)}\"?\.", sql, re.I):
|
|
185
|
+
sql = re.sub(r"^(\s*CREATE\s+(?:UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?)", rf'\1"{schema}".', sql, count=1, flags=re.I)
|
|
186
|
+
err = _pg_script(sb, sql, schema, name)
|
|
187
|
+
if err:
|
|
188
|
+
report["failed"].append({"table": key, "error": err[:300]})
|
|
189
|
+
else:
|
|
190
|
+
have.add(key)
|
|
191
|
+
report["built"] += 1
|
|
192
|
+
for t in (inventory or {}).get("tables") or []:
|
|
193
|
+
raw = (t.get("name") or "").replace('"', "").replace("`", "")
|
|
194
|
+
if not raw or t.get("test_only") or t.get("engine") or "«" in raw or raw.startswith("?"):
|
|
195
|
+
continue
|
|
196
|
+
key = raw.lower() if "." in raw else f"public.{raw.lower()}"
|
|
197
|
+
if key in have or (names is not None and TP._bare(raw) not in names):
|
|
198
|
+
continue
|
|
199
|
+
d = postgres_definition(inventory, raw)
|
|
200
|
+
if not d:
|
|
201
|
+
continue
|
|
202
|
+
exact = d["name"]
|
|
203
|
+
# the keys the repository declares stay keys here: an ON CONFLICT names them (the data load builds them plain)
|
|
204
|
+
pk = [c.strip().strip('"`') for c in re.split(r"\s*,\s*", t.get("primary_key") or "") if c.strip()]
|
|
205
|
+
uniques = [pk] if len(pk) > 1 else []
|
|
206
|
+
uniques += [ix["columns"] for ix in t.get("indexes") or [] if ix.get("unique") and ix.get("columns")]
|
|
207
|
+
script = d["create_sql"]
|
|
208
|
+
for cols in uniques:
|
|
209
|
+
script += ";\nCREATE UNIQUE INDEX ON " + _pg_name(exact) + " (" + ", ".join(_pg_name(c) for c in cols) + ")"
|
|
210
|
+
err = _pg_script(sb, script, exact.split(".")[0] if "." in exact else "public", exact)
|
|
211
|
+
if err:
|
|
212
|
+
report["repository_failed"].append({"table": key, "error": err[:300]})
|
|
213
|
+
else:
|
|
214
|
+
have.add(key)
|
|
215
|
+
report["repository"] += 1
|
|
216
|
+
if t.get("schema_source") == "test_fixtures":
|
|
217
|
+
report.setdefault("from_test_fixtures", []).append(key) # schema from the repository's test fixtures
|
|
218
|
+
for f in (inventory or {}).get("sql_functions") or []:
|
|
219
|
+
if f.get("name") and f.get("sql"):
|
|
220
|
+
if "." in f["name"]:
|
|
221
|
+
sb._try(f'CREATE SCHEMA IF NOT EXISTS "{f["name"].split(".")[0]}"')
|
|
222
|
+
if not sb._try(f["sql"]):
|
|
223
|
+
report["functions"] = report.get("functions", 0) + 1
|
|
224
|
+
report["tables"] = sorted(have)
|
|
225
|
+
return report
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _pg_name(name: str) -> str:
|
|
229
|
+
return ".".join('"' + p.replace('"', "") + '"' for p in name.replace('"', "").split("."))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _pg_script(sb, script: str, schema: str, table: str) -> str:
|
|
233
|
+
"""Run a table's definition as written, keys and unique constraints kept (a statement's ON CONFLICT plans against
|
|
234
|
+
them); foreign keys and checks left out (the referenced table may be built later). "" or the CREATE TABLE's error."""
|
|
235
|
+
from .engines.pg_ddl import split_statements, statement_kind
|
|
236
|
+
if schema and schema != "public":
|
|
237
|
+
sb._try(f'CREATE SCHEMA IF NOT EXISTS "{schema}"')
|
|
238
|
+
for stmt in split_statements(script):
|
|
239
|
+
kind = statement_kind(stmt)
|
|
240
|
+
if kind == "table":
|
|
241
|
+
stmt = re.sub(r",\s*(?:CONSTRAINT\s+\S+\s+)?FOREIGN\s+KEY\s*\([^)]*\)\s*REFERENCES\s+[^,()]+(?:\([^)]*\))?(?:\s+ON\s+\w+\s+(?:NO\s+ACTION|SET\s+NULL|SET\s+DEFAULT|\w+))*(?:\s+(?:NOT\s+)?DEFERRABLE)?(?:\s+INITIALLY\s+\w+)?",
|
|
242
|
+
"", stmt, flags=re.I)
|
|
243
|
+
stmt = re.sub(r"\s+REFERENCES\s+[\w.\"]+\s*(?:\([^)]*\))?(?:\s+ON\s+(?:DELETE|UPDATE)\s+(?:NO\s+ACTION|SET\s+NULL|SET\s+DEFAULT|CASCADE|RESTRICT))*",
|
|
244
|
+
"", stmt, flags=re.I)
|
|
245
|
+
stmt = re.sub(r"^(\s*CREATE\s+)(?:UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?", r"\1TABLE IF NOT EXISTS ", stmt, count=1, flags=re.I)
|
|
246
|
+
err = sb._run_ddl(stmt, table)
|
|
247
|
+
if err:
|
|
248
|
+
# keys or a clause the server refuses: the table as the data load builds it
|
|
249
|
+
try:
|
|
250
|
+
sb.create_table({"name": table, "create_sql": script})
|
|
251
|
+
return ""
|
|
252
|
+
except Exception as e: # noqa: BLE001
|
|
253
|
+
return str(e)
|
|
254
|
+
elif kind in ("unique_index", "index", "type", "schema", "sequence", "function", "extension"):
|
|
255
|
+
sb._run_ddl(re.sub(r"\bCONCURRENTLY\s+", "", stmt, count=1, flags=re.I), table)
|
|
256
|
+
return ""
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def columns_of(engine: str, catalog: dict | None, inventory: dict | None) -> dict[str, dict[str, str]]:
|
|
260
|
+
"""Every table's columns and types: the real catalog first, then the repository's definitions."""
|
|
261
|
+
return TP.merged_columns(TP.columns_from_catalog(catalog, engine), TP.columns_from_inventory(inventory, engine))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ---- the statements ------------------------------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
def kind_of(sql: str) -> str:
|
|
267
|
+
m = re.match(r"\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(\w+)", sql or "", re.S)
|
|
268
|
+
w = (m.group(1) if m else "").upper()
|
|
269
|
+
return {"SELECT": "select", "WITH": "select", "INSERT": "insert", "UPDATE": "update", "DELETE": "delete", "MERGE": "merge",
|
|
270
|
+
"VALUES": "select"}.get(w, "other")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def pieces(sites: list[dict]) -> dict[str, dict]:
|
|
274
|
+
"""site id -> the site whose statement holds this site's whole text (the shortest such), for a site whose text is
|
|
275
|
+
only a piece: a clause (WHERE ..., AND ...), or a SELECT/INSERT found inside a longer statement of another site
|
|
276
|
+
of the same file first, then of the repository."""
|
|
277
|
+
def norm(s: str) -> str:
|
|
278
|
+
return re.sub(r"\s+", " ", RUNTIME_PART.sub(" ", s or "")).strip().lower()
|
|
279
|
+
texts = [(s, norm(s.get("sql") or "")) for s in sites if s.get("sql")]
|
|
280
|
+
out: dict[str, dict] = {}
|
|
281
|
+
longer = sorted(texts, key=lambda x: len(x[1]))
|
|
282
|
+
for s, t in texts:
|
|
283
|
+
if len(t) < 12:
|
|
284
|
+
continue
|
|
285
|
+
hosts = [(h, ht) for h, ht in longer if h is not s and len(ht) > len(t) + 8 and t in ht and kind_of(h.get("sql") or "") != "other"]
|
|
286
|
+
if not hosts:
|
|
287
|
+
continue
|
|
288
|
+
same = [h for h, _ in hosts if h.get("file") == s.get("file")]
|
|
289
|
+
out[s["id"]] = (same or [h for h, _ in hosts])[0]
|
|
290
|
+
return out
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def has_runtime_part(sql: str) -> bool:
|
|
294
|
+
"""A «part» discover marked, or a format slot `{name}` (no type: not a ClickHouse parameter) outside strings and
|
|
295
|
+
comments: text the code fills at run time (Rust format!, Python str.format), so not a statement yet."""
|
|
296
|
+
from .engines.base import QUOTED
|
|
297
|
+
return bool(RUNTIME_PART.search(QUOTED.sub(" ", sql or "")))
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def cte_bodies(sites: list[dict]) -> dict[str, dict]:
|
|
301
|
+
"""name -> {text: `name AS (...)`, site}: every WITH definition in the repository's statements (a CTE written at
|
|
302
|
+
the start of a text, after WITH, or after a comma), with its parenthesised body."""
|
|
303
|
+
out: dict[str, dict] = {}
|
|
304
|
+
for st in sites:
|
|
305
|
+
sql = st.get("sql") or ""
|
|
306
|
+
for m in re.finditer(r"(?:^\s*|\bWITH\s+|,\s*)([A-Za-z_]\w*)\s+AS\s*\(", sql, re.I | re.M):
|
|
307
|
+
name = m.group(1).lower()
|
|
308
|
+
if name in out or name in ("select", "with"):
|
|
309
|
+
continue
|
|
310
|
+
depth, i = 0, m.end() - 1
|
|
311
|
+
while i < len(sql):
|
|
312
|
+
if sql[i] == "(":
|
|
313
|
+
depth += 1
|
|
314
|
+
elif sql[i] == ")":
|
|
315
|
+
depth -= 1
|
|
316
|
+
if depth == 0:
|
|
317
|
+
break
|
|
318
|
+
i += 1
|
|
319
|
+
if depth == 0 and i < len(sql):
|
|
320
|
+
out[name] = {"text": sql[m.start(1):i + 1], "site": st}
|
|
321
|
+
return out
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def statement_sites(inventory: dict, engine: str) -> list[dict]:
|
|
325
|
+
"""The non-test query and write sites of the engine whose statement text is known."""
|
|
326
|
+
out = []
|
|
327
|
+
for s in inventory.get("call_sites") or []:
|
|
328
|
+
if s.get("is_test") or s.get("engine") != engine or not (s.get("sql") or "").strip():
|
|
329
|
+
continue
|
|
330
|
+
if s.get("statement") not in ("select", "insert", "update", "delete"):
|
|
331
|
+
continue
|
|
332
|
+
out.append(s)
|
|
333
|
+
return out
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _error_class(err: str) -> str:
|
|
337
|
+
from .blockers import error_class
|
|
338
|
+
return error_class(err, "")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def plan(sb, engine: str, sql: str, columns: dict[str, dict[str, str]], values=None) -> dict:
|
|
342
|
+
"""{planned: bool | None, kind, error, typed: Bound.to_dict()} for one statement. None: not a kind that plans here."""
|
|
343
|
+
k = kind_of(sql)
|
|
344
|
+
if k not in KINDS[engine]:
|
|
345
|
+
return {"planned": None, "kind": k, "error": ""}
|
|
346
|
+
b = TP.bind(sql.strip().rstrip(";"), engine, columns, values)
|
|
347
|
+
text = re.sub(r"\s+FORMAT\s+\w+\s*$", "", b.sql.strip().rstrip(";"), flags=re.I)
|
|
348
|
+
try:
|
|
349
|
+
if engine == "postgres":
|
|
350
|
+
_pg_plan(sb, text, b)
|
|
351
|
+
elif k == "select":
|
|
352
|
+
_ch_try(sb, "EXPLAIN PLAN ", text, b)
|
|
353
|
+
else:
|
|
354
|
+
m = re.match(r"\s*INSERT\s+INTO\s+(?:TABLE\s+)?(?P<t>(?:`[^`]+`|[\w.])+)", text, re.I)
|
|
355
|
+
if not m:
|
|
356
|
+
raise RuntimeError("INSERT with no target table")
|
|
357
|
+
target = m.group("t").replace("`", "")
|
|
358
|
+
got = sb.rows("SELECT count() AS n FROM system.tables WHERE database = {d:String} AND name = {t:String}",
|
|
359
|
+
{"d": target.split(".")[0] if "." in target else sb.database, "t": target.split(".")[-1]})
|
|
360
|
+
if not got or int(got[0]["n"]) == 0:
|
|
361
|
+
raise RuntimeError(f"UNKNOWN_TABLE: Table {target} does not exist")
|
|
362
|
+
sel = re.search(r"\b(SELECT|WITH)\b.*", text, re.S | re.I)
|
|
363
|
+
if sel and not re.search(r"\bVALUES\b", text[:sel.start()], re.I):
|
|
364
|
+
_ch_try(sb, "EXPLAIN PLAN ", sel.group(0), b)
|
|
365
|
+
except Exception as e: # noqa: BLE001 - the server's message is the result
|
|
366
|
+
return {"planned": False, "kind": k, "error": str(e)[:400], "typed": b.to_dict()}
|
|
367
|
+
return {"planned": True, "kind": k, "error": "", "typed": b.to_dict()}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _ch_try(sb, head: str, text: str, b) -> None:
|
|
371
|
+
"""EXPLAIN with the typed parameters; a placeholder no rule typed is written as a stand-in literal, tried in turn
|
|
372
|
+
(NULL, '', 0, a time, [], a uuid) while the server's error is about that value's type. When the typed values
|
|
373
|
+
themselves are refused for their type, every placeholder the code did not type itself is tried as a stand-in."""
|
|
374
|
+
try:
|
|
375
|
+
_ch_stand_ins(sb, head, text, b.params, set(b.untyped))
|
|
376
|
+
except Exception as e: # noqa: BLE001
|
|
377
|
+
loose = {k for k, v in b.basis.items() if v != "declared"}
|
|
378
|
+
if not STAND_IN_ERROR.search(str(e)) or loose <= set(b.untyped):
|
|
379
|
+
raise
|
|
380
|
+
_ch_stand_ins(sb, head, text, b.params, loose)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _ch_stand_ins(sb, head: str, text: str, values: dict, untyped: set) -> None:
|
|
384
|
+
if not untyped:
|
|
385
|
+
sb.execute(head + text, values)
|
|
386
|
+
return
|
|
387
|
+
params = {k: v for k, v in values.items() if k not in untyped}
|
|
388
|
+
last = None
|
|
389
|
+
for stand in STAND_INS:
|
|
390
|
+
sql = re.sub(r"\{(\w+):[^{}]+\}", lambda m: stand if m.group(1) in untyped else m.group(0), text)
|
|
391
|
+
try:
|
|
392
|
+
sb.execute(head + sql, params)
|
|
393
|
+
return
|
|
394
|
+
except Exception as e: # noqa: BLE001
|
|
395
|
+
last = e
|
|
396
|
+
if not STAND_IN_ERROR.search(str(e)):
|
|
397
|
+
raise
|
|
398
|
+
raise last
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _pg_plan(sb, text: str, b) -> None:
|
|
402
|
+
"""PREPARE with every placeholder a `$n` the server types from its context (as the code's driver sends it); only when
|
|
403
|
+
the server cannot ("could not determine data type") are the typed ones declared."""
|
|
404
|
+
order: list[str] = []
|
|
405
|
+
|
|
406
|
+
def dollar(m: re.Match) -> str:
|
|
407
|
+
if m.group(1) not in order:
|
|
408
|
+
order.append(m.group(1))
|
|
409
|
+
cast = f"::{m.group(2)}" if b.basis.get(m.group(1)) == "cast" else ""
|
|
410
|
+
return f"${order.index(m.group(1)) + 1}{cast}"
|
|
411
|
+
sql = re.sub(r"\{(\w+):([^{}]+)\}", dollar, text)
|
|
412
|
+
try:
|
|
413
|
+
sb._psql(f"PREPARE codecop_plan AS {sql};\nDEALLOCATE codecop_plan;")
|
|
414
|
+
except Exception as e: # noqa: BLE001
|
|
415
|
+
if "could not determine data type" not in str(e) and "is of type" not in str(e) and "operator is not unique" not in str(e):
|
|
416
|
+
raise
|
|
417
|
+
types = [b.types.get(n, "unknown") if n not in b.untyped else "unknown" for n in order]
|
|
418
|
+
sb._psql(f"PREPARE codecop_plan ({', '.join(types)}) AS {sql};\nDEALLOCATE codecop_plan;")
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def reason_of(result: dict, sql: str, known: set[str], ctes: set[str] = frozenset()) -> tuple[str, dict]:
|
|
422
|
+
"""(coverage reason code, evidence) for a statement that did not plan."""
|
|
423
|
+
err = result.get("error") or ""
|
|
424
|
+
if PARSE_ERROR.search(err):
|
|
425
|
+
return "does_not_parse", {"error_class": _error_class(err)}
|
|
426
|
+
for rx in MISSING_TABLE:
|
|
427
|
+
m = rx.search(err)
|
|
428
|
+
if m:
|
|
429
|
+
name = next((g for g in m.groups() if g), "") if m.groups() else ""
|
|
430
|
+
name = name.replace("`", "").replace('"', "")
|
|
431
|
+
bare = name.split(".")[-1].lower()
|
|
432
|
+
if bare and bare in ctes:
|
|
433
|
+
return "piece_whole_not_found", {"cte": bare}
|
|
434
|
+
if bare and bare not in known:
|
|
435
|
+
qual = name.split(".")[0] if "." in name else ""
|
|
436
|
+
return "table_not_pulled", {"table": name, "next": ("codecop db pull --database <the database that holds "
|
|
437
|
+
f"{qual + '.' if qual else ''}{bare}>")}
|
|
438
|
+
return "does_not_plan", {"error_class": _error_class(err), "table": name}
|
|
439
|
+
return "does_not_plan", {"error_class": _error_class(err)}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def schema_inventory(inventory: dict, others: list[dict] | None) -> dict:
|
|
443
|
+
"""The repository's table definitions, then those of the organisation's other repositories that share its databases
|
|
444
|
+
(a table one service migrates and another reads): the repository's own win for a name both define."""
|
|
445
|
+
if not others:
|
|
446
|
+
return inventory
|
|
447
|
+
tables = list(inventory.get("tables") or [])
|
|
448
|
+
for o in others:
|
|
449
|
+
tables += [{**t, "defined_in_other_repository": True} for t in o.get("tables") or []]
|
|
450
|
+
return {**inventory, "tables": tables}
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def check(sb, engine: str, inventory: dict, catalog: dict | None, facts=None, log=lambda s: None, values=None,
|
|
454
|
+
others: list[dict] | None = None) -> dict:
|
|
455
|
+
"""Build the schema, plan every site's statement (a piece as its whole). Returns {build, sites: {id: result}, totals}.
|
|
456
|
+
`others`: inventories of the organisation's other repositories whose tables this one's statements may read."""
|
|
457
|
+
schema_inv = schema_inventory(inventory, others)
|
|
458
|
+
build = (build_postgres if engine == "postgres" else build_clickhouse)(sb, catalog, schema_inv, facts, log=log)
|
|
459
|
+
columns = columns_of(engine, catalog, schema_inv)
|
|
460
|
+
known = set(columns)
|
|
461
|
+
sites = statement_sites(inventory, engine)
|
|
462
|
+
whole = pieces(sites)
|
|
463
|
+
# names a WITH clause of some statement of the repository defines (`name AS (`): never tables to pull
|
|
464
|
+
ctes = cte_bodies([x for x in inventory.get("call_sites") or [] if x.get("engine") == engine and x.get("sql") and not x.get("is_test")])
|
|
465
|
+
cache: dict[str, dict] = {}
|
|
466
|
+
results: dict[str, dict] = {}
|
|
467
|
+
for s in sites:
|
|
468
|
+
sql = s["sql"]
|
|
469
|
+
if has_runtime_part(sql):
|
|
470
|
+
results[s["id"]] = {"planned": None, "reason": "run_time_parts"}
|
|
471
|
+
continue
|
|
472
|
+
host = whole.get(s["id"])
|
|
473
|
+
clause = bool(PIECE_START.match(sql))
|
|
474
|
+
if not clause and kind_of(sql) not in KINDS[engine]:
|
|
475
|
+
results[s["id"]] = {"planned": None, "kind": kind_of(sql)} # ALTER ... DELETE, a mutation: not planned here
|
|
476
|
+
continue
|
|
477
|
+
if clause and host is None:
|
|
478
|
+
results[s["id"]] = {"planned": False, "reason": "piece_whole_not_found"}
|
|
479
|
+
continue
|
|
480
|
+
r = None
|
|
481
|
+
if not clause:
|
|
482
|
+
r = cache.get(sql)
|
|
483
|
+
if r is None:
|
|
484
|
+
r = cache[sql] = plan(sb, engine, sql, columns, values)
|
|
485
|
+
if r["planned"] is not False:
|
|
486
|
+
host = None # it plans on its own: a statement, not a piece
|
|
487
|
+
text = sql
|
|
488
|
+
if host is not None:
|
|
489
|
+
# a clause, or a statement that fails alone and whose text sits inside a longer one: planned as that whole
|
|
490
|
+
text = host["sql"]
|
|
491
|
+
if has_runtime_part(text):
|
|
492
|
+
results[s["id"]] = {"planned": None, "reason": "run_time_parts", "whole_of": host["id"]}
|
|
493
|
+
continue
|
|
494
|
+
r = cache.get(text)
|
|
495
|
+
if r is None:
|
|
496
|
+
r = cache[text] = plan(sb, engine, text, columns, values)
|
|
497
|
+
out = {k: v for k, v in r.items() if k != "typed"}
|
|
498
|
+
out["untyped"] = (r.get("typed") or {}).get("untyped") or []
|
|
499
|
+
if host is not None:
|
|
500
|
+
out["whole_of"] = host["id"]
|
|
501
|
+
if r["planned"] is False and host is None:
|
|
502
|
+
# a statement over a WITH name another site of the repository defines (a shared CTE file or constant the code
|
|
503
|
+
# puts in front of it): planned with that definition in front, as the code sends it
|
|
504
|
+
m = re.search(r"Unknown table expression identifier '([^']+)'|relation \"([^\"]+)\" does not exist", r.get("error") or "")
|
|
505
|
+
name = (m.group(1) or m.group(2)).lower() if m else ""
|
|
506
|
+
if name in ctes and ctes[name]["site"] is not s:
|
|
507
|
+
lead = ctes[name]
|
|
508
|
+
joined = f"WITH {lead['text']}\n" + (re.sub(r"^\s*WITH\s+", ", ", sql, count=1, flags=re.I) if re.match(r"\s*WITH\b", sql, re.I) else sql)
|
|
509
|
+
if re.match(r"\s*WITH\b", sql, re.I):
|
|
510
|
+
joined = f"WITH {lead['text']}" + re.sub(r"^\s*WITH\s+", ",\n", sql, count=1, flags=re.I)
|
|
511
|
+
r2 = cache.get(joined) or plan(sb, engine, joined, columns, values)
|
|
512
|
+
cache[joined] = r2
|
|
513
|
+
if r2["planned"]:
|
|
514
|
+
r, text = r2, joined
|
|
515
|
+
out = {k: v for k, v in r.items() if k != "typed"}
|
|
516
|
+
out["whole_of"] = lead["site"]["id"]
|
|
517
|
+
out["assembled"] = f"WITH {name} from {lead['site'].get('file')}:{lead['site'].get('line')}"
|
|
518
|
+
if r["planned"] is False:
|
|
519
|
+
out["reason"], ev = reason_of(r, text, known, set(ctes))
|
|
520
|
+
out.update(ev)
|
|
521
|
+
results[s["id"]] = out
|
|
522
|
+
tot = Counter()
|
|
523
|
+
for r in results.values():
|
|
524
|
+
tot["sites"] += 1
|
|
525
|
+
if r.get("planned") is None and r.get("reason") == "run_time_parts":
|
|
526
|
+
tot["run_time_parts"] += 1
|
|
527
|
+
elif r.get("planned") is None:
|
|
528
|
+
tot["not_planned_kind"] += 1
|
|
529
|
+
elif r["planned"]:
|
|
530
|
+
tot["planned"] += 1
|
|
531
|
+
else:
|
|
532
|
+
tot["failed"] += 1
|
|
533
|
+
tot["reason:" + r.get("reason", "")] += 1
|
|
534
|
+
return {"engine": engine, "build": build, "totals": dict(tot), "sites": results}
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def mark(inventory: dict, result: dict) -> int:
|
|
538
|
+
"""Puts each site's outcome on the inventory (`site["plan"]`, read by coverage.py). Returns sites marked."""
|
|
539
|
+
n = 0
|
|
540
|
+
by_id = result.get("sites") or {}
|
|
541
|
+
for s in inventory.get("call_sites") or []:
|
|
542
|
+
r = by_id.get(s.get("id"))
|
|
543
|
+
if r is None or r.get("planned") is None:
|
|
544
|
+
continue
|
|
545
|
+
s["plan"] = {"ok": bool(r["planned"]), **({"reason": r["reason"]} if not r["planned"] else {}),
|
|
546
|
+
**({"whole_of": r["whole_of"]} if r.get("whole_of") else {}),
|
|
547
|
+
**({"next": r["next"]} if r.get("next") else {})}
|
|
548
|
+
n += 1
|
|
549
|
+
return n
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def write(out_dir: Path, result: dict) -> Path:
|
|
553
|
+
path = Path(out_dir) / f"schema_check_{result['engine']}.json"
|
|
554
|
+
path.write_text(json.dumps(result, indent=1, default=str))
|
|
555
|
+
return path
|