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,630 @@
1
+ """Turn a data profile into Postgres INSERT statements.
2
+
3
+ Same profile format as datagen.py (kinds, null_fraction, pinned, fixtures), a
4
+ different dialect. Generation is set-based: one
5
+
6
+ INSERT INTO t (cols) SELECT ... FROM generate_series(a, b) AS number ON CONFLICT DO NOTHING
7
+
8
+ per batch. The row index is called `number`, as in ClickHouse, so an `expr`
9
+ column and a fixture mean the same thing on both engines.
10
+
11
+ Values are a pure function of the row number: every "random" draw is a hash of
12
+ `number` and a per-column seed, so two runs of the same profile load the same
13
+ data and two tables can derive a join key from `number`.
14
+
15
+ Differences from ClickHouse that the generator has to cover:
16
+ - A NOT NULL column without a default has no implicit value. Columns the profile
17
+ leaves out are filled with a neutral value of their type.
18
+ - Primary keys and unique indexes reject duplicates. ON CONFLICT DO NOTHING drops
19
+ the colliding rows instead of failing the load; the loaded row count is reported.
20
+ - A generated column is never written. An identity column is written only when the
21
+ profile describes it (OVERRIDING SYSTEM VALUE), so that a key derived from
22
+ `number` means the same row in the parent and in the child; left out, it takes
23
+ its sequence value, which starts at 1 and does not follow `number`.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ import re
30
+
31
+ from . import sizes
32
+ from .datagen import FIXTURE_SLOTS, REALISM, ProfileError
33
+
34
+ PHRASE = "the request returned a result with status and content for the user " # 64 characters that compress
35
+
36
+ INTEGER = re.compile(r"^(smallint|integer|bigint|int2|int4|int8|smallserial|serial|bigserial|oid)\b")
37
+ NUMERIC = re.compile(r"^(numeric|decimal|real|double precision|float4|float8|money)\b")
38
+ TIMESTAMP = re.compile(r"^timestamp")
39
+ TEXTUAL = re.compile(r"^(text|character varying|varchar|character|char|bpchar|citext|name)\b")
40
+
41
+
42
+ def base_type(pg_type: str) -> str:
43
+ return pg_type.strip().lower()
44
+
45
+
46
+ def is_array(pg_type: str) -> bool:
47
+ return pg_type.strip().endswith("[]")
48
+
49
+
50
+ def quote(value) -> str:
51
+ return "'" + str(value).replace("'", "''") + "'"
52
+
53
+
54
+ def ident(name: str) -> str:
55
+ return '"' + name.replace('"', '""') + '"'
56
+
57
+
58
+ def qualified(name: str) -> str:
59
+ return ".".join(ident(p) for p in name.split("."))
60
+
61
+
62
+ def literal(value, pg_type: str) -> str:
63
+ bt = base_type(pg_type)
64
+ if value is None:
65
+ return "NULL"
66
+ if isinstance(value, bool):
67
+ value = "true" if value else "false"
68
+ if (INTEGER.match(bt) or NUMERIC.match(bt)) and re.fullmatch(r"-?\d+(\.\d+)?", str(value)):
69
+ return str(value)
70
+ if bt == "boolean" and str(value).lower() in ("true", "false", "t", "f", "1", "0"):
71
+ return "true" if str(value).lower() in ("true", "t", "1") else "false"
72
+ return quote(value)
73
+
74
+
75
+ class _Seeds:
76
+ def __init__(self, start: int):
77
+ self.n = start
78
+
79
+ def next(self) -> int:
80
+ self.n += 1
81
+ return self.n
82
+
83
+
84
+ def _hash(seed: int) -> str:
85
+ """A non-negative 62-bit integer that depends only on the row number and the seed."""
86
+ return f"(hashint8extended(number, {seed}) & 4611686018427387903)"
87
+
88
+
89
+ def _uniform(seed: int) -> str:
90
+ """A float in [0, 1)."""
91
+ return f"(({_hash(seed)} % 1000000007)::float8 / 1000000007.0)"
92
+
93
+
94
+ def _index(spec: dict, seeds: _Seeds, distinct: int) -> str:
95
+ """An integer in [0, distinct): uniform, or skewed so that low numbers are far more common."""
96
+ distinct = max(int(distinct), 1)
97
+ if spec.get("distribution", "uniform") == "skewed" and distinct > 1:
98
+ return f"least(floor(exp({_uniform(seeds.next())} * {math.log(distinct):.6f}))::bigint - 1, {distinct - 1})"
99
+ return f"({_hash(seeds.next())} % {distinct})"
100
+
101
+
102
+ def _from_index(idx: str, pg_type: str, prefix: str) -> str:
103
+ bt = base_type(pg_type)
104
+ if bt == "uuid":
105
+ return f"('00000000-0000-4000-8000-' || lpad(({idx})::text, 12, '0'))::uuid"
106
+ if INTEGER.match(bt) or NUMERIC.match(bt):
107
+ return f"({idx})"
108
+ return f"({quote(prefix)} || ({idx})::text)"
109
+
110
+
111
+ def _text(n: int, seed: int) -> str:
112
+ """`n` characters that do not compress: base64 of a hash chain. Long values repeat after 64 blocks."""
113
+ blocks = min(max(math.ceil(n / 88), 1), 64)
114
+ one = "translate(encode(sha512((number::text || '/{s}/' || {i})::bytea), 'base64'), E'\\n', '')"
115
+ parts = " || ".join(one.format(s=seed, i=i) for i in range(blocks))
116
+ if n > blocks * 88:
117
+ parts = f"repeat({parts}, {math.ceil(n / (blocks * 88))})"
118
+ return f"substr({parts}, 1, {n})"
119
+
120
+
121
+ def _length(model: dict, seeds: _Seeds, scale: str = "") -> str:
122
+ """A length in characters per row: log-normal around the median, the tail cut at three standard deviations."""
123
+ if model["sigma"] <= 0:
124
+ base = f"{model['median']:.1f}"
125
+ else:
126
+ z = (f"least(sqrt(-2 * ln({_uniform(seeds.next())} + 1e-12)) * cos(6.283185307179586 * {_uniform(seeds.next())}), {sizes.Z_CAP})")
127
+ base = f"{model['median']:.2f} * exp({model['sigma']:.4f} * {z})"
128
+ if scale:
129
+ base = f"({base}) * {scale}"
130
+ return f"least(greatest(round({base}), 1), {sizes.MAX_VALUE_BYTES})::int"
131
+
132
+
133
+ def _sized_text(length: str, median: float, seed: int, compressible: bool) -> str:
134
+ """Text of `length` characters. Compressible text is two thirds a fixed phrase and one third a hash, so pglz (TOAST)
135
+ shrinks it about threefold, as it does real JSON and prose; the other kind is a hash chain that does not compress.
136
+ A value longer than the chain repeats it."""
137
+ if compressible:
138
+ one, unit = "md5(number::text || '/{s}/' || {i}) || " + quote(PHRASE), 96
139
+ else:
140
+ one, unit = "translate(encode(sha512((number::text || '/{s}/' || {i})::bytea), 'base64'), E'\\n', '')", 88
141
+ blocks = min(max(math.ceil(median * 3 / unit), 1), 64)
142
+ chain = " || ".join(one.format(s=seed, i=i) for i in range(blocks))
143
+ return f"substr(repeat({chain}, greatest(ceil(({length}) / {blocks * unit}.0)::int, 1)), 1, {length})"
144
+
145
+
146
+ def cast(expr: str, pg_type: str) -> str:
147
+ """CAST that also works where a plain cast from text would not: json wants a JSON value, an array wants an array."""
148
+ bt = base_type(pg_type)
149
+ if bt in ("json", "jsonb"):
150
+ # an object, as application JSON nearly always is: a scalar refuses `doc - 'key'` and `doc ->> 'k'` finds nothing
151
+ return f"CAST(jsonb_build_object('v', {expr}) AS {pg_type})"
152
+ if is_array(pg_type):
153
+ return f"CAST(ARRAY[{expr}] AS {pg_type})"
154
+ if bt == "bytea":
155
+ return f"convert_to(({expr})::text, 'UTF8')"
156
+ return f"CAST({expr} AS {pg_type})"
157
+
158
+
159
+ def _literal_cast(value, pg_type: str) -> str:
160
+ """A profile value as the column's type. A value that is already JSON or an array literal is cast as written."""
161
+ bt = base_type(pg_type)
162
+ text = str(value).strip() if value is not None else ""
163
+ if value is None:
164
+ return f"CAST(NULL AS {pg_type})"
165
+ if bt == "uuid" and not re.fullmatch(r"[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}", text):
166
+ # a value that is not a UUID (`tenant-other`, a description made without the real type): the UUID derived from
167
+ # it, as observed.fitting derives a parameter's, so a value and its fixture rows stay one
168
+ import uuid as uuid_mod
169
+ # 'qopt:': the seed from before the rename (formerly qopt), kept so the generated values stay the same
170
+ return f"CAST({quote(str(uuid_mod.uuid5(uuid_mod.NAMESPACE_URL, 'qopt:' + text)))} AS {pg_type})"
171
+ if bt in ("json", "jsonb") and text[:1] in "{[\"":
172
+ return f"CAST({quote(text)} AS {pg_type})"
173
+ if is_array(pg_type) and text.startswith("{"):
174
+ return f"CAST({quote(text)} AS {pg_type})"
175
+ if bt in ("json", "jsonb") or is_array(pg_type) or bt == "bytea":
176
+ return cast(quote(value), pg_type)
177
+ return f"CAST({literal(value, pg_type)} AS {pg_type})"
178
+
179
+
180
+ def default_expr(pg_type: str) -> str:
181
+ """A neutral value for a NOT NULL column the profile does not describe."""
182
+ bt = base_type(pg_type)
183
+ if is_array(pg_type):
184
+ return f"CAST('{{}}' AS {pg_type})"
185
+ if INTEGER.match(bt) or NUMERIC.match(bt):
186
+ return f"CAST(0 AS {pg_type})"
187
+ if bt == "boolean":
188
+ return "false"
189
+ if bt == "uuid":
190
+ return "('00000000-0000-4000-8000-' || lpad(number::text, 12, '0'))::uuid"
191
+ if TIMESTAMP.match(bt) or bt == "date":
192
+ return f"CAST(now() AS {pg_type})"
193
+ if bt.startswith("time"):
194
+ return f"CAST('00:00' AS {pg_type})"
195
+ if bt.startswith("interval"):
196
+ return "interval '0'"
197
+ if bt in ("json", "jsonb"):
198
+ return f"CAST('{{}}' AS {pg_type})"
199
+ if bt == "bytea":
200
+ return "''::bytea"
201
+ if bt in ("inet", "cidr"):
202
+ return f"CAST('10.0.0.1' AS {pg_type})"
203
+ if TEXTUAL.match(bt):
204
+ return f"CAST('' AS {pg_type})"
205
+ return f"CAST(NULL AS {pg_type})" # an enum or extension type: nothing sensible to invent
206
+
207
+
208
+ TIME_PG = re.compile(r"^(timestamp|date|time)\b")
209
+
210
+
211
+ def fit_kind(kind: str, col: dict, bt: str) -> tuple[str, dict]:
212
+ """The generator kind the real column type can hold. A description made without the real catalog (the agent's, or
213
+ the catalog-only one, which reads ClickHouse type names) can give a uuid column text, a boolean a 0..1000 range or a
214
+ timestamp a number: PostgreSQL then refuses every row ("invalid input syntax for type uuid"). The real type decides;
215
+ the description's values (distinct counts, the share of nulls, pinned values) stay."""
216
+ if is_array(bt):
217
+ return kind, col
218
+ if bt == "uuid" and kind in ("text", "int", "float", "timestamp"):
219
+ return "unique", col
220
+ if bt in ("boolean", "bool") and kind in ("int", "float", "text", "timestamp", "key", "unique"):
221
+ return "categorical", {**col, "values": [{"value": "false", "weight": 1}, {"value": "true", "weight": 1}]}
222
+ if TIME_PG.match(bt) and kind in ("text", "int", "float", "key", "unique"):
223
+ return "timestamp", {**col, "days_back": col.get("days_back", 30)}
224
+ if (INTEGER.match(bt) or NUMERIC.match(bt)) and kind == "text":
225
+ return ("int" if INTEGER.match(bt) else "float"), {**col, "min": col.get("min", 0), "max": col.get("max", 1000)}
226
+ return kind, col
227
+
228
+
229
+ def column_expr(col: dict, pg_type: str, seeds: _Seeds, nullable: bool = True, realism: tuple = REALISM, scale: str = "") -> str:
230
+ kind = col.get("kind", "")
231
+ bt = base_type(pg_type)
232
+ name = col.get("name", "?")
233
+ typed = False # True when `expr` already has the column's type
234
+ kind, col = fit_kind(kind, col, bt)
235
+ if kind == "unique":
236
+ expr = _from_index("number", pg_type, col.get("prefix") or f"{name}_")
237
+ elif kind == "key":
238
+ if not col.get("distinct"):
239
+ raise ProfileError(f"{name}: kind 'key' needs 'distinct'")
240
+ expr = _from_index(_index(col, seeds, col["distinct"]), pg_type, col.get("prefix") or f"{name}_")
241
+ elif kind == "categorical":
242
+ values = col.get("values") or []
243
+ if not values:
244
+ raise ProfileError(f"{name}: kind 'categorical' needs 'values'")
245
+ total = sum(float(v.get("weight", 1)) for v in values) or 1.0
246
+ u, acc, arms = _uniform(seeds.next()), 0.0, []
247
+ for v in values[:-1]:
248
+ acc += float(v.get("weight", 1)) / total
249
+ arms.append(f"WHEN {u} < {acc:.6f} THEN {_literal_cast(v['value'], pg_type)}")
250
+ last = _literal_cast(values[-1]["value"], pg_type)
251
+ expr = f"(CASE {' '.join(arms)} ELSE {last} END)" if arms else last
252
+ typed = True
253
+ elif kind in ("int", "float"):
254
+ lo, hi = float(col.get("min", 0)), float(col.get("max", 1000))
255
+ span = max(hi - lo, 1.0)
256
+ u = _uniform(seeds.next())
257
+ if col.get("distribution") == "skewed":
258
+ u = f"power({u}, 4)"
259
+ expr = f"({lo} + {u} * {span})"
260
+ if kind == "int":
261
+ expr = f"floor({expr})::bigint"
262
+ elif kind == "timestamp":
263
+ seconds = max(int(float(col.get("days_back", 30)) * 86400), 1)
264
+ drawn = seeds.next() # drawn either way: the columns after it keep their values
265
+ u = _uniform(int(col.get("_time_seed") or drawn))
266
+ if col.get("distribution") == "skewed":
267
+ u = f"power({u}, 2)"
268
+ ts = f"(now() - make_interval(secs => floor({u} * {seconds})))"
269
+ if col.get("_after_s"):
270
+ # the end of an interval whose start is another column of the row (endTime after startTime): the start's
271
+ # instant plus a short duration, not an independent instant up to days_back away
272
+ ts = f"({ts} + make_interval(secs => floor({_uniform(drawn)} * {int(col['_after_s'])})))"
273
+ if INTEGER.match(bt) or NUMERIC.match(bt):
274
+ expr = f"floor(extract(epoch FROM {ts}))::bigint" # the column stores epoch seconds
275
+ else:
276
+ expr = ts
277
+ elif kind == "text":
278
+ model = sizes.size_model(col) if "sizes" in realism else None
279
+ if model is None:
280
+ expr = _text(max(int(col.get("avg_len", 40)), 1), seeds.next())
281
+ elif "content" not in realism:
282
+ expr = _text(max(int(round(model["mean"])), 1), seeds.next())
283
+ else:
284
+ expr = _sized_text(_length(model, seeds, scale), model["median"], seeds.next(),
285
+ compressible=(col.get("content") or "text") not in sizes.INCOMPRESSIBLE)
286
+ m = re.search(r"\((\d+)\)", bt) if TEXTUAL.match(bt) else None
287
+ if m:
288
+ expr = f"left({expr}, {m.group(1)})"
289
+ elif kind == "constant":
290
+ expr, typed = _literal_cast(col.get("value"), pg_type), True
291
+ elif kind == "expr":
292
+ if not col.get("sql"):
293
+ raise ProfileError(f"{name}: kind 'expr' needs 'sql'")
294
+ expr = f"CAST(({col['sql']}) AS {pg_type})"
295
+ typed = True
296
+ else:
297
+ raise ProfileError(f"{name}: unknown generator kind '{kind}'")
298
+ if not typed:
299
+ expr = cast(expr, pg_type)
300
+
301
+ pinned = [p for p in (col.get("pinned") or []) if float(p.get("share", 0)) > 0]
302
+ if pinned:
303
+ u, acc, arms = _uniform(seeds.next()), 0.0, []
304
+ for p in pinned:
305
+ acc += float(p["share"])
306
+ arms.append(f"WHEN {u} < {acc:.6f} THEN {_literal_cast(p['value'], pg_type)}")
307
+ expr = f"(CASE {' '.join(arms)} ELSE {expr} END)"
308
+ nulls = float(col.get("null_fraction") or 0)
309
+ if nulls > 0 and nullable:
310
+ expr = f"(CASE WHEN {_uniform(seeds.next())} < {nulls:.6f} THEN NULL ELSE {expr} END)"
311
+ return expr
312
+
313
+
314
+ def _fixture_conditions(fixtures: list[dict], placed: dict[str, dict]) -> list[tuple[str, dict]]:
315
+ """(condition, {column: value}) per fixture. The guaranteed rows are tested first, so they win over a hash slice."""
316
+ sure, sliced = [], []
317
+ slot_of = f"({_hash(7777)} % {FIXTURE_SLOTS})"
318
+ for f in fixtures or []:
319
+ slot = placed.get(str(f.get("id") or ""))
320
+ values = {v["column"]: v["value"] for v in f.get("values") or [] if v.get("column")}
321
+ if not slot or not values:
322
+ continue
323
+ # The slot reserves the largest min_rows any table asked for; this table fills only what it asked for itself.
324
+ # A query that expects exactly one row per key (HAVING count(DISTINCT ...) = 1) would otherwise get twenty.
325
+ own = min(max(int(f.get("min_rows") or 1), 1), slot["min_rows"])
326
+ sure.append((f"(number >= {slot['offset']} AND number < {slot['offset'] + own})", values))
327
+ share = min(max(float(f.get("share") or 0), 0.0), slot["width"])
328
+ a, b = int(slot["start"] * FIXTURE_SLOTS), int((slot["start"] + share) * FIXTURE_SLOTS)
329
+ if b > a:
330
+ sliced.append((f"({slot_of} >= {a} AND {slot_of} < {b})", values))
331
+ return sure + sliced
332
+
333
+
334
+ def _size_scale(name: str, fixtures: list[dict], placed: dict[str, dict]) -> str:
335
+ """A fixture's size factor for this column on that fixture's rows and 1 elsewhere, or ""."""
336
+ arms = []
337
+ slot_of = f"({_hash(7777)} % {FIXTURE_SLOTS})"
338
+ for f in fixtures or []:
339
+ factor = next((float(s.get("factor") or 0) for s in f.get("size_factors") or [] if s.get("column") == name), 0.0)
340
+ slot = placed.get(str(f.get("id") or ""))
341
+ if factor <= 0 or factor == 1 or not slot:
342
+ continue
343
+ own = min(max(int(f.get("min_rows") or 1), 1), slot["min_rows"])
344
+ share = min(max(float(f.get("share") or 0), 0.0), slot["width"])
345
+ a, b = int(slot["start"] * FIXTURE_SLOTS), int((slot["start"] + share) * FIXTURE_SLOTS)
346
+ cond = f"(number >= {slot['offset']} AND number < {slot['offset'] + own})"
347
+ if b > a:
348
+ cond = f"({cond} OR ({slot_of} >= {a} AND {slot_of} < {b}))"
349
+ arms.append(f"WHEN {cond} THEN {factor:.4f}")
350
+ return f"(CASE {' '.join(arms)} ELSE 1 END)" if arms else ""
351
+
352
+
353
+ def _with_fixtures(expr: str, name: str, pg_type: str, conditions: list[tuple[str, dict]]) -> str:
354
+ arms = [f"WHEN {cond} THEN {_literal_cast(None if values[name] == 'NULL' else values[name], pg_type)}"
355
+ for cond, values in conditions if name in values]
356
+ return f"(CASE {' '.join(arms)} ELSE {expr} END)" if arms else expr
357
+
358
+
359
+ UNIQUE_AS_IS = ("unique", "expr", "text", "timestamp", "float") # kinds left alone on a column that is unique on its own
360
+ RELATION_SEED = 9100
361
+
362
+
363
+ def required_expr(pg_type: str, info: dict) -> str:
364
+ """The value a NOT NULL column gets when its generator gives NULL: the column's own default when it has one
365
+ (a constant default; a sequence or now() is as good), else a neutral value of its type, an enum's first label."""
366
+ default = (info.get("default") or "").strip()
367
+ if default and not re.search(r"\bnextval\s*\(", default, re.I):
368
+ return f"CAST(({default}) AS {pg_type})"
369
+ if info.get("enum"):
370
+ return f"CAST({quote(info['enum'][0])} AS {pg_type})"
371
+ return default_expr(pg_type)
372
+
373
+
374
+ def fit_enum(col: dict, labels: list[str], notes: list[str]) -> dict:
375
+ """An enum column takes only its labels: a value outside them would fail the whole load. Such values are dropped
376
+ from a categorical or pinned list; a constant becomes the first label."""
377
+ allowed = set(labels)
378
+ out = dict(col)
379
+ dropped = []
380
+ if out.get("kind") == "categorical":
381
+ keep = [v for v in out.get("values") or [] if str(v.get("value")) in allowed]
382
+ dropped += [str(v.get("value")) for v in out.get("values") or [] if str(v.get("value")) not in allowed]
383
+ out["values"] = keep or [{"value": labels[0], "weight": 1}]
384
+ elif out.get("kind") == "constant" and out.get("value") is not None and str(out["value"]) not in allowed:
385
+ dropped.append(str(out["value"]))
386
+ out["value"] = labels[0]
387
+ elif out.get("kind") in ("key", "unique", "int", "float", "text", "timestamp"):
388
+ dropped.append(f"kind {out['kind']}")
389
+ out = {**out, "kind": "categorical", "values": [{"value": x, "weight": 1} for x in labels]}
390
+ if out.get("pinned"):
391
+ dropped += [str(p.get("value")) for p in out["pinned"] if str(p.get("value")) not in allowed]
392
+ out["pinned"] = [p for p in out["pinned"] if str(p.get("value")) in allowed]
393
+ if dropped:
394
+ notes.append(f"{col['name']}: not a label of the enum type, left out of the generated values: {', '.join(dropped[:6])}")
395
+ return out
396
+
397
+
398
+ def apply_domain(expr: str, pg_type: str, domain: dict, seed: int) -> str:
399
+ """Keep a generated value inside what a simple CHECK allows (pg_ddl.check_domain): a value outside a list is
400
+ replaced by one of the list, a number outside a range is moved to its edge, a text is cut to the length."""
401
+ bt = base_type(pg_type)
402
+ if domain.get("values"):
403
+ values = [str(v) for v in domain["values"]]
404
+ allowed = ", ".join(quote(v) for v in values)
405
+ pick = f"(ARRAY[{allowed}])[1 + ({_hash(seed)} % {len(values)})::int]"
406
+ return f"(CASE WHEN ({expr}) IS NULL OR ({expr})::text IN ({allowed}) THEN ({expr}) ELSE CAST({pick} AS {pg_type}) END)"
407
+ if "max_length" in domain and TEXTUAL.match(bt):
408
+ return f"CAST(left(({expr})::text, {int(domain['max_length'])}) AS {pg_type})"
409
+ if ("min" in domain or "max" in domain) and (INTEGER.match(bt) or NUMERIC.match(bt)):
410
+ step = 1 if INTEGER.match(bt) else 1e-6
411
+ out = f"({expr})"
412
+ if "min" in domain:
413
+ lo = domain["min"] + (step if domain.get("min_open") else 0)
414
+ out = f"greatest({out}, CAST({lo:g} AS {pg_type}))"
415
+ if "max" in domain:
416
+ hi = domain["max"] - (step if domain.get("max_open") else 0)
417
+ out = f"least({out}, CAST({hi:g} AS {pg_type}))"
418
+ return out
419
+ return expr
420
+
421
+
422
+ def _relation_layer(inner: str, names: list[str], types: dict[str, str], rel: dict, seed: int) -> str:
423
+ """One relation applied to the rows of `inner` (relations.py says what is kept and what is chosen).
424
+
425
+ `rel`: {column, group, same: [(child column, map column)], map, counts, total, skewed, always}. `map` is the
426
+ parent's keys as (rn, k, x, grn, d1..): `k` the key as text, `x` the group column (the first shared column),
427
+ `rn` a row number over all keys and `grn` one within each `x`; `counts` is (x, n)."""
428
+ g = lambda col: f"g.{ident(col)}" # noqa: E731
429
+ fk, group = rel["column"], rel.get("group")
430
+ h = f"(hashint8extended(g.number, {seed}) & 4611686018427387903)"
431
+
432
+ def ordinal(n: str) -> str:
433
+ if not rel.get("skewed"):
434
+ return f"({h} % {n})"
435
+ u = f"(({h} % 1000000007)::float8 / 1000000007.0)"
436
+ return f"least(floor(exp({u} * ln(greatest({n}, 1)::float8)))::bigint - 1, {n} - 1)"
437
+
438
+ joins = [f"LEFT JOIN {rel['map']} p0 ON p0.k = ({g(fk)})::text"]
439
+ agrees = "p0.k IS NOT NULL"
440
+ if group:
441
+ agrees += f" AND p0.x IS NOT DISTINCT FROM ({g(group)})::text"
442
+ joins.append(f"LEFT JOIN {rel['counts']} pc ON pc.x = ({g(group)})::text")
443
+ joins.append(f"LEFT JOIN {rel['map']} pg ON pg.x = ({g(group)})::text AND pg.grn = {ordinal('pc.n')}")
444
+ joins.append(f"LEFT JOIN {rel['map']} pa ON pa.rn = {ordinal(str(int(rel['total'])))}")
445
+ absent = "" if rel.get("always") else f"WHEN {g(fk)} IS NULL THEN {{own}} "
446
+
447
+ def choose(own: str, kept: str, grouped: str, named: str, any_: str) -> str:
448
+ arms = absent.format(own=own) + f"WHEN {agrees} THEN {kept} "
449
+ if group:
450
+ arms += f"WHEN pg.k IS NOT NULL THEN {grouped} WHEN p0.k IS NOT NULL THEN {named} "
451
+ return f"(CASE {arms}ELSE {any_} END)"
452
+
453
+ def typed(alias: str, column: str, name: str) -> str:
454
+ return f"CAST({alias}.{column} AS {types[name]})"
455
+
456
+ replaced = {fk: choose(g(fk), g(fk), typed("pg", "k", fk), g(fk), typed("pa", "k", fk))}
457
+ for child, map_col in rel.get("same") or []:
458
+ if child == group:
459
+ replaced[child] = choose(g(child), g(child), g(child), typed("p0", "x", child), typed("pa", "x", child))
460
+ else:
461
+ replaced[child] = choose(g(child), typed("p0", map_col, child), typed("pg", map_col, child), typed("p0", map_col, child),
462
+ typed("pa", map_col, child))
463
+ select = ", ".join(f"{replaced[n]} AS {ident(n)}" if n in replaced else g(n) for n in names)
464
+ return f"SELECT g.number, {select} FROM ({inner}) g {' '.join(joins)}"
465
+
466
+
467
+ END_WORD = re.compile(r"(?i)(end|finish|stop)")
468
+ INTERVAL_AFTER_S = 300 # the longest an interval's end is generated after its start
469
+ INT_RANGE = {"smallint": (-32768, 32767), "int2": (-32768, 32767), "integer": (-2147483648, 2147483647),
470
+ "int": (-2147483648, 2147483647), "int4": (-2147483648, 2147483647)}
471
+
472
+
473
+ def paired_times(columns: list[dict], notes: list[str]) -> list[dict]:
474
+ """Timestamp columns that are the two ends of one interval (startTime / endTime, started_at / ended_at,
475
+ started_at / finished_at): the end is generated as the row's start plus at most INTERVAL_AFTER_S seconds. Drawn
476
+ independently, the two were up to days_back apart, and `EXTRACT(EPOCH FROM (end - start)) * 1000)::integer`, a
477
+ duration in ms the code computes, overflowed integer ("integer out of range", the whole baseline failed)."""
478
+ times = {c["name"]: c for c in columns if c.get("kind") == "timestamp"}
479
+ if len(times) < 2:
480
+ return columns
481
+ lower = {n.lower(): n for n in times}
482
+ out, seed = [], 9700
483
+ pairs = {}
484
+ for name in times:
485
+ for word in ("start", "begin"):
486
+ start = lower.get(END_WORD.sub(word, name, count=1).lower())
487
+ if start and start != name and END_WORD.search(name):
488
+ pairs[name] = start
489
+ break
490
+ if not pairs:
491
+ return columns
492
+ seed_of = {}
493
+ for end, start in pairs.items():
494
+ seed_of.setdefault(start, seed + len(seed_of))
495
+ for c in columns:
496
+ if c["name"] in seed_of:
497
+ c = {**c, "_time_seed": seed_of[c["name"]]}
498
+ elif c["name"] in pairs:
499
+ s = times[pairs[c["name"]]]
500
+ c = {**c, "_time_seed": seed_of[pairs[c["name"]]], "_after_s": INTERVAL_AFTER_S,
501
+ "days_back": s.get("days_back", c.get("days_back")), "distribution": s.get("distribution")}
502
+ out.append(c)
503
+ notes.append("interval ends generated after their starts (at most "
504
+ f"{INTERVAL_AFTER_S}s): " + ", ".join(f"{e} after {s}" for e, s in sorted(pairs.items())))
505
+ return out
506
+
507
+
508
+ def _fit_int_range(col: dict, pg_type: str, notes: list[str]) -> dict:
509
+ """An int generator kept inside the column's integer type: a profile range past it fails every row."""
510
+ lim = INT_RANGE.get(base_type(pg_type))
511
+ if not lim or col.get("kind") != "int":
512
+ return col
513
+ lo, hi = float(col.get("min", 0)), float(col.get("max", 1000))
514
+ if lo >= lim[0] and hi <= lim[1]:
515
+ return col
516
+ notes.append(f"{col['name']}: range {lo:g}..{hi:g} cut to what {base_type(pg_type)} holds")
517
+ return {**col, "min": max(min(lo, lim[1]), lim[0]), "max": max(min(hi, lim[1]), lim[0])}
518
+
519
+
520
+ def insert_statements(table: str, rows: int, columns: list[dict], types: dict[str, str], batches: int = 4,
521
+ max_batch: int = 5_000_000, fixtures: list[dict] | None = None,
522
+ placed: dict[str, dict] | None = None, meta: dict[str, dict] | None = None, realism: tuple = REALISM,
523
+ relations: list[dict] | None = None, domains: dict[str, list[dict]] | None = None,
524
+ notes: list[str] | None = None) -> list[str]:
525
+ """INSERT statements that load `rows` rows in several batches.
526
+
527
+ `types` is column -> type as the server reports it. `meta` is column ->
528
+ {notnull, has_default, default, identity, generated, unique_alone, enum}; without it every column is taken as
529
+ nullable and unconstrained. What the table declares is respected:
530
+ NOT NULL a generator that gives NULL (a constant null, an expression, a fixture) falls back to the column's
531
+ default, else to a neutral value of its type
532
+ unique a column that is unique on its own gets one value per row whatever kind the profile gave it
533
+ CHECK `domains` (column -> what its simple CHECKs allow) keeps values inside a list, a range or a length
534
+ enum values that are not labels of the type are left out
535
+ `relations`: this table's relations, resolved against the loaded parents (see _relation_layer).
536
+ `notes` collects what was changed, in words."""
537
+ meta = meta or {}
538
+ notes = notes if notes is not None else []
539
+ relations = relations or []
540
+ profiled = {c["name"] for c in columns}
541
+ writable = {n for n in types if not meta.get(n, {}).get("generated") and (not meta.get(n, {}).get("identity") or n in profiled)}
542
+ known = []
543
+ for c in columns:
544
+ if c["name"] not in writable:
545
+ continue
546
+ info = meta.get(c["name"], {})
547
+ if info.get("enum"):
548
+ c = fit_enum(c, info["enum"], notes)
549
+ if info.get("unique_alone") and c.get("kind") not in UNIQUE_AS_IS:
550
+ notes.append(f"{c['name']}: unique on its own, so every row gets its own value (the profile said {c.get('kind')})")
551
+ c = {k: v for k, v in c.items() if k not in ("distinct", "distribution", "values", "value", "min", "max")} | {"kind": "unique"}
552
+ known.append(c)
553
+ if not known:
554
+ raise ProfileError(f"{table}: none of the profiled columns exist in the table")
555
+ known = paired_times(known, notes)
556
+ known = [_fit_int_range(c, types.get(c["name"], ""), notes) for c in known]
557
+ conditions = _fixture_conditions(fixtures or [], placed or {})
558
+
559
+ def off_label(n: str, v) -> bool:
560
+ labels = (meta.get(n) or {}).get("enum")
561
+ return bool(labels) and v is not None and v != "NULL" and str(v) not in labels
562
+ # a fixture's value on an enum column that is not one of its labels would fail the whole load: left out (the rows
563
+ # take a generated label), and said
564
+ off = sorted({f"{n}={v}" for _, values in conditions for n, v in values.items() if off_label(n, v)})
565
+ if off:
566
+ notes.append(f"fixture values that are not labels of their enum type, left out: {', '.join(off[:6])}")
567
+ conditions = [(cond, {n: v for n, v in values.items() if not off_label(n, v)}) for cond, values in conditions]
568
+ conditions = [(cond, values) for cond, values in conditions if values]
569
+ named = {c["name"] for c in known}
570
+ extra = sorted({n for _, values in conditions for n in values if n in writable and n not in named})
571
+ # a relation's columns are written even when nobody described them: they take the parent's values
572
+ related = [n for r in relations for n in [r["column"]] + [c for c, _ in r.get("same") or []]]
573
+ extra += sorted({n for n in related if n in writable and n not in named and n not in extra})
574
+ relations = [{**r, "always": r["column"] not in profiled and r["column"] not in
575
+ {n for _, values in conditions for n in values}} for r in relations
576
+ if r["column"] in writable and all(c in writable for c, _ in r.get("same") or [])]
577
+ overriding = "OVERRIDING SYSTEM VALUE " if any(meta.get(n, {}).get("identity") for n in writable
578
+ if n in named or n in extra) else ""
579
+ # NOT NULL columns with no default that nobody described: Postgres has no implicit value for them
580
+ needed = sorted(n for n in writable if n not in named and n not in extra
581
+ and meta.get(n, {}).get("notnull") and not meta.get(n, {}).get("has_default"))
582
+ domains = domains or {}
583
+
584
+ def finish(expr: str, name: str, seeds: _Seeds) -> str:
585
+ """The declared constraints, applied to whatever the generator and the fixtures gave."""
586
+ for d in domains.get(name) or []:
587
+ expr = apply_domain(expr, types[name], d, seeds.next())
588
+ if meta.get(name, {}).get("notnull"):
589
+ expr = f"COALESCE({expr}, {required_expr(types[name], meta[name])})"
590
+ return expr
591
+
592
+ batches = max(batches, math.ceil(rows / max_batch), 1)
593
+ size = math.ceil(rows / batches)
594
+ out, offset = [], 0
595
+ while offset < rows:
596
+ n = min(size, rows - offset)
597
+ seeds = _Seeds(1000) # the same seeds in every batch: a column's shape does not depend on the batch
598
+ late = _Seeds(5000) # constraints draw from their own range, so adding one does not move a column's values
599
+ exprs = []
600
+ for c in known:
601
+ t = types[c["name"]]
602
+ nullable = not meta.get(c["name"], {}).get("notnull")
603
+ scale = _size_scale(c["name"], fixtures or [], placed or {})
604
+ value = _with_fixtures(column_expr(c, t, seeds, nullable, realism, scale), c["name"], t, conditions)
605
+ exprs.append(f"{finish(value, c['name'], late)} AS {ident(c['name'])}")
606
+ for name in extra:
607
+ info = meta.get(name, {})
608
+ fallback = required_expr(types[name], info) if info.get("notnull") and not info.get("identity") else f"CAST(NULL AS {types[name]})"
609
+ exprs.append(f"{_with_fixtures(fallback, name, types[name], conditions)} AS {ident(name)}")
610
+ exprs += [f"{required_expr(types[name], meta.get(name, {}))} AS {ident(name)}" for name in needed]
611
+ names = [c["name"] for c in known] + extra + needed
612
+ cols = ", ".join(ident(x) for x in names)
613
+ series = f"generate_series({offset}::bigint, {offset + n - 1}::bigint) AS number"
614
+ if not relations:
615
+ out.append(f"INSERT INTO {qualified(table)} ({cols}) {overriding}SELECT {', '.join(exprs)} FROM {series} ON CONFLICT DO NOTHING")
616
+ else:
617
+ # Only the columns a relation touches go through the joins, as narrow rows that are cheap to put back in
618
+ # row-number order; every other column is computed from the row number afterwards. Joining and sorting whole
619
+ # rows wrote each wide row to a sort file first.
620
+ involved = {r["column"] for r in relations} | {c for r in relations for c, _ in r.get("same") or []}
621
+ narrow = [x for x in names if x in involved]
622
+ by_name = dict(zip(names, exprs))
623
+ rows_sql = f"SELECT number, {', '.join(by_name[x] for x in narrow)} FROM {series}"
624
+ for i, rel in enumerate(relations):
625
+ rows_sql = _relation_layer(rows_sql, narrow, types, rel, RELATION_SEED + i)
626
+ select = ", ".join(f"codecop_rows.{ident(x)}" if x in involved else by_name[x] for x in names)
627
+ out.append(f"INSERT INTO {qualified(table)} ({cols}) {overriding}SELECT {select} FROM "
628
+ f"(SELECT * FROM ({rows_sql}) codecop_joined ORDER BY number) codecop_rows ON CONFLICT DO NOTHING")
629
+ offset += n
630
+ return out