@capagents/forgeqe 2.10.5 → 3.0.0

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 (110) hide show
  1. package/HOW_TO_USE.md +93 -19
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/dist/docs-site/docs/index.html +78 -16
  4. package/dist/docs-site/docs/search.js +1 -1
  5. package/dist/forgeqe.js +1946 -1929
  6. package/dist/web/assets/Agent-DISh0THc.js +8 -0
  7. package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
  8. package/dist/web/assets/Browse-WylAQZvD.js +2 -0
  9. package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
  10. package/dist/web/assets/{CommandPalette-D7ufvlUN.js → CommandPalette-CkreEJ8R.js} +1 -1
  11. package/dist/web/assets/Compare-CgOfZofk.js +1 -0
  12. package/dist/web/assets/{Cost-DGZ5t-Q_.js → Cost-Dl5-viu4.js} +1 -1
  13. package/dist/web/assets/{Data-DqGA1ZtQ.js → Data-Bv2S5wkW.js} +4 -4
  14. package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
  15. package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
  16. package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
  17. package/dist/web/assets/{Explore-TtfTWmGW.js → Explore-c85VGE9Q.js} +2 -2
  18. package/dist/web/assets/{Features-DazoSiEi.js → Features-DXL_vSjn.js} +1 -1
  19. package/dist/web/assets/{Flags-Brja-ZXF.js → Flags-B7x2pDud.js} +2 -2
  20. package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
  21. package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
  22. package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
  23. package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
  24. package/dist/web/assets/Migration-BOLN1duU.js +2 -0
  25. package/dist/web/assets/Product-C0FeEaJg.js +7 -0
  26. package/dist/web/assets/Production-BSMQyWKd.js +1 -0
  27. package/dist/web/assets/{Quality-C4Aak_hw.js → Quality-DsM9gWZb.js} +1 -1
  28. package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
  29. package/dist/web/assets/Record-CPx-lK53.js +2 -0
  30. package/dist/web/assets/Regression-BXbX46nO.js +5 -0
  31. package/dist/web/assets/{RelationGraph-DLeEarQd.js → RelationGraph-eoGXXz5t.js} +1 -1
  32. package/dist/web/assets/{Reports-ClSAzQOh.js → Reports-36YQzVhA.js} +2 -2
  33. package/dist/web/assets/Response-DplUOsue.js +4 -0
  34. package/dist/web/assets/{RunDiff-0ibEcmI5.js → RunDiff-D0fDhRmK.js} +1 -1
  35. package/dist/web/assets/{Runs-T8yF8Hi0.js → Runs-Bv1Ef8zq.js} +2 -2
  36. package/dist/web/assets/{Steps-CB30w6BA.js → Steps-Cm-atRtk.js} +2 -2
  37. package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
  38. package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
  39. package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
  40. package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
  41. package/dist/web/assets/{WhatsNew-D7n48IsG.js → WhatsNew-CdnbMvrr.js} +1 -1
  42. package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
  43. package/dist/web/assets/{dataParts-CZAcb4L_.js → dataParts-Bn-tzbKg.js} +3 -3
  44. package/dist/web/assets/{families-D2ygriY6.js → families-DPlFfKf2.js} +1 -1
  45. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  46. package/dist/web/assets/{fold-BhYvId2X.js → fold-BhRpA0sy.js} +1 -1
  47. package/dist/web/assets/frame-D_TPoUTD.js +16 -0
  48. package/dist/web/assets/index-BRB-oAMd.js +67 -0
  49. package/dist/web/assets/index-CIw5WfL8.css +2 -0
  50. package/dist/web/assets/{logos-DmK40tlV.js → logos-839CfoKx.js} +1 -1
  51. package/dist/web/assets/{markdown-Bej6qyls.js → markdown-6z0km3hN.js} +3 -3
  52. package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
  53. package/dist/web/assets/{parts-BOpbd90H.js → parts-VPcxh6Jc.js} +1 -1
  54. package/dist/web/assets/{productParts-B3_FGd-T.js → productParts-BjfWgMtq.js} +1 -1
  55. package/dist/web/assets/{qualityParts-B8yJRVpP.js → qualityParts-PGN65yfI.js} +1 -1
  56. package/dist/web/assets/{recordTest-CZUrGm8I.js → recordTest-EkxSMWbe.js} +1 -1
  57. package/dist/web/assets/{rows-BcG6gFCy.js → rows-uLoguIo5.js} +1 -1
  58. package/dist/web/assets/{segmented-ffWUfF8N.js → segmented-DphDskQz.js} +1 -1
  59. package/dist/web/assets/{usePageChat-T6vQY_1C.js → usePageChat-DqEwGcyO.js} +1 -1
  60. package/dist/web/index.html +5 -5
  61. package/docs/user-guide.html +78 -16
  62. package/package.json +3 -1
  63. package/prompts/requests-rule.md +1 -1
  64. package/prompts/talk-summary.md +43 -0
  65. package/prompts/talk.md +49 -0
  66. package/prompts/test-agent.md +1 -0
  67. package/py/forgeqe_data/__init__.py +1 -0
  68. package/py/forgeqe_data/__main__.py +12 -0
  69. package/py/forgeqe_data/connect.py +290 -0
  70. package/py/forgeqe_data/connstr.py +169 -0
  71. package/py/forgeqe_data/flows.py +603 -0
  72. package/py/forgeqe_data/guard.py +214 -0
  73. package/py/forgeqe_data/mongo.py +219 -0
  74. package/py/forgeqe_data/schema.py +431 -0
  75. package/py/forgeqe_data/service.py +651 -0
  76. package/py/forgeqe_data/streams.py +400 -0
  77. package/py/forgeqe_data/subset.py +299 -0
  78. package/py/forgeqe_data/testdata.py +861 -0
  79. package/py/forgeqe_data/vector.py +113 -0
  80. package/py/forgeqe_talk/__init__.py +1 -0
  81. package/py/forgeqe_talk/__main__.py +65 -0
  82. package/py/forgeqe_voice/worker.py +24 -4
  83. package/dist/web/assets/Agent-bSVNDlcU.js +0 -8
  84. package/dist/web/assets/ApiTests-DOxGgoZC.js +0 -10
  85. package/dist/web/assets/Browse-CG8jzqR1.js +0 -2
  86. package/dist/web/assets/Chat-DzufzeGg.js +0 -5
  87. package/dist/web/assets/Compare-6vHuAaKv.js +0 -1
  88. package/dist/web/assets/Desktop-CSOFE8cN.js +0 -1
  89. package/dist/web/assets/DesktopReview-BWtionFH.js +0 -1
  90. package/dist/web/assets/Evidence-D8pLFcbr.js +0 -1
  91. package/dist/web/assets/Flaky-jJlHFFCa.js +0 -1
  92. package/dist/web/assets/Impact-b60dmhJK.js +0 -3
  93. package/dist/web/assets/Jobs-Y9W9nBgx.js +0 -5
  94. package/dist/web/assets/KindPage-Y72w2UwG.js +0 -6
  95. package/dist/web/assets/Migration-CvIeTB9p.js +0 -2
  96. package/dist/web/assets/Product-BEe2GyO6.js +0 -7
  97. package/dist/web/assets/Production-D2qmPFYy.js +0 -1
  98. package/dist/web/assets/Readiness-ClXnnmLo.js +0 -1
  99. package/dist/web/assets/Record-LaLYhQgk.js +0 -2
  100. package/dist/web/assets/Regression-DKz05MC_.js +0 -5
  101. package/dist/web/assets/Response-De60pk_7.js +0 -10
  102. package/dist/web/assets/TestCases-Ba6bUE4i.js +0 -1
  103. package/dist/web/assets/TestData-DefDzeMW.js +0 -2
  104. package/dist/web/assets/TestDebt-zohltDHp.js +0 -1
  105. package/dist/web/assets/Tosca-jAtdiG28.js +0 -3
  106. package/dist/web/assets/filters-CYaF2RvC.js +0 -1
  107. package/dist/web/assets/frame-DeJBYtBX.js +0 -11
  108. package/dist/web/assets/index-CYlacOTX.css +0 -2
  109. package/dist/web/assets/index-DXpBYobT.js +0 -67
  110. package/dist/web/assets/paletteCommands-CKBMmhb4.js +0 -1
@@ -0,0 +1,861 @@
1
+ """
2
+ Test data from a spec: realistic rows that fit the schema, parents before children, the same rows for the same seed.
3
+
4
+ A spec (YAML in the project, read by ForgeQE and sent here as JSON) names tables, how many rows, and rules for the
5
+ columns that matter; every other column is filled from the schema: its type and size, NOT NULL, unique keys, CHECK
6
+ constraints with a list or bounds, enum types, and its name (email, phone, city, created_at). Keys the database makes
7
+ (serial, identity, auto-increment) are left to it.
8
+
9
+ seed: 42
10
+ locale: en_IN
11
+ edge_cases: true # a few rows per table at the limits: longest text, unicode, zero, nulls where allowed
12
+ tables:
13
+ customers:
14
+ rows: 20
15
+ columns:
16
+ email: {faker: email, unique: true}
17
+ country: {one_of: [IN, UK, US], weights: [5, 3, 2]}
18
+ orders:
19
+ per: {customers: [0, 4]} # each customer gets 0 to 4 orders
20
+ columns:
21
+ status: {one_of: [NEW, PAID, SHIPPED, CANCELLED]}
22
+ total: {range: [5, 500], decimals: 2}
23
+ placed_at: {date_between: ["-90d", "today"]}
24
+ reference: {sequence: "ORD-{n:05d}"}
25
+
26
+ Rules: a plain value; ``faker`` (a Faker method, with ``args``); ``one_of`` (with ``weights``); ``range`` (with
27
+ ``decimals``); ``date_between``; ``sequence`` (``{n}`` counts from 1); ``bothify`` (``#`` a digit, ``?`` a letter);
28
+ ``ref`` (``table.column``: a row of a table in the spec, or one already in the database); ``null_ratio``; ``unique``.
29
+
30
+ Rows go to files (csv, json, sql) or into a database marked writable: in one transaction, with every key recorded
31
+ in a batch file so the batch can be removed again, children first. Statements are built by SQLAlchemy with bound
32
+ values; no SQL is taken from the spec.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import csv
37
+ import datetime as dt
38
+ import decimal
39
+ import json
40
+ import random
41
+ import re
42
+ import time
43
+ import uuid
44
+ from dataclasses import dataclass, field
45
+ from pathlib import Path
46
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple
47
+
48
+ MAX_ROWS = 100_000
49
+ MAX_TABLES = 50
50
+ UNIQUE_TRIES = 60
51
+ FORMATS = ("csv", "json", "sql")
52
+ RULE_KEYS = {"value", "faker", "args", "one_of", "weights", "range", "decimals", "date_between", "sequence", "bothify", "ref", "via", "template", "null_ratio", "unique"}
53
+ # Rows inserted per statement where the database returns the keys it makes in order.
54
+ BULK = 500
55
+ # Faker methods that change Faker itself rather than make a value.
56
+ _FAKER_DENY = re.compile(r"^(seed|add_|get_|set_|provider|parse$|format$|random$|weights$|factories|locales|unique$|optional$|items$)")
57
+ EDGE_TEXT = ["Zoë Ørsted-Łukasz 漢字 ✓", "O'Brien; DROP TABLE x --", " leading and trailing ", "😀 emoji"]
58
+
59
+
60
+ class SpecError(ValueError):
61
+ pass
62
+
63
+
64
+ @dataclass
65
+ class Ref:
66
+ """A key that points at a parent row: its index in the rows made here, or a key read from the database."""
67
+ table: str
68
+ column: str
69
+ index: Optional[int] = None
70
+ value: Any = None
71
+
72
+
73
+ @dataclass
74
+ class TablePlan:
75
+ name: str
76
+ count: int = 0
77
+ per: Optional[Tuple[str, int, int]] = None
78
+ rules: Dict[str, Dict[str, Any]] = field(default_factory=dict)
79
+
80
+
81
+ # --------------------------------------------------------------------------------------------------- the spec
82
+
83
+
84
+ def _rule(raw: Any, where: str) -> Dict[str, Any]:
85
+ if not isinstance(raw, dict):
86
+ return {"value": raw}
87
+ unknown = set(raw) - RULE_KEYS
88
+ if unknown:
89
+ raise SpecError(f"{where}: unknown rule {', '.join(sorted(unknown))} (rules: {', '.join(sorted(RULE_KEYS))})")
90
+ if "faker" in raw:
91
+ name = str(raw["faker"])
92
+ if not re.fullmatch(r"[a-z][a-z0-9_]*", name) or _FAKER_DENY.match(name):
93
+ raise SpecError(f"{where}: faker {name!r} is not a value generator")
94
+ args = raw.get("args") or {}
95
+ if not isinstance(args, dict) or not all(isinstance(v, (str, int, float, bool, type(None), list)) for v in args.values()):
96
+ raise SpecError(f"{where}: faker args must be a mapping of plain values")
97
+ if "one_of" in raw and (not isinstance(raw["one_of"], list) or not raw["one_of"]):
98
+ raise SpecError(f"{where}: one_of must be a non-empty list")
99
+ if "weights" in raw and (not isinstance(raw["weights"], list) or len(raw["weights"]) != len(raw.get("one_of") or [])):
100
+ raise SpecError(f"{where}: weights must have one number per one_of value")
101
+ if "range" in raw and (not isinstance(raw["range"], list) or len(raw["range"]) != 2):
102
+ raise SpecError(f"{where}: range is [min, max]")
103
+ if "date_between" in raw and (not isinstance(raw["date_between"], list) or len(raw["date_between"]) != 2):
104
+ raise SpecError(f"{where}: date_between is [start, end], for example ['-1y', 'today']")
105
+ if "ref" in raw and not re.fullmatch(r"[\w$#.]+\.[\w$#]+", str(raw["ref"])):
106
+ raise SpecError(f"{where}: ref is table.column")
107
+ if "via" in raw and ("ref" not in raw or not re.fullmatch(r"[\w$#]+", str(raw["via"]))):
108
+ raise SpecError(f"{where}: via names this table's key column whose parent row ref reads, for example {{ref: products.price, via: product_id}}")
109
+ if "template" in raw:
110
+ _fields(str(raw["template"]), where)
111
+ if "sequence" in raw and set(_fields(str(raw["sequence"]), where)) - {"n"}:
112
+ raise SpecError(f"{where}: sequence counts with {{n}} only, for example ORD-{{n:05d}}")
113
+ if "null_ratio" in raw and not (isinstance(raw["null_ratio"], (int, float)) and 0 <= raw["null_ratio"] <= 1):
114
+ raise SpecError(f"{where}: null_ratio is between 0 and 1")
115
+ return dict(raw)
116
+
117
+
118
+ def _fields(text: str, where: str) -> List[str]:
119
+ """The fields of a template: plain column names only; {x.attr} and {x[0]} reach into Python objects and are refused."""
120
+ import string
121
+
122
+ names: List[str] = []
123
+ try:
124
+ parsed = list(string.Formatter().parse(text))
125
+ except ValueError as err:
126
+ raise SpecError(f"{where}: {err}") from None
127
+ for _, field_name, spec, conversion in parsed:
128
+ if field_name is None:
129
+ continue
130
+ if not re.fullmatch(r"[A-Za-z_][\w$#]*", field_name) or conversion or (spec and "{" in spec):
131
+ raise SpecError(f"{where}: {{{field_name}}} is not allowed; a template names columns of the row, as {{first_name}}")
132
+ names.append(field_name)
133
+ return names
134
+
135
+
136
+ def _format(text: str, values: Mapping[str, Any]) -> str:
137
+ return text.format(**{k: "" if v is None else v for k, v in values.items()})
138
+
139
+
140
+ def plan(spec: Mapping[str, Any], catalog: Mapping[str, Any]) -> List[TablePlan]:
141
+ """The spec checked against the catalog, in the order rows must be made: every table after the tables it refers to."""
142
+ tables = spec.get("tables")
143
+ if not isinstance(tables, dict) or not tables:
144
+ raise SpecError("tables: name at least one table")
145
+ if len(tables) > MAX_TABLES:
146
+ raise SpecError(f"tables: at most {MAX_TABLES} tables in one spec")
147
+ known = catalog.get("tables") or {}
148
+ plans: Dict[str, TablePlan] = {}
149
+ for name, raw in tables.items():
150
+ where = f"tables.{name}"
151
+ if name not in known:
152
+ raise SpecError(f"{where}: no such table in the database" + _suggest(name, known))
153
+ raw = raw or {}
154
+ if not isinstance(raw, dict):
155
+ raise SpecError(f"{where} must be a mapping")
156
+ p = TablePlan(name)
157
+ if "per" in raw:
158
+ per = raw["per"]
159
+ if not (isinstance(per, dict) and len(per) == 1):
160
+ raise SpecError(f"{where}.per is one parent table with [min, max] rows each, for example per: {{customers: [1, 3]}}")
161
+ parent, span = next(iter(per.items()))
162
+ if parent not in tables:
163
+ raise SpecError(f"{where}.per: {parent} is not a table of the spec")
164
+ if not (isinstance(span, list) and len(span) == 2 and all(isinstance(x, int) and x >= 0 for x in span) and span[0] <= span[1]):
165
+ raise SpecError(f"{where}.per.{parent} is [min, max]")
166
+ if not _fk_to(known[name], parent, known):
167
+ raise SpecError(f"{where}.per: {name} has no foreign key to {parent}, and no column named {_singular(parent)}_id")
168
+ p.per = (parent, span[0], span[1])
169
+ else:
170
+ rows = raw.get("rows", 10)
171
+ if not isinstance(rows, int) or rows < 0:
172
+ raise SpecError(f"{where}.rows must be a whole number")
173
+ p.count = rows
174
+ cols = {c["name"] for c in known[name]["columns"]}
175
+ for col, rule in (raw.get("columns") or {}).items():
176
+ if col not in cols:
177
+ raise SpecError(f"{where}.columns.{col}: no such column" + _suggest(col, {c: 1 for c in cols}))
178
+ p.rules[col] = _rule(rule, f"{where}.columns.{col}")
179
+ plans[name] = p
180
+ return _ordered(plans, known)
181
+
182
+
183
+ def _suggest(name: str, options: Mapping[str, Any]) -> str:
184
+ import difflib
185
+
186
+ near = difflib.get_close_matches(name, list(options), n=3, cutoff=0.6) or [o for o in options if name.lower() in o.lower()][:3]
187
+ return f" (did you mean {', '.join(near)}?)" if near else ""
188
+
189
+
190
+ def _fk_to(table: Mapping[str, Any], parent: str, known: Optional[Mapping[str, Any]] = None) -> Optional[Dict[str, Any]]:
191
+ """The key from `table` to `parent`: a declared foreign key, else (given the catalog) a column named for the parent."""
192
+ declared = next((fk for fk in table.get("fks", []) if fk["table"] == parent and len(fk["columns"]) == 1), None)
193
+ return declared or (_logical_fk(table, parent, known) if known is not None else None)
194
+
195
+
196
+ def _fks(table: Mapping[str, Any], spec_tables: Mapping[str, Any], known: Mapping[str, Any]) -> List[Dict[str, Any]]:
197
+ """Declared foreign keys, and keys by name to tables of the spec that have no declared one."""
198
+ out = list(table.get("fks", []))
199
+ declared = {fk["table"] for fk in out}
200
+ for parent in spec_tables:
201
+ if parent not in declared and parent != table.get("name"):
202
+ fk = _logical_fk(table, parent, known)
203
+ if fk and fk["columns"][0] not in {c for f in out for c in f["columns"]}:
204
+ out.append(fk)
205
+ return out
206
+
207
+
208
+ def _singular(word: str) -> str:
209
+ w = word.lower()
210
+ return w[:-3] + "y" if w.endswith("ies") else w[:-2] if w.endswith(("ses", "xes")) else w[:-1] if w.endswith("s") and not w.endswith("ss") else w
211
+
212
+
213
+ def _logical_fk(table: Mapping[str, Any], parent: str, known: Mapping[str, Any]) -> Optional[Dict[str, Any]]:
214
+ """Schemas that declare no foreign keys name them: orders.customer_id refers to customers' single-column key."""
215
+ pk = (known.get(parent) or {}).get("pk") or []
216
+ if len(pk) != 1:
217
+ return None
218
+ names = {c["name"].lower(): c["name"] for c in table.get("columns", [])}
219
+ base = parent.lower().split(".")[-1]
220
+ for candidate in (f"{_singular(base)}_id", f"{base}_id", f"{_singular(base)}id"):
221
+ if candidate in names:
222
+ return {"columns": [names[candidate]], "table": parent, "references": pk, "logical": True}
223
+ return None
224
+
225
+
226
+ def _ordered(plans: Dict[str, TablePlan], known: Mapping[str, Any]) -> List[TablePlan]:
227
+ deps: Dict[str, Set[str]] = {}
228
+ for name, p in plans.items():
229
+ d = {fk["table"] for fk in _fks(known[name], plans, known) if fk["table"] in plans and fk["table"] != name}
230
+ d |= {r["ref"].rsplit(".", 1)[0] for r in p.rules.values() if "ref" in r and r["ref"].rsplit(".", 1)[0] in plans and r["ref"].rsplit(".", 1)[0] != name}
231
+ if p.per:
232
+ d.add(p.per[0])
233
+ deps[name] = d
234
+ out: List[TablePlan] = []
235
+ done: Set[str] = set()
236
+ while len(out) < len(plans):
237
+ ready = [n for n in plans if n not in done and deps[n] <= done]
238
+ if not ready:
239
+ # A cycle: the table whose keys into the others can be left empty goes first.
240
+ ready = [min((n for n in plans if n not in done), key=lambda n: len(deps[n] - done))]
241
+ for n in ready:
242
+ out.append(plans[n])
243
+ done.add(n)
244
+ return out
245
+
246
+
247
+ # --------------------------------------------------------------------------------------------------- values
248
+
249
+ _RELATIVE = re.compile(r"^([+-]?\d+)([dwmy])$")
250
+
251
+
252
+ def _date(text: Any, today: dt.date) -> dt.date:
253
+ if isinstance(text, (dt.date, dt.datetime)):
254
+ return text if isinstance(text, dt.date) and not isinstance(text, dt.datetime) else text.date()
255
+ s = str(text).strip().lower()
256
+ if s in ("today", "now"):
257
+ return today
258
+ m = _RELATIVE.match(s)
259
+ if m:
260
+ n, unit = int(m.group(1)), m.group(2)
261
+ return today + dt.timedelta(days=n * {"d": 1, "w": 7, "m": 30, "y": 365}[unit])
262
+ try:
263
+ return dt.date.fromisoformat(s[:10])
264
+ except ValueError:
265
+ raise SpecError(f"date {text!r}: use YYYY-MM-DD, today, or -30d, -6m, +1y") from None
266
+
267
+
268
+ # Column names to Faker methods: what a realistic value for that name looks like.
269
+ _BY_NAME: List[Tuple[re.Pattern[str], str]] = [
270
+ (re.compile(p, re.IGNORECASE), f)
271
+ for p, f in [
272
+ (r"pass(word|wd)?_?hash|digest|checksum|(^|_)hash$", "sha256"), (r"pass(word|wd)?$|(^|_)pwd$", "password"), (r"token|api_?key|secret", "sha1"),
273
+ (r"e_?mail", "email"), (r"(^|_)(first_?name|given_?name|fname)$", "first_name"), (r"(^|_)(last_?name|surname|family_?name|lname)$", "last_name"),
274
+ (r"(^|_)(full_?name|customer_?name|contact_?name|display_?name)$", "name"), (r"user_?name|login", "user_name"),
275
+ (r"phone|mobile|tel", "phone_number"), (r"(^|_)(city|town)$", "city"), (r"(^|_)country(_?code)?$", "country_code"),
276
+ (r"(^|_)(state|province|region)$", "state"), (r"zip|post(al)?_?code", "postcode"), (r"street|address", "street_address"),
277
+ (r"company|employer|organi[sz]ation", "company"), (r"(^|_)url$|website|homepage", "url"), (r"(^|_)ip(_?address)?$", "ipv4"),
278
+ (r"iban", "iban"), (r"(^|_)(title|subject|headline)$", "sentence"), (r"description|comment|note|remarks|bio|summary", "paragraph"),
279
+ (r"(^|_)(job|position|role_?title)$", "job"), (r"currency", "currency_code"), (r"color|colour", "color_name"),
280
+ (r"(^|_)(sku|code|ref(erence)?)$", "bothify"), (r"(^|_)name$", "name"),
281
+ ]
282
+ ]
283
+
284
+
285
+ class Values:
286
+ """Makes the values of one run: one random source, so a seed gives the same rows."""
287
+
288
+ def __init__(self, seed: int, locale: str, today: dt.date) -> None:
289
+ from faker import Faker
290
+
291
+ self.rng = random.Random(seed)
292
+ try:
293
+ self.fake = Faker(locale or "en_US")
294
+ except AttributeError:
295
+ raise SpecError(f"locale {locale!r} is not one Faker knows (en_US, en_GB, en_IN, de_DE, fr_FR, ...)") from None
296
+ self.fake.seed_instance(seed)
297
+ self.today = today
298
+ self.sequences: Dict[str, int] = {}
299
+
300
+ def faker(self, name: str, args: Mapping[str, Any], where: str) -> Any:
301
+ fn = getattr(self.fake, name, None)
302
+ if fn is None or not callable(fn):
303
+ raise SpecError(f"{where}: Faker has no {name}")
304
+ try:
305
+ return fn(**dict(args))
306
+ except TypeError as err:
307
+ raise SpecError(f"{where}: faker {name}: {err}") from None
308
+
309
+ def rule(self, rule: Mapping[str, Any], col: Mapping[str, Any], key: str, where: str) -> Any:
310
+ if rule.get("null_ratio") and self.rng.random() < float(rule["null_ratio"]):
311
+ return None
312
+ if "value" in rule:
313
+ return rule["value"]
314
+ if "one_of" in rule:
315
+ return self.rng.choices(rule["one_of"], weights=rule.get("weights"))[0]
316
+ if "range" in rule:
317
+ lo, hi = rule["range"]
318
+ places = rule.get("decimals")
319
+ if places is None and isinstance(lo, int) and isinstance(hi, int):
320
+ return self.rng.randint(lo, hi)
321
+ return round(self.rng.uniform(float(lo), float(hi)), int(places if places is not None else 2))
322
+ if "date_between" in rule:
323
+ start, end = (_date(x, self.today) for x in rule["date_between"])
324
+ day = start + dt.timedelta(days=self.rng.randint(0, max(0, (end - start).days)))
325
+ return self._as_time(day, col)
326
+ if "sequence" in rule:
327
+ n = self.sequences[key] = self.sequences.get(key, 0) + 1
328
+ return _format(str(rule["sequence"]), {"n": n})
329
+ if "bothify" in rule:
330
+ return self.fake.bothify(str(rule["bothify"]))
331
+ if "faker" in rule:
332
+ return self.faker(rule["faker"], rule.get("args") or {}, where)
333
+ return self.infer(col, key)
334
+
335
+ def _as_time(self, day: dt.date, col: Mapping[str, Any]) -> Any:
336
+ kind = (col.get("python") or "").lower()
337
+ if kind == "datetime" or "TIME" in col.get("type", "").upper() and "DATE" in col.get("type", "").upper() or "TIMESTAMP" in col.get("type", "").upper():
338
+ return dt.datetime.combine(day, dt.time(self.rng.randint(8, 19), self.rng.randint(0, 59), self.rng.randint(0, 59)))
339
+ return day
340
+
341
+ def infer(self, col: Mapping[str, Any], key: str) -> Any:
342
+ """A value from the column alone: its CHECK list or enum, its name, then its type."""
343
+ if col.get("enum"):
344
+ return self.rng.choice(col["enum"])
345
+ if col.get("check_values"):
346
+ return self.rng.choice(col["check_values"])
347
+ kind = (col.get("python") or "").lower()
348
+ type_ = col.get("type", "").upper()
349
+ name = col["name"]
350
+ lo, hi = col.get("check_range") or (None, None)
351
+ if kind in ("str", "") and not any(t in type_ for t in ("INT", "NUM", "DEC", "FLOAT", "REAL", "DOUBLE", "DATE", "TIME", "BOOL", "BIT", "UUID", "JSON", "BLOB", "BINARY", "BYTEA")):
352
+ for pattern, method in _BY_NAME:
353
+ if pattern.search(name):
354
+ value = self.fake.bothify("???-#####").upper() if method == "bothify" else getattr(self.fake, method)()
355
+ return value
356
+ return self.fake.word() if (col.get("length") or 255) < 24 else self.fake.sentence(nb_words=4).rstrip(".")
357
+ if kind == "bool" or "BOOL" in type_ or type_ == "BIT":
358
+ return self.rng.random() < 0.5
359
+ if kind == "int" or "INT" in type_:
360
+ low = int(lo) if lo is not None else (1 if re.search(r"(qty|quantity|count|age)", name, re.I) else 0)
361
+ high = int(hi) if hi is not None else (99 if low >= 0 and re.search(r"(qty|quantity|count|age)", name, re.I) else 10_000)
362
+ return self.rng.randint(low, max(low, high))
363
+ if kind in ("decimal", "float") or any(t in type_ for t in ("NUM", "DEC", "FLOAT", "REAL", "DOUBLE", "MONEY")):
364
+ scale = col.get("scale") if isinstance(col.get("scale"), int) else 2
365
+ precision = col.get("precision") if isinstance(col.get("precision"), int) else 10
366
+ top = min(10 ** (precision - scale) - 1, float(hi) if hi is not None else 10_000)
367
+ bottom = float(lo) if lo is not None else 0.0
368
+ return decimal.Decimal(str(round(self.rng.uniform(bottom, max(bottom, top)), scale)))
369
+ if kind in ("datetime", "date") or "DATE" in type_ or "TIME" in type_:
370
+ day = self.today - dt.timedelta(days=self.rng.randint(0, 365))
371
+ return self._as_time(day, col) if kind != "date" else day
372
+ if kind == "uuid" or "UUID" in type_ or "UNIQUEIDENTIFIER" in type_:
373
+ return str(uuid.UUID(int=self.rng.getrandbits(128), version=4))
374
+ if "JSON" in type_:
375
+ return json.dumps({"generated": True, "n": self.rng.randint(1, 100)})
376
+ if any(t in type_ for t in ("BLOB", "BINARY", "BYTEA")):
377
+ return bytes(self.rng.getrandbits(8) for _ in range(8))
378
+ return self.fake.word()
379
+
380
+
381
+ def _check_hints(table: Mapping[str, Any]) -> Dict[str, Dict[str, Any]]:
382
+ """What simple CHECK constraints say about a column: a list of values (IN, or ORs of =) or bounds."""
383
+ hints: Dict[str, Dict[str, Any]] = {}
384
+ for text in table.get("checks") or []:
385
+ m = re.search(r"\(?\s*[\"`\[]?(\w+)[\"`\]]?\s*\)?\s*(?:::\w+)?\s*\)?\s*(?:IN|=\s*ANY)\s*\(+(?:ARRAY\s*\[)?(.+?)\]?\)+", text, re.IGNORECASE)
386
+ if m:
387
+ values = re.findall(r"'((?:[^']|'')*)'", m.group(2))
388
+ if values:
389
+ hints.setdefault(m.group(1), {})["check_values"] = [v.replace("''", "'") for v in values]
390
+ continue
391
+ ors = re.findall(r"[\"`\[]?(\w+)[\"`\]]?\s*(?:::\w+)?\s*=\s*'((?:[^']|'')*)'", text)
392
+ if len(ors) > 1 and len({c for c, _ in ors}) == 1:
393
+ hints.setdefault(ors[0][0], {})["check_values"] = [v for _, v in ors]
394
+ continue
395
+ for col, op, num in re.findall(r"[\"`\[]?(\w+)[\"`\]]?\s*(>=|>|<=|<)\s*\(?(-?\d+(?:\.\d+)?)", text):
396
+ lo, hi = hints.setdefault(col, {}).get("check_range") or (None, None)
397
+ n = float(num)
398
+ if op in (">", ">="):
399
+ lo = n + (1 if op == ">" else 0)
400
+ else:
401
+ hi = n - (1 if op == "<" else 0)
402
+ hints[col]["check_range"] = (lo, hi)
403
+ m = re.search(r"[\"`\[]?(\w+)[\"`\]]?\s+BETWEEN\s+(-?\d+(?:\.\d+)?)\s+AND\s+(-?\d+(?:\.\d+)?)", text, re.IGNORECASE)
404
+ if m:
405
+ hints.setdefault(m.group(1), {})["check_range"] = (float(m.group(2)), float(m.group(3)))
406
+ return hints
407
+
408
+
409
+ # --------------------------------------------------------------------------------------------------- rows
410
+
411
+
412
+ @dataclass
413
+ class Generated:
414
+ order: List[str]
415
+ rows: Dict[str, List[Dict[str, Any]]]
416
+ # Columns the database fills (serial, identity): left out of the rows, filled back in when rows are inserted.
417
+ generated: Dict[str, List[str]]
418
+ warnings: List[str]
419
+ # For files: the columns the database would fill, numbered here (1, 2, ...) so files keep their references.
420
+ numbered: Dict[str, List[str]] = field(default_factory=dict)
421
+
422
+
423
+ def _generated_cols(table: Mapping[str, Any], dialect: str) -> List[str]:
424
+ cols = [c["name"] for c in table["columns"] if c.get("generated") or c.get("computed")]
425
+ pk = table.get("pk") or []
426
+ if not cols and dialect == "sqlite" and len(pk) == 1:
427
+ col = next((c for c in table["columns"] if c["name"] == pk[0]), None)
428
+ if col and "INT" in col["type"].upper():
429
+ cols = [pk[0]]
430
+ return cols
431
+
432
+
433
+ def generate(
434
+ spec: Mapping[str, Any],
435
+ catalog: Mapping[str, Any],
436
+ *,
437
+ dialect: str = "",
438
+ existing: Optional[Callable[[str, str], List[Any]]] = None,
439
+ lookup: Optional[Callable[[str, str, Any, str], Any]] = None,
440
+ for_files: bool = False,
441
+ today: Optional[dt.date] = None,
442
+ ) -> Generated:
443
+ """
444
+ The rows of a spec. `existing(table, column)` gives keys already in the database, for a ref to a table outside the
445
+ spec, and `lookup(table, key_column, key, column)` a column of one of those rows (for via). With `for_files`, keys
446
+ the database would make are numbered here (1, 2, ...) so files keep their references.
447
+ """
448
+ plans = plan(spec, catalog)
449
+ seed = spec.get("seed", 1)
450
+ if not isinstance(seed, int):
451
+ raise SpecError("seed must be a whole number")
452
+ values = Values(seed, str(spec.get("locale") or "en_US"), today or dt.date.today())
453
+ known = catalog["tables"]
454
+ rows: Dict[str, List[Dict[str, Any]]] = {}
455
+ generated: Dict[str, List[str]] = {}
456
+ warnings: List[str] = []
457
+ total = 0
458
+ numbered: Dict[str, List[str]] = {}
459
+
460
+ for p in plans:
461
+ table = known[p.name]
462
+ gen_cols = _generated_cols(table, dialect)
463
+ generated[p.name] = [] if for_files else gen_cols
464
+ hints = _check_hints(table)
465
+ cols = [{**c, **hints.get(c["name"], {})} for c in table["columns"]]
466
+ uniques = [set(u) for u in table.get("unique") or []] + ([set(table["pk"])] if table.get("pk") else [])
467
+ seen: Dict[Tuple[str, ...], Set[Tuple[Any, ...]]] = {tuple(sorted(u)): set() for u in uniques}
468
+ for col, rule in p.rules.items():
469
+ if rule.get("unique"):
470
+ seen.setdefault((col,), set())
471
+ # Keys to other tables: those the spec makes, else keys already in the database.
472
+ fks: Dict[str, Ref] = {}
473
+ for fk in _fks({**table, "name": p.name}, {q.name: q for q in plans}, known):
474
+ if len(fk["columns"]) != 1:
475
+ continue
476
+ if fk.get("logical"):
477
+ warnings.append(f"{p.name}.{fk['columns'][0]}: no foreign key is declared; it refers to {fk['table']} by its name")
478
+ col = fk["columns"][0]
479
+ if col in p.rules and "ref" not in p.rules[col]:
480
+ continue
481
+ fks[col] = Ref(fk["table"], fk["references"][0])
482
+ for col, rule in p.rules.items():
483
+ if "ref" in rule and "via" not in rule:
484
+ t, c = rule["ref"].rsplit(".", 1)
485
+ fks[col] = Ref(t, c)
486
+ for col, rule in p.rules.items():
487
+ if "via" in rule:
488
+ via = rule["via"]
489
+ if via not in fks:
490
+ raise SpecError(f"tables.{p.name}.columns.{col}: via {via} is not a key of {p.name} to another table")
491
+ if fks[via].table != rule["ref"].rsplit(".", 1)[0]:
492
+ raise SpecError(f"tables.{p.name}.columns.{col}: {via} refers to {fks[via].table}, not {rule['ref'].rsplit('.', 1)[0]}")
493
+ if fks[via].table in {q.name for q in plans} and rule["ref"].rsplit(".", 1)[1] in _generated_cols(known[fks[via].table], dialect) and not for_files:
494
+ raise SpecError(f"tables.{p.name}.columns.{col}: {rule['ref']} is made by the database, so it is not known before the insert; use the key column itself")
495
+ parents: Dict[str, Optional[List[Any]]] = {}
496
+ for col, ref in fks.items():
497
+ if ref.table in rows:
498
+ parents[col] = list(range(len(rows[ref.table])))
499
+ elif existing is not None and not for_files:
500
+ parents[col] = existing(ref.table, ref.column) or None
501
+ else:
502
+ parents[col] = None
503
+ if for_files:
504
+ warnings.append(f"{p.name}.{col}: {ref.table} is not in the spec, so files leave {col} empty; add {ref.table} to the spec, or insert into the database to use its rows")
505
+ # How many rows, and for `per`, which parent row each belongs to.
506
+ owners: List[Optional[int]] = []
507
+ if p.per:
508
+ parent, lo, hi = p.per
509
+ per_col = _fk_to(table, parent, known)["columns"][0] # type: ignore[index]
510
+ for i in range(len(rows[parent])):
511
+ owners += [i] * values.rng.randint(lo, hi)
512
+ else:
513
+ per_col = None
514
+ owners = [None] * p.count
515
+ edge = bool(spec.get("edge_cases"))
516
+ made: List[Dict[str, Any]] = []
517
+ for n, owner in enumerate(owners):
518
+ row = _row(p, cols, gen_cols, fks, parents, owner, per_col, values, seen, n, rows, for_files, warnings, lookup=lookup)
519
+ if row is not None:
520
+ made.append(row)
521
+ if edge:
522
+ # Three rows at the limits: the longest text, text that breaks naive quoting, and nulls where allowed.
523
+ for e in range(3 if made else 0):
524
+ row = _row(p, cols, gen_cols, fks, parents, None if per_col is None else (owners[0] if owners else None), per_col, values, seen, len(made), rows, for_files, warnings, edge=e, lookup=lookup)
525
+ if row is not None:
526
+ made.append(row)
527
+ total += len(made)
528
+ if total > MAX_ROWS:
529
+ raise SpecError(f"the spec makes more than {MAX_ROWS} rows; ask for fewer")
530
+ rows[p.name] = made
531
+ if for_files:
532
+ numbered[p.name] = list(gen_cols)
533
+ for col in gen_cols:
534
+ for i, r in enumerate(made, 1):
535
+ r[col] = i
536
+ return Generated(order=[p.name for p in plans], rows=rows, generated=generated, warnings=sorted(set(warnings)), numbered=numbered)
537
+
538
+
539
+ def _row(
540
+ p: TablePlan, cols: List[Dict[str, Any]], gen_cols: List[str], fks: Dict[str, Ref], parents: Dict[str, Optional[List[Any]]],
541
+ owner: Optional[int], per_col: Optional[str], values: Values, seen: Dict[Tuple[str, ...], Set[Tuple[Any, ...]]], n: int,
542
+ rows: Mapping[str, List[Dict[str, Any]]], for_files: bool, warnings: List[str], edge: Optional[int] = None,
543
+ lookup: Optional[Callable[[str, str, Any, str], Any]] = None,
544
+ ) -> Optional[Dict[str, Any]]:
545
+ # Keys first, then values, then what reads them: a column via a key, and templates of the row's other columns.
546
+ def stage(col: Mapping[str, Any]) -> int:
547
+ rule = p.rules.get(col["name"]) or {}
548
+ return 2 if "via" in rule else 3 if "template" in rule else 0 if col["name"] in fks or col["name"] == per_col else 1
549
+
550
+ ordered = sorted(cols, key=stage)
551
+ for _ in range(UNIQUE_TRIES):
552
+ row: Dict[str, Any] = {}
553
+ for col in ordered:
554
+ name = col["name"]
555
+ if name in gen_cols:
556
+ continue
557
+ rule = p.rules.get(name)
558
+ where = f"tables.{p.name}.columns.{name}"
559
+ if rule is not None and "via" in rule:
560
+ row[name] = _via(row.get(rule["via"]), rule["ref"].rsplit(".", 1)[1], rows, lookup, where)
561
+ elif rule is not None and "template" in rule:
562
+ fields = _fields(str(rule["template"]), where)
563
+ missing = [f for f in fields if f not in row]
564
+ if missing:
565
+ raise SpecError(f"{where}: the template names {', '.join(missing)}, which is not a column of {p.name} filled before it")
566
+ if any(isinstance(row[f], Ref) for f in fields):
567
+ raise SpecError(f"{where}: a template reads values, not keys to other tables")
568
+ row[name] = _format(str(rule["template"]), {f: row[f] for f in fields})
569
+ elif name == per_col and owner is not None:
570
+ row[name] = Ref(fks[name].table, fks[name].column, index=owner)
571
+ elif name in fks and (rule is None or "ref" in rule):
572
+ options = parents.get(name)
573
+ if not options:
574
+ if col["nullable"]:
575
+ row[name] = None
576
+ else:
577
+ warnings.append(f"{p.name}.{name}: no rows of {fks[name].table} to refer to; add {fks[name].table} to the spec")
578
+ row[name] = None
579
+ continue
580
+ pick = values.rng.choice(options)
581
+ row[name] = Ref(fks[name].table, fks[name].column, index=pick) if fks[name].table in rows else Ref(fks[name].table, fks[name].column, value=pick)
582
+ elif rule is not None:
583
+ row[name] = values.rule(rule, col, f"{p.name}.{name}", where)
584
+ elif col.get("default") is not None and col["nullable"]:
585
+ continue # the database's default
586
+ elif edge is not None and col["nullable"] and edge == 2:
587
+ row[name] = None
588
+ else:
589
+ row[name] = values.infer(col, f"{p.name}.{name}")
590
+ if edge is not None and row[name] is not None and rule is None and _free_text(col):
591
+ row[name] = _edge(row[name], col, edge)
592
+ row[name] = _fit(row[name], col)
593
+ if _unique_ok(row, seen):
594
+ return row
595
+ warnings.append(f"{p.name}: could not make enough unique values; fewer rows than asked")
596
+ return None
597
+
598
+
599
+ def _via(key: Any, column: str, rows: Mapping[str, List[Dict[str, Any]]], lookup: Optional[Callable[[str, str, Any, str], Any]], where: str) -> Any:
600
+ """A column of the parent row a key of this row points at: a row the spec made, or one already in the database."""
601
+ if not isinstance(key, Ref):
602
+ return None
603
+ if key.index is not None:
604
+ return rows[key.table][key.index].get(column)
605
+ if lookup is None:
606
+ raise SpecError(f"{where}: via reads rows already in the database, which files cannot; add {key.table} to the spec")
607
+ return lookup(key.table, key.column, key.value, column)
608
+
609
+
610
+ # Columns whose values have a shape (an address, a code): edge-case text would only make them invalid.
611
+ _SHAPED = re.compile(r"e_?mail|phone|mobile|tel|url|website|(^|_)ip|iban|zip|post(al)?_?code|country|currency|(^|_)(sku|code|ref|uuid|guid)$|hash|token|password|status|type$|kind$", re.IGNORECASE)
612
+
613
+
614
+ def _free_text(col: Mapping[str, Any]) -> bool:
615
+ return not (col.get("enum") or col.get("check_values") or _SHAPED.search(col["name"]))
616
+
617
+
618
+ def _edge(value: Any, col: Mapping[str, Any], edge: int) -> Any:
619
+ if isinstance(value, str) and not col.get("enum") and not col.get("check_values"):
620
+ length = col.get("length")
621
+ if edge == 0 and length:
622
+ return ("X" * length)[:length]
623
+ return EDGE_TEXT[edge % len(EDGE_TEXT)]
624
+ if isinstance(value, bool):
625
+ return value
626
+ if isinstance(value, int) and not col.get("check_range"):
627
+ return 0 if edge == 0 else value
628
+ return value
629
+
630
+
631
+ def _fit(value: Any, col: Mapping[str, Any]) -> Any:
632
+ """A value cut to the column: text to its length, decimals to its scale."""
633
+ if isinstance(value, str) and isinstance(col.get("length"), int) and len(value) > col["length"]:
634
+ return value[: col["length"]]
635
+ if isinstance(value, float) and isinstance(col.get("scale"), int):
636
+ return round(value, col["scale"])
637
+ return value
638
+
639
+
640
+ def _unique_ok(row: Mapping[str, Any], seen: Dict[Tuple[str, ...], Set[Tuple[Any, ...]]]) -> bool:
641
+ keys = []
642
+ for cols, used in seen.items():
643
+ if not all(c in row for c in cols):
644
+ continue
645
+ key = tuple(_plain(row[c]) for c in cols)
646
+ if any(v is None for v in key):
647
+ continue
648
+ if key in used:
649
+ return False
650
+ keys.append((used, key))
651
+ for used, key in keys:
652
+ used.add(key)
653
+ return True
654
+
655
+
656
+ def _plain(v: Any) -> Any:
657
+ if isinstance(v, Ref):
658
+ return ("ref", v.table, v.index, v.value)
659
+ return v
660
+
661
+
662
+ def resolve(row: Mapping[str, Any], keys: Mapping[str, List[Dict[str, Any]]]) -> Dict[str, Any]:
663
+ """A row with each reference replaced by the parent's key: from the parent rows (their keys once inserted)."""
664
+ out: Dict[str, Any] = {}
665
+ for k, v in row.items():
666
+ if isinstance(v, Ref):
667
+ out[k] = v.value if v.index is None else keys[v.table][v.index].get(v.column)
668
+ else:
669
+ out[k] = v
670
+ return out
671
+
672
+
673
+ # --------------------------------------------------------------------------------------------------- output
674
+
675
+
676
+ def _json_value(v: Any) -> Any:
677
+ if isinstance(v, (dt.date, dt.datetime)):
678
+ return v.isoformat()
679
+ if isinstance(v, decimal.Decimal):
680
+ return str(v)
681
+ if isinstance(v, bytes):
682
+ return v.hex()
683
+ return v
684
+
685
+
686
+ def write_files(g: Generated, out_dir: Path, fmt: str, *, engine: Any = None, schema: Optional[str] = None) -> List[str]:
687
+ """Files for the rows: one csv per table, one json, or one sql file of INSERT statements in the database's dialect."""
688
+ if fmt not in FORMATS:
689
+ raise SpecError(f"format must be one of {', '.join(FORMATS)}")
690
+ out_dir.mkdir(parents=True, exist_ok=True)
691
+ resolved = {t: [] for t in g.order} # type: Dict[str, List[Dict[str, Any]]]
692
+ for t in g.order:
693
+ resolved[t] = [resolve(r, resolved) for r in g.rows[t]]
694
+ files: List[str] = []
695
+ if fmt == "csv":
696
+ for t in g.order:
697
+ path = out_dir / f"{t}.csv"
698
+ cols = list(dict.fromkeys(c for r in resolved[t] for c in r))
699
+ with path.open("w", newline="", encoding="utf-8") as f:
700
+ w = csv.DictWriter(f, fieldnames=cols)
701
+ w.writeheader()
702
+ for r in resolved[t]:
703
+ w.writerow({k: _json_value(v) for k, v in r.items()})
704
+ files.append(str(path))
705
+ elif fmt == "json":
706
+ path = out_dir / "data.json"
707
+ path.write_text(json.dumps({t: [{k: _json_value(v) for k, v in r.items()} for r in resolved[t]] for t in g.order}, indent=2, ensure_ascii=False), encoding="utf-8")
708
+ files.append(str(path))
709
+ else:
710
+ from sqlalchemy import MetaData, Table, insert
711
+ from sqlalchemy.dialects import postgresql
712
+
713
+ path = out_dir / "data.sql"
714
+ lines = []
715
+ # A key the database fills (serial, identity) is left to the database, so the script runs on a database that
716
+ # already has rows; only a key another row of the script points at keeps its number.
717
+ referenced = {(v.table, v.column) for t in g.order for r in g.rows[t] for v in r.values() if isinstance(v, Ref) and v.index is not None}
718
+ omit = {t: {c for c in g.numbered.get(t, []) if (t, c) not in referenced} for t in g.order}
719
+ kept = sorted(f"{t}.{c}" for t in g.order for c in g.numbered.get(t, []) if (t, c) in referenced)
720
+ if kept:
721
+ lines.append(f"-- {', '.join(kept)}: numbered here because other rows of this script point at them; on a database with rows, they may collide.")
722
+ dialect = engine.dialect if engine is not None else postgresql.dialect()
723
+ meta = MetaData(schema=schema)
724
+ for t in g.order:
725
+ table = Table(t, meta, autoload_with=engine) if engine is not None else _loose_table(t, resolved[t], meta)
726
+ for r in resolved[t]:
727
+ r = {k: v for k, v in r.items() if k not in omit.get(t, set())}
728
+ stmt = insert(table).values(**r).compile(dialect=dialect, compile_kwargs={"literal_binds": True})
729
+ # The key the database makes is not read back by a script: no RETURNING.
730
+ lines.append(re.sub(r"\s+RETURNING\s+[^;]*$", "", str(stmt)) + ";")
731
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
732
+ files.append(str(path))
733
+ return files
734
+
735
+
736
+ def _loose_table(name: str, rows: Sequence[Mapping[str, Any]], meta: Any) -> Any:
737
+ from sqlalchemy import Column, Table
738
+ from sqlalchemy.types import NullType
739
+
740
+ cols = list(dict.fromkeys(c for r in rows for c in r))
741
+ return Table(name, meta, *[Column(c, NullType()) for c in cols])
742
+
743
+
744
+ def insert_rows(g: Generated, engine: Any, catalog: Mapping[str, Any], inserted: Optional[Dict[str, List[Dict[str, Any]]]] = None) -> Dict[str, Any]:
745
+ """
746
+ The rows into the database in one transaction; returns each table's keys for the batch file, and fills `inserted`
747
+ (when given) with the rows as they went in, keys the database made included. Nothing is kept on an error.
748
+ """
749
+ from sqlalchemy import MetaData, Table
750
+
751
+ schema = catalog.get("schema") or None
752
+ meta = MetaData(schema=schema)
753
+ keys: Dict[str, List[Dict[str, Any]]] = {}
754
+ batch: Dict[str, Any] = {}
755
+ with engine.connect() as conn:
756
+ try:
757
+ for t in g.order:
758
+ table = Table(t, meta, autoload_with=conn)
759
+ pk = [c.name for c in table.primary_key.columns]
760
+ if not pk:
761
+ raise SpecError(f"{t} has no primary key, so its rows could not be removed again; ForgeQE inserts only into tables with one")
762
+ made = _insert_table(conn, table, pk, [resolve(row, keys) for row in g.rows[t]], bool(g.generated.get(t)))
763
+ keys[t] = made
764
+ batch[t] = {"pk": pk, "keys": [[_json_value(r.get(c)) for c in pk] for r in made]}
765
+ if inserted is not None:
766
+ inserted[t] = [{k: _json_value(v) for k, v in r.items()} for r in made]
767
+ conn.commit()
768
+ except Exception:
769
+ conn.rollback()
770
+ raise
771
+ return batch
772
+
773
+
774
+ def _insert_table(conn: Any, table: Any, pk: List[str], rows: List[Dict[str, Any]], db_keys: bool) -> List[Dict[str, Any]]:
775
+ """
776
+ One table's rows, with the keys of each as inserted. Rows of the same columns go in together: as one statement per
777
+ BULK rows where the keys are already in them or the database returns the keys it makes in the rows' order
778
+ (PostgreSQL, SQL Server, SQLite, MariaDB), else one row at a time (MySQL, Oracle) so each key can be read.
779
+ """
780
+ from sqlalchemy import insert
781
+ from sqlalchemy.exc import InvalidRequestError
782
+
783
+ bulk_returning = bool(getattr(conn.dialect, "insert_executemany_returning_sort_by_parameter_order", False))
784
+ made: List[Dict[str, Any]] = [{} for _ in rows]
785
+ groups: Dict[Tuple[str, ...], List[int]] = {}
786
+ for i, r in enumerate(rows):
787
+ groups.setdefault(tuple(sorted(r)), []).append(i)
788
+ for cols, idxs in groups.items():
789
+ if not db_keys or bulk_returning:
790
+ for start in range(0, len(idxs), BULK):
791
+ chunk = idxs[start : start + BULK]
792
+ params = [rows[i] for i in chunk]
793
+ if not cols:
794
+ for i in chunk: # nothing to give but defaults: one row each
795
+ made[i] = {**rows[i], **_key(conn.execute(insert(table)), pk)}
796
+ continue
797
+ if db_keys:
798
+ try:
799
+ result = conn.execute(insert(table).returning(*[table.c[c] for c in pk], sort_by_parameter_order=True), params)
800
+ except InvalidRequestError:
801
+ # SQLAlchemy cannot match returned keys to rows for this table (no sentinel column): one at a time.
802
+ # It refuses before anything is sent, so nothing of this chunk went in.
803
+ bulk_returning = False
804
+ for i in idxs[start:]:
805
+ made[i] = {**rows[i], **_key(conn.execute(insert(table).values(**rows[i])), pk)}
806
+ break
807
+ for i, key in zip(chunk, result.fetchall()):
808
+ made[i] = {**rows[i], **dict(zip(pk, key))}
809
+ else:
810
+ conn.execute(insert(table), params)
811
+ for i in chunk:
812
+ made[i] = dict(rows[i])
813
+ else:
814
+ for i in idxs:
815
+ made[i] = {**rows[i], **_key(conn.execute(insert(table).values(**rows[i])), pk)}
816
+ return made
817
+
818
+
819
+ def _key(result: Any, pk: List[str]) -> Dict[str, Any]:
820
+ return {k: v for k, v in zip(pk, result.inserted_primary_key or ()) if v is not None}
821
+
822
+
823
+ def delete_batch(engine: Any, catalog: Mapping[str, Any], batch: Mapping[str, Any]) -> Dict[str, int]:
824
+ """A batch's rows out again, children first, by their keys only; in one transaction."""
825
+ from sqlalchemy import MetaData, Table, and_, delete, or_
826
+
827
+ schema = catalog.get("schema") or None
828
+ meta = MetaData(schema=schema)
829
+ removed: Dict[str, int] = {}
830
+ with engine.connect() as conn:
831
+ try:
832
+ for t in reversed(list(batch["tables"])):
833
+ info = batch["tables"][t]
834
+ table = Table(t, meta, autoload_with=conn)
835
+ cols = [table.c[c] for c in info["pk"]]
836
+ count = 0
837
+ for i in range(0, len(info["keys"]), 500):
838
+ chunk = info["keys"][i : i + 500]
839
+ cond = cols[0].in_([k[0] for k in chunk]) if len(cols) == 1 else or_(*[and_(*[c == v for c, v in zip(cols, k)]) for k in chunk])
840
+ count += int(conn.execute(delete(table).where(cond)).rowcount or 0)
841
+ removed[t] = count
842
+ conn.commit()
843
+ except Exception:
844
+ conn.rollback()
845
+ raise
846
+ return removed
847
+
848
+
849
+ def preview(g: Generated, sample: int = 3) -> Dict[str, Any]:
850
+ out: Dict[str, Any] = {}
851
+ for t in g.order:
852
+ rows = g.rows[t]
853
+ shown = []
854
+ for r in rows[:sample]:
855
+ shown.append({k: (f"→ {v.table} row {v.index + 1}" if isinstance(v, Ref) and v.index is not None else f"→ {v.table} {v.value}" if isinstance(v, Ref) else _json_value(v)) for k, v in r.items()})
856
+ out[t] = {"rows": len(rows), "sample": shown, **({"database_fills": g.generated[t]} if g.generated.get(t) else {})}
857
+ return out
858
+
859
+
860
+ def new_batch_id() -> str:
861
+ return time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:6]