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,462 @@
|
|
|
1
|
+
"""From a candidate (the rule's scenario and the statements linked to it) to the facts a scenario builder takes: the
|
|
2
|
+
repository's statements bound to generated rows when they bind (`statements: extracted`), else modelled statements
|
|
3
|
+
on the same table names (`statements: modelled`), with the reason it fell back."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from . import bind
|
|
10
|
+
from .bind import Unbound, analyze, named, quote
|
|
11
|
+
|
|
12
|
+
MARKER = re.compile(r"(?:_at|_on|ed|processed|delivered|sent|done|claimed|locked|handled|notified|published)$", re.I)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def facts_for(cand: dict, inventory: dict, catalog: dict | None, settings: dict) -> dict:
|
|
16
|
+
"""The builder's facts for one candidate; `statements` says extracted or modelled, `fallback` why."""
|
|
17
|
+
code = cand["scenario"]
|
|
18
|
+
engine = cand.get("engine") or "postgres"
|
|
19
|
+
base = {"engine": engine, "sessions": settings.get("sessions"), "think_ms": settings.get("think_ms"),
|
|
20
|
+
"operations": settings.get("operations"), "hot_rows": settings.get("hot_rows")}
|
|
21
|
+
base = {k: v for k, v in base.items() if v is not None}
|
|
22
|
+
if code == "poll_then_mark":
|
|
23
|
+
base["sessions"] = int(settings.get("poll_sessions") or 2)
|
|
24
|
+
base.pop("operations", None)
|
|
25
|
+
for key in ("items", "batch"):
|
|
26
|
+
if settings.get(key):
|
|
27
|
+
base[key] = settings[key]
|
|
28
|
+
fn = {"poll_then_mark": _poll, "queue_claim": _queue, "read_modify_write": _rmw, "call_in_transaction": _call,
|
|
29
|
+
"fk_without_index": _fk, "lock_order": _order, "sqlite_deferred_begin": _sqlite_begin,
|
|
30
|
+
"sqlite_no_wal_timeout": _sqlite_open}[code]
|
|
31
|
+
try:
|
|
32
|
+
got = fn(cand, inventory, catalog, engine, settings)
|
|
33
|
+
kind = "extracted" if got.get("_extracted") else "schema" if got.get("_schema") else "modelled"
|
|
34
|
+
return {**base, **got, "statements": kind}
|
|
35
|
+
except Unbound as e:
|
|
36
|
+
modelled = _modelled(cand, engine)
|
|
37
|
+
return {**base, **modelled, "statements": "modelled", "fallback": str(e)[:160]}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _modelled(cand: dict, engine: str) -> dict:
|
|
41
|
+
"""Modelled statements on the shape's table names (the builder's defaults with the real names)."""
|
|
42
|
+
t = (cand.get("tables") or [None])[0]
|
|
43
|
+
out: dict = {}
|
|
44
|
+
if t and re.fullmatch(r"[\w.]+", t):
|
|
45
|
+
out["table"] = "codecop_" + t.split(".")[-1]
|
|
46
|
+
if cand["scenario"] == "fk_without_index":
|
|
47
|
+
fk = cand.get("fk") or {}
|
|
48
|
+
for k_from, k_to in (("parent", "parent"), ("parent_key", "parent_key"), ("child", "child"), ("column", "fk")):
|
|
49
|
+
if fk.get(k_from):
|
|
50
|
+
out[k_to] = fk[k_from] if k_from in ("parent_key", "column") else fk[k_from].split(".")[-1]
|
|
51
|
+
out.pop("table", None)
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# --- shared seeding ---------------------------------------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
class Seeder:
|
|
58
|
+
"""Table definitions and one consistent set of constants across the statements of a scenario."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, inventory: dict, catalog: dict | None, engine: str):
|
|
61
|
+
self.inventory, self.catalog, self.engine = inventory, catalog, engine
|
|
62
|
+
self.defs: dict[str, dict] = {}
|
|
63
|
+
self.consts: dict[tuple[str, str], object] = {}
|
|
64
|
+
self.n = 0
|
|
65
|
+
|
|
66
|
+
def d(self, table: str) -> dict:
|
|
67
|
+
key = table.lower()
|
|
68
|
+
if key not in self.defs:
|
|
69
|
+
got = bind.definition(table, self.inventory, self.catalog, self.engine)
|
|
70
|
+
if not got:
|
|
71
|
+
raise Unbound(f"no definition of {table} in the repository or the catalog")
|
|
72
|
+
self.defs[key] = got
|
|
73
|
+
return self.defs[key]
|
|
74
|
+
|
|
75
|
+
def col(self, table: str, column: str) -> dict:
|
|
76
|
+
for c in self.d(table)["columns"]:
|
|
77
|
+
if c["name"].lower() == column.lower():
|
|
78
|
+
return c
|
|
79
|
+
raise Unbound(f"{table}.{column} is not in its definition")
|
|
80
|
+
|
|
81
|
+
def const(self, table: str, column: str):
|
|
82
|
+
key = (table.lower(), column.lower())
|
|
83
|
+
if key not in self.consts:
|
|
84
|
+
self.n += 1
|
|
85
|
+
self.consts[key] = bind.const_for(self.col(table, column)["family"], self.n)
|
|
86
|
+
return self.consts[key]
|
|
87
|
+
|
|
88
|
+
def setup(self, tables: list[str]) -> list[str]:
|
|
89
|
+
out = []
|
|
90
|
+
for t in tables:
|
|
91
|
+
out += bind.create_statements(self.d(t), self.engine)
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _param_values(a: dict, seeder: Seeder, skip: set[str], batch: int) -> dict:
|
|
96
|
+
out = {}
|
|
97
|
+
for name, p in a["params"].items():
|
|
98
|
+
if name in skip:
|
|
99
|
+
continue
|
|
100
|
+
if p.get("limit"):
|
|
101
|
+
out[name] = batch
|
|
102
|
+
elif p.get("table") and p.get("column"):
|
|
103
|
+
out[name] = seeder.const(p["table"], p["column"])
|
|
104
|
+
else:
|
|
105
|
+
got = _by_context(a.get("sql") or "", name)
|
|
106
|
+
if got is _NONE:
|
|
107
|
+
raise Unbound(f"placeholder :{name} is not compared with a column")
|
|
108
|
+
out[name] = got
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_NONE = object()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _by_context(sql: str, name: str):
|
|
116
|
+
"""A value for a placeholder no column decides, from where it stands: `CASE WHEN :p` (true), `make_interval(hours =>
|
|
117
|
+
:p)` or `:p * interval` (a number of units that keeps generated recent rows inside the window), `:p IS NULL OR`
|
|
118
|
+
(null: the optional filter off)."""
|
|
119
|
+
ph = re.escape(f":{name}")
|
|
120
|
+
if re.search(rf"\bWHEN\s+{ph}\b", sql, re.I):
|
|
121
|
+
return True
|
|
122
|
+
if re.search(rf"=>\s*{ph}\b|{ph}\s*\*\s*interval|interval\s*'[^']*'\s*\*\s*{ph}", sql, re.I):
|
|
123
|
+
return 48
|
|
124
|
+
if re.search(rf"{ph}(?:::\w+)?\s+IS\s+NULL\b", sql, re.I):
|
|
125
|
+
return None
|
|
126
|
+
return _NONE
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _seed_table(seeder: Seeder, table: str, rows: int, analyses: list[dict], *, unique: set[str], extra_consts: dict | None = None,
|
|
130
|
+
nulls: set[str] | None = None) -> str:
|
|
131
|
+
consts, nul, recent = {}, set(nulls or ()), set()
|
|
132
|
+
for a in analyses:
|
|
133
|
+
for f in a["filters"]:
|
|
134
|
+
if f["table"].lower() != table.lower():
|
|
135
|
+
continue
|
|
136
|
+
c = f["column"].lower()
|
|
137
|
+
if f["op"] in ("eq", "in"):
|
|
138
|
+
consts[c] = f["value"]
|
|
139
|
+
elif f["op"] == "neq":
|
|
140
|
+
# "qopt_not_": kept from before the rename (formerly qopt) so the generated values stay the same
|
|
141
|
+
consts.setdefault(c, f"qopt_not_{f['value']}" if f.get("string") else 0)
|
|
142
|
+
elif f["op"] == "is_null":
|
|
143
|
+
nul.add(c)
|
|
144
|
+
elif f["op"] == "is_not_null":
|
|
145
|
+
consts.setdefault(c, bind.const_for(seeder.col(table, f["column"])["family"], 99) or "x")
|
|
146
|
+
elif f["op"] == "recent":
|
|
147
|
+
recent.add(c)
|
|
148
|
+
for (t, c), v in seeder.consts.items():
|
|
149
|
+
if t == table.lower() and c not in unique:
|
|
150
|
+
consts[c] = v
|
|
151
|
+
consts.update(extra_consts or {})
|
|
152
|
+
for c in list(consts):
|
|
153
|
+
if c in unique:
|
|
154
|
+
consts.pop(c)
|
|
155
|
+
return bind.seed_rows(seeder.d(table), seeder.engine, rows, consts, unique=unique, nulls=nul - set(consts), recent=recent)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _join_consts(seeder: Seeder, analyses: list[dict], skip_tables: set[str]) -> None:
|
|
159
|
+
"""Make both sides of every inner join equal (one shared constant per joined key)."""
|
|
160
|
+
for a in analyses:
|
|
161
|
+
for t1, c1, t2, c2, side in a["joins"]:
|
|
162
|
+
if side == "left" or t1.lower() in skip_tables or t2.lower() in skip_tables:
|
|
163
|
+
continue
|
|
164
|
+
v = seeder.const(t2, c2) if (t2.lower(), c2.lower()) in seeder.consts or (t1.lower(), c1.lower()) not in seeder.consts else seeder.const(t1, c1)
|
|
165
|
+
seeder.consts[(t1.lower(), c1.lower())] = v
|
|
166
|
+
seeder.consts[(t2.lower(), c2.lower())] = v
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# --- poll, act, mark -------------------------------------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
def _poll(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
172
|
+
sel_sql, sel_names = named(cand["select_sql"])
|
|
173
|
+
mark_sql, mark_names = named(cand["mark_sql"])
|
|
174
|
+
sel, mark = analyze(sel_sql, engine), analyze(mark_sql, engine)
|
|
175
|
+
T = sel["main"]
|
|
176
|
+
if not T:
|
|
177
|
+
raise Unbound("the poll's main table is not known")
|
|
178
|
+
seeder = Seeder(inventory, catalog, engine)
|
|
179
|
+
keycols = [c["name"] for c in seeder.d(T)["columns"] if c["pk"]]
|
|
180
|
+
marker = (sel["anti"][0]["table"] if sel["anti"] else T)
|
|
181
|
+
# the item: the mark's placeholder compared with a key of the polled table that the poll returns
|
|
182
|
+
item_param, item_col = None, None
|
|
183
|
+
assigned = {s["param"] for s in mark["set"] if s.get("param")}
|
|
184
|
+
for name, p in mark["params"].items():
|
|
185
|
+
if name not in assigned and p.get("table", "").lower() == T.lower() and p.get("column") and p["column"] in keycols:
|
|
186
|
+
item_param, item_col = name, p["column"]
|
|
187
|
+
break
|
|
188
|
+
if item_param is None:
|
|
189
|
+
for name, p in mark["params"].items():
|
|
190
|
+
if name not in assigned and p.get("column") and \
|
|
191
|
+
p["column"].lower() in {k.lower() for k in keycols} | {"id", f"{T.split('.')[-1].rstrip('s')}_id"}:
|
|
192
|
+
item_param, item_col = name, p["column"]
|
|
193
|
+
break
|
|
194
|
+
if item_param is None:
|
|
195
|
+
returned = {c["column"].lower() for c in sel["select_columns"] if c["column"]}
|
|
196
|
+
for name, p in mark["params"].items(): # a key the definition does not mark, which the poll returns
|
|
197
|
+
if name not in assigned and p.get("column") and p["column"].lower() in returned and p.get("table", "").lower() == T.lower():
|
|
198
|
+
item_param, item_col = name, p["column"]
|
|
199
|
+
break
|
|
200
|
+
if item_param is None:
|
|
201
|
+
for name, p in mark["params"].items(): # INSERT .. VALUES ($1, ..): the first value is the item
|
|
202
|
+
if p.get("values"):
|
|
203
|
+
item_param, item_col = name, keycols[0] if keycols else "id"
|
|
204
|
+
break
|
|
205
|
+
if item_param is None or not item_col:
|
|
206
|
+
raise Unbound("the mark's item placeholder could not be found")
|
|
207
|
+
idx = next((i for i, c in enumerate(sel["select_columns"]) if c["column"].lower() == item_col.lower()
|
|
208
|
+
and (not c["table"] or c["table"].lower() == T.lower())), None)
|
|
209
|
+
if idx is None:
|
|
210
|
+
idx = next((i for i, c in enumerate(sel["select_columns"]) if c["column"].lower() == item_col.lower()), None)
|
|
211
|
+
if idx is None:
|
|
212
|
+
raise Unbound(f"the poll does not return {item_col}")
|
|
213
|
+
items = int(settings.get("items") or 100)
|
|
214
|
+
batch = int(settings.get("batch") or 20)
|
|
215
|
+
_join_consts(seeder, [sel, mark], {marker.lower()} if marker != T else set())
|
|
216
|
+
sel_params = _param_values(sel, seeder, set(), batch)
|
|
217
|
+
mark_params = _param_values(mark, seeder, {item_param}, batch)
|
|
218
|
+
tables = [t for t in dict.fromkeys(sel["tables"] + mark["tables"])]
|
|
219
|
+
setup = seeder.setup(tables)
|
|
220
|
+
unique = {item_col.lower()} | {k.lower() for k in keycols}
|
|
221
|
+
setup.append(_seed_table(seeder, T, items, [sel], unique=unique))
|
|
222
|
+
for t in tables:
|
|
223
|
+
if t.lower() in (T.lower(), marker.lower()):
|
|
224
|
+
continue
|
|
225
|
+
pk = {c["name"].lower() for c in seeder.d(t)["columns"] if c["pk"]}
|
|
226
|
+
pinned = {c for (tt, c) in seeder.consts if tt == t.lower()}
|
|
227
|
+
setup.append(_seed_table(seeder, t, 1, [sel, mark], unique=pk - pinned))
|
|
228
|
+
if marker.lower() != T.lower():
|
|
229
|
+
count = f"SELECT count(*) FROM {quote(marker)}"
|
|
230
|
+
else:
|
|
231
|
+
col = next((f["column"] for f in sel["filters"] if f["table"].lower() == T.lower() and f["op"] in ("is_null", "eq", "in")), None)
|
|
232
|
+
if not col:
|
|
233
|
+
raise Unbound("the poll's unmarked condition is not a simple filter")
|
|
234
|
+
flt = next(f for f in sel["filters"] if f["column"] == col and f["table"].lower() == T.lower())
|
|
235
|
+
count = (f"SELECT count(*) FROM {quote(T)} WHERE \"{col}\" IS NOT NULL" if flt["op"] == "is_null"
|
|
236
|
+
else f"SELECT count(*) FROM {quote(T)} WHERE \"{col}\" IS DISTINCT FROM {bind.literal(flt['value'], 'text', engine)}")
|
|
237
|
+
claim = _claim_of(mark_sql, mark, sel, T, engine)
|
|
238
|
+
return {"_extracted": True, "select_sql": sel_sql, "select_params": sel_params, "item_index": idx, "mark_sql": mark_sql.replace(f":{item_param}", ":item"),
|
|
239
|
+
"claim_sql": claim.replace(f":{item_param}", ":item"), "mark_params": mark_params, "count_marked_sql": count, "setup": setup,
|
|
240
|
+
"items": items, "batch": batch, "table": T, "sessions": int(settings.get("poll_sessions") or 2)}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _claim_of(mark_sql: str, mark: dict, sel: dict, T: str, engine: str) -> str:
|
|
244
|
+
"""The mark as a claim: it changes a row only when the item was not marked yet."""
|
|
245
|
+
if mark["kind"] == "insert":
|
|
246
|
+
if mark["on_conflict"]:
|
|
247
|
+
return mark_sql
|
|
248
|
+
return mark_sql.rstrip().rstrip(";") + " ON CONFLICT DO NOTHING"
|
|
249
|
+
if mark["kind"] == "update":
|
|
250
|
+
cond = []
|
|
251
|
+
for f in sel["filters"]:
|
|
252
|
+
if f["table"].lower() != T.lower():
|
|
253
|
+
continue
|
|
254
|
+
if f["op"] == "is_null":
|
|
255
|
+
cond.append(f'"{f["column"]}" IS NULL')
|
|
256
|
+
elif f["op"] in ("eq", "in"):
|
|
257
|
+
cond.append(f'"{f["column"]}" = {bind.literal(f["value"], "text" if f.get("string") else "int", engine)}')
|
|
258
|
+
if not cond:
|
|
259
|
+
raise Unbound("no unmarked condition to guard the mark with")
|
|
260
|
+
where = re.split(r"\bWHERE\b", mark_sql, flags=re.I)[-1]
|
|
261
|
+
cols = [re.match(r'"(\w+)"', c).group(1) for c in cond]
|
|
262
|
+
if all(re.search(rf"\b{re.escape(c)}\b", where) for c in cols):
|
|
263
|
+
return mark_sql # already guarded: it changes a row only once
|
|
264
|
+
body = re.sub(r"\s*;?\s*$", "", mark_sql)
|
|
265
|
+
ret = re.search(r"\s+RETURNING\b.*$", body, re.I | re.S)
|
|
266
|
+
head, tail = (body[:ret.start()], body[ret.start():]) if ret else (body, "")
|
|
267
|
+
return head + " AND " + " AND ".join(cond) + tail
|
|
268
|
+
raise Unbound("the mark is neither an INSERT nor an UPDATE")
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# --- a queue claimed with FOR UPDATE ------------------------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
def _queue(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
274
|
+
sql, _ = named(cand["select_sql"])
|
|
275
|
+
a = analyze(sql, engine)
|
|
276
|
+
T = a["main"]
|
|
277
|
+
seeder = Seeder(inventory, catalog, engine)
|
|
278
|
+
keycols = [c["name"] for c in seeder.d(T)["columns"] if c["pk"]]
|
|
279
|
+
if len(keycols) != 1:
|
|
280
|
+
raise Unbound("the queue table has no single-column key")
|
|
281
|
+
key = keycols[0]
|
|
282
|
+
if not any(c["column"].lower() == key.lower() for c in a["select_columns"]) and not any(c["column"] == "*" or c["column"] == "" for c in a["select_columns"]):
|
|
283
|
+
raise Unbound(f"the claim does not return the key {key}")
|
|
284
|
+
idx = next((i for i, c in enumerate(a["select_columns"]) if c["column"].lower() == key.lower()), 0)
|
|
285
|
+
items = int(settings.get("items") or 200)
|
|
286
|
+
params = _param_values(a, seeder, set(), 1)
|
|
287
|
+
done_sql = None
|
|
288
|
+
if cand.get("done_sql"):
|
|
289
|
+
dsql, _ = named(cand["done_sql"])
|
|
290
|
+
d = analyze(dsql, engine)
|
|
291
|
+
kp = next((n for n, p in d["params"].items() if p.get("column", "").lower() == key.lower()), None)
|
|
292
|
+
if kp and d["kind"] == "update" and d["main"].lower() == T.lower():
|
|
293
|
+
dparams = _param_values(d, seeder, {kp}, 1)
|
|
294
|
+
done_sql = (dsql.replace(f":{kp}", ":id"), dparams)
|
|
295
|
+
# without the repository's own "done" statement: mark the claimed row out of the queue on its pending filter
|
|
296
|
+
flt = next((f for f in a["filters"] if f["table"].lower() == T.lower() and f["op"] in ("eq", "in", "is_null")), None)
|
|
297
|
+
if done_sql is None:
|
|
298
|
+
if flt is None:
|
|
299
|
+
raise Unbound("the claim has no filter that takes a row out of the queue")
|
|
300
|
+
c = seeder.col(T, flt["column"])
|
|
301
|
+
newval = "'codecop_done'" if c["family"] == "text" else bind.default_value(c["family"], engine) if flt["op"] == "is_null" else "NULL"
|
|
302
|
+
if flt["op"] == "is_null":
|
|
303
|
+
newval = bind.unique_expr(c["family"], engine).replace("x", "1") if c["family"] in ("time",) else bind.default_value(c["family"], engine)
|
|
304
|
+
done_sql = (f'UPDATE {quote(T)} SET "{flt["column"]}" = {newval} WHERE "{key}" = :id', {})
|
|
305
|
+
setup = seeder.setup([t for t in a["tables"]])
|
|
306
|
+
setup.append(_seed_table(seeder, T, items, [a], unique={key.lower()}))
|
|
307
|
+
for t in a["tables"]:
|
|
308
|
+
if t.lower() != T.lower():
|
|
309
|
+
pk = {c["name"].lower() for c in seeder.d(t)["columns"] if c["pk"]}
|
|
310
|
+
setup.append(_seed_table(seeder, t, 1, [a], unique=pk - {c for (tt, c) in seeder.consts if tt == t.lower()}))
|
|
311
|
+
out_sql = sql
|
|
312
|
+
if idx:
|
|
313
|
+
out_sql = sql # the key is read from column idx in the program
|
|
314
|
+
claim = out_sql
|
|
315
|
+
count_done = f'SELECT count(*) FROM {quote(T)} WHERE NOT ({_pending_sql(a, T, engine)})'
|
|
316
|
+
return {"_extracted": True, "table": T, "key": key, "claim_sql": claim, "claim_params": params, "done_sql": done_sql[0],
|
|
317
|
+
"done_params": done_sql[1], "count_done_sql": count_done, "setup": setup, "items": items, "key_index": idx,
|
|
318
|
+
"think_ms": settings.get("work_ms", 5)}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _pending_sql(a: dict, T: str, engine: str) -> str:
|
|
322
|
+
conds = []
|
|
323
|
+
for f in a["filters"]:
|
|
324
|
+
if f["table"].lower() != T.lower():
|
|
325
|
+
continue
|
|
326
|
+
if f["op"] == "is_null":
|
|
327
|
+
conds.append(f'"{f["column"]}" IS NULL')
|
|
328
|
+
elif f["op"] in ("eq", "in"):
|
|
329
|
+
conds.append(f'"{f["column"]}" IS NOT DISTINCT FROM {bind.literal(f["value"], "text" if f.get("string") else "int", engine)}')
|
|
330
|
+
return " AND ".join(conds) or "false"
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# --- read, compute, write back ------------------------------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
def _rmw(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
336
|
+
if not cand.get("read_sql") or not cand.get("write_sql"):
|
|
337
|
+
raise Unbound("the read and the write are not both SQL the repository wrote")
|
|
338
|
+
rsql, _ = named(cand["read_sql"])
|
|
339
|
+
wsql, _ = named(cand["write_sql"])
|
|
340
|
+
r, w = analyze(rsql, engine), analyze(wsql, engine)
|
|
341
|
+
T = w["main"]
|
|
342
|
+
seeder = Seeder(inventory, catalog, engine)
|
|
343
|
+
col = cand.get("column") or next((s["column"] for s in w["set"] if s["param"]), None)
|
|
344
|
+
if not col:
|
|
345
|
+
raise Unbound("the write does not set a column from a value")
|
|
346
|
+
c = seeder.col(T, col)
|
|
347
|
+
if c["family"] != "int":
|
|
348
|
+
raise Unbound(f"{T}.{col} is not a number: lost updates cannot be counted on it")
|
|
349
|
+
setp = next(s["param"] for s in w["set"] if s["column"] == col)
|
|
350
|
+
kp = next((n for n, p in w["params"].items() if p.get("column") and n != setp), None)
|
|
351
|
+
rk = next((n for n, p in r["params"].items() if p.get("column")), None)
|
|
352
|
+
if not kp or not rk:
|
|
353
|
+
raise Unbound("the row's key placeholder was not found")
|
|
354
|
+
key = w["params"][kp]["column"]
|
|
355
|
+
idx = next((i for i, x in enumerate(r["select_columns"]) if x["column"].lower() == col.lower()), None)
|
|
356
|
+
if idx is None:
|
|
357
|
+
raise Unbound(f"the read does not return {col}")
|
|
358
|
+
hot = int(settings.get("hot_rows") or 2)
|
|
359
|
+
seeder.consts[(T.lower(), col.lower())] = 0
|
|
360
|
+
others = {n: seeder.const(p["table"], p["column"]) for n, p in w["params"].items() if n not in (kp, setp) and p.get("column")}
|
|
361
|
+
setup = seeder.setup([T]) + [_seed_table(seeder, T, hot, [], unique={key.lower()})]
|
|
362
|
+
keys_sql = f'SELECT "{key}" FROM {quote(T)} ORDER BY 1'
|
|
363
|
+
read = rsql.replace(f":{rk}", ":k")
|
|
364
|
+
if idx:
|
|
365
|
+
read = f'SELECT "{col}" FROM ({rsql.replace(f":{rk}", ":k")}) q'
|
|
366
|
+
return {"_extracted": True, "table": T, "key": key, "col": col, "read_sql": read, "write_sql": wsql.replace(f":{kp}", ":k").replace(f":{setp}", ":v"),
|
|
367
|
+
"atomic_sql": re.sub(rf'(\bSET\b.*?"?{re.escape(col)}"?\s*=\s*):{setp}\b', rf'\1"{col}" + :delta', wsql, flags=re.I | re.S).replace(f":{kp}", ":k"),
|
|
368
|
+
"sum_sql": f'SELECT coalesce(sum("{col}"), 0) FROM {quote(T)}', "setup": setup, "keys_sql": keys_sql, "params": others, "hot_rows": hot}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# --- a transaction held open across a call ----------------------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
def _call(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
374
|
+
if not cand.get("write_sql"):
|
|
375
|
+
raise Unbound("no write before the call")
|
|
376
|
+
wsql, _ = named(cand["write_sql"])
|
|
377
|
+
w = analyze(wsql, engine)
|
|
378
|
+
T = w["main"]
|
|
379
|
+
seeder = Seeder(inventory, catalog, engine)
|
|
380
|
+
keycols = [c["name"] for c in seeder.d(T)["columns"] if c["pk"]]
|
|
381
|
+
kp = next((n for n, p in w["params"].items() if p.get("column") and p["column"] in keycols), None)
|
|
382
|
+
if not kp:
|
|
383
|
+
raise Unbound("the write is not keyed by the table's key")
|
|
384
|
+
hot = int(settings.get("hot_rows") or 2)
|
|
385
|
+
params = {}
|
|
386
|
+
for n, p in w["params"].items():
|
|
387
|
+
if n == kp:
|
|
388
|
+
continue
|
|
389
|
+
if p.get("column"):
|
|
390
|
+
params[n] = seeder.const(p["table"], p["column"])
|
|
391
|
+
elif p.get("unknown") or True:
|
|
392
|
+
col = next((s["column"] for s in w["set"] if s["param"] == n), None)
|
|
393
|
+
if not col:
|
|
394
|
+
raise Unbound(f"placeholder :{n} of the write is not bound")
|
|
395
|
+
fam = seeder.col(T, col)["family"]
|
|
396
|
+
params[n] = {"int": 1, "bool": True, "uuid": bind.CONST_UUID.format(77)}.get(fam, "v")
|
|
397
|
+
key = w["params"][kp]["column"]
|
|
398
|
+
setup = seeder.setup([T]) + [_seed_table(seeder, T, hot, [w], unique={key.lower()})]
|
|
399
|
+
cols = [c["name"] for c in seeder.d(T)["columns"]]
|
|
400
|
+
time_cols = [c["name"] for c in seeder.d(T)["columns"] if c["family"] == "time"]
|
|
401
|
+
return {"_extracted": True, "table": T, "key": key, "write_sql": wsql.replace(f":{kp}", ":k"), "write_params": params, "setup": setup,
|
|
402
|
+
"keys": None, "keys_sql": f'SELECT "{key}" FROM {quote(T)} ORDER BY 1', "final_sql": f"SELECT * FROM {quote(T)} ORDER BY 1",
|
|
403
|
+
"final_columns": cols, "time_columns": time_cols, "hot_rows": hot,
|
|
404
|
+
"think_ms": settings.get("call_ms", settings.get("think_ms", 50)), "begin_mode": cand.get("begin_mode") or ""}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _fk(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
408
|
+
fk = cand.get("fk") or {}
|
|
409
|
+
out = {"parent": fk.get("parent"), "parent_key": fk.get("parent_key") or "id", "child": fk.get("child"), "fk": fk.get("column"),
|
|
410
|
+
"on_delete": fk.get("on_delete") or "NO ACTION", "parents": settings.get("parents"), "children": settings.get("children")}
|
|
411
|
+
if isinstance(fk.get("child_rows"), int) and fk["child_rows"] > 0 and out.get("children"):
|
|
412
|
+
out["children"] = max(1000, min(int(out["children"]), fk["child_rows"])) # the catalog's size, capped by the setting
|
|
413
|
+
out = {k: v for k, v in out.items() if v}
|
|
414
|
+
if out.get("parent") and out.get("child") and out.get("fk"):
|
|
415
|
+
out["_schema"] = True # the repository's (or the catalog's) tables and key, with modelled columns
|
|
416
|
+
if cand.get("delete_sql"):
|
|
417
|
+
dsql, _ = named(cand["delete_sql"])
|
|
418
|
+
d = analyze(dsql, engine)
|
|
419
|
+
kp = next((n for n, p in d["params"].items() if p.get("column", "").lower() == out.get("parent_key", "id").lower()), None)
|
|
420
|
+
if kp and len(d["params"]) == 1 and d["kind"] == "delete":
|
|
421
|
+
out["delete_sql"] = re.sub(r'(?i)\bFROM\s+[\w."]+', f"FROM {quote(out['parent'])}", dsql, count=1).replace(f":{kp}", ":id")
|
|
422
|
+
out["_extracted"] = True
|
|
423
|
+
return out
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _order(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
427
|
+
if not cand.get("update_sql"):
|
|
428
|
+
raise Unbound("no keyed update to replay")
|
|
429
|
+
usql, _ = named(cand["update_sql"])
|
|
430
|
+
u = analyze(usql, engine)
|
|
431
|
+
T = u["main"]
|
|
432
|
+
seeder = Seeder(inventory, catalog, engine)
|
|
433
|
+
keycols = [c["name"] for c in seeder.d(T)["columns"] if c["pk"]]
|
|
434
|
+
kp = next((n for n, p in u["params"].items() if p.get("column") in keycols), None)
|
|
435
|
+
if not kp:
|
|
436
|
+
raise Unbound("the update is not keyed by the table's key")
|
|
437
|
+
key = u["params"][kp]["column"]
|
|
438
|
+
params = {}
|
|
439
|
+
for n, p in u["params"].items():
|
|
440
|
+
if n == kp:
|
|
441
|
+
continue
|
|
442
|
+
col = p.get("column") or next((s["column"] for s in u["set"] if s["param"] == n), None)
|
|
443
|
+
if not col:
|
|
444
|
+
raise Unbound(f"placeholder :{n} is not bound")
|
|
445
|
+
fam = seeder.col(T, col)["family"]
|
|
446
|
+
params[n] = seeder.const(T, col) if p.get("column") else {"int": 1, "bool": True}.get(fam, "v")
|
|
447
|
+
rows = int(settings.get("lock_rows") or 6)
|
|
448
|
+
setup = seeder.setup([T]) + [_seed_table(seeder, T, rows, [u], unique={key.lower()})]
|
|
449
|
+
return {"_extracted": True, "table": T, "key": key, "update_sql": usql.replace(f":{kp}", ":k"), "params": params, "setup": setup,
|
|
450
|
+
"keys_sql": f'SELECT "{key}" FROM {quote(T)} ORDER BY 1', "rows": rows,
|
|
451
|
+
"sum_sql": f"SELECT count(*) FROM {quote(T)}"}
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _sqlite_begin(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
455
|
+
out = {"journal_mode": "wal" if cand.get("wal") else "delete" if cand.get("wal") is False else "delete",
|
|
456
|
+
"busy_timeout_ms": cand.get("busy_timeout_ms") if cand.get("busy_timeout_ms") is not None else 0, "_schema": True}
|
|
457
|
+
return out
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _sqlite_open(cand: dict, inventory: dict, catalog: dict | None, engine: str, settings: dict) -> dict:
|
|
461
|
+
return {"journal_mode": "wal" if cand.get("wal") else "delete",
|
|
462
|
+
"busy_timeout_ms": cand.get("busy_timeout_ms") if cand.get("busy_timeout_ms") is not None else 0, "_schema": True}
|