@capagents/forgeqe 2.10.4 → 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.
- package/HOW_TO_USE.md +119 -16
- package/README.md +1 -1
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/dist/docs-site/docs/architecture/index.html +1 -0
- package/dist/docs-site/docs/cost-architecture/index.html +1 -1
- package/dist/docs-site/docs/index.html +158 -19
- package/dist/docs-site/docs/mobile/index.html +38 -2
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +2121 -1947
- package/dist/web/assets/Agent-DISh0THc.js +8 -0
- package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
- package/dist/web/assets/Browse-WylAQZvD.js +2 -0
- package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
- package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
- package/dist/web/assets/Compare-CgOfZofk.js +1 -0
- package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
- package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
- package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
- package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
- package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
- package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
- package/dist/web/assets/Features-DXL_vSjn.js +1 -0
- package/dist/web/assets/Flags-B7x2pDud.js +2 -0
- package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
- package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
- package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
- package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
- package/dist/web/assets/Migration-BOLN1duU.js +2 -0
- package/dist/web/assets/Product-C0FeEaJg.js +7 -0
- package/dist/web/assets/Production-BSMQyWKd.js +1 -0
- package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
- package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
- package/dist/web/assets/Record-CPx-lK53.js +2 -0
- package/dist/web/assets/Regression-BXbX46nO.js +5 -0
- package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
- package/dist/web/assets/Reports-36YQzVhA.js +2 -0
- package/dist/web/assets/Response-DplUOsue.js +4 -0
- package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
- package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
- package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
- package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
- package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
- package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
- package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
- package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
- package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
- package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
- package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
- package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
- package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
- package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
- package/dist/web/assets/fold-BhRpA0sy.js +1 -0
- package/dist/web/assets/frame-D_TPoUTD.js +16 -0
- package/dist/web/assets/index-BRB-oAMd.js +67 -0
- package/dist/web/assets/index-CIw5WfL8.css +2 -0
- package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
- package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
- package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
- package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
- package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
- package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
- package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
- package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
- package/dist/web/assets/rows-uLoguIo5.js +1 -0
- package/dist/web/assets/segmented-DphDskQz.js +1 -0
- package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
- package/dist/web/index.html +6 -6
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/COST_ARCHITECTURE.md +1 -1
- package/docs/MOBILE.md +40 -0
- package/docs/user-guide.html +158 -19
- package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
- package/forgeqe.example.yaml +11 -1
- package/package.json +4 -1
- package/prompts/brain.md +4 -0
- package/prompts/browser-goal-verification.md +2 -0
- package/prompts/refine.md +2 -0
- package/prompts/requests-rule.md +1 -1
- package/prompts/talk-summary.md +43 -0
- package/prompts/talk.md +49 -0
- package/prompts/test-agent.md +1 -0
- package/prompts/test-reviewer.md +2 -1
- package/prompts/test-rules.md +3 -0
- package/py/forgeqe_data/__init__.py +1 -0
- package/py/forgeqe_data/__main__.py +12 -0
- package/py/forgeqe_data/connect.py +290 -0
- package/py/forgeqe_data/connstr.py +169 -0
- package/py/forgeqe_data/flows.py +603 -0
- package/py/forgeqe_data/guard.py +214 -0
- package/py/forgeqe_data/mongo.py +219 -0
- package/py/forgeqe_data/schema.py +431 -0
- package/py/forgeqe_data/service.py +651 -0
- package/py/forgeqe_data/streams.py +400 -0
- package/py/forgeqe_data/subset.py +299 -0
- package/py/forgeqe_data/testdata.py +861 -0
- package/py/forgeqe_data/vector.py +113 -0
- package/py/forgeqe_desktop/workflow.py +6 -4
- package/py/forgeqe_engine/capture.py +5 -4
- package/py/forgeqe_engine/diagnostics.py +2 -2
- package/py/forgeqe_engine/lenient_json.py +96 -0
- package/py/forgeqe_engine/llm.py +4 -0
- package/py/forgeqe_engine/network.py +93 -15
- package/py/forgeqe_engine/neutral_log.py +16 -1
- package/py/forgeqe_engine/recordsession.py +54 -1
- package/py/forgeqe_engine/service.py +22 -3
- package/py/forgeqe_mobile/appium_driver.py +9 -0
- package/py/forgeqe_mobile/apps.py +4 -0
- package/py/forgeqe_mobile/maestro.py +3 -0
- package/py/forgeqe_mobile/record.py +610 -0
- package/py/forgeqe_mobile/service.py +37 -7
- package/py/forgeqe_talk/__init__.py +1 -0
- package/py/forgeqe_talk/__main__.py +65 -0
- package/py/forgeqe_voice/worker.py +141 -0
- package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
- package/skills/playwright-typescript/SKILL.md +1 -1
- package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
- package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
- package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
- package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
- package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
- package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
- package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
- package/dist/web/assets/Data-BWTme_Yw.js +0 -6
- package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
- package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
- package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
- package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
- package/dist/web/assets/Features-DazEWqYu.js +0 -1
- package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
- package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
- package/dist/web/assets/Impact-De87sv5J.js +0 -3
- package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
- package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
- package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
- package/dist/web/assets/Product-DpK-PIxV.js +0 -7
- package/dist/web/assets/Production-D6A89rZZ.js +0 -1
- package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
- package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
- package/dist/web/assets/Record-DcgBatJJ.js +0 -2
- package/dist/web/assets/Regression-BJLYrqST.js +0 -5
- package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
- package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
- package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
- package/dist/web/assets/Runs-lb78rvPV.js +0 -2
- package/dist/web/assets/Steps-BDSeIznj.js +0 -2
- package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
- package/dist/web/assets/TestData-DP7cvW48.js +0 -2
- package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
- package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
- package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
- package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
- package/dist/web/assets/filters-CflRmNDz.js +0 -1
- package/dist/web/assets/fold-pOBiaSlF.js +0 -1
- package/dist/web/assets/frame-CYYiRu5P.js +0 -4
- package/dist/web/assets/index-CNDoTeRV.css +0 -2
- package/dist/web/assets/index-D4a0w3Vl.js +0 -67
- package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
- package/dist/web/assets/parts-C53RxMcR.js +0 -1
- package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
- package/dist/web/assets/rows-D6rPRkHl.js +0 -1
- package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
- package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
|
@@ -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
|