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,688 @@
1
+ """Reading a real database, read-only: connections, limits, the statement allowlist and the audit file.
2
+
3
+ This is the only package that connects to a database the developer runs for real.
4
+ The rules it is built around:
5
+
6
+ * Credentials are read from an env file (or the environment) when a command runs. They live in
7
+ `Connection` objects in memory, are sent to the database host and nowhere else, and are never
8
+ printed, logged, written to a file, put in a process argument list or shown to an agent.
9
+ Host, user and database names are treated the same way in everything that is printed or uploaded.
10
+ * Read-only is enforced by the server on every request (ClickHouse `readonly`, Postgres
11
+ `default_transaction_read_only`), together with time, row, byte and memory limits.
12
+ * Only statements from the fixed tables in clickhouse.py and postgres.py run. Their text is constant;
13
+ values go in as bound parameters. SQL written by an agent or found in a repository is never sent,
14
+ and neither is a candidate's baseline or variant.
15
+ * Every statement sent is appended to `db_audit.jsonl` in the out dir: its id and text, when, how
16
+ long, how many rows came back and what the server says it read.
17
+
18
+ Tiers: A catalog (system tables), B workload (query log aggregates), C plans without execution,
19
+ D column statistics by sampling. D reads table data and runs only with an explicit flag.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import re
27
+ import time
28
+ import tomllib
29
+ from dataclasses import dataclass, field, replace
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+ from urllib.parse import unquote, urlsplit
33
+
34
+ AUDIT_FILE = "db_audit.jsonl"
35
+ CATALOG_FILE = "db_catalog.json"
36
+ WORKLOAD_FILE = "db_workload.json"
37
+ SAMPLE_FILE = "db_sample.json"
38
+ MATCH_FILE = "db_match.json"
39
+ # Keys the local db files use for things that never leave the machine (see client.build_bundle).
40
+ LOCAL_ONLY_KEYS = ("text", "normalized_text", "create_sql", "create_table_query", "database", "databases", "query", "definition")
41
+
42
+
43
+ class DbError(RuntimeError):
44
+ """Anything that went wrong talking to a real database. The text is already scrubbed of host, user and database."""
45
+
46
+
47
+ class Refused(DbError):
48
+ """The server refused a statement (a limit, a missing privilege, a read-only violation)."""
49
+
50
+
51
+ class Secret:
52
+ """A value that must not be shown. `repr` and `str` never reveal it; `.reveal()` is used only to authenticate."""
53
+ __slots__ = ("_value",)
54
+
55
+ def __init__(self, value: str):
56
+ self._value = value
57
+
58
+ def reveal(self) -> str:
59
+ return self._value
60
+
61
+ def __bool__(self) -> bool:
62
+ return bool(self._value)
63
+
64
+ def __repr__(self) -> str:
65
+ return "Secret(***)"
66
+
67
+ __str__ = __repr__
68
+
69
+ def __eq__(self, other) -> bool:
70
+ return isinstance(other, Secret) and other._value == self._value
71
+
72
+ def __hash__(self) -> int:
73
+ return hash(self._value)
74
+
75
+
76
+ @dataclass(eq=False)
77
+ class Connection:
78
+ """Where one database is and how to sign in. Printing it shows the name and the env file, nothing else."""
79
+ name: str # "clickhouse", "postgres", "clickhouse:REPORTING"
80
+ engine: str # clickhouse | postgres
81
+ host: str
82
+ port: int
83
+ user: str
84
+ password: Secret
85
+ database: str = ""
86
+ secure: bool = True
87
+ source: str = "" # the env file's base name, for messages
88
+ notes: list[str] = field(default_factory=list)
89
+ # How the server's TLS certificate is checked (see tls_request): None = not set here (CODECOP_DB_TLS_NO_VERIFY decides)
90
+ tls_no_verify: bool | None = None
91
+ tls_ca_file: str = "" # verify against this CA bundle instead of the system's
92
+ tls_from: str = "" # where the TLS choice came from: --tls-no-verify, codecop.toml [db.<name>], ...
93
+
94
+ def __repr__(self) -> str:
95
+ return f"<{self.engine} connection '{self.name}' from {self.source or 'the environment'}>"
96
+
97
+ __str__ = __repr__
98
+
99
+ @property
100
+ def label(self) -> str:
101
+ return f"{self.name} ({self.source})" if self.source else self.name
102
+
103
+ def identity(self) -> tuple:
104
+ return (self.engine, self.host.lower(), self.port, self.user)
105
+
106
+ def local(self) -> bool:
107
+ return self.host in ("127.0.0.1", "localhost", "::1")
108
+
109
+ def mask_secret(self, text: str) -> str:
110
+ """For statement text kept in the local db files (definitions, normalized queries): only the password is masked.
111
+
112
+ The account and database names are not touched there. An account name can be an ordinary SQL word (an account
113
+ called `default` would turn every DEFAULT clause into a marker), and the database name is part of the
114
+ statement. Those files never leave the machine (see client.build_bundle)."""
115
+ secret = self.password.reveal()
116
+ return str(text).replace(secret, "<password>") if len(secret) >= 3 else str(text)
117
+
118
+ def scrub(self, text: str, *, database: bool = True) -> str:
119
+ """Remove this connection's host, user, password and database from a message before it is shown or stored.
120
+ For errors and audit lines, never for statement text (see mask_secret)."""
121
+ text = str(text)
122
+ for value, mark in ((self.password.reveal(), "<password>"), (self.host, "<host>"), (self.user, "<user>"),
123
+ (self.database if database else "", "<database>")):
124
+ if value and len(value) >= 3:
125
+ text = re.sub(re.escape(value), mark, text, flags=re.I)
126
+ return re.sub(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", "<ip>", text) if not self.local() else text
127
+
128
+
129
+ # ---- limits --------------------------------------------------------------
130
+
131
+ @dataclass(frozen=True)
132
+ class Limits:
133
+ """What one statement may cost the server. Sent with every request; the server enforces it."""
134
+ seconds: int = 30
135
+ rows_to_read: int = 5_000_000
136
+ bytes_to_read: int = 2_000_000_000
137
+ result_rows: int = 200_000
138
+ memory_bytes: int = 1_000_000_000
139
+ threads: int = 2
140
+
141
+
142
+ CATALOG_LIMITS = Limits()
143
+ WORKLOAD_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=8_000_000_000, result_rows=20_000,
144
+ memory_bytes=2_000_000_000, threads=2)
145
+ TEXT_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=5_000,
146
+ memory_bytes=2_000_000_000, threads=2)
147
+ SAMPLE_LIMITS = Limits(seconds=20, rows_to_read=2_000_000, bytes_to_read=1_000_000_000, result_rows=1_000,
148
+ memory_bytes=1_000_000_000, threads=2)
149
+ # Per-partition catalog detail (system.parts, system.parts_columns): one row read per active part, or per active part and
150
+ # column. The result is cut on the server (`LIMIT n BY table` and a total), so it stays under result_rows.
151
+ PARTITION_LIMITS = Limits(seconds=30, rows_to_read=5_000_000, bytes_to_read=2_000_000_000, result_rows=200_000,
152
+ memory_bytes=1_000_000_000, threads=2)
153
+ # The spread per query shape: four integer columns of the query log, for the shapes already kept.
154
+ SPREAD_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=5_000,
155
+ memory_bytes=2_000_000_000, threads=2)
156
+ # Parts and marks selected per run: reads the query log's ProfileEvents map, about a kilobyte a row, so the window it
157
+ # reads is cut to a number of log rows before it runs and it may read less than the other workload statements.
158
+ SELECTED_LIMITS = Limits(seconds=30, rows_to_read=5_000_000, bytes_to_read=3_000_000_000, result_rows=5_000,
159
+ memory_bytes=1_000_000_000, threads=2)
160
+ # Tags, labels and client names per query shape: one more column of the query log (log_comment, client_name...) over the
161
+ # rows the spread statement reads, for the shapes already kept. A shape can carry several tags: more result rows.
162
+ TAG_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=50_000,
163
+ memory_bytes=2_000_000_000, threads=2)
164
+ # Columns and projections per query shape: two array columns of the query log (names, few per row), for the shapes kept.
165
+ COLUMN_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=5_000,
166
+ memory_bytes=2_000_000_000, threads=2)
167
+ # Executions per distinct full statement: reads the `query` column (the whole text of every run), so its window is cut to a
168
+ # number of log rows first, like the ProfileEvents statement, and its bytes are capped like the texts statement's.
169
+ REPEAT_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=5_000,
170
+ memory_bytes=2_000_000_000, threads=2)
171
+ # Runs per minute for the heaviest shapes: small columns only, but one result row per shape and active minute.
172
+ MINUTE_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=200_000,
173
+ memory_bytes=1_000_000_000, threads=2)
174
+ # Inserts per target table: small columns of the INSERT rows of the query log, one result row per table.
175
+ INSERT_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=20_000,
176
+ memory_bytes=1_000_000_000, threads=2)
177
+ # CPU per shape and the CPU totals: they read the ProfileEvents map like ch.workload.selected, so their window is cut to a
178
+ # number of log rows first (db_pull.resources_max_log_rows) and they get that statement's limits.
179
+ RESOURCE_LIMITS = SELECTED_LIMITS
180
+ # Failed runs per shape: small columns of the failed rows of the query log (codes, never the exception text).
181
+ FAILURE_LIMITS = Limits(seconds=60, rows_to_read=30_000_000, bytes_to_read=4_000_000_000, result_rows=5_000,
182
+ memory_bytes=1_000_000_000, threads=2)
183
+
184
+ # ---- settings ------------------------------------------------------------
185
+ # `[db_pull]` in codecop.toml. Each is a cap on what a pull asks for or keeps; `[db_pull.limits.<statement id>]` changes what
186
+ # one statement (or every statement whose id starts with that text) may cost the server.
187
+ PULL_DEFAULTS: dict = {
188
+ "partition_detail": True, # the two per-partition catalog statements
189
+ "partitions_per_table": 1000, # parts per partition: partitions kept per table, the highest partition ids first
190
+ "column_partitions_per_table": 120, # column sizes per partition: partitions kept per table, the highest ids first
191
+ "partition_rows": 150_000, # rows either per-partition statement may return in all
192
+ "spread": "auto", # quantiles per query shape: auto | exact | tdigest | off
193
+ "spread_exact_max_runs": 10_000_000, # auto: runs of the kept shapes up to which the exact form is used
194
+ "selected": True, # average parts and marks selected per run (reads ProfileEvents)
195
+ "selected_shapes": 400, # ... for this many of the heaviest shapes
196
+ "selected_max_log_rows": 500_000, # ... over the most recent hours in which about this many queries finished
197
+ "text_max_chars": 100_000, # a normalized query text is cut at this many characters (was 20,000 in the statement)
198
+ "tags": True, # call-site tags from log_comment (ch.workload.tags): only text matching codecop:<tag>
199
+ "comments": True, # the application's own log_comment labels (ch.workload.comments): stay on this machine
200
+ "clients": True, # driver and tool names (ch.workload.clients): stay on this machine
201
+ "columns": True, # columns read and projections used per shape (ch.workload.columns)
202
+ "columns_per_shape": 200, # ... at most this many distinct column names (and projection names) per shape
203
+ "repeats": True, # runs per distinct full statement and minutes active per shape (ch.workload.repeats)
204
+ "repeats_max_log_rows": 500_000, # ... over the most recent hours in which about this many queries finished
205
+ "minutes": True, # runs per minute of the heaviest shapes (ch.workload.minutes): stays on this machine
206
+ "minutes_shapes": 200, # ... for this many of the heaviest shapes by bytes read
207
+ "minutes_max_rows": 500_000, # ... and at most this many (shape, minute) rows in all
208
+ "inserts": True, # inserts per target table (ch.workload.inserts)
209
+ "inserts_tables": 5_000, # ... at most this many tables, the most bytes written first
210
+ # the resource profile per shape: each is optional, a refusal is a note and the fact reads "not in this pull"
211
+ "memory": True, # peak memory quantiles, memory held, time quantiles, threads (ch.workload.memory)
212
+ "cpu": True, # CPU per shape and its totals (ch.workload.resources, .resource_totals; PostgreSQL pg.workload.resources)
213
+ "resources_max_log_rows": 500_000, # ... ClickHouse: over the most recent hours in which about this many queries finished
214
+ "failures": True, # runs that failed per shape, by code (ch.workload.failures): memory limit, time limit
215
+ "failures_shapes": 5_000, # ... at most this many shapes, those stopped at the memory limit most first
216
+ "pressure": True, # how much runs at once, per minute (ch.workload.pressure)
217
+ "capacity": True, # the server's memory, limit and cores (ch.check.capacity); PostgreSQL pg.check.settings
218
+ "kcache": True, # PostgreSQL: CPU per statement from pg_stat_kcache, when the extension is there
219
+ # --watch-locks (realdb/locks.py): the sampled watch of pg_stat_activity and pg_locks, and the ClickHouse window
220
+ "watch_samples": 60, # samples of the sessions (one grouped statement each, plus one when a session waits)
221
+ "watch_interval_ms": 2000, # ... this far apart (60 x 2 s: a two-minute window)
222
+ "watch_days": 7, # ClickHouse: mutations, part log and refused inserts over the last N days
223
+ # ClickHouse locality (realdb/locality.py): skip indexes, projections and re-keys counted on production by aggregates.
224
+ # Reads table data (counts only leave the server): `codecop db pull --locality`, or a scan given a pull (--env-file).
225
+ "locality": True, # a scan with a configured pull counts the advisor's candidates (false: never)
226
+ "locality_rows_per_statement": 5_000_000, # rows of parts one statement may read (it reads them three or four times)
227
+ # simulation statements per pull, most valuable first (load of the statements served x table rows); the CPU cap below
228
+ # is the guard
229
+ "locality_max_statements": 200,
230
+ "locality_cpu_seconds_total": 120, # server CPU seconds they may take in all, per pull
231
+ "locality_min_table_rows": 32_768, # a table with fewer rows (4 granules of 8192) is nothing to gain: no statement sent
232
+ "locality_probes": 63, # values drawn from rows per statement (at most 63)
233
+ "locality_draws": 3, # the probes split in this many draws: the spread of the answer
234
+ "locality_window_hours": 168, # a statement bounded by time whose bound is a parameter: the window assumed
235
+ "locality_cpu_ns_per_row": 1_000, # planned CPU per row of parts, for --dry-run (an estimate)
236
+ "locality_max_parts": 2_000, # active parts listed per table to choose from
237
+ "locality_parts_per_statement": 256, # parts one statement may read: its memory and time grow with the parts it opens
238
+ "locality_log_wait_s": 10, # seconds to wait for the query log before reading each statement's own cost
239
+ }
240
+ SPREAD_FORMS = ("auto", "exact", "tdigest", "off")
241
+ LIMIT_FIELDS = ("seconds", "rows_to_read", "bytes_to_read", "result_rows", "memory_bytes", "threads")
242
+
243
+
244
+ def pull_settings(config: dict | None, **given) -> dict:
245
+ """The pull's settings: the defaults, `[db_pull]` from codecop.toml on top, then what the command line gave (not None)."""
246
+ table = (config or {}).get("db_pull") or {}
247
+ out = dict(PULL_DEFAULTS)
248
+ for key, default in PULL_DEFAULTS.items():
249
+ for value in (table.get(key), given.get(key)):
250
+ if value is None:
251
+ continue
252
+ if isinstance(default, bool):
253
+ out[key] = bool(value)
254
+ elif isinstance(default, int):
255
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
256
+ raise DbError(f"db_pull.{key} must be a number of zero or more.")
257
+ out[key] = int(value)
258
+ else:
259
+ out[key] = str(value)
260
+ if out["spread"] not in SPREAD_FORMS:
261
+ raise DbError(f"db_pull.spread must be one of {', '.join(SPREAD_FORMS)}.")
262
+ limits = {}
263
+ for name, fields in (table.get("limits") or {}).items():
264
+ if not isinstance(fields, dict):
265
+ continue
266
+ unknown = [k for k in fields if k not in LIMIT_FIELDS]
267
+ if unknown or not all(isinstance(v, int) and not isinstance(v, bool) and v > 0 for v in fields.values()):
268
+ raise DbError(f"db_pull.limits.{name}: takes whole numbers above zero for {', '.join(LIMIT_FIELDS)}.")
269
+ limits[str(name)] = dict(fields)
270
+ out["limits"] = limits
271
+ return out
272
+
273
+
274
+ def compact_json(data, indent: int = 1) -> str:
275
+ """JSON as the db files are written: one key a line, but a list of numbers (or of such lists) on one line.
276
+
277
+ The per-partition detail is tens of thousands of short rows of numbers; one number a line would make the file
278
+ several times larger for nothing. Lists of text stay one item a line, as before."""
279
+ def number(x) -> bool:
280
+ return x is None or (isinstance(x, (int, float)) and not isinstance(x, bool))
281
+
282
+ def flat(v: list) -> bool:
283
+ return all(number(x) or (isinstance(x, list) and all(number(y) for y in x)) for x in v)
284
+
285
+ def walk(v, depth: int) -> str:
286
+ pad, inner = " " * (indent * depth), " " * (indent * (depth + 1))
287
+ if isinstance(v, dict):
288
+ if not v:
289
+ return "{}"
290
+ return "{\n" + ",\n".join(f"{inner}{json.dumps(str(k), ensure_ascii=False)}: {walk(x, depth + 1)}" for k, x in v.items()) + f"\n{pad}}}"
291
+ if isinstance(v, (list, tuple)):
292
+ if not v:
293
+ return "[]"
294
+ if flat(list(v)):
295
+ return json.dumps(v, separators=(",", ":"))
296
+ return "[\n" + ",\n".join(f"{inner}{walk(x, depth + 1)}" for x in v) + f"\n{pad}]"
297
+ return json.dumps(v, ensure_ascii=False, default=str)
298
+ return walk(data, 0)
299
+
300
+
301
+ # ---- statements ----------------------------------------------------------
302
+
303
+ @dataclass(frozen=True)
304
+ class Statement:
305
+ """One allowed statement. `sql` is constant text; `{name:Type}` (ClickHouse) or `%(name)s` (Postgres) are bound values."""
306
+ id: str
307
+ tier: str # A | B | C | D | check
308
+ sql: str
309
+ purpose: str
310
+ limits: Limits = CATALOG_LIMITS
311
+ optional: bool = False # a system table an account may not see, or a version may not have
312
+
313
+
314
+ def with_limits(stmt: Statement, overrides: dict | None) -> Statement:
315
+ """The statement with the limits a setting gives it: the entry named by its id, else by the longest prefix of it.
316
+ Only the limits change; the text stays the allowlist's."""
317
+ names = [n for n in (overrides or {}) if stmt.id == n or stmt.id.startswith(n)]
318
+ if not names:
319
+ return stmt
320
+ return replace(stmt, limits=replace(stmt.limits, **overrides[max(names, key=len)]))
321
+
322
+
323
+ READ_ONLY_START = re.compile(r"^\s*(?:SELECT|WITH|SHOW|EXPLAIN)\b", re.I)
324
+ FORBIDDEN_WORDS = re.compile(
325
+ r"\b(?:INSERT|UPDATE|DELETE|ALTER|CREATE|DROP|TRUNCATE|RENAME|ATTACH|DETACH|OPTIMIZE|SYSTEM\s+\w+|GRANT|REVOKE|KILL|SET\s+\w+\s*=|"
326
+ r"(?<![.])SETTINGS|COPY|VACUUM|ANALYZE|pg_sleep\w*|pg_terminate_backend|pg_cancel_backend|pg_advisory\w*|nextval|setval|REINDEX|CLUSTER|LOCK|CALL|DO|EXECUTE|PREPARE|INTO\s+OUTFILE|REFRESH|EXCHANGE|MOVE|BACKUP|RESTORE)\b", re.I)
327
+
328
+
329
+ def check_statement(stmt: Statement) -> None:
330
+ """A second lock behind the allowlist: the text of a statement this tool sends is a single read."""
331
+ text = re.sub(r"'(?:[^'\\]|\\.|'')*'", "''", stmt.sql) # words inside string literals do not count
332
+ text = re.sub(r"--[^\n]*", " ", text)
333
+ if not READ_ONLY_START.match(text) or ";" in text.rstrip().rstrip(";"):
334
+ raise DbError(f"Statement {stmt.id} is not a single read: refused before sending.")
335
+ hit = FORBIDDEN_WORDS.search(text)
336
+ if hit:
337
+ raise DbError(f"Statement {stmt.id} contains `{hit.group(0)}`: refused before sending.")
338
+
339
+
340
+ # ---- audit ---------------------------------------------------------------
341
+
342
+ class Audit:
343
+ """Appends one line per statement sent to a real database. No credentials, host, user or password ever reach it."""
344
+
345
+ def __init__(self, out_dir: Path | None, connection: Connection, dry_run: bool = False):
346
+ self.path = (out_dir / AUDIT_FILE) if out_dir else None
347
+ self.connection, self.dry_run = connection, dry_run
348
+ self.entries: list[dict] = []
349
+ self.tls = "" # the TLS mode the reader connected with (tls_attempts), written on every line
350
+
351
+ def record(self, stmt: Statement, params: dict, *, started: float, rows: int = 0, read_rows: int | None = None,
352
+ read_bytes: int | None = None, error: str = "", sent: bool = True) -> dict:
353
+ entry = {
354
+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "connection": self.connection.name,
355
+ "source": self.connection.source, "engine": self.connection.engine, "tier": stmt.tier, "id": stmt.id,
356
+ "sent": sent, "tls": self.tls or "not connected", "statement": " ".join(stmt.sql.split()),
357
+ "params": {k: (f"<{len(v)} values>" if isinstance(v, (list, tuple)) and len(v) > 8 else v) for k, v in params.items()},
358
+ "limits": dict(stmt.limits.__dict__),
359
+ "duration_ms": round((time.monotonic() - started) * 1000, 1), "rows": rows,
360
+ "read_rows": read_rows, "read_bytes": read_bytes, "ok": not error, "error": self.connection.scrub(error)[:300],
361
+ }
362
+ self.entries.append(entry)
363
+ if self.path is not None and sent:
364
+ self.path.parent.mkdir(parents=True, exist_ok=True)
365
+ with self.path.open("a") as fh:
366
+ fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
367
+ return entry
368
+
369
+ def summary(self) -> dict:
370
+ sent = [e for e in self.entries if e["sent"]]
371
+ return {"statements": len(sent), "failed": sum(1 for e in sent if not e["ok"]),
372
+ "duration_ms": round(sum(e["duration_ms"] for e in sent), 1), "rows_returned": sum(e["rows"] for e in sent),
373
+ "read_rows": sum(e["read_rows"] or 0 for e in sent), "read_bytes": sum(e["read_bytes"] or 0 for e in sent),
374
+ "by_tier": {t: sum(1 for e in sent if e["tier"] == t) for t in sorted({e["tier"] for e in sent})}}
375
+
376
+
377
+ # ---- env files -----------------------------------------------------------
378
+
379
+ ENV_LINE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$")
380
+
381
+
382
+ def read_env_file(path: Path) -> dict[str, str]:
383
+ """KEY=VALUE lines. Quotes are removed, `#` comments are ignored. Values are never logged."""
384
+ env: dict[str, str] = {}
385
+ for line in path.read_text(errors="replace").splitlines():
386
+ if not line.strip() or line.lstrip().startswith("#"):
387
+ continue
388
+ m = ENV_LINE.match(line)
389
+ if not m:
390
+ continue
391
+ value = m.group(2)
392
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
393
+ value = value[1:-1]
394
+ elif " #" in value:
395
+ value = value.split(" #", 1)[0].rstrip()
396
+ env[m.group(1)] = value
397
+ return env
398
+
399
+
400
+ CH_FAMILY = ("CH", "CLICKHOUSE")
401
+ PG_FAMILY = ("PG", "POSTGRES", "POSTGRESQL")
402
+ FIELDS = {
403
+ "host": ("HOST", "HOSTNAME", "SERVER"),
404
+ "port": ("HTTPS_PORT", "HTTP_PORT", "PORT"),
405
+ "user": ("USERNAME", "USER"),
406
+ "password": ("PASSWORD", "PASS", "KEY"),
407
+ "database": ("DATABASE", "DB", "DBNAME", "DB_NAME"),
408
+ "secure": ("SECURE", "SSL", "TLS", "USE_SSL"),
409
+ }
410
+ NATIVE_TO_HTTP = {9000: 8123, 9440: 8443}
411
+ TRUE = ("1", "true", "yes", "on", "require", "required")
412
+
413
+
414
+ def _pick(env: dict[str, str], prefix: str, family: tuple[str, ...], names: tuple[str, ...]) -> str:
415
+ for fam in family:
416
+ for name in names:
417
+ value = env.get(f"{prefix}{fam}_{name}")
418
+ if value:
419
+ return value
420
+ return ""
421
+
422
+
423
+ def _from_url(name: str, engine: str, url: str, source: str) -> Connection | None:
424
+ parts = urlsplit(url)
425
+ if not parts.hostname:
426
+ return None
427
+ default = 5432 if engine == "postgres" else (8443 if parts.scheme in ("https", "clickhouses") else 8123)
428
+ secure = parts.scheme in ("https", "clickhouses") or "sslmode=require" in parts.query or "sslmode=verify" in parts.query \
429
+ or (engine == "postgres" and parts.hostname not in ("127.0.0.1", "localhost"))
430
+ return Connection(name, engine, parts.hostname, parts.port or default, unquote(parts.username or ""),
431
+ Secret(unquote(parts.password or "")), unquote(parts.path.lstrip("/")), secure, source)
432
+
433
+
434
+ def find_connections(env: dict[str, str], source: str = "") -> list[Connection]:
435
+ """Every database an env file describes, from the usual variable names.
436
+
437
+ ClickHouse: [PREFIX_]CH_* or [PREFIX_]CLICKHOUSE_* (HOST, PORT, USERNAME/USER, PASSWORD, DATABASE/DB, SECURE), or
438
+ CLICKHOUSE_URL. Postgres: [PREFIX_]PG_* / POSTGRES_* (HOST, PORT, USER, PASSWORD, DB/DATABASE), libpq's PGHOST...,
439
+ or DATABASE_URL. Two sets that point at the same server with the same user become one connection."""
440
+ found: list[Connection] = []
441
+ for family, engine in ((CH_FAMILY, "clickhouse"), (PG_FAMILY, "postgres")):
442
+ prefixes = []
443
+ for key in env:
444
+ for fam in family:
445
+ m = re.fullmatch(rf"(.*?){fam}_(?:HOST|HOSTNAME|SERVER)", key)
446
+ if m and (not m.group(1) or m.group(1).endswith("_")) and m.group(1) not in prefixes:
447
+ prefixes.append(m.group(1))
448
+ for prefix in sorted(prefixes, key=len):
449
+ host = _pick(env, prefix, family, FIELDS["host"])
450
+ if not host:
451
+ continue
452
+ notes = []
453
+ if "://" in host:
454
+ parts = urlsplit(host)
455
+ host, url_port, url_secure = parts.hostname or "", parts.port, parts.scheme == "https"
456
+ else:
457
+ url_port, url_secure = None, False
458
+ raw_port = _pick(env, prefix, family, FIELDS["port"])
459
+ port = url_port or (int(raw_port) if raw_port.isdigit() else (5432 if engine == "postgres" else 8123))
460
+ if engine == "clickhouse" and port in NATIVE_TO_HTTP:
461
+ notes.append(f"port {port} is the native protocol; using the HTTP interface on {NATIVE_TO_HTTP[port]}")
462
+ port = NATIVE_TO_HTTP[port]
463
+ flag = _pick(env, prefix, family, FIELDS["secure"]).lower()
464
+ local = host in ("127.0.0.1", "localhost", "::1")
465
+ secure = url_secure or flag in TRUE or (engine == "clickhouse" and port in (8443, 443)) or (engine == "postgres" and not local)
466
+ database = _pick(env, prefix, family, FIELDS["database"])
467
+ if not database and engine == "postgres": # PG_AUTH_DB, PG_APP_DB: any *_DB under the same prefix
468
+ database = next((v for k, v in env.items() if re.fullmatch(rf"{prefix}(?:{'|'.join(family)})_\w*DB(?:NAME)?", k) and v), "")
469
+ name = engine if not prefix else f"{engine}:{prefix.rstrip('_')}"
470
+ found.append(Connection(name, engine, host, port, _pick(env, prefix, family, FIELDS["user"]),
471
+ Secret(_pick(env, prefix, family, FIELDS["password"])), database, secure, source, notes))
472
+ if env.get("PGHOST") and not any(c.engine == "postgres" for c in found):
473
+ port = env.get("PGPORT", "5432")
474
+ found.append(Connection("postgres", "postgres", env["PGHOST"], int(port) if port.isdigit() else 5432, env.get("PGUSER", ""),
475
+ Secret(env.get("PGPASSWORD", "")), env.get("PGDATABASE", ""), env["PGHOST"] not in ("127.0.0.1", "localhost"), source))
476
+ for key, value in env.items():
477
+ scheme = value.split("://", 1)[0].lower() if "://" in value else ""
478
+ engine = "postgres" if scheme in ("postgres", "postgresql") else "clickhouse" if scheme in ("clickhouse", "clickhouses") or \
479
+ (key.upper().endswith(("CLICKHOUSE_URL", "CH_URL")) and scheme in ("http", "https")) else ""
480
+ if engine:
481
+ base = re.sub(r"_?(DATABASE_URL|CLICKHOUSE_URL|CH_URL|POSTGRES_URL|PG_URL|URL|DSN)$", "", key).rstrip("_")
482
+ conn = _from_url(engine if not base else f"{engine}:{base}", engine, value, source)
483
+ if conn:
484
+ found.append(conn)
485
+ unique: list[Connection] = []
486
+ for conn in found:
487
+ same = next((u for u in unique if u.identity() == conn.identity()), None)
488
+ if same is None:
489
+ unique.append(conn)
490
+ elif conn.database and conn.database != same.database:
491
+ same.notes.append(f"{conn.name} is the same server and user with another database")
492
+ else:
493
+ same.notes.append(f"{conn.name} is the same server and user")
494
+ return unique
495
+
496
+
497
+ def connection_from_mapping(name: str, mapping: dict[str, str], env: dict[str, str], source: str = "") -> Connection:
498
+ """A connection whose fields are named explicitly: {"engine": "clickhouse", "host_env": "MY_CH", ...}.
499
+
500
+ Used for `--map name.host=VAR` and for `[db.<name>]` in codecop.toml. A mapping names variables; it never holds a value."""
501
+ engine = (mapping.get("engine") or name.split(":")[0]).lower()
502
+ if engine in ("pg", "postgresql"):
503
+ engine = "postgres"
504
+ if engine not in ("clickhouse", "postgres"):
505
+ raise DbError(f"Connection '{name}': engine must be clickhouse or postgres.")
506
+
507
+ def value(field_name: str) -> str:
508
+ var = mapping.get(f"{field_name}_env") or mapping.get(field_name)
509
+ if field_name != "engine" and var and var not in env and field_name in ("host", "user", "password") and mapping.get(f"{field_name}_env"):
510
+ raise DbError(f"Connection '{name}': the variable {var} is not set.")
511
+ return env.get(var, "") if var else ""
512
+
513
+ url = value("url")
514
+ if url:
515
+ conn = _from_url(name, engine, url, source)
516
+ if conn is None:
517
+ raise DbError(f"Connection '{name}': the URL variable does not hold a database URL.")
518
+ return conn
519
+ host = value("host")
520
+ if not host:
521
+ raise DbError(f"Connection '{name}': no host variable is mapped or it is empty.")
522
+ port = value("port")
523
+ number = int(port) if port.isdigit() else (5432 if engine == "postgres" else 8443)
524
+ local = host in ("127.0.0.1", "localhost", "::1")
525
+ secure_flag = value("secure").lower()
526
+ secure = secure_flag in TRUE if secure_flag else (number in (8443, 443) if engine == "clickhouse" else not local)
527
+ return Connection(name, engine, host, number, value("user"), Secret(value("password")), value("database"), secure, source)
528
+
529
+
530
+ # ---- TLS -----------------------------------------------------------------
531
+ #
532
+ # How a server's certificate is checked, per connection. The first that is set wins:
533
+ # 1. --tls-ca-file PATH / --tls-no-verify on `codecop db check` and `codecop db pull`
534
+ # 2. tls_ca_file / tls_no_verify under [db.<connection name>] in codecop.toml
535
+ # 3. tls_ca_file / tls_no_verify under [db] in codecop.toml (every connection)
536
+ # 4. the environment variable CODECOP_DB_TLS_NO_VERIFY=1 (kept from before the options existed)
537
+ # Otherwise the certificate is verified against the system's CAs. A CA file is the preferred way to reach a server
538
+ # with a self-signed or private certificate: it is still verified. Without verification any machine between here and
539
+ # the server could pose as it and receive the password, so that mode is said on every run.
540
+
541
+ TLS_KEYS = ("tls_no_verify", "tls_ca_file")
542
+ TLS_ENV = "CODECOP_DB_TLS_NO_VERIFY"
543
+ TLS_MODES = {
544
+ "system": "TLS, certificate verified against the system's CAs",
545
+ "ca_file": "TLS, certificate verified against the CA file {path}",
546
+ "unverified": "TLS, certificate NOT verified ({why})",
547
+ "plain": "no TLS",
548
+ }
549
+ TLS_VERIFY_HINT = (" The server's certificate could not be verified. Give the CA that signed it with --tls-ca-file PATH (or tls_ca_file "
550
+ "under [db.<connection>] in codecop.toml); --tls-no-verify connects without verifying.")
551
+
552
+
553
+ def _tls_bool(value, where: str) -> bool:
554
+ if isinstance(value, bool):
555
+ return value
556
+ text = str(value).strip().lower()
557
+ if text in ("1", "true", "yes", "on"):
558
+ return True
559
+ if text in ("0", "false", "no", "off", ""):
560
+ return False
561
+ raise DbError(f"{where}: tls_no_verify must be true or false.")
562
+
563
+
564
+ def apply_tls(conns: list[Connection], config: dict | None = None, *, root: Path | None = None, no_verify: bool = False,
565
+ ca_file: Path | str | None = None) -> None:
566
+ """Set each connection's TLS choice by the order above. A CA file must exist; a CA file and no verification for one
567
+ connection at one level is refused (they contradict each other)."""
568
+ db = (config or {}).get("db") or {}
569
+ base = root or Path.cwd()
570
+
571
+ def ca_path(value: str, where: str, relative_to: Path) -> str:
572
+ p = Path(str(value)).expanduser()
573
+ p = p if p.is_absolute() else relative_to / p
574
+ if not p.is_file():
575
+ raise DbError(f"{where}: no CA file at {p}.")
576
+ return str(p.resolve())
577
+
578
+ if no_verify and ca_file:
579
+ raise DbError("--tls-ca-file and --tls-no-verify contradict each other: give one.")
580
+ for conn in conns:
581
+ levels = []
582
+ if no_verify or ca_file:
583
+ levels.append(("--tls-ca-file" if ca_file else "--tls-no-verify", {"tls_ca_file": str(ca_file)} if ca_file else {"tls_no_verify": True},
584
+ Path.cwd()))
585
+ own = db.get(conn.name)
586
+ if isinstance(own, dict) and any(k in own for k in TLS_KEYS):
587
+ levels.append((f"codecop.toml [db.{conn.name}]", own, base))
588
+ if any(k in db and not isinstance(db.get(k), dict) for k in TLS_KEYS):
589
+ levels.append(("codecop.toml [db]", {k: db[k] for k in TLS_KEYS if k in db}, base))
590
+ for where, table, rel in levels:
591
+ ca = table.get("tls_ca_file")
592
+ nv = _tls_bool(table["tls_no_verify"], where) if "tls_no_verify" in table else None
593
+ if ca and nv:
594
+ raise DbError(f"{where}: tls_ca_file and tls_no_verify = true contradict each other: give one.")
595
+ conn.tls_ca_file = ca_path(ca, where, rel) if ca else ""
596
+ conn.tls_no_verify = False if ca else nv
597
+ conn.tls_from = where
598
+ break
599
+
600
+
601
+ def tls_request(conn: Connection) -> tuple[str, str]:
602
+ """What the connection asks for: ("ca_file" | "unverified" | "system" | "plain", where it came from)."""
603
+ if not conn.secure:
604
+ return "plain", ""
605
+ if conn.tls_ca_file:
606
+ return "ca_file", conn.tls_from
607
+ if conn.tls_no_verify:
608
+ return "unverified", conn.tls_from
609
+ if conn.tls_no_verify is None and os.environ.get(TLS_ENV) == "1":
610
+ return "unverified", f"{TLS_ENV}=1"
611
+ return "system", ""
612
+
613
+
614
+ def tls_mode_text(kind: str, conn: Connection, why: str = "") -> str:
615
+ return TLS_MODES[kind].format(path=conn.tls_ca_file, why=why)
616
+
617
+
618
+ def tls_warning(conn: Connection) -> str:
619
+ """The one line said on every run that connects without verifying the certificate, or ''."""
620
+ kind, why = tls_request(conn)
621
+ if kind != "unverified":
622
+ return ""
623
+ return (f"Warning: {conn.label}: the server's TLS certificate is not verified ({why}); a machine between here and the server "
624
+ "could pose as it and receive the password. Prefer --tls-ca-file with the server's CA.")
625
+
626
+
627
+ def tls_attempts(conn: Connection):
628
+ """The SSL contexts to try in order, each with the mode it stands for: [(ssl.SSLContext, mode text)]. Empty for a
629
+ connection without TLS. A local server (localhost) may fall back to no verification when nothing was asked for."""
630
+ import ssl
631
+ kind, why = tls_request(conn)
632
+ if kind == "plain":
633
+ return []
634
+ if kind == "ca_file":
635
+ return [(ssl.create_default_context(cafile=conn.tls_ca_file), tls_mode_text("ca_file", conn))]
636
+ unverified = ssl.create_default_context()
637
+ unverified.check_hostname = False
638
+ unverified.verify_mode = ssl.CERT_NONE
639
+ if kind == "unverified":
640
+ return [(unverified, tls_mode_text("unverified", conn, why))]
641
+ out = [(ssl.create_default_context(), tls_mode_text("system", conn))]
642
+ if conn.local():
643
+ out.append((unverified, tls_mode_text("unverified", conn, "a local server")))
644
+ return out
645
+
646
+
647
+ def load_connections(env_file: Path | None, *, maps: list[str] | None = None, config: dict | None = None,
648
+ use_environment: bool = False) -> list[Connection]:
649
+ """Connections from an env file, plus explicit mappings from --map and from `[db.*]` in codecop.toml. The TLS keys of a
650
+ `[db.<name>]` table (tls_no_verify, tls_ca_file) are not a mapping: a table holding only them names a connection found
651
+ in the env file (apply_tls reads them)."""
652
+ env: dict[str, str] = dict(os.environ) if use_environment or env_file is None else {}
653
+ source = ""
654
+ if env_file is not None:
655
+ if not env_file.is_file():
656
+ raise DbError(f"No env file at {env_file}.")
657
+ env.update(read_env_file(env_file))
658
+ source = env_file.name
659
+ explicit: dict[str, dict[str, str]] = {}
660
+ for name, table in ((config or {}).get("db") or {}).items():
661
+ if isinstance(table, dict):
662
+ fields_ = {k: str(v) for k, v in table.items() if k not in TLS_KEYS}
663
+ if fields_:
664
+ explicit[name] = fields_
665
+ for item in maps or []:
666
+ m = re.fullmatch(r"([\w:.-]+)\.(engine|host|port|user|password|database|secure|url)=(\w+)", item.strip())
667
+ if not m:
668
+ raise DbError(f"--map takes name.field=VARIABLE (fields: engine, host, port, user, password, database, secure, url); got `{item}`.")
669
+ explicit.setdefault(m.group(1), {})[m.group(2) if m.group(2) == "engine" else f"{m.group(2)}_env"] = m.group(3)
670
+ mapped = [connection_from_mapping(name, mapping, env, source) for name, mapping in explicit.items()]
671
+ auto = [] if mapped and not env_file else find_connections(env, source)
672
+ names = {c.name for c in mapped}
673
+ return mapped + [c for c in auto if c.name not in names and not any(c.identity() == m.identity() for m in mapped)]
674
+
675
+
676
+ def load_toml_db(root: Path) -> dict:
677
+ from .. import formerly
678
+ path = formerly.repo_config(root)
679
+ return tomllib.loads(path.read_text()) if path.exists() else {}
680
+
681
+
682
+ def open_reader(connection: Connection, audit: Audit, **options):
683
+ """The read-only client for a connection."""
684
+ if connection.engine == "clickhouse":
685
+ from .clickhouse import ClickHouseReader
686
+ return ClickHouseReader(connection, audit, **options)
687
+ from .postgres import PostgresReader
688
+ return PostgresReader(connection, audit, **options) # of the pull settings PostgreSQL reads the resource switches only