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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,160 @@
1
+ """One statement per arm of an if / else (or match) that appends to a query string.
2
+
3
+ The Java and Rust extractors replay what happens to a string variable. Until now the arm that was not followed
4
+ was written into the statement as a run-time part (`... AND tenant = ? «or: AND tenant IS NULL» ...`). `Arms`
5
+ keeps, beside that text, the whole statement of every arm: appends in the then-arm go to the variants that
6
+ existed before the `if`, appends in an else-arm go to copies taken before the then-arm, and whatever follows
7
+ goes to all of them. The number of variants is capped by `[discover] max_variants`; past the cap (or when the
8
+ string is rebuilt in a way that cannot be followed per arm) the extractor falls back to the single statement
9
+ with the «or: ...» part, so nothing is dropped silently.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from tree_sitter import Node
15
+
16
+
17
+ def max_variants() -> int:
18
+ from . import go as go_mod
19
+ return go_mod.MAX_VARIANTS
20
+
21
+
22
+ class Arms:
23
+ def __init__(self, join, limit: int | None = None):
24
+ self.join = join # join([value, piece]) -> value
25
+ self.limit = limit if limit is not None else max_variants()
26
+ self.vs: list | None = None
27
+ self.snaps: dict[int, list] = {}
28
+ self.arm_of: dict[tuple[int, int], list[int]] = {}
29
+ self.dead = False
30
+
31
+ def reset(self, value) -> None:
32
+ self.vs = [value] if value is not None else None
33
+ self.snaps.clear()
34
+ self.arm_of.clear()
35
+
36
+ def kill(self) -> None:
37
+ self.dead = True
38
+
39
+ def then(self, keys: list[int]) -> None:
40
+ """Before an append inside the first arm of the constructs `keys`: remember the variants as they were."""
41
+ if self.vs is None:
42
+ return
43
+ for k in keys:
44
+ self.snaps.setdefault(k, list(self.vs))
45
+
46
+ def append(self, piece, front: bool = False) -> None:
47
+ if self.vs is not None:
48
+ self.vs = [self.join([piece, v] if front else [v, piece]) for v in self.vs]
49
+
50
+ def append_else(self, key: tuple[int, int] | None, piece) -> None:
51
+ """An append inside another arm: it extends that arm's own variants, made from the snapshot."""
52
+ if self.vs is None or self.dead:
53
+ return
54
+ if key is None:
55
+ self.dead = True
56
+ return
57
+ idx = self.arm_of.get(key)
58
+ if idx is None:
59
+ base = self.snaps.get(key[0])
60
+ if base is None or len(self.vs) + len(base) > self.limit:
61
+ self.dead = True
62
+ return
63
+ start = len(self.vs)
64
+ self.vs.extend(self.join([b, piece]) for b in base)
65
+ self.arm_of[key] = list(range(start, len(self.vs)))
66
+ else:
67
+ for i in idx:
68
+ self.vs[i] = self.join([self.vs[i], piece])
69
+
70
+ def result(self) -> list:
71
+ if self.dead or self.vs is None or len(self.vs) < 2:
72
+ return []
73
+ return list(self.vs)
74
+
75
+
76
+ def _if_parts(n: Node) -> tuple[Node | None, Node | None]:
77
+ """(first arm, the rest) of an `if`, for Java (`if_statement`) and Rust (`if_expression`)."""
78
+ cons, alt = n.child_by_field_name("consequence"), n.child_by_field_name("alternative")
79
+ if alt is not None and alt.type == "else_clause": # Rust wraps the else part
80
+ inner = [c for c in alt.named_children]
81
+ alt = inner[-1] if inner else None
82
+ return cons, alt
83
+
84
+
85
+ def _within(node: Node, outer: Node | None) -> bool:
86
+ return outer is not None and outer.start_byte <= node.start_byte and node.end_byte <= outer.end_byte
87
+
88
+
89
+ IF_TYPES = ("if_statement", "if_expression")
90
+
91
+
92
+ def _constructs(node: Node, stop: Node | None, anchor: int):
93
+ """The if and match constructs around `node`, outermost first, that do not contain the use at `anchor`."""
94
+ out = []
95
+ n = node.parent
96
+ while n is not None and (stop is None or n.id != stop.id) and n.type not in ("function_item", "method_declaration",
97
+ "constructor_declaration", "class_declaration"):
98
+ if n.type in IF_TYPES or n.type == "match_expression":
99
+ if not (n.start_byte <= anchor < n.end_byte):
100
+ out.append(n)
101
+ n = n.parent
102
+ out.reverse()
103
+ return out
104
+
105
+
106
+ def _is_chain_root(n: Node) -> bool:
107
+ p = n.parent
108
+ if p is None:
109
+ return True
110
+ if p.type == "else_clause":
111
+ return False
112
+ return not (p.type in IF_TYPES and p.child_by_field_name("alternative") is not None and p.child_by_field_name("alternative").id == n.id)
113
+
114
+
115
+ def _match_arms(n: Node) -> list[Node]:
116
+ body = n.child_by_field_name("body")
117
+ return [c for c in (body.named_children if body is not None else []) if c.type == "match_arm"]
118
+
119
+
120
+ def then_keys(node: Node, stop: Node | None, anchor: int) -> list[int]:
121
+ """Constructs in whose first arm `node` sits."""
122
+ keys = []
123
+ for n in _constructs(node, stop, anchor):
124
+ if n.type == "match_expression":
125
+ arms = _match_arms(n)
126
+ if arms and _within(node, arms[0]):
127
+ keys.append(n.id)
128
+ elif _is_chain_root(n):
129
+ cons, _alt = _if_parts(n)
130
+ if _within(node, cons):
131
+ keys.append(n.id)
132
+ return keys
133
+
134
+
135
+ def arm_key(node: Node, stop: Node | None, anchor: int) -> tuple[int, int] | None:
136
+ """(construct, arm) when `node` sits in an arm other than the first of the outermost such construct."""
137
+ for n in _constructs(node, stop, anchor):
138
+ if n.type == "match_expression":
139
+ arms = _match_arms(n)
140
+ for a in arms[1:]:
141
+ if _within(node, a):
142
+ return n.id, a.id
143
+ continue
144
+ if not _is_chain_root(n):
145
+ continue
146
+ cons, alt = _if_parts(n)
147
+ if not _within(node, alt):
148
+ continue
149
+ arm = alt
150
+ while arm is not None and arm.type in IF_TYPES: # else if ... else if ... else
151
+ c2, a2 = _if_parts(arm)
152
+ if _within(node, c2):
153
+ arm = c2
154
+ break
155
+ if _within(node, a2):
156
+ arm = a2
157
+ continue
158
+ break
159
+ return (n.id, arm.id) if arm is not None else None
160
+ return None
@@ -0,0 +1,234 @@
1
+ """Shared types for discovery.
2
+
3
+ A language extractor turns source files into RawSite records. It does no SQL
4
+ analysis: it only finds where SQL reaches a driver and resolves the SQL text as
5
+ far as it can statically.
6
+
7
+ SQL templates use «expr» for a part that is only known at run time, where expr
8
+ is the source expression (for example «table» or «", ".join(cols)»).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import tomllib
15
+ from dataclasses import dataclass, field
16
+ from importlib import resources
17
+ from pathlib import Path
18
+
19
+ PLACEHOLDER = re.compile(r"«[^»]*»")
20
+
21
+ # A string that starts like a full statement. Case-sensitive on purpose: prose such
22
+ # as "Select a file from the list" must not match. Lower-case SQL is still found
23
+ # when it is the argument of a known sink.
24
+ SQL_START = re.compile(
25
+ r"^\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(?:"
26
+ r"SELECT\b[\s\S]+?\bFROM\b|SELECT\s+[\w(*]|WITH\s+[\s\S]+?\bAS\b\s*\(?|INSERT\s+(?:OR\s+\w+\s+)?INTO\b|"
27
+ r"CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMPORARY\s+)?(?:TABLE|MATERIALIZED|VIEW|DICTIONARY|INDEX|UNIQUE)\b|"
28
+ r"ALTER\s+TABLE\b|DELETE\s+FROM\b|UPDATE\s+[\w.«»\"`]+\s+SET\b|DROP\s+(?:TABLE|VIEW|INDEX)\b|"
29
+ r"OPTIMIZE\s+TABLE\b|TRUNCATE\s+TABLE\b|SHOW\s+(?:CREATE|TABLES|DATABASES)\b|EXPLAIN\s|"
30
+ r"DESCRIBE\s+TABLE\b|SYSTEM\s+[A-Z]+|PRAGMA\s+\w+|EXISTS\s+TABLE\b)"
31
+ )
32
+ SQL_START_ANYCASE = re.compile(SQL_START.pattern, re.IGNORECASE)
33
+ # The words of a DDL statement with nothing after them ("ALTER TABLE ", "CREATE VIEW"): a fragment that code
34
+ # appends a name to, or a keyword in a list. A statement names the thing it changes. Checked on the text a
35
+ # site ends up with, not in looks_like_sql: the extractors use that on the first literal of a concatenation
36
+ # (`"ALTER TABLE " + name + " ADD ..."`), where the words alone are how a real statement starts.
37
+ BARE_DDL = re.compile(
38
+ r"^\s*(?:CREATE(?:\s+OR\s+REPLACE)?(?:\s+TEMPORARY)?(?:\s+UNIQUE)?(?:\s+MATERIALIZED)?|ALTER|DROP|TRUNCATE|OPTIMIZE|RENAME)"
39
+ r"(?:\s+(?:TABLE|VIEW|INDEX|DICTIONARY|DATABASE|SCHEMA|SEQUENCE|TYPE|FUNCTION|TRIGGER))?"
40
+ r"(?:\s+IF\s+(?:NOT\s+)?EXISTS)?\s*;?\s*$", re.I)
41
+
42
+
43
+ def looks_like_sql(text: str, *, any_case: bool = False) -> bool:
44
+ if not text or len(text) < 12:
45
+ return False
46
+ return bool((SQL_START_ANYCASE if any_case else SQL_START).match(text))
47
+
48
+
49
+ @dataclass
50
+ class RawSite:
51
+ file: str # path relative to the repo root
52
+ line: int # 1-based line of the call (or of the string for sql_string)
53
+ end_line: int
54
+ language: str # python | rust | go | java | sql
55
+ kind: str # call | sql_string | sql_file
56
+ sink: str # callee text, e.g. "client.query"; "" when not attached to a call
57
+ symbol: str # enclosing function, e.g. "UserStore.fetch_page"; "" at module level
58
+ sql: str | None # resolved template, or None when unresolved
59
+ resolution: str # literal | constant | template | file | unresolved
60
+ expr: str = "" # source text of the SQL argument, trimmed
61
+ in_loop: bool = False
62
+ engine_hint: str = "" # from the sink rule or the file's imports; "" when unknown
63
+ is_test: bool = False
64
+ known_sink: bool = True # False when the callee is not in the sink rules (a likely wrapper)
65
+ orm: dict | None = None # resolution "orm": {library, model_or_table, operation, confidence, notes?}
66
+ # where engine_hint came from when it was not the file's own imports: {basis: handle | package, detail?},
67
+ # {unsure: why no engine was given} when the evidence names two, {binds: "qmark"} for `?` placeholders (Go)
68
+ engine_evidence: dict | None = None
69
+
70
+
71
+ @dataclass
72
+ class Sink:
73
+ names: set[str]
74
+ engine: str
75
+ args: list[int]
76
+ kwargs: set[str]
77
+
78
+
79
+ @dataclass
80
+ class LangRules:
81
+ sinks: list[Sink] = field(default_factory=list)
82
+ imports: dict[str, str] = field(default_factory=dict)
83
+
84
+ def sink_for(self, name: str) -> Sink | None:
85
+ for s in self.sinks:
86
+ if name in s.names:
87
+ return s
88
+ return None
89
+
90
+
91
+ def load_rules(language: str, extra_wrappers: list[dict] | None = None) -> LangRules:
92
+ """Load the packaged sink rules for a language, plus wrappers from codecop.toml."""
93
+ text = resources.files("codecop.rules").joinpath("sinks.toml").read_text()
94
+ data = tomllib.loads(text).get(language, {})
95
+ rules = LangRules(imports=dict(data.get("imports", {})))
96
+ for raw in list(data.get("sink", [])) + [w for w in (extra_wrappers or []) if w.get("language", language) == language]:
97
+ names = raw.get("names") or [raw["name"]]
98
+ rules.sinks.append(
99
+ Sink(set(names), raw.get("engine", ""), list(raw.get("args", [0])), set(raw.get("kwargs", [])))
100
+ )
101
+ return rules
102
+
103
+
104
+ def walk_tree(node, stop: tuple[str, ...] = ()):
105
+ """Depth-first over a tree-sitter node's descendants in document order, not descending into node types in
106
+ `stop`. A cursor does the walking: asking each node for `.children` instead makes the binding keep a list of
107
+ child objects on every node visited, so one node held afterwards (a file's root, a call kept for later) keeps
108
+ an object for every node of its subtree alive, several times the size of the tree itself."""
109
+ cursor = node.walk()
110
+ if not cursor.goto_first_child():
111
+ return
112
+ depth = 1
113
+ while True:
114
+ n = cursor.node
115
+ yield n
116
+ if n.type not in stop and cursor.goto_first_child():
117
+ depth += 1
118
+ continue
119
+ while not cursor.goto_next_sibling():
120
+ cursor.goto_parent()
121
+ depth -= 1
122
+ if depth == 0:
123
+ return
124
+
125
+
126
+ TEST_PATH = re.compile(r"(^|/)(tests?|testdata|__tests__|page_tests|fixtures|testutils?|test_utils?|testhelpers?|test_helpers?|testing)(/|$)|(^|/)test_[^/]*$|_test\.[a-z]+$|(^|/)conftest\.py$|(^|/)tests\.rs$|_tests\.rs$|"
127
+ r"[.-](?:test|spec|e2e|integration-test|integration|smoke|mock|mocks|fixture|fixtures)\.[cm]?[jt]sx?$|_spec\.rb$")
128
+
129
+
130
+ def is_test_path(rel: str) -> bool:
131
+ return bool(TEST_PATH.search(rel))
132
+
133
+
134
+ def trim(text: str, n: int = 300) -> str:
135
+ text = " ".join(text.split())
136
+ return text if len(text) <= n else text[: n - 1] + "…"
137
+
138
+
139
+ # The largest file discovery reads, in bytes. A setting, not a constant: `[discover] max_file_bytes` in
140
+ # codecop.toml or `codecop discover --max-file-bytes`. Generated query code (sqlc) runs to several megabytes, so the
141
+ # default is generous; a file over the limit is never dropped silently, it is listed in the inventory.
142
+ DEFAULT_MAX_FILE_BYTES = 64_000_000
143
+
144
+
145
+ class ReadState:
146
+ """The file-size limit of the current run and every file it kept out, with its size."""
147
+
148
+ def __init__(self) -> None:
149
+ self.max_file_bytes = DEFAULT_MAX_FILE_BYTES
150
+ self.skipped: dict[str, int] = {} # absolute path -> size in bytes
151
+
152
+ def begin(self, max_file_bytes: int | None = None) -> None:
153
+ self.max_file_bytes = int(max_file_bytes) if max_file_bytes else DEFAULT_MAX_FILE_BYTES
154
+ self.skipped = {}
155
+
156
+ def too_large(self, path: Path, size: int | None = None) -> bool:
157
+ """True (and noted) when the file is over the limit. Every reader of repository files asks here."""
158
+ if size is None:
159
+ size = path.stat().st_size
160
+ if size > self.max_file_bytes:
161
+ self.skipped[str(path)] = size
162
+ return True
163
+ return False
164
+
165
+
166
+ READ = ReadState()
167
+
168
+
169
+ def read_text(path: Path, limit: int | None = None) -> str | None:
170
+ """The file's text, or None when it cannot be read or is over the size limit (noted in READ.skipped).
171
+ `limit` is accepted for old callers and ignored: there is one limit, the run's setting."""
172
+ try:
173
+ if READ.too_large(path):
174
+ return None
175
+ return path.read_text(encoding="utf-8", errors="replace")
176
+ except OSError:
177
+ return None
178
+
179
+
180
+ # ---- engine evidence outside the SQL text ------------------------------------------------------------------
181
+ _ENGINE_WORDS = {
182
+ "clickhouse": "clickhouse", "click_house": "clickhouse", "chconn": "clickhouse", "chclient": "clickhouse",
183
+ "chdb": "clickhouse", "chpool": "clickhouse",
184
+ "postgres": "postgres", "postgresql": "postgres", "pgsql": "postgres", "psql": "postgres", "pg": "postgres",
185
+ "pgx": "postgres", "pgpool": "postgres", "pgconn": "postgres", "pgdb": "postgres", "pgclient": "postgres",
186
+ "mysql": "mysql", "mariadb": "mysql",
187
+ "sqlite": "sqlite", "sqlite3": "sqlite",
188
+ "mssql": "mssql", "sqlserver": "mssql",
189
+ }
190
+ _WORD_SPLIT = re.compile(r"[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])")
191
+ DURABLE_OBJECT_SQL = re.compile(r"(?:^|\.)storage\.sql$")
192
+
193
+
194
+ def _engine_words(text: str) -> list[str]:
195
+ found = []
196
+ for part in re.split(r"[^A-Za-z0-9_]+", text):
197
+ low = part.lower().strip("_")
198
+ if low in _ENGINE_WORDS:
199
+ found.append(_ENGINE_WORDS[low])
200
+ continue
201
+ for word in _WORD_SPLIT.split(part):
202
+ eng = _ENGINE_WORDS.get(word.lower())
203
+ if eng:
204
+ found.append(eng)
205
+ return found
206
+
207
+
208
+ def receiver_engine(sink: str) -> str:
209
+ """The engine a call's receiver names: `s.chConn.Select` -> clickhouse, `self.pg_pool.fetch` -> postgres.
210
+ Empty when the receiver names no engine or more than one. A Cloudflare Durable Object's own storage
211
+ (`this.ctx.storage.sql.exec`, `state.storage.sql.exec`) is SQLite, whatever the project's other database is."""
212
+ receiver = sink.rsplit(".", 1)[0] if "." in sink else ""
213
+ if DURABLE_OBJECT_SQL.search(receiver):
214
+ return "sqlite"
215
+ found = set(_engine_words(receiver))
216
+ return next(iter(found)) if len(found) == 1 else ""
217
+
218
+
219
+ def path_engine(rel: str) -> str:
220
+ """The engine a directory stands for: `sqlplugin/sqlite/admin.go`, `migrations/postgres/001.sql`,
221
+ `jdbc-mysql/src/...`. The deepest directory that names one wins; a name that says two says nothing.
222
+ A file counts only when its whole name is the engine (`postgres.go`): `clickhouse_cache.py` may
223
+ be a SQLite cache in front of ClickHouse."""
224
+ parts = rel.split("/")
225
+ stem = parts.pop().rsplit(".", 1)[0].lower()
226
+ if stem in _ENGINE_WORDS:
227
+ return _ENGINE_WORDS[stem]
228
+ for part in reversed(parts):
229
+ found = set(_engine_words(part))
230
+ if len(found) == 1:
231
+ return next(iter(found))
232
+ if found:
233
+ return ""
234
+ return ""