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,323 @@
1
+ """Turn a data profile into SQLite INSERT statements.
2
+
3
+ Same profile format as datagen.py and datagen_postgres.py (kinds, null_fraction, pinned, fixtures), SQLite's dialect.
4
+ Generation is set-based: one
5
+
6
+ INSERT OR IGNORE INTO t (cols) WITH RECURSIVE codecop_n(number) AS (...) SELECT ... FROM codecop_n
7
+
8
+ per batch. The row index is called `number`, as on the other engines, so an `expr` column and a fixture mean the same
9
+ thing everywhere.
10
+
11
+ Values are a pure function of the row number: every "random" draw is `codecop_hash(number, seed)`, a function the
12
+ sandbox registers on its connection (engines/sqlite.py, FUNCTIONS), so two runs of the same profile load the same data.
13
+ SQLite has no hash function of its own, and its integer arithmetic turns to floating point on overflow, so the mixing is
14
+ done there rather than in SQL.
15
+
16
+ What SQLite does differently, and how the generator covers it:
17
+ - A column's declared type only gives it an affinity (INTEGER, REAL, TEXT, BLOB, NUMERIC). Nothing is CAST to the
18
+ declared type: CAST(x AS DATETIME) is a NUMERIC cast that turns '2026-11-29 10:00:00' into 2026. The column's
19
+ affinity converts what is inserted, as it does for the application's own writes.
20
+ - Time: a column with INTEGER affinity holds epoch seconds; any other holds 'YYYY-MM-DD HH:MM:SS' text, what
21
+ CURRENT_TIMESTAMP writes. The clock is the instant the sandbox was started (`clock`), not the time of each batch.
22
+ - A boolean is 0 or 1.
23
+ - A NOT NULL column with no default has no implicit value: such a column the profile leaves out gets a neutral value
24
+ of its affinity, and a generator that gives NULL there falls back to it.
25
+ - INSERT OR IGNORE drops a row that breaks a primary key or a unique index, as ON CONFLICT DO NOTHING does on
26
+ PostgreSQL; the loaded row count says how many were kept.
27
+ - An INTEGER PRIMARY KEY (the rowid) is written only when the profile describes it; left out, SQLite numbers the rows.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ import re
34
+
35
+ from . import sizes
36
+ from .datagen import FIXTURE_SLOTS, REALISM, ProfileError
37
+
38
+
39
+ def affinity(declared: str) -> str:
40
+ """SQLite's rules (datatype3.html, 3.1): the first that matches of INT, CHAR/CLOB/TEXT, BLOB or none, REAL/FLOA/DOUB."""
41
+ t = (declared or "").upper()
42
+ if "INT" in t:
43
+ return "INTEGER"
44
+ if "CHAR" in t or "CLOB" in t or "TEXT" in t:
45
+ return "TEXT"
46
+ if "BLOB" in t or not t.strip():
47
+ return "BLOB"
48
+ if "REAL" in t or "FLOA" in t or "DOUB" in t:
49
+ return "REAL"
50
+ return "NUMERIC"
51
+
52
+
53
+ def is_boolean(declared: str) -> bool:
54
+ return bool(re.match(r"^\s*BOOL", declared or "", re.I))
55
+
56
+
57
+ def is_time(declared: str) -> bool:
58
+ return bool(re.search(r"DATE|TIME", declared or "", re.I))
59
+
60
+
61
+ def quote(value) -> str:
62
+ return "'" + str(value).replace("'", "''") + "'"
63
+
64
+
65
+ def ident(name: str) -> str:
66
+ return '"' + name.replace('"', '""') + '"'
67
+
68
+
69
+ def literal(value, declared: str) -> str:
70
+ """A profile value as SQLite writes it for a column of this declared type."""
71
+ if value is None or (isinstance(value, str) and value.upper() == "NULL"):
72
+ return "NULL"
73
+ aff = affinity(declared)
74
+ text = str(value)
75
+ if isinstance(value, bool) or (is_boolean(declared) and text.lower() in ("true", "false", "t", "f")):
76
+ truthy = value if isinstance(value, bool) else text.lower() in ("true", "t")
77
+ return "1" if truthy else "0"
78
+ if aff in ("INTEGER", "REAL", "NUMERIC") and re.fullmatch(r"-?\d+(\.\d+)?([eE][-+]?\d+)?", text):
79
+ return text
80
+ if isinstance(value, (dict, list)):
81
+ import json
82
+ return quote(json.dumps(value))
83
+ return quote(value)
84
+
85
+
86
+ class _Seeds:
87
+ def __init__(self, start: int):
88
+ self.n = start
89
+
90
+ def next(self) -> int:
91
+ self.n += 1
92
+ return self.n
93
+
94
+
95
+ def _hash(seed: int) -> str:
96
+ return f"codecop_hash(number, {seed})"
97
+
98
+
99
+ def _uniform(seed: int) -> str:
100
+ return f"codecop_u(number, {seed})"
101
+
102
+
103
+ def _index(spec: dict, seeds: _Seeds, distinct: int) -> str:
104
+ """An integer in [0, distinct): uniform, or skewed so that low numbers are far more common."""
105
+ distinct = max(int(distinct), 1)
106
+ if spec.get("distribution", "uniform") == "skewed" and distinct > 1:
107
+ return f"codecop_skewed(number, {seeds.next()}, {distinct})"
108
+ return f"({_hash(seeds.next())} % {distinct})"
109
+
110
+
111
+ def _from_index(idx: str, declared: str, prefix: str) -> str:
112
+ if re.match(r"^\s*UUID", declared or "", re.I):
113
+ return f"('00000000-0000-4000-8000-' || printf('%012d', {idx}))"
114
+ if affinity(declared) in ("INTEGER", "REAL", "NUMERIC") and not is_time(declared):
115
+ return f"({idx})"
116
+ return f"({quote(prefix)} || ({idx}))"
117
+
118
+
119
+ def _time(u: str, seconds: int, declared: str, clock: int) -> str:
120
+ offset = f"CAST({u} * {seconds} AS INTEGER)"
121
+ if affinity(declared) == "INTEGER":
122
+ return f"({clock} - {offset})" # epoch seconds
123
+ return f"datetime({clock} - {offset}, 'unixepoch')"
124
+
125
+
126
+ def default_expr(declared: str, clock: int) -> str:
127
+ """A neutral value for a NOT NULL column the profile does not describe."""
128
+ aff = affinity(declared)
129
+ if is_time(declared) and aff != "INTEGER":
130
+ return f"datetime({clock}, 'unixepoch')"
131
+ if re.match(r"^\s*UUID", declared or "", re.I):
132
+ return "('00000000-0000-4000-8000-' || printf('%012d', number))"
133
+ if aff in ("INTEGER", "NUMERIC") or is_boolean(declared):
134
+ return "0"
135
+ if aff == "REAL":
136
+ return "0.0"
137
+ if aff == "BLOB" and (declared or "").strip():
138
+ return "X''"
139
+ return "''"
140
+
141
+
142
+ def required_expr(declared: str, info: dict, clock: int) -> str:
143
+ """What a NOT NULL column gets when its generator gives NULL: its own default when it has one, else a neutral value."""
144
+ default = (info.get("default") or "").strip()
145
+ if default and not re.search(r"\b(?:random|randomblob)\s*\(", default, re.I):
146
+ return f"({default})" if not re.match(r"^CURRENT_(?:TIMESTAMP|DATE|TIME)$", default, re.I) else default_expr("DATETIME", clock)
147
+ return default_expr(declared, clock)
148
+
149
+
150
+ def column_expr(col: dict, declared: str, seeds: _Seeds, clock: int, realism: tuple = REALISM, scale: str = "") -> str:
151
+ kind = col.get("kind", "")
152
+ name = col.get("name", "?")
153
+ if kind == "unique":
154
+ expr = _from_index("number", declared, col.get("prefix") or f"{name}_")
155
+ elif kind == "key":
156
+ if not col.get("distinct"):
157
+ raise ProfileError(f"{name}: kind 'key' needs 'distinct'")
158
+ expr = _from_index(_index(col, seeds, col["distinct"]), declared, col.get("prefix") or f"{name}_")
159
+ elif kind == "categorical":
160
+ values = col.get("values") or []
161
+ if not values:
162
+ raise ProfileError(f"{name}: kind 'categorical' needs 'values'")
163
+ total = sum(float(v.get("weight", 1)) for v in values) or 1.0
164
+ u, acc, arms = _uniform(seeds.next()), 0.0, []
165
+ for v in values[:-1]:
166
+ acc += float(v.get("weight", 1)) / total
167
+ arms.append(f"WHEN {u} < {acc:.6f} THEN {literal(v['value'], declared)}")
168
+ last = literal(values[-1]["value"], declared)
169
+ expr = f"(CASE {' '.join(arms)} ELSE {last} END)" if arms else last
170
+ elif kind in ("int", "float"):
171
+ lo, hi = float(col.get("min", 0)), float(col.get("max", 1000))
172
+ span = max(hi - lo, 1.0)
173
+ u = _uniform(seeds.next())
174
+ if col.get("distribution") == "skewed":
175
+ u = f"({u} * {u} * {u} * {u})"
176
+ expr = f"({lo!r} + {u} * {span!r})"
177
+ if kind == "int":
178
+ expr = f"CAST({expr} AS INTEGER)"
179
+ elif kind == "timestamp":
180
+ seconds = max(int(float(col.get("days_back", 30)) * 86400), 1)
181
+ u = _uniform(seeds.next())
182
+ if col.get("distribution") == "skewed":
183
+ u = f"({u} * {u})"
184
+ expr = _time(u, seconds, declared, clock)
185
+ elif kind == "text":
186
+ model = sizes.size_model(col) if "sizes" in realism else None
187
+ if model is None:
188
+ length = str(max(int(col.get("avg_len", 40)), 1))
189
+ elif "content" not in realism or model["sigma"] <= 0:
190
+ length = str(max(int(round(model["mean"] if "content" not in realism else model["median"])), 1))
191
+ else:
192
+ length = (f"codecop_length(number, {seeds.next()}, {model['median']:.2f}, {model['sigma']:.4f}, {scale or 1}, "
193
+ f"{sizes.Z_CAP}, {sizes.MAX_VALUE_BYTES})")
194
+ m = re.search(r"\((\d+)\)", declared or "")
195
+ if m and affinity(declared) == "TEXT":
196
+ length = f"min({length}, {m.group(1)})"
197
+ expr = f"codecop_text(number, {seeds.next()}, {length})"
198
+ elif kind == "constant":
199
+ expr = literal(col.get("value"), declared)
200
+ elif kind == "expr":
201
+ if not col.get("sql"):
202
+ raise ProfileError(f"{name}: kind 'expr' needs 'sql'")
203
+ expr = f"({col['sql']})"
204
+ else:
205
+ raise ProfileError(f"{name}: unknown generator kind '{kind}'")
206
+
207
+ pinned = [p for p in (col.get("pinned") or []) if float(p.get("share", 0)) > 0]
208
+ if pinned:
209
+ u, acc, arms = _uniform(seeds.next()), 0.0, []
210
+ for p in pinned:
211
+ acc += float(p["share"])
212
+ arms.append(f"WHEN {u} < {acc:.6f} THEN {literal(p['value'], declared)}")
213
+ expr = f"(CASE {' '.join(arms)} ELSE {expr} END)"
214
+ nulls = float(col.get("null_fraction") or 0)
215
+ if nulls > 0:
216
+ expr = f"(CASE WHEN {_uniform(seeds.next())} < {nulls:.6f} THEN NULL ELSE {expr} END)"
217
+ return expr
218
+
219
+
220
+ def _slot_of() -> str:
221
+ return f"({_hash(7777)} % {FIXTURE_SLOTS})"
222
+
223
+
224
+ def _fixture_conditions(fixtures: list[dict], placed: dict[str, dict]) -> list[tuple[str, dict]]:
225
+ """(condition, {column: value}) per fixture. The guaranteed rows are tested first, so they win over a hash slice."""
226
+ sure, sliced = [], []
227
+ for f in fixtures or []:
228
+ slot = placed.get(str(f.get("id") or ""))
229
+ values = {v["column"]: v["value"] for v in f.get("values") or [] if v.get("column")}
230
+ if not slot or not values:
231
+ continue
232
+ own = min(max(int(f.get("min_rows") or 1), 1), slot["min_rows"])
233
+ sure.append((f"(number >= {slot['offset']} AND number < {slot['offset'] + own})", values))
234
+ share = min(max(float(f.get("share") or 0), 0.0), slot["width"])
235
+ a, b = int(slot["start"] * FIXTURE_SLOTS), int((slot["start"] + share) * FIXTURE_SLOTS)
236
+ if b > a:
237
+ sliced.append((f"({_slot_of()} >= {a} AND {_slot_of()} < {b})", values))
238
+ return sure + sliced
239
+
240
+
241
+ def _size_scale(name: str, fixtures: list[dict], placed: dict[str, dict]) -> str:
242
+ arms = []
243
+ for f in fixtures or []:
244
+ factor = next((float(s.get("factor") or 0) for s in f.get("size_factors") or [] if s.get("column") == name), 0.0)
245
+ slot = placed.get(str(f.get("id") or ""))
246
+ if factor <= 0 or factor == 1 or not slot:
247
+ continue
248
+ own = min(max(int(f.get("min_rows") or 1), 1), slot["min_rows"])
249
+ share = min(max(float(f.get("share") or 0), 0.0), slot["width"])
250
+ a, b = int(slot["start"] * FIXTURE_SLOTS), int((slot["start"] + share) * FIXTURE_SLOTS)
251
+ cond = f"(number >= {slot['offset']} AND number < {slot['offset'] + own})"
252
+ if b > a:
253
+ cond = f"({cond} OR ({_slot_of()} >= {a} AND {_slot_of()} < {b}))"
254
+ arms.append(f"WHEN {cond} THEN {factor:.4f}")
255
+ return f"(CASE {' '.join(arms)} ELSE 1 END)" if arms else ""
256
+
257
+
258
+ def _with_fixtures(expr: str, name: str, declared: str, conditions: list[tuple[str, dict]]) -> str:
259
+ arms = [f"WHEN {cond} THEN {literal(None if values[name] == 'NULL' else values[name], declared)}"
260
+ for cond, values in conditions if name in values]
261
+ return f"(CASE {' '.join(arms)} ELSE {expr} END)" if arms else expr
262
+
263
+
264
+ UNIQUE_AS_IS = ("unique", "expr", "text", "timestamp", "float")
265
+
266
+
267
+ def insert_statements(table: str, rows: int, columns: list[dict], types: dict[str, str], *, clock: int, batches: int = 4,
268
+ max_batch: int = 500_000, fixtures: list[dict] | None = None, placed: dict[str, dict] | None = None,
269
+ meta: dict[str, dict] | None = None, realism: tuple = REALISM, notes: list[str] | None = None) -> list[str]:
270
+ """INSERT statements that load `rows` rows in batches.
271
+
272
+ `types`: column -> declared type, as PRAGMA table_xinfo reports it. `meta`: column -> {notnull, has_default, default,
273
+ rowid, generated, unique_alone}. `clock`: the epoch second time columns count back from."""
274
+ meta = meta or {}
275
+ notes = notes if notes is not None else []
276
+ profiled = {c["name"] for c in columns}
277
+ writable = {n for n in types if not meta.get(n, {}).get("generated") and (not meta.get(n, {}).get("rowid") or n in profiled)}
278
+ known = []
279
+ for c in columns:
280
+ if c["name"] not in writable:
281
+ continue
282
+ info = meta.get(c["name"], {})
283
+ if info.get("unique_alone") and c.get("kind") not in UNIQUE_AS_IS:
284
+ notes.append(f"{c['name']}: unique on its own, so every row gets its own value (the profile said {c.get('kind')})")
285
+ c = {k: v for k, v in c.items() if k not in ("distinct", "distribution", "values", "value", "min", "max")} | {"kind": "unique"}
286
+ known.append(c)
287
+ if not known:
288
+ raise ProfileError(f"{table}: none of the profiled columns exist in the table")
289
+ conditions = _fixture_conditions(fixtures or [], placed or {})
290
+ named = {c["name"] for c in known}
291
+ extra = sorted({n for _, values in conditions for n in values if n in writable and n not in named})
292
+ needed = sorted(n for n in writable if n not in named and n not in extra
293
+ and meta.get(n, {}).get("notnull") and not meta.get(n, {}).get("has_default") and not meta.get(n, {}).get("rowid"))
294
+
295
+ def finish(expr: str, name: str) -> str:
296
+ if meta.get(name, {}).get("notnull"):
297
+ return f"COALESCE({expr}, {required_expr(types[name], meta[name], clock)})"
298
+ return expr
299
+
300
+ batches = max(batches, math.ceil(rows / max(max_batch, 1)), 1)
301
+ size = math.ceil(rows / batches)
302
+ out, offset = [], 0
303
+ while offset < rows:
304
+ n = min(size, rows - offset)
305
+ seeds = _Seeds(1000) # the same seeds in every batch: a column's shape does not depend on the batch
306
+ exprs = []
307
+ for c in known:
308
+ t = types[c["name"]]
309
+ scale = _size_scale(c["name"], fixtures or [], placed or {})
310
+ value = _with_fixtures(column_expr(c, t, seeds, clock, realism, scale), c["name"], t, conditions)
311
+ exprs.append(f"{finish(value, c['name'])} AS {ident(c['name'])}")
312
+ for name in extra:
313
+ info = meta.get(name, {})
314
+ fallback = required_expr(types[name], info, clock) if info.get("notnull") else "NULL"
315
+ exprs.append(f"{_with_fixtures(fallback, name, types[name], conditions)} AS {ident(name)}")
316
+ exprs += [f"{required_expr(types[name], meta.get(name, {}), clock)} AS {ident(name)}" for name in needed]
317
+ names = [c["name"] for c in known] + extra + needed
318
+ cols = ", ".join(ident(x) for x in names)
319
+ series = (f"WITH RECURSIVE codecop_n(number) AS (SELECT {offset} UNION ALL SELECT number + 1 FROM codecop_n "
320
+ f"WHERE number < {offset + n - 1})")
321
+ out.append(f"INSERT OR IGNORE INTO {ident(table)} ({cols}) {series} SELECT {', '.join(exprs)} FROM codecop_n")
322
+ offset += n
323
+ return out