@capagents/forgeqe 2.10.5 → 3.0.1

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 (113) hide show
  1. package/HOW_TO_USE.md +104 -19
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/dist/docs-site/docs/index.html +97 -16
  4. package/dist/docs-site/docs/mobile/index.html +8 -0
  5. package/dist/docs-site/docs/search.js +1 -1
  6. package/dist/forgeqe.js +1950 -1932
  7. package/dist/web/assets/Agent-BqVEwTVC.js +8 -0
  8. package/dist/web/assets/ApiTests-DCatslaV.js +10 -0
  9. package/dist/web/assets/Browse-Bl8Qmv19.js +2 -0
  10. package/dist/web/assets/Chat-CclDgwrO.js +5 -0
  11. package/dist/web/assets/{CommandPalette-D7ufvlUN.js → CommandPalette-yhEQVq1q.js} +1 -1
  12. package/dist/web/assets/Compare-y9bBCySM.js +1 -0
  13. package/dist/web/assets/{Cost-DGZ5t-Q_.js → Cost-DJ3HO9gf.js} +1 -1
  14. package/dist/web/assets/{Data-DqGA1ZtQ.js → Data-HZP8SHLn.js} +4 -4
  15. package/dist/web/assets/Desktop-CI6C43R3.js +1 -0
  16. package/dist/web/assets/DesktopReview-CGDj4Ujf.js +1 -0
  17. package/dist/web/assets/Evidence-C1Vyg39z.js +1 -0
  18. package/dist/web/assets/{Explore-TtfTWmGW.js → Explore-BPWjMsOz.js} +2 -2
  19. package/dist/web/assets/{Features-DazoSiEi.js → Features-BXBE6r6G.js} +1 -1
  20. package/dist/web/assets/{Flags-Brja-ZXF.js → Flags-gDtVVBId.js} +2 -2
  21. package/dist/web/assets/Flaky-h8C09CFf.js +1 -0
  22. package/dist/web/assets/Impact-BT55F8b-.js +3 -0
  23. package/dist/web/assets/Jobs-BZJxI0NN.js +5 -0
  24. package/dist/web/assets/KindPage-DtUCsf9W.js +6 -0
  25. package/dist/web/assets/Migration-DTauoKTG.js +2 -0
  26. package/dist/web/assets/Product-CvKbCdHY.js +7 -0
  27. package/dist/web/assets/Production-CJQsBg05.js +1 -0
  28. package/dist/web/assets/{Quality-C4Aak_hw.js → Quality-CjipajoK.js} +1 -1
  29. package/dist/web/assets/Readiness-LaLczR5L.js +1 -0
  30. package/dist/web/assets/Record-TQ_WSnsE.js +2 -0
  31. package/dist/web/assets/Regression-CrjROhTU.js +5 -0
  32. package/dist/web/assets/{RelationGraph-DLeEarQd.js → RelationGraph-eoGXXz5t.js} +1 -1
  33. package/dist/web/assets/{Reports-ClSAzQOh.js → Reports-BTF2tHQN.js} +2 -2
  34. package/dist/web/assets/{Response-De60pk_7.js → Response-Dm1See-Y.js} +3 -9
  35. package/dist/web/assets/{RunDiff-0ibEcmI5.js → RunDiff-B6t56dwu.js} +1 -1
  36. package/dist/web/assets/{Runs-T8yF8Hi0.js → Runs-Oj-NO8Vl.js} +2 -2
  37. package/dist/web/assets/{Steps-CB30w6BA.js → Steps-Cm-atRtk.js} +2 -2
  38. package/dist/web/assets/TestCases-SL9YqWlm.js +1 -0
  39. package/dist/web/assets/TestData-C6j4ZbaF.js +2 -0
  40. package/dist/web/assets/TestDebt-CISwXKl-.js +1 -0
  41. package/dist/web/assets/Tosca-DTVz50ex.js +3 -0
  42. package/dist/web/assets/{WhatsNew-D7n48IsG.js → WhatsNew-2AgkrdMk.js} +1 -1
  43. package/dist/web/assets/agentLink-DfJdkmLQ.js +1 -0
  44. package/dist/web/assets/{dataParts-CZAcb4L_.js → dataParts-BwxK_p1D.js} +3 -3
  45. package/dist/web/assets/{families-D2ygriY6.js → families-DPlFfKf2.js} +1 -1
  46. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  47. package/dist/web/assets/{fold-BhYvId2X.js → fold-BD-sox6G.js} +1 -1
  48. package/dist/web/assets/frame-B428t9gN.js +18 -0
  49. package/dist/web/assets/index-BtYlZE0c.js +67 -0
  50. package/dist/web/assets/index-DUWIa2Tp.css +2 -0
  51. package/dist/web/assets/{logos-DmK40tlV.js → logos-DCsyIKX5.js} +1 -1
  52. package/dist/web/assets/{markdown-Bej6qyls.js → markdown-6z0km3hN.js} +3 -3
  53. package/dist/web/assets/paletteCommands-3NG1WPGZ.js +1 -0
  54. package/dist/web/assets/{parts-BOpbd90H.js → parts-VPcxh6Jc.js} +1 -1
  55. package/dist/web/assets/{productParts-B3_FGd-T.js → productParts-BjfWgMtq.js} +1 -1
  56. package/dist/web/assets/{qualityParts-B8yJRVpP.js → qualityParts-BA-1cidT.js} +1 -1
  57. package/dist/web/assets/{recordTest-CZUrGm8I.js → recordTest-EkxSMWbe.js} +1 -1
  58. package/dist/web/assets/{rows-BcG6gFCy.js → rows-BOGSBviK.js} +1 -1
  59. package/dist/web/assets/{segmented-ffWUfF8N.js → segmented-DphDskQz.js} +1 -1
  60. package/dist/web/assets/{usePageChat-T6vQY_1C.js → usePageChat-Zg7SGziM.js} +1 -1
  61. package/dist/web/index.html +5 -5
  62. package/docs/MOBILE.md +9 -0
  63. package/docs/user-guide.html +97 -16
  64. package/forgeqe.example.yaml +2 -0
  65. package/package.json +3 -1
  66. package/prompts/brain.md +3 -2
  67. package/prompts/requests-rule.md +1 -1
  68. package/prompts/talk-summary.md +43 -0
  69. package/prompts/talk.md +63 -0
  70. package/prompts/test-agent.md +2 -1
  71. package/py/forgeqe_data/__init__.py +1 -0
  72. package/py/forgeqe_data/__main__.py +12 -0
  73. package/py/forgeqe_data/connect.py +290 -0
  74. package/py/forgeqe_data/connstr.py +169 -0
  75. package/py/forgeqe_data/flows.py +603 -0
  76. package/py/forgeqe_data/guard.py +214 -0
  77. package/py/forgeqe_data/mongo.py +219 -0
  78. package/py/forgeqe_data/schema.py +431 -0
  79. package/py/forgeqe_data/service.py +651 -0
  80. package/py/forgeqe_data/streams.py +400 -0
  81. package/py/forgeqe_data/subset.py +299 -0
  82. package/py/forgeqe_data/testdata.py +861 -0
  83. package/py/forgeqe_data/vector.py +113 -0
  84. package/py/forgeqe_talk/__init__.py +1 -0
  85. package/py/forgeqe_talk/__main__.py +65 -0
  86. package/py/forgeqe_voice/worker.py +24 -4
  87. package/dist/web/assets/Agent-bSVNDlcU.js +0 -8
  88. package/dist/web/assets/ApiTests-DOxGgoZC.js +0 -10
  89. package/dist/web/assets/Browse-CG8jzqR1.js +0 -2
  90. package/dist/web/assets/Chat-DzufzeGg.js +0 -5
  91. package/dist/web/assets/Compare-6vHuAaKv.js +0 -1
  92. package/dist/web/assets/Desktop-CSOFE8cN.js +0 -1
  93. package/dist/web/assets/DesktopReview-BWtionFH.js +0 -1
  94. package/dist/web/assets/Evidence-D8pLFcbr.js +0 -1
  95. package/dist/web/assets/Flaky-jJlHFFCa.js +0 -1
  96. package/dist/web/assets/Impact-b60dmhJK.js +0 -3
  97. package/dist/web/assets/Jobs-Y9W9nBgx.js +0 -5
  98. package/dist/web/assets/KindPage-Y72w2UwG.js +0 -6
  99. package/dist/web/assets/Migration-CvIeTB9p.js +0 -2
  100. package/dist/web/assets/Product-BEe2GyO6.js +0 -7
  101. package/dist/web/assets/Production-D2qmPFYy.js +0 -1
  102. package/dist/web/assets/Readiness-ClXnnmLo.js +0 -1
  103. package/dist/web/assets/Record-LaLYhQgk.js +0 -2
  104. package/dist/web/assets/Regression-DKz05MC_.js +0 -5
  105. package/dist/web/assets/TestCases-Ba6bUE4i.js +0 -1
  106. package/dist/web/assets/TestData-DefDzeMW.js +0 -2
  107. package/dist/web/assets/TestDebt-zohltDHp.js +0 -1
  108. package/dist/web/assets/Tosca-jAtdiG28.js +0 -3
  109. package/dist/web/assets/filters-CYaF2RvC.js +0 -1
  110. package/dist/web/assets/frame-DeJBYtBX.js +0 -11
  111. package/dist/web/assets/index-CYlacOTX.css +0 -2
  112. package/dist/web/assets/index-DXpBYobT.js +0 -67
  113. package/dist/web/assets/paletteCommands-CKBMmhb4.js +0 -1
@@ -0,0 +1,299 @@
1
+ """
2
+ A masked subset of a database: real rows, few of them, with every row they need, and no real personal data.
3
+
4
+ subset:
5
+ from: shop_prod # a databases: entry, read in read-only sessions
6
+ start: {table: orders, where: "status = 'PAID'", limit: 100}
7
+ children: [order_items] # rows of these tables that point at the rows taken
8
+ mask: # more columns to mask, by Faker method or null
9
+ customers.notes: paragraph
10
+ keep: [customers.country] # columns not to mask though their names look personal
11
+ seed: 7
12
+
13
+ The start rows come from one SELECT built from table and where, checked by guard.py like any query. Every row they point
14
+ at is taken too, and the rows they point at, until nothing is missing; then the children named, and their parents.
15
+
16
+ Masking is deterministic: the same value becomes the same fake value in every table and every run, so joins on a
17
+ masked column still match. Keys are never masked: they hold the rows together. A masked value in a unique column stays
18
+ unique. Rows then go to files with their keys as they were, or into a writable database through testdata.py, where
19
+ keys the database makes are made new and every reference follows them.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import re
25
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Tuple
26
+
27
+ from . import guard
28
+ from .testdata import MAX_ROWS, Generated, Ref, SpecError, _generated_cols
29
+
30
+ MAX_DEPTH = 12
31
+ CHUNK = 500
32
+
33
+ # Personal data by column name, and how it is masked (a Faker method, or a hash).
34
+ PERSONAL: List[Tuple[re.Pattern[str], str]] = [
35
+ (re.compile(p, re.IGNORECASE), m)
36
+ for p, m in [
37
+ (r"pass(word|wd)?|(^|_)pwd$|hash|digest|salt", "sha256"), (r"token|secret|api_?key", "sha1"),
38
+ (r"e_?mail", "email"), (r"(^|_)(first_?name|given_?name|fname)$", "first_name"), (r"(^|_)(last_?name|surname|family_?name|lname)$", "last_name"),
39
+ (r"(^|_)(full_?name|customer_?name|contact_?name|display_?name)$", "name"), (r"user_?name|login", "user_name"),
40
+ (r"phone|mobile|(^|_)tel$|fax", "phone_number"), (r"street|address|addr(_|$)", "street_address"), (r"zip|post(al)?_?code", "postcode"),
41
+ (r"(^|_)city$", "city"), (r"birth|(^|_)dob$", "date_of_birth"), (r"ssn|social_?security|national_?id|tax_?id|pan_?(no|number)?$|aadhaar|passport", "ssn"),
42
+ (r"iban|account_?(no|number)", "iban"), (r"card_?(no|number)|(^|_)pan$|cvv|cvc", "credit_card_number"), (r"(^|_)ip(_?addr(ess)?)?$", "ipv4"),
43
+ (r"latitude|longitude|(^|_)(lat|lng|lon)$", "null"),
44
+ ]
45
+ ]
46
+
47
+
48
+ # A bare "name" is personal in a table of people, and a product's, a country's or a team's name elsewhere.
49
+ BARE_NAME = re.compile(r"(^|_)name$", re.IGNORECASE)
50
+ PEOPLE = re.compile(r"customer|client|user|person|people|employee|staff|contact|member|patient|student|applicant|candidate|guest|subscriber|driver|owner|holder|beneficiar|partner|traveller|passenger|account", re.IGNORECASE)
51
+
52
+
53
+ def mask_plan(catalog: Mapping[str, Any], tables: List[str], spec: Mapping[str, Any]) -> Dict[str, Dict[str, str]]:
54
+ """Per table, the columns masked and how: named in mask:, or personal by name; never keys, never those in keep:."""
55
+ known = catalog["tables"]
56
+ explicit = spec.get("mask") or {}
57
+ keep = set(spec.get("keep") or [])
58
+ if not isinstance(explicit, dict) or not isinstance(spec.get("keep") or [], list):
59
+ raise SpecError("mask is a mapping of table.column to a Faker method or null; keep is a list of table.column")
60
+ for key, method in explicit.items():
61
+ t, _, c = str(key).partition(".")
62
+ if t not in known or c not in {col["name"] for col in known[t]["columns"]}:
63
+ raise SpecError(f"mask: {key} is not a column of the database")
64
+ if method is not None and not re.fullmatch(r"[a-z][a-z0-9_]*", str(method)):
65
+ raise SpecError(f"mask: {key}: {method!r} is not a Faker method")
66
+ out: Dict[str, Dict[str, str]] = {}
67
+ for t in tables:
68
+ table = known[t]
69
+ keys = set(table.get("pk") or []) | {c for fk in table.get("fks", []) for c in fk["columns"]}
70
+ chosen: Dict[str, str] = {}
71
+ for col in table["columns"]:
72
+ name = col["name"]
73
+ ref = f"{t}.{name}"
74
+ if ref in explicit:
75
+ chosen[name] = "null" if explicit[ref] is None else str(explicit[ref])
76
+ elif name in keys or ref in keep:
77
+ continue
78
+ else:
79
+ method = next((m for p, m in PERSONAL if p.search(name)), None)
80
+ if method is None and BARE_NAME.search(name) and PEOPLE.search(t):
81
+ method = "name"
82
+ if method:
83
+ chosen[name] = method
84
+ if chosen:
85
+ out[t] = chosen
86
+ return out
87
+
88
+
89
+ class Masker:
90
+ """The same original value always gives the same fake value: seeded from a hash of the seed, column kind, and value."""
91
+
92
+ def __init__(self, seed: int, locale: str) -> None:
93
+ from faker import Faker
94
+
95
+ self.seed = seed
96
+ self.fake = Faker(locale or "en_US")
97
+
98
+ def __call__(self, value: Any, method: str, unique: bool, col: Mapping[str, Any]) -> Any:
99
+ if value is None or method == "null":
100
+ return None
101
+ digest = hashlib.sha256(f"{self.seed}|{method}|{value}".encode("utf-8")).hexdigest()
102
+ if method in ("sha256", "sha1", "md5"):
103
+ out: Any = hashlib.new(method, digest.encode()).hexdigest()
104
+ else:
105
+ self.fake.seed_instance(int(digest[:16], 16))
106
+ fn = getattr(self.fake, method, None)
107
+ if fn is None or not callable(fn) or method.startswith(("seed", "add_", "get_", "set_", "provider")):
108
+ raise SpecError(f"mask: Faker has no value generator {method}")
109
+ out = fn()
110
+ if unique and isinstance(out, str):
111
+ out = f"{out.split('@')[0]}.{digest[:6]}@{out.split('@')[1]}" if "@" in out else f"{out}-{digest[:6]}"
112
+ length = col.get("length")
113
+ if isinstance(out, str) and isinstance(length, int) and len(out) > length:
114
+ out = out[-length:] if unique else out[:length]
115
+ return out
116
+
117
+
118
+ def _start_sql(start: Mapping[str, Any], engine_name: str, dialect: Any, schema: Optional[str], known: Mapping[str, Any]) -> str:
119
+ table = str(start.get("table") or "")
120
+ if table not in known:
121
+ raise SpecError(f"subset.start.table: no table {table!r} in the source database")
122
+ quoted = dialect.identifier_preparer.quote(table)
123
+ if schema:
124
+ quoted = f"{dialect.identifier_preparer.quote_schema(schema)}.{quoted}"
125
+ where = str(start.get("where") or "").strip()
126
+ if re.search(r"\b(order\s+by|limit|offset|fetch)\b", where, re.IGNORECASE):
127
+ raise SpecError("subset.start.where is a condition only; rows are taken in key order up to limit")
128
+ pk = known[table].get("pk") or []
129
+ order = ", ".join(dialect.identifier_preparer.quote(c) for c in pk)
130
+ sql = f"SELECT * FROM {quoted}" + (f" WHERE {where}" if where else "") + (f" ORDER BY {order}" if order else "")
131
+ verdict = guard.check(sql, engine_name)
132
+ if not verdict.ok:
133
+ raise SpecError(f"subset.start.where: {verdict.reason}")
134
+ # A filter of the start table, nothing more: no UNION bringing in other rows, and only tables of this schema.
135
+ import sqlglot
136
+ from sqlglot import exp
137
+
138
+ tree = sqlglot.parse_one(verdict.sql, read=guard.dialect_of(engine_name) or None)
139
+ if not isinstance(tree, exp.Select):
140
+ raise SpecError("subset.start.where: a condition on the start table only (no UNION, INTERSECT or EXCEPT)")
141
+ lower = {k.lower() for k in known}
142
+ foreign = [n for n in verdict.tables if n.split(".")[-1].lower() not in lower]
143
+ if foreign:
144
+ raise SpecError(f"subset.start.where: reads {', '.join(foreign)}, which is not a table of the source database's schema")
145
+ limit = start.get("limit", 100)
146
+ if not isinstance(limit, int) or not 1 <= limit <= MAX_ROWS:
147
+ raise SpecError(f"subset.start.limit is 1 to {MAX_ROWS}")
148
+ return guard.limited(verdict.sql, engine_name, limit)
149
+
150
+
151
+ def take(engine: Any, engine_name: str, catalog: Mapping[str, Any], spec: Mapping[str, Any], log: Callable[[str], None] = lambda _: None) -> Tuple[Dict[str, List[Dict[str, Any]]], List[str]]:
152
+ """The rows of the subset, by table, read in one read-only session; and warnings."""
153
+ from sqlalchemy import MetaData, Table, select, text
154
+
155
+ sub = spec.get("subset")
156
+ if not isinstance(sub, dict) or not isinstance(sub.get("start"), dict):
157
+ raise SpecError("subset: needs from and start: {table, where, limit}")
158
+ known = catalog["tables"]
159
+ schema = catalog.get("schema") or None
160
+ children = sub.get("children") or []
161
+ if not isinstance(children, list) or any(c not in known for c in children):
162
+ raise SpecError(f"subset.children: tables of the source database (unknown: {', '.join(c for c in children if c not in known)})")
163
+ rows: Dict[str, Dict[Tuple[Any, ...], Dict[str, Any]]] = {}
164
+ warnings: List[str] = []
165
+ meta = MetaData(schema=schema)
166
+
167
+ def pk_of(t: str) -> List[str]:
168
+ pk = known[t].get("pk") or []
169
+ if not pk:
170
+ raise SpecError(f"{t} has no primary key, so its rows cannot be told apart; a subset takes tables with one")
171
+ return pk
172
+
173
+ def add(t: str, found: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
174
+ bucket = rows.setdefault(t, {})
175
+ new = []
176
+ for r in found:
177
+ key = tuple(r.get(c) for c in pk_of(t))
178
+ if key not in bucket:
179
+ bucket[key] = r
180
+ new.append(r)
181
+ if sum(len(b) for b in rows.values()) > MAX_ROWS:
182
+ raise SpecError(f"the subset takes more than {MAX_ROWS} rows; lower start.limit or name fewer children")
183
+ return new
184
+
185
+ with engine.connect() as conn:
186
+ tables: Dict[str, Any] = {}
187
+
188
+ def table(t: str) -> Any:
189
+ if t not in tables:
190
+ tables[t] = Table(t, meta, autoload_with=conn)
191
+ return tables[t]
192
+
193
+ def fetch(t: str, column: str, values: List[Any]) -> List[Dict[str, Any]]:
194
+ out: List[Dict[str, Any]] = []
195
+ tb = table(t)
196
+ for i in range(0, len(values), CHUNK):
197
+ part = values[i : i + CHUNK]
198
+ out += [dict(r._mapping) for r in conn.execute(select(tb).where(tb.c[column].in_(part))).fetchall()]
199
+ return out
200
+
201
+ def parents(t: str, found: List[Dict[str, Any]], depth: int = 0) -> None:
202
+ if not found or depth > MAX_DEPTH:
203
+ return
204
+ for fk in known[t].get("fks", []):
205
+ if len(fk["columns"]) != 1 or fk["table"] not in known:
206
+ continue
207
+ col, parent, ref = fk["columns"][0], fk["table"], fk["references"][0]
208
+ have = {r.get(ref) for r in rows.get(parent, {}).values()}
209
+ wanted = sorted({r.get(col) for r in found if r.get(col) is not None and r.get(col) not in have}, key=str)
210
+ if wanted:
211
+ parents(parent, add(parent, fetch(parent, ref, wanted)), depth + 1)
212
+
213
+ start = sub["start"]
214
+ sql = _start_sql(start, engine_name, engine.dialect, schema, known)
215
+ log(f"Taking rows of {start['table']}.")
216
+ first = [dict(r._mapping) for r in conn.execute(text(sql)).fetchall()]
217
+ parents(start["table"], add(start["table"], first))
218
+ for child in children:
219
+ links = [fk for fk in known[child].get("fks", []) if len(fk["columns"]) == 1 and fk["table"] in rows]
220
+ if not links:
221
+ warnings.append(f"subset.children: {child} has no foreign key to the tables taken; left out")
222
+ continue
223
+ found: List[Dict[str, Any]] = []
224
+ for fk in links:
225
+ keys = sorted({r.get(fk["references"][0]) for r in rows[fk["table"]].values()}, key=str)
226
+ found += fetch(child, fk["columns"][0], keys)
227
+ parents(child, add(child, found))
228
+ conn.rollback()
229
+ # Rows in key order, so the same spec takes and writes the same rows in the same order every run.
230
+ return {t: [b[k] for k in sorted(b, key=lambda key: tuple((v is None, str(type(v)), v) for v in key))] for t, b in rows.items()}, warnings
231
+
232
+
233
+ def _order(tables: List[str], known: Mapping[str, Any]) -> List[str]:
234
+ out: List[str] = []
235
+ left = set(tables)
236
+ while left:
237
+ ready = sorted(t for t in left if not ({fk["table"] for fk in known[t].get("fks", []) if fk["table"] != t} & left))
238
+ ready = ready or [sorted(left)[0]]
239
+ out += ready
240
+ left -= set(ready)
241
+ return out
242
+
243
+
244
+ def build(
245
+ taken: Dict[str, List[Dict[str, Any]]], source: Mapping[str, Any], spec: Mapping[str, Any], *,
246
+ target: Optional[Mapping[str, Any]] = None, target_dialect: str = "", for_files: bool = False,
247
+ ) -> Tuple[Generated, Dict[str, Dict[str, str]]]:
248
+ """The subset as rows to write: masked, parents first; for a target database, its keys left to it and references following."""
249
+ known = source["tables"]
250
+ order = _order(list(taken), known)
251
+ plan = mask_plan(source, order, spec)
252
+ seed = spec.get("seed", 1)
253
+ masker = Masker(int(seed) if isinstance(seed, int) else 1, str(spec.get("locale") or "en_US"))
254
+ warnings: List[str] = []
255
+ rows: Dict[str, List[Dict[str, Any]]] = {}
256
+ generated: Dict[str, List[str]] = {}
257
+ index: Dict[str, Dict[Any, int]] = {}
258
+ for t in order:
259
+ table = known[t]
260
+ cols = {c["name"]: c for c in table["columns"]}
261
+ uniques = {c for u in table.get("unique") or [] for c in u if len(u) == 1}
262
+ masks = plan.get(t, {})
263
+ gen: List[str] = []
264
+ allowed = set(cols)
265
+ if target is not None and not for_files:
266
+ if t not in target["tables"]:
267
+ raise SpecError(f"the target database has no table {t}")
268
+ tcols = {c["name"] for c in target["tables"][t]["columns"]}
269
+ dropped = sorted(set(cols) - tcols)
270
+ if dropped:
271
+ warnings.append(f"{t}: the target has no column {', '.join(dropped)}; left out")
272
+ allowed = set(cols) & tcols
273
+ gen = _generated_cols(target["tables"][t], target_dialect)
274
+ generated[t] = gen
275
+ # References to other tables of the subset follow their rows' new keys; one to the same table keeps its value.
276
+ links = {fk["columns"][0]: fk for fk in table.get("fks", []) if len(fk["columns"]) == 1 and fk["table"] in taken and fk["table"] != t}
277
+ if any(fk["table"] == t for fk in table.get("fks", [])) and gen and not for_files:
278
+ warnings.append(f"{t} refers to itself; those references keep their original keys, which the target may not have")
279
+ out: List[Dict[str, Any]] = []
280
+ for r in taken[t]:
281
+ row: Dict[str, Any] = {}
282
+ for name, value in r.items():
283
+ if name not in allowed or name in gen:
284
+ continue
285
+ if name in links and value is not None and not for_files:
286
+ fk = links[name]
287
+ pos = index.get(f"{fk['table']}.{fk['references'][0]}", {}).get(value)
288
+ row[name] = Ref(fk["table"], fk["references"][0], index=pos) if pos is not None else value
289
+ elif name in masks:
290
+ row[name] = masker(value, masks[name], name in uniques, cols[name])
291
+ else:
292
+ row[name] = value
293
+ out.append(row)
294
+ rows[t] = out
295
+ # Every column another table's key points at: a reference to a value of it becomes a reference to its row.
296
+ pointed = {fk["references"][0] for tt in taken for fk in known[tt].get("fks", []) if fk["table"] == t and len(fk["references"]) == 1}
297
+ for col in pointed:
298
+ index[f"{t}.{col}"] = {r.get(col): i for i, r in enumerate(taken[t])}
299
+ return Generated(order=order, rows=rows, generated=generated, warnings=warnings), plan