@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,214 @@
1
+ """
2
+ The check every statement passes before it reaches a database. SQL comes from the model, which reads text other people
3
+ control (tickets, schemas, table comments), so it is untrusted: it is parsed with sqlglot in the database's dialect and
4
+ judged on the parse tree, never on keywords in the text.
5
+
6
+ - **Read** (any connection): exactly one SELECT (with CTEs and set operations), SHOW, DESCRIBE, or EXPLAIN of a SELECT.
7
+ Nothing inside may write (a data-modifying CTE, SELECT INTO), lock rows (FOR UPDATE), or call a function that
8
+ reaches outside the query (files, other sessions, other servers, sleeps).
9
+ - **Write** (only on a connection marked writable, and only after the user confirms): one INSERT, or one UPDATE or
10
+ DELETE with a WHERE clause. Never DDL, MERGE, TRUNCATE, procedures or several statements.
11
+
12
+ Anything sqlglot cannot parse is refused: what cannot be read cannot be judged. The connection is also opened read-only
13
+ where the database supports it (connect.py), so this check is one of two layers.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import re
19
+ from dataclasses import dataclass, field
20
+ from typing import List, Optional
21
+
22
+ import sqlglot
23
+ from sqlglot import exp
24
+
25
+ # sqlglot logs a warning when it falls back to an opaque Command; that statement is refused anyway.
26
+ logging.getLogger("sqlglot").setLevel(logging.ERROR)
27
+
28
+ # ForgeQE's engine names to sqlglot dialects. An engine not listed parses with sqlglot's generic dialect.
29
+ DIALECTS = {
30
+ "postgres": "postgres",
31
+ "redshift": "redshift",
32
+ "cockroachdb": "postgres",
33
+ "mysql": "mysql",
34
+ "mariadb": "mysql",
35
+ "mssql": "tsql",
36
+ "oracle": "oracle",
37
+ "sqlite": "sqlite",
38
+ "duckdb": "duckdb",
39
+ "snowflake": "snowflake",
40
+ "bigquery": "bigquery",
41
+ "clickhouse": "clickhouse",
42
+ "databricks": "databricks",
43
+ "trino": "trino",
44
+ }
45
+
46
+ # Functions that read files, run commands, reach other servers or sessions, change settings or sequences, or sleep.
47
+ # Matched on the lower-case name: an exact name, or a prefix ending in "_" for a family.
48
+ _BLOCKED_FUNCTIONS = {
49
+ # Postgres
50
+ "pg_read_file", "pg_read_binary_file", "pg_ls_dir", "pg_stat_file", "pg_terminate_backend", "pg_cancel_backend",
51
+ "pg_reload_conf", "pg_rotate_logfile", "pg_sleep", "pg_sleep_for", "pg_sleep_until", "set_config", "nextval",
52
+ "setval", "query_to_xml", "query_to_xml_and_xmlschema", "query_to_xmlschema", "lo_import", "lo_export",
53
+ "lo_unlink", "lo_from_bytea", "lo_put", "pg_logical_emit_message", "pg_switch_wal", "pg_create_restore_point",
54
+ "pg_promote", "txid_current", "pg_current_xact_id",
55
+ # MySQL / MariaDB
56
+ "load_file", "sleep", "benchmark", "get_lock", "release_lock", "release_all_locks", "sys_exec", "sys_eval",
57
+ "master_pos_wait", "source_pos_wait",
58
+ # SQL Server
59
+ "openrowset", "opendatasource", "openquery", "waitfor",
60
+ # Oracle
61
+ "httpuritype", "dbms_lock", "dbms_pipe",
62
+ # SQLite (extensions, the fileio functions of the shell) and DuckDB (files and the network)
63
+ "load_extension", "readfile", "writefile", "edit", "fts3_tokenizer", "glob", "install", "load", "sniff_csv",
64
+ "httpfs", "query_table", "query",
65
+ }
66
+ _BLOCKED_PREFIXES = ("pg_advisory", "lo_", "dblink", "xp_", "sp_", "utl_", "dbms_", "fn_xe_", "read_", "parquet_", "iceberg_", "delta_scan")
67
+
68
+ # MySQL runs the text of /*! ... */ comments as SQL; sqlglot drops them as comments.
69
+ _EXECUTABLE_COMMENT = re.compile(r"/\*[!M]")
70
+ _EXPLAIN = re.compile(r"^\s*explain\s+(?!analy[sz]e\b)", re.IGNORECASE)
71
+
72
+ # Nodes that change data or the database, or hand the text to the server unparsed. None may appear in a read.
73
+ _WRITES = (exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.Create, exp.Drop, exp.Alter, exp.TruncateTable,
74
+ exp.Command, exp.Copy, exp.Execute, exp.Into, exp.Lock, exp.Set, exp.Transaction, exp.Commit,
75
+ exp.Rollback, exp.Grant, exp.Use, exp.Pragma, exp.LoadData)
76
+
77
+
78
+ @dataclass
79
+ class Verdict:
80
+ ok: bool
81
+ kind: str = "" # read or write
82
+ reason: str = ""
83
+ # The statement to run: sqlglot's rendering of the tree it judged, so what runs is what was checked.
84
+ sql: str = ""
85
+ tables: List[str] = field(default_factory=list)
86
+
87
+
88
+ def dialect_of(engine: str) -> str:
89
+ return DIALECTS.get((engine or "").lower(), "")
90
+
91
+
92
+ def _refuse(reason: str) -> Verdict:
93
+ return Verdict(ok=False, reason=reason)
94
+
95
+
96
+ def _function_name(node: exp.Func) -> str:
97
+ return (node.name if isinstance(node, exp.Anonymous) else node.sql_name()).lower()
98
+
99
+
100
+ def _blocked_function(tree: exp.Expression) -> Optional[str]:
101
+ for node in tree.find_all(exp.Func):
102
+ name = _function_name(node)
103
+ if name in _BLOCKED_FUNCTIONS or name.startswith(_BLOCKED_PREFIXES):
104
+ return name
105
+ # Qualified calls name the function or its package in the qualifier: pg_catalog.pg_read_file(), UTL_HTTP.REQUEST().
106
+ for node in tree.find_all(exp.Dot):
107
+ part: exp.Expression = node
108
+ while isinstance(part, exp.Dot):
109
+ for name in (part.expression.name.lower(), part.this.name.lower()):
110
+ if name in _BLOCKED_FUNCTIONS or name.startswith(_BLOCKED_PREFIXES):
111
+ return name
112
+ part = part.this
113
+ return None
114
+
115
+
116
+ def _tables(tree: exp.Expression) -> List[str]:
117
+ ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
118
+ out: List[str] = []
119
+ for t in tree.find_all(exp.Table):
120
+ name = ".".join(p for p in (t.catalog, t.db, t.name) if p)
121
+ if name and name.lower() not in ctes and name not in out:
122
+ out.append(name)
123
+ return out
124
+
125
+
126
+ def _parse_one(sql: str, dialect: str) -> exp.Expression:
127
+ trees = [t for t in sqlglot.parse(sql, read=dialect or None) if t is not None]
128
+ if len(trees) != 1:
129
+ raise ValueError("Exactly one statement is allowed" if trees else "Empty SQL statement")
130
+ return trees[0]
131
+
132
+
133
+ def _is_read_root(tree: exp.Expression) -> bool:
134
+ return isinstance(tree, (exp.Select, exp.SetOperation, exp.Show, exp.Describe))
135
+
136
+
137
+ def check(sql: str, engine: str, *, writable: bool = False) -> Verdict:
138
+ """Judge one statement for a database of `engine`; `writable` allows the narrow set of writes above."""
139
+ text = (sql or "").strip().rstrip(";").strip()
140
+ if not text:
141
+ return _refuse("Empty SQL statement")
142
+ if _EXECUTABLE_COMMENT.search(text):
143
+ return _refuse("MySQL executable comments (/*! */) are not allowed")
144
+ dialect = dialect_of(engine)
145
+ explain = _EXPLAIN.match(text)
146
+ body = text[explain.end():] if explain else text
147
+ try:
148
+ tree = _parse_one(body, dialect)
149
+ except ValueError as err:
150
+ return _refuse(str(err))
151
+ except Exception as err: # sqlglot raises ParseError, TokenError and others
152
+ return _refuse(f"Could not parse the SQL for {engine or 'this database'}: {str(err).splitlines()[0][:200]}")
153
+
154
+ blocked = _blocked_function(tree)
155
+ if blocked:
156
+ return _refuse(f"The function {blocked} is not allowed: it reaches outside the query")
157
+
158
+ if _is_read_root(tree):
159
+ found = next((n for n in tree.walk() if isinstance(n, _WRITES)), None)
160
+ if found is not None:
161
+ what = "SELECT INTO" if isinstance(found, exp.Into) else "FOR UPDATE" if isinstance(found, exp.Lock) else found.key.upper()
162
+ return _refuse(f"Only read-only queries are allowed; this one contains {what}")
163
+ rendered = tree.sql(dialect=dialect or None)
164
+ return Verdict(ok=True, kind="read", sql=f"EXPLAIN {rendered}" if explain else rendered, tables=_tables(tree))
165
+
166
+ if explain:
167
+ return _refuse("EXPLAIN is allowed for SELECT queries only")
168
+ if not isinstance(tree, (exp.Insert, exp.Update, exp.Delete)):
169
+ return _refuse(f"{tree.key.upper()} statements are not allowed")
170
+ if not writable:
171
+ return _refuse("This connection is read-only; writes need a connection marked writable: true")
172
+ nested = [n for n in tree.walk() if n is not tree and isinstance(n, _WRITES)]
173
+ if nested:
174
+ return _refuse(f"The {tree.key.upper()} contains another statement ({nested[0].key.upper()})")
175
+ if isinstance(tree, (exp.Update, exp.Delete)) and not tree.args.get("where"):
176
+ return _refuse(f"{tree.key.upper()} without a WHERE clause would change every row; add a WHERE clause")
177
+ return Verdict(ok=True, kind="write", sql=tree.sql(dialect=dialect or None), tables=_tables(tree))
178
+
179
+
180
+ def zero_rows(sql: str, engine: str) -> Optional[str]:
181
+ """
182
+ A checked read wrapped to return no rows: SELECT * FROM (<query>) WHERE 1 = 0. The database still resolves every
183
+ table, column and function in it, so a dry run finds wrong names and types without reading data. None for SHOW,
184
+ DESCRIBE and EXPLAIN, which the database cannot wrap.
185
+ """
186
+ dialect = dialect_of(engine)
187
+ try:
188
+ tree = _parse_one(sql, dialect)
189
+ except Exception:
190
+ return None
191
+ if not isinstance(tree, (exp.Select, exp.SetOperation)):
192
+ return None
193
+ inner = tree.copy()
194
+ # An ORDER BY without TOP is not allowed in a subquery on SQL Server, and changes nothing about the names.
195
+ if not (inner.args.get("limit") or inner.args.get("fetch")):
196
+ inner.set("order", None)
197
+ wrapped = exp.select("*").from_(inner.subquery("forgeqe_check")).where("1 = 0")
198
+ return wrapped.sql(dialect=dialect or None)
199
+
200
+
201
+ def limited(sql: str, engine: str, rows: int) -> str:
202
+ """A checked read with a row cap in the database's own syntax (LIMIT, TOP, FETCH FIRST), unless it has one already."""
203
+ dialect = dialect_of(engine)
204
+ if _EXPLAIN.match(sql):
205
+ return sql
206
+ try:
207
+ tree = _parse_one(sql, dialect)
208
+ except Exception:
209
+ return sql
210
+ if not isinstance(tree, (exp.Select, exp.SetOperation)):
211
+ return sql
212
+ if tree.args.get("limit") or tree.args.get("fetch"):
213
+ return sql
214
+ return tree.limit(rows).sql(dialect=dialect or None)
@@ -0,0 +1,219 @@
1
+ """
2
+ MongoDB, the same way as the SQL databases: a connection from a databases: entry, what the collections hold, and
3
+ operations checked before they run. The model writes an operation as JSON instead of SQL:
4
+
5
+ {"op": "find", "collection": "orders", "filter": {"status": "PAID"}, "projection": {"_id": 0}, "sort": {"total": -1}, "limit": 20}
6
+ {"op": "aggregate", "collection": "orders", "pipeline": [{"$group": {"_id": "$country", "n": {"$sum": 1}}}]}
7
+ {"op": "count", "collection": "orders", "filter": {}} {"op": "distinct", "collection": "orders", "field": "status"}
8
+
9
+ Reads: find, aggregate, count, distinct. Nowhere in a filter or pipeline: operators that run JavaScript ($where,
10
+ $function, $accumulator) or write ($out, $merge), and no system.* collection. Writes (insert_one, insert_many,
11
+ update_one, update_many, delete_one, delete_many) only on a database marked writable, after the user confirms, and an
12
+ update or a delete needs a filter that is not empty. MongoDB has no read-only session: use a read-only user.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import datetime as dt
17
+ import decimal
18
+ import json
19
+ import time
20
+ from typing import Any, Dict, List, Mapping, Optional, Tuple
21
+
22
+ from .connect import ConnectError, Target
23
+
24
+ READS = ("find", "aggregate", "count", "distinct")
25
+ WRITES = ("insert_one", "insert_many", "update_one", "update_many", "delete_one", "delete_many")
26
+ FORBIDDEN = {"$where", "$function", "$accumulator", "$out", "$merge"}
27
+ SAMPLE = 50
28
+
29
+
30
+ def uri(t: Target) -> str:
31
+ """The connection URI: mongodb:// or mongodb+srv:// with the user and password, quoted."""
32
+ from urllib.parse import quote_plus
33
+
34
+ i = t.info
35
+ scheme = "mongodb+srv" if i.params.get("srv") == "true" or "+srv" in (i.params.get("_scheme") or "") else "mongodb"
36
+ auth = f"{quote_plus(i.user)}:{quote_plus(i.password)}@" if i.user else ""
37
+ host = i.host if scheme == "mongodb+srv" else f"{i.host}:{i.port or 27017}"
38
+ query = {k: v for k, v in i.params.items() if not k.startswith("_") and k != "srv"}
39
+ if t.ssl == "verify" or (t.cloud and t.ssl != "disable"):
40
+ query.setdefault("tls", "true")
41
+ q = "&".join(f"{k}={quote_plus(str(v))}" for k, v in query.items())
42
+ return f"{scheme}://{auth}{host}/{i.database or ''}{'?' + q if q else ''}"
43
+
44
+
45
+ def client(t: Target) -> Any:
46
+ try:
47
+ from pymongo import MongoClient
48
+ except ImportError as err:
49
+ raise ConnectError("MongoDB needs pymongo in the data engine (forgeqe sets it up for a mongodb database)") from err
50
+ return MongoClient(uri(t), serverSelectionTimeoutMS=15_000, socketTimeoutMS=t.timeout * 1000, connectTimeoutMS=15_000, appname="forgeqe")
51
+
52
+
53
+ def _db(t: Target, c: Any) -> Any:
54
+ name = t.info.database or t.info.schema
55
+ if not name:
56
+ raise ConnectError(f"{t.name}: name the MongoDB database (database:, or the path of the connection string)")
57
+ return c[name]
58
+
59
+
60
+ def _plain(v: Any) -> Any:
61
+ """BSON values as JSON: ObjectId and the like as text, dates as ISO, Decimal128 as text."""
62
+ if isinstance(v, dict):
63
+ return {k: _plain(x) for k, x in v.items()}
64
+ if isinstance(v, (list, tuple)):
65
+ return [_plain(x) for x in v]
66
+ if isinstance(v, (dt.datetime, dt.date)):
67
+ return v.isoformat()
68
+ if isinstance(v, (str, int, float, bool)) or v is None:
69
+ return v
70
+ if isinstance(v, (bytes, bytearray)):
71
+ return f"<{len(v)} bytes>"
72
+ if isinstance(v, decimal.Decimal):
73
+ return str(v)
74
+ return str(v)
75
+
76
+
77
+ def check(raw: str, writable: bool) -> Tuple[Dict[str, Any], str]:
78
+ """The operation parsed and judged: (operation, "read" or "write"); raises ValueError with the reason when refused."""
79
+ try:
80
+ op = json.loads(raw) if isinstance(raw, str) else raw
81
+ except ValueError as err:
82
+ raise ValueError(f"A MongoDB operation is JSON, for example {{\"op\": \"find\", \"collection\": \"orders\", \"filter\": {{}}}}: {err}") from None
83
+ if not isinstance(op, dict):
84
+ raise ValueError("A MongoDB operation is a JSON object with op and collection")
85
+ kind = op.get("op")
86
+ if kind not in READS + WRITES:
87
+ raise ValueError(f"op is one of {', '.join(READS + WRITES)}")
88
+ coll = op.get("collection")
89
+ if not isinstance(coll, str) or not coll or coll.startswith("system.") or "$" in coll:
90
+ raise ValueError("collection names a collection of the database (never system.*)")
91
+ found = _forbidden(op)
92
+ if found:
93
+ raise ValueError(f"{found} is not allowed: it runs code on the server or writes another collection")
94
+ if kind in WRITES:
95
+ if not writable:
96
+ raise ValueError("This connection is read-only; writes need a connection marked writable: true")
97
+ if kind.startswith(("update", "delete")) and not op.get("filter"):
98
+ raise ValueError(f"{kind} without a filter would change every document; give a filter")
99
+ if kind.startswith("update") and not (isinstance(op.get("update"), dict) and all(k.startswith("$") for k in op["update"])):
100
+ raise ValueError("update is an update document of operators, for example {\"$set\": {\"status\": \"PAID\"}}")
101
+ if kind.startswith("insert") and not (op.get("documents") if kind == "insert_many" else op.get("document")):
102
+ raise ValueError("insert_one takes document, insert_many documents")
103
+ return op, "write" if kind in WRITES else "read"
104
+
105
+
106
+ def _forbidden(value: Any) -> Optional[str]:
107
+ if isinstance(value, dict):
108
+ for k, v in value.items():
109
+ if k in FORBIDDEN:
110
+ return k
111
+ if k in ("$lookup", "$graphLookup", "$unionWith") and isinstance(v, (dict, str)):
112
+ target = v if isinstance(v, str) else v.get("from") or v.get("coll") or ""
113
+ if str(target).startswith("system."):
114
+ return f"{k} from {target}"
115
+ found = _forbidden(v)
116
+ if found:
117
+ return found
118
+ elif isinstance(value, list):
119
+ for v in value:
120
+ found = _forbidden(v)
121
+ if found:
122
+ return found
123
+ return None
124
+
125
+
126
+ def op_test(t: Target) -> Dict[str, Any]:
127
+ started = time.time()
128
+ c = client(t)
129
+ try:
130
+ c.admin.command("ping")
131
+ info = c.server_info()
132
+ _db(t, c).list_collection_names()
133
+ finally:
134
+ c.close()
135
+ return {"ok": True, "server_version": info.get("version"), "ms": int((time.time() - started) * 1000)}
136
+
137
+
138
+ def _shape(docs: List[Mapping[str, Any]]) -> Dict[str, List[str]]:
139
+ """Field paths of sampled documents (one level into sub-documents) and the types seen for each."""
140
+ fields: Dict[str, set] = {}
141
+ for d in docs:
142
+ for k, v in d.items():
143
+ fields.setdefault(k, set()).add(type(v).__name__)
144
+ if isinstance(v, dict):
145
+ for k2, v2 in v.items():
146
+ fields.setdefault(f"{k}.{k2}", set()).add(type(v2).__name__)
147
+ return {k: sorted(v) for k, v in fields.items()}
148
+
149
+
150
+ def read_catalog(t: Target) -> Dict[str, Any]:
151
+ """Collections with their sampled fields, indexes and document counts, in the same shape as a SQL catalog."""
152
+ c = client(t)
153
+ try:
154
+ db = _db(t, c)
155
+ tables: Dict[str, Any] = {}
156
+ for name in sorted(n for n in db.list_collection_names() if not n.startswith("system.")):
157
+ coll = db[name]
158
+ docs = list(coll.find({}, limit=SAMPLE))
159
+ shape = _shape(docs)
160
+ uniques = [list(ix["key"].keys()) for ix in coll.list_indexes() if ix.get("unique")]
161
+ tables[name] = {
162
+ "kind": "collection",
163
+ "columns": [{"name": k, "type": "|".join(v), "nullable": True} for k, v in shape.items()],
164
+ "pk": ["_id"],
165
+ "fks": [],
166
+ "unique": uniques,
167
+ "comment": "",
168
+ "rows": coll.estimated_document_count(),
169
+ }
170
+ finally:
171
+ c.close()
172
+ return {"version": 2, "schema": None, "tables": tables, "read_at": time.time(), "fingerprint": None, "checked_at": time.time()}
173
+
174
+
175
+ def render(catalog: Mapping[str, Any], names: List[str]) -> str:
176
+ out = []
177
+ for n in names:
178
+ t = catalog["tables"].get(n)
179
+ if not t:
180
+ continue
181
+ fields = ", ".join(f"{c['name']}: {c['type']}" for c in t["columns"][:60])
182
+ out.append(f"collection {n} (~{t.get('rows', '?')} documents): {fields}" + (f"\n unique: {t['unique']}" if t.get("unique") else ""))
183
+ return "\n".join(out)
184
+
185
+
186
+ def run(t: Target, raw: str, *, confirmed: bool, max_rows: int, mask: Any) -> Dict[str, Any]:
187
+ op, kind = check(raw, t.writable)
188
+ if kind == "write" and not confirmed:
189
+ return {"ok": False, "needs_confirmation": True, "sql": json.dumps(op), "tables": [op["collection"]]}
190
+ started = time.time()
191
+ c = client(t)
192
+ try:
193
+ coll = _db(t, c)[op["collection"]]
194
+ name = op["op"]
195
+ if name == "find":
196
+ cursor = coll.find(op.get("filter") or {}, op.get("projection") or None, limit=max_rows + 1, max_time_ms=t.timeout * 1000)
197
+ if op.get("sort"):
198
+ cursor = cursor.sort(list(op["sort"].items()))
199
+ docs = list(cursor)
200
+ elif name == "aggregate":
201
+ pipeline = list(op.get("pipeline") or []) + [{"$limit": max_rows + 1}]
202
+ docs = list(coll.aggregate(pipeline, maxTimeMS=t.timeout * 1000))
203
+ elif name == "count":
204
+ docs = [{"count": coll.count_documents(op.get("filter") or {}, maxTimeMS=t.timeout * 1000)}]
205
+ elif name == "distinct":
206
+ docs = [{"value": v} for v in coll.distinct(str(op.get("field") or ""), op.get("filter") or {}, maxTimeMS=t.timeout * 1000)][: max_rows + 1]
207
+ else:
208
+ result = getattr(coll, name)(*([op["document"]] if name == "insert_one" else [op["documents"]] if name == "insert_many" else [op["filter"], op["update"]] if name.startswith("update") else [op["filter"]]))
209
+ changed = getattr(result, "modified_count", None) or getattr(result, "deleted_count", None) or len(getattr(result, "inserted_ids", []) or ([] if getattr(result, "inserted_id", None) is None else [1]))
210
+ return {"ok": True, "kind": "write", "sql": json.dumps(op), "tables": [op["collection"]], "rows_affected": int(changed or 0), "ms": int((time.time() - started) * 1000)}
211
+ finally:
212
+ c.close()
213
+ columns = list(dict.fromkeys(k for d in docs[:max_rows] for k in d))
214
+ masked = [mask(k) for k in columns]
215
+ rows = [["•••" if masked[i] and d.get(k) is not None else _plain(d.get(k)) for i, k in enumerate(columns)] for d in docs[:max_rows]]
216
+ out: Dict[str, Any] = {"ok": True, "kind": "read", "sql": json.dumps(op), "tables": [op["collection"]], "columns": columns, "rows": rows, "row_count": len(rows), "truncated": len(docs) > max_rows, "ms": int((time.time() - started) * 1000)}
217
+ if any(masked):
218
+ out["masked_columns"] = [k for k, m in zip(columns, masked) if m]
219
+ return out