@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.
- package/HOW_TO_USE.md +93 -19
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/dist/docs-site/docs/index.html +78 -16
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +1946 -1929
- 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-D7ufvlUN.js → CommandPalette-CkreEJ8R.js} +1 -1
- package/dist/web/assets/Compare-CgOfZofk.js +1 -0
- package/dist/web/assets/{Cost-DGZ5t-Q_.js → Cost-Dl5-viu4.js} +1 -1
- package/dist/web/assets/{Data-DqGA1ZtQ.js → Data-Bv2S5wkW.js} +4 -4
- 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-TtfTWmGW.js → Explore-c85VGE9Q.js} +2 -2
- package/dist/web/assets/{Features-DazoSiEi.js → Features-DXL_vSjn.js} +1 -1
- package/dist/web/assets/{Flags-Brja-ZXF.js → Flags-B7x2pDud.js} +2 -2
- 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-C4Aak_hw.js → Quality-DsM9gWZb.js} +1 -1
- 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-DLeEarQd.js → RelationGraph-eoGXXz5t.js} +1 -1
- package/dist/web/assets/{Reports-ClSAzQOh.js → Reports-36YQzVhA.js} +2 -2
- package/dist/web/assets/Response-DplUOsue.js +4 -0
- package/dist/web/assets/{RunDiff-0ibEcmI5.js → RunDiff-D0fDhRmK.js} +1 -1
- package/dist/web/assets/{Runs-T8yF8Hi0.js → Runs-Bv1Ef8zq.js} +2 -2
- package/dist/web/assets/{Steps-CB30w6BA.js → Steps-Cm-atRtk.js} +2 -2
- 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-D7n48IsG.js → WhatsNew-CdnbMvrr.js} +1 -1
- package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
- package/dist/web/assets/{dataParts-CZAcb4L_.js → dataParts-Bn-tzbKg.js} +3 -3
- package/dist/web/assets/{families-D2ygriY6.js → families-DPlFfKf2.js} +1 -1
- package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
- package/dist/web/assets/{fold-BhYvId2X.js → fold-BhRpA0sy.js} +1 -1
- 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/{logos-DmK40tlV.js → logos-839CfoKx.js} +1 -1
- package/dist/web/assets/{markdown-Bej6qyls.js → markdown-6z0km3hN.js} +3 -3
- package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
- package/dist/web/assets/{parts-BOpbd90H.js → parts-VPcxh6Jc.js} +1 -1
- package/dist/web/assets/{productParts-B3_FGd-T.js → productParts-BjfWgMtq.js} +1 -1
- package/dist/web/assets/{qualityParts-B8yJRVpP.js → qualityParts-PGN65yfI.js} +1 -1
- package/dist/web/assets/{recordTest-CZUrGm8I.js → recordTest-EkxSMWbe.js} +1 -1
- package/dist/web/assets/{rows-BcG6gFCy.js → rows-uLoguIo5.js} +1 -1
- package/dist/web/assets/{segmented-ffWUfF8N.js → segmented-DphDskQz.js} +1 -1
- package/dist/web/assets/{usePageChat-T6vQY_1C.js → usePageChat-DqEwGcyO.js} +1 -1
- package/dist/web/index.html +5 -5
- package/docs/user-guide.html +78 -16
- package/package.json +3 -1
- 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/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_talk/__init__.py +1 -0
- package/py/forgeqe_talk/__main__.py +65 -0
- package/py/forgeqe_voice/worker.py +24 -4
- package/dist/web/assets/Agent-bSVNDlcU.js +0 -8
- package/dist/web/assets/ApiTests-DOxGgoZC.js +0 -10
- package/dist/web/assets/Browse-CG8jzqR1.js +0 -2
- package/dist/web/assets/Chat-DzufzeGg.js +0 -5
- package/dist/web/assets/Compare-6vHuAaKv.js +0 -1
- package/dist/web/assets/Desktop-CSOFE8cN.js +0 -1
- package/dist/web/assets/DesktopReview-BWtionFH.js +0 -1
- package/dist/web/assets/Evidence-D8pLFcbr.js +0 -1
- package/dist/web/assets/Flaky-jJlHFFCa.js +0 -1
- package/dist/web/assets/Impact-b60dmhJK.js +0 -3
- package/dist/web/assets/Jobs-Y9W9nBgx.js +0 -5
- package/dist/web/assets/KindPage-Y72w2UwG.js +0 -6
- package/dist/web/assets/Migration-CvIeTB9p.js +0 -2
- package/dist/web/assets/Product-BEe2GyO6.js +0 -7
- package/dist/web/assets/Production-D2qmPFYy.js +0 -1
- package/dist/web/assets/Readiness-ClXnnmLo.js +0 -1
- package/dist/web/assets/Record-LaLYhQgk.js +0 -2
- package/dist/web/assets/Regression-DKz05MC_.js +0 -5
- package/dist/web/assets/Response-De60pk_7.js +0 -10
- package/dist/web/assets/TestCases-Ba6bUE4i.js +0 -1
- package/dist/web/assets/TestData-DefDzeMW.js +0 -2
- package/dist/web/assets/TestDebt-zohltDHp.js +0 -1
- package/dist/web/assets/Tosca-jAtdiG28.js +0 -3
- package/dist/web/assets/filters-CYaF2RvC.js +0 -1
- package/dist/web/assets/frame-DeJBYtBX.js +0 -11
- package/dist/web/assets/index-CYlacOTX.css +0 -2
- package/dist/web/assets/index-DXpBYobT.js +0 -67
- package/dist/web/assets/paletteCommands-CKBMmhb4.js +0 -1
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Opening a database from a ``databases:`` entry (forgeqe.yaml or the active environment in env.yaml). The entry holds
|
|
3
|
+
names of environment variables, never secrets: ``url_env`` (a whole connection string), or host, port, database, user
|
|
4
|
+
and ``password_env``. ``auth`` picks how to sign in: ``password``, ``azure`` (a Microsoft Entra ID token from
|
|
5
|
+
azure-identity, for Azure SQL and Azure Database for PostgreSQL and MySQL), or ``aws_iam`` (an RDS IAM token).
|
|
6
|
+
|
|
7
|
+
Every connection is opened for one purpose:
|
|
8
|
+
|
|
9
|
+
- **read**: in a read-only session where the database has one (Postgres, MySQL, Oracle, SQLite, DuckDB), always rolled
|
|
10
|
+
back at the end, so even a statement the guard missed cannot keep a change;
|
|
11
|
+
- **write**: only for a connection marked ``writable: true``, after the user confirmed the statement.
|
|
12
|
+
|
|
13
|
+
Each has a statement timeout in the database's own setting, and TLS is verified for cloud hosts.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import ssl as ssl_lib
|
|
20
|
+
import struct
|
|
21
|
+
import urllib.request
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Dict, Mapping, Optional
|
|
25
|
+
|
|
26
|
+
from .connstr import DEFAULT_PORTS, FILE_ENGINES, ConnInfo, cloud_of, parse
|
|
27
|
+
|
|
28
|
+
SUPPORTED = ("postgres", "cockroachdb", "redshift", "mysql", "mariadb", "mssql", "oracle", "sqlite", "duckdb", "snowflake", "mongodb", "kafka")
|
|
29
|
+
|
|
30
|
+
AZURE_DB_SCOPE = "https://ossrdbms-aad.database.windows.net/.default"
|
|
31
|
+
AZURE_SQL_SCOPE = "https://database.windows.net/.default"
|
|
32
|
+
RDS_CA_URL = "https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem"
|
|
33
|
+
# SQL_COPT_SS_ACCESS_TOKEN: the ODBC attribute that hands SQL Server an Entra ID token.
|
|
34
|
+
_SQL_COPT_SS_ACCESS_TOKEN = 1256
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ConnectError(Exception):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Target:
|
|
43
|
+
name: str
|
|
44
|
+
engine: str
|
|
45
|
+
info: ConnInfo
|
|
46
|
+
auth: str = "password"
|
|
47
|
+
region: str = ""
|
|
48
|
+
writable: bool = False
|
|
49
|
+
timeout: int = 30
|
|
50
|
+
# verify (default for cloud hosts), require (encrypt only), disable, or "" for the driver's default.
|
|
51
|
+
ssl: str = ""
|
|
52
|
+
ssl_ca: str = ""
|
|
53
|
+
options: Dict[str, str] = field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def cloud(self) -> str:
|
|
57
|
+
return cloud_of(self.info.host)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _env(env: Mapping[str, str], name: Any, what: str) -> str:
|
|
61
|
+
if not name:
|
|
62
|
+
return ""
|
|
63
|
+
value = env.get(str(name), "")
|
|
64
|
+
if not value:
|
|
65
|
+
raise ConnectError(f"{what}: the environment variable {name} is not set (save it with /auth {name})")
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def resolve(db: Mapping[str, Any], env: Mapping[str, str]) -> Target:
|
|
70
|
+
"""The connection a ``databases:`` entry describes, with secrets read from `env` by name."""
|
|
71
|
+
name = str(db.get("name") or "database")
|
|
72
|
+
info = parse(_env(env, db.get("url_env"), f"{name}.url_env")) if db.get("url_env") else ConnInfo()
|
|
73
|
+
for key in ("host", "database", "user", "schema", "path"):
|
|
74
|
+
if db.get(key):
|
|
75
|
+
setattr(info, key, str(db[key]))
|
|
76
|
+
if db.get("port"):
|
|
77
|
+
info.port = int(db["port"])
|
|
78
|
+
engine = str(db.get("engine") or info.engine or "").lower()
|
|
79
|
+
if engine not in SUPPORTED:
|
|
80
|
+
raise ConnectError(f"{name}: engine must be one of {', '.join(SUPPORTED)}" + (f", not {engine}" if engine else ""))
|
|
81
|
+
info.engine = engine
|
|
82
|
+
info.port = info.port or (None if info.params.get("srv") == "true" else DEFAULT_PORTS.get(engine))
|
|
83
|
+
auth = str(db.get("auth") or "password").lower()
|
|
84
|
+
if auth not in ("password", "azure", "aws_iam", "none"):
|
|
85
|
+
raise ConnectError(f"{name}: auth must be password, azure, aws_iam or none")
|
|
86
|
+
if db.get("password_env"):
|
|
87
|
+
info.password = _env(env, db.get("password_env"), f"{name}.password_env")
|
|
88
|
+
if engine not in FILE_ENGINES and not info.host:
|
|
89
|
+
raise ConnectError(f"{name}: no host (set host, or url_env with a connection string)")
|
|
90
|
+
if engine in FILE_ENGINES and not info.path:
|
|
91
|
+
raise ConnectError(f"{name}: no path to the {engine} file")
|
|
92
|
+
region = str(db.get("region") or "")
|
|
93
|
+
if auth == "aws_iam" and not region:
|
|
94
|
+
m = re.search(r"\.([a-z]{2}(?:-gov)?-[a-z]+-\d)\.(?:rds|redshift)", info.host)
|
|
95
|
+
region = m.group(1) if m else ""
|
|
96
|
+
options = {str(k): str(v) for k, v in (db.get("options") or {}).items()}
|
|
97
|
+
return Target(
|
|
98
|
+
name=name, engine=engine, info=info, auth=auth, region=region, writable=bool(db.get("writable")),
|
|
99
|
+
timeout=int(db.get("timeout_seconds") or 30), ssl=str(db.get("ssl") or "").lower(),
|
|
100
|
+
ssl_ca=str(db.get("ssl_ca") or ""), options=options,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _azure_token(scope: str) -> str:
|
|
105
|
+
try:
|
|
106
|
+
from azure.identity import DefaultAzureCredential
|
|
107
|
+
except ImportError as err:
|
|
108
|
+
raise ConnectError("auth: azure needs azure-identity in the data engine (forgeqe db setup)") from err
|
|
109
|
+
try:
|
|
110
|
+
return DefaultAzureCredential(exclude_interactive_browser_credential=True).get_token(scope).token
|
|
111
|
+
except Exception as err:
|
|
112
|
+
raise ConnectError(f"Could not get a Microsoft Entra ID token for the database ({err.__class__.__name__}). Sign in with `az login`, or set a managed identity or service principal.") from err
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _aws_token(t: Target) -> str:
|
|
116
|
+
try:
|
|
117
|
+
import boto3
|
|
118
|
+
except ImportError as err:
|
|
119
|
+
raise ConnectError("auth: aws_iam needs boto3 in the data engine (forgeqe db setup)") from err
|
|
120
|
+
if not t.region:
|
|
121
|
+
raise ConnectError(f"{t.name}: auth: aws_iam needs region (it could not be read from the host name)")
|
|
122
|
+
try:
|
|
123
|
+
client = boto3.client("rds", region_name=t.region)
|
|
124
|
+
return client.generate_db_auth_token(DBHostname=t.info.host, Port=t.info.port, DBUsername=t.info.user, Region=t.region)
|
|
125
|
+
except Exception as err:
|
|
126
|
+
raise ConnectError(f"Could not get an RDS IAM token ({err.__class__.__name__}: {err})") from err
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _home() -> Path:
|
|
130
|
+
return Path(os.environ.get("FORGEQE_HOME") or Path.home() / ".forgeqe")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def rds_ca() -> str:
|
|
134
|
+
"""Amazon RDS's CA bundle (not in the system's trust store), fetched once over verified HTTPS."""
|
|
135
|
+
path = _home() / "data" / "certs" / "rds-global-bundle.pem"
|
|
136
|
+
if not path.exists():
|
|
137
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
138
|
+
with urllib.request.urlopen(RDS_CA_URL, timeout=30, context=ssl_lib.create_default_context()) as res:
|
|
139
|
+
body = res.read()
|
|
140
|
+
if b"BEGIN CERTIFICATE" not in body:
|
|
141
|
+
raise ConnectError("The Amazon RDS CA bundle download did not contain certificates")
|
|
142
|
+
path.write_bytes(body)
|
|
143
|
+
return str(path)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _password(t: Target) -> str:
|
|
147
|
+
if t.auth == "azure":
|
|
148
|
+
return _azure_token(AZURE_SQL_SCOPE if t.engine == "mssql" else AZURE_DB_SCOPE)
|
|
149
|
+
if t.auth == "aws_iam":
|
|
150
|
+
return _aws_token(t)
|
|
151
|
+
return t.info.password
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _ssl_mode(t: Target) -> str:
|
|
155
|
+
if t.ssl:
|
|
156
|
+
return t.ssl
|
|
157
|
+
return "verify" if t.cloud or t.auth in ("azure", "aws_iam") else ""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _ca(t: Target) -> str:
|
|
161
|
+
if t.ssl_ca:
|
|
162
|
+
return t.ssl_ca
|
|
163
|
+
return rds_ca() if t.cloud == "aws" else ""
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def build(t: Target, *, write: bool = False) -> Any:
|
|
167
|
+
"""A SQLAlchemy engine for one request: no pool, read-only unless `write`, with a statement timeout."""
|
|
168
|
+
from sqlalchemy import create_engine, event
|
|
169
|
+
from sqlalchemy.engine import URL
|
|
170
|
+
from sqlalchemy.pool import NullPool
|
|
171
|
+
|
|
172
|
+
if write and not t.writable:
|
|
173
|
+
raise ConnectError(f"{t.name} is read-only; mark it writable: true to allow confirmed writes")
|
|
174
|
+
read_only = not write
|
|
175
|
+
ms = t.timeout * 1000
|
|
176
|
+
info, engine = t.info, t.engine
|
|
177
|
+
mode = _ssl_mode(t)
|
|
178
|
+
connect_args: Dict[str, Any] = {}
|
|
179
|
+
on_connect = []
|
|
180
|
+
on_begin = []
|
|
181
|
+
query: Dict[str, str] = {}
|
|
182
|
+
|
|
183
|
+
if engine in ("postgres", "cockroachdb", "redshift"):
|
|
184
|
+
url = URL.create("postgresql+psycopg", username=info.user or None, password=_password(t) or None, host=info.host, port=info.port, database=info.database or None)
|
|
185
|
+
if mode == "verify":
|
|
186
|
+
query.update(sslmode="verify-full", sslrootcert=_ca(t) or "system")
|
|
187
|
+
elif mode in ("require", "disable"):
|
|
188
|
+
query["sslmode"] = mode
|
|
189
|
+
if engine == "redshift":
|
|
190
|
+
on_connect.append(f"SET statement_timeout TO {ms}")
|
|
191
|
+
else:
|
|
192
|
+
connect_args["options"] = f"-c statement_timeout={ms}" + (" -c default_transaction_read_only=on" if read_only else "")
|
|
193
|
+
connect_args["connect_timeout"] = 15
|
|
194
|
+
elif engine in ("mysql", "mariadb"):
|
|
195
|
+
url = URL.create("mysql+pymysql", username=info.user or None, password=_password(t) or None, host=info.host, port=info.port, database=info.database or None)
|
|
196
|
+
if mode == "verify":
|
|
197
|
+
import certifi
|
|
198
|
+
|
|
199
|
+
connect_args["ssl"] = {"ca": _ca(t) or certifi.where()}
|
|
200
|
+
connect_args["ssl_verify_cert"] = True
|
|
201
|
+
connect_args["ssl_verify_identity"] = True
|
|
202
|
+
elif mode == "require":
|
|
203
|
+
connect_args["ssl"] = {"ca": None}
|
|
204
|
+
connect_args.update(connect_timeout=15, read_timeout=t.timeout + 10, write_timeout=t.timeout + 10)
|
|
205
|
+
on_connect.append(f"SET SESSION max_statement_time = {t.timeout}" if engine == "mariadb" else f"SET SESSION MAX_EXECUTION_TIME = {ms}")
|
|
206
|
+
if read_only:
|
|
207
|
+
on_connect.append("SET SESSION TRANSACTION READ ONLY")
|
|
208
|
+
elif engine == "mssql":
|
|
209
|
+
if t.auth == "azure":
|
|
210
|
+
# Entra ID tokens reach SQL Server only through Microsoft's ODBC driver.
|
|
211
|
+
odbc = ";".join([
|
|
212
|
+
f"DRIVER={{{t.options.get('odbc_driver', 'ODBC Driver 18 for SQL Server')}}}",
|
|
213
|
+
f"SERVER=tcp:{info.host},{info.port}", f"DATABASE={info.database}",
|
|
214
|
+
"Encrypt=yes", "TrustServerCertificate=no" if mode != "require" else "TrustServerCertificate=yes",
|
|
215
|
+
*(["ApplicationIntent=ReadOnly"] if read_only else []),
|
|
216
|
+
])
|
|
217
|
+
raw = _password(t).encode("utf-16-le")
|
|
218
|
+
url = URL.create("mssql+pyodbc", query={"odbc_connect": odbc})
|
|
219
|
+
connect_args["attrs_before"] = {_SQL_COPT_SS_ACCESS_TOKEN: struct.pack(f"<I{len(raw)}s", len(raw), raw)}
|
|
220
|
+
connect_args["timeout"] = 15
|
|
221
|
+
else:
|
|
222
|
+
url = URL.create("mssql+pymssql", username=info.user or None, password=_password(t) or None, host=info.host, port=info.port, database=info.database or None)
|
|
223
|
+
connect_args.update(timeout=t.timeout, login_timeout=15)
|
|
224
|
+
if mode in ("verify", "require"):
|
|
225
|
+
connect_args["tds_version"] = "7.4"
|
|
226
|
+
elif engine == "oracle":
|
|
227
|
+
url = URL.create("oracle+oracledb", username=info.user or None, password=_password(t) or None, host=info.host, port=info.port, query={"service_name": info.database} if info.database else {})
|
|
228
|
+
if mode == "verify":
|
|
229
|
+
connect_args.update(protocol="tcps", ssl_server_dn_match=True)
|
|
230
|
+
if read_only:
|
|
231
|
+
on_begin.append("SET TRANSACTION READ ONLY")
|
|
232
|
+
elif engine == "sqlite":
|
|
233
|
+
path = Path(info.path).expanduser()
|
|
234
|
+
if read_only:
|
|
235
|
+
url = URL.create("sqlite", database=f"file:{path}", query={"mode": "ro", "uri": "true"})
|
|
236
|
+
else:
|
|
237
|
+
url = URL.create("sqlite", database=str(path))
|
|
238
|
+
elif engine == "duckdb":
|
|
239
|
+
url = URL.create("duckdb", database=str(Path(info.path).expanduser()))
|
|
240
|
+
connect_args["read_only"] = read_only
|
|
241
|
+
elif engine == "snowflake":
|
|
242
|
+
account = info.host.split(".snowflakecomputing.com", 1)[0]
|
|
243
|
+
query = {k: v for k, v in info.params.items() if k in ("warehouse", "role")}
|
|
244
|
+
query.update({k: v for k, v in t.options.items() if k in ("warehouse", "role")})
|
|
245
|
+
url = URL.create("snowflake", username=info.user or None, password=_password(t) or None, host=account, database="/".join(p for p in (info.database, info.schema) if p) or None, query=query)
|
|
246
|
+
query = {}
|
|
247
|
+
connect_args["session_parameters"] = {"STATEMENT_TIMEOUT_IN_SECONDS": t.timeout}
|
|
248
|
+
else: # resolve() refuses anything else
|
|
249
|
+
raise ConnectError(f"Unsupported engine {engine}")
|
|
250
|
+
|
|
251
|
+
if query:
|
|
252
|
+
url = url.update_query_dict(query)
|
|
253
|
+
eng = create_engine(url, poolclass=NullPool, connect_args=connect_args)
|
|
254
|
+
|
|
255
|
+
if engine == "oracle":
|
|
256
|
+
@event.listens_for(eng, "connect")
|
|
257
|
+
def _oracle_timeout(dbapi_conn: Any, _rec: Any) -> None:
|
|
258
|
+
dbapi_conn.call_timeout = ms
|
|
259
|
+
|
|
260
|
+
if engine == "mssql" and t.auth == "azure":
|
|
261
|
+
@event.listens_for(eng, "connect")
|
|
262
|
+
def _odbc_timeout(dbapi_conn: Any, _rec: Any) -> None:
|
|
263
|
+
dbapi_conn.timeout = t.timeout
|
|
264
|
+
|
|
265
|
+
if on_connect:
|
|
266
|
+
@event.listens_for(eng, "connect")
|
|
267
|
+
def _session(dbapi_conn: Any, _rec: Any) -> None:
|
|
268
|
+
cur = dbapi_conn.cursor()
|
|
269
|
+
try:
|
|
270
|
+
for stmt in on_connect:
|
|
271
|
+
cur.execute(stmt)
|
|
272
|
+
finally:
|
|
273
|
+
cur.close()
|
|
274
|
+
if hasattr(dbapi_conn, "commit"):
|
|
275
|
+
dbapi_conn.commit()
|
|
276
|
+
|
|
277
|
+
if on_begin:
|
|
278
|
+
@event.listens_for(eng, "begin")
|
|
279
|
+
def _begin(conn: Any) -> None:
|
|
280
|
+
for stmt in on_begin:
|
|
281
|
+
conn.exec_driver_sql(stmt)
|
|
282
|
+
|
|
283
|
+
return eng
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def describe(t: Target) -> Dict[str, Any]:
|
|
287
|
+
"""The connection as ForgeQE may show it: no password, no token."""
|
|
288
|
+
i = t.info
|
|
289
|
+
where = i.path if t.engine in FILE_ENGINES else i.host if t.engine == "kafka" and ":" in i.host else f"{i.host}:{i.port}" if t.engine == "kafka" else f"{i.host}:{i.port}/{i.database}"
|
|
290
|
+
return {"name": t.name, "engine": t.engine, "where": where, "user": i.user, "auth": t.auth, "writable": t.writable, "cloud": t.cloud or None, "tls": _ssl_mode(t) or "driver default"}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Connection strings as teams have them: a URI (``postgresql://user@host:5432/db``, ``mssql://``, ``oracle://``,
|
|
3
|
+
``sqlite:///file.db``), JDBC (``jdbc:sqlserver://host:1433;databaseName=x``), or ADO.NET (``Server=tcp:x,1433;
|
|
4
|
+
Database=y;User ID=z``, as the Azure portal shows it). Parsed into one shape; the password, when the string carries
|
|
5
|
+
one, stays in the result only for connect.py and is never logged or returned to ForgeQE.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Dict, Optional
|
|
12
|
+
from urllib.parse import parse_qs, unquote, urlparse
|
|
13
|
+
|
|
14
|
+
ENGINES = {
|
|
15
|
+
"postgresql": "postgres", "postgres": "postgres", "psql": "postgres", "redshift": "redshift",
|
|
16
|
+
"cockroach": "cockroachdb", "cockroachdb": "cockroachdb", "mysql": "mysql", "mariadb": "mariadb",
|
|
17
|
+
"mssql": "mssql", "sqlserver": "mssql", "oracle": "oracle", "sqlite": "sqlite", "duckdb": "duckdb",
|
|
18
|
+
"snowflake": "snowflake", "clickhouse": "clickhouse", "trino": "trino", "mongodb": "mongodb",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
DEFAULT_PORTS = {
|
|
22
|
+
"postgres": 5432, "redshift": 5439, "cockroachdb": 26257, "mysql": 3306, "mariadb": 3306, "mssql": 1433,
|
|
23
|
+
"oracle": 1521, "clickhouse": 8123, "trino": 8080, "mongodb": 27017, "kafka": 9092,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
FILE_ENGINES = ("sqlite", "duckdb")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ConnInfo:
|
|
31
|
+
engine: str = ""
|
|
32
|
+
host: str = ""
|
|
33
|
+
port: Optional[int] = None
|
|
34
|
+
database: str = ""
|
|
35
|
+
user: str = ""
|
|
36
|
+
password: str = field(default="", repr=False)
|
|
37
|
+
# A file database's path (sqlite, duckdb).
|
|
38
|
+
path: str = ""
|
|
39
|
+
schema: str = ""
|
|
40
|
+
# Driver settings the string carried (sslmode, encrypt, warehouse, Authentication, ...), lower-case keys.
|
|
41
|
+
params: Dict[str, str] = field(default_factory=dict)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _engine(name: str) -> str:
|
|
45
|
+
key = (name or "").lower().split("+", 1)[0]
|
|
46
|
+
engine = ENGINES.get(key)
|
|
47
|
+
if not engine:
|
|
48
|
+
raise ValueError(f"Unsupported database type in the connection string: {name}")
|
|
49
|
+
return engine
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _port(raw: object) -> Optional[int]:
|
|
53
|
+
try:
|
|
54
|
+
return int(str(raw)) if raw not in (None, "") else None
|
|
55
|
+
except ValueError:
|
|
56
|
+
raise ValueError(f"Port must be a number, not {raw}") from None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _uri(raw: str) -> ConnInfo:
|
|
60
|
+
parsed = urlparse(raw)
|
|
61
|
+
engine = _engine(parsed.scheme)
|
|
62
|
+
query = {k.lower(): v[-1] for k, v in parse_qs(parsed.query).items()}
|
|
63
|
+
info = ConnInfo(engine=engine, params=query)
|
|
64
|
+
if engine in FILE_ENGINES:
|
|
65
|
+
# sqlite:///relative.db and sqlite:////abs/path.db, as SQLAlchemy spells them.
|
|
66
|
+
info.path = parsed.path[1:] if parsed.path.startswith("/") else parsed.path
|
|
67
|
+
return info
|
|
68
|
+
info.host = parsed.hostname or ""
|
|
69
|
+
if parsed.scheme.lower() == "mongodb+srv":
|
|
70
|
+
# An SRV name has no port: the DNS record lists the servers.
|
|
71
|
+
query["srv"] = "true"
|
|
72
|
+
info.port = parsed.port or (None if query.get("srv") == "true" else DEFAULT_PORTS.get(engine))
|
|
73
|
+
info.user = unquote(parsed.username or "")
|
|
74
|
+
info.password = unquote(parsed.password or "")
|
|
75
|
+
path = parsed.path.lstrip("/")
|
|
76
|
+
if engine == "snowflake" and "/" in path:
|
|
77
|
+
info.database, info.schema = path.split("/", 1)
|
|
78
|
+
else:
|
|
79
|
+
info.database = path
|
|
80
|
+
info.user = info.user or query.pop("user", "")
|
|
81
|
+
info.password = info.password or query.pop("password", "")
|
|
82
|
+
query.pop("password", None)
|
|
83
|
+
info.schema = info.schema or query.pop("currentschema", "") or query.pop("schema", "")
|
|
84
|
+
return info
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _jdbc(raw: str) -> ConnInfo:
|
|
88
|
+
body = raw[5:]
|
|
89
|
+
kind, _, rest = body.partition(":")
|
|
90
|
+
engine = _engine(kind)
|
|
91
|
+
if engine == "mssql":
|
|
92
|
+
# jdbc:sqlserver://host:1433;databaseName=x;user=y;password=z;encrypt=true
|
|
93
|
+
addr, *pairs = rest.lstrip("/").split(";")
|
|
94
|
+
props = {k.strip().lower(): v.strip() for k, _, v in (p.partition("=") for p in pairs if "=" in p)}
|
|
95
|
+
host, _, port = addr.partition(":")
|
|
96
|
+
host = host.split("\\", 1)[0]
|
|
97
|
+
return ConnInfo(
|
|
98
|
+
engine=engine, host=host, port=_port(port) or DEFAULT_PORTS[engine],
|
|
99
|
+
database=props.pop("databasename", "") or props.pop("database", ""),
|
|
100
|
+
user=props.pop("user", "") or props.pop("username", ""), password=props.pop("password", ""), params=props,
|
|
101
|
+
)
|
|
102
|
+
if engine == "oracle":
|
|
103
|
+
# jdbc:oracle:thin:@//host:1521/service or jdbc:oracle:thin:@host:1521:SID
|
|
104
|
+
m = re.match(r"^thin:(?:(?P<user>[^/@]*)/(?P<pw>[^@]*))?@(?://)?(?P<host>[^:/]+)(?::(?P<port>\d+))?[:/](?P<db>[^?]+)", rest)
|
|
105
|
+
if not m:
|
|
106
|
+
raise ValueError("Could not read the Oracle JDBC string; expected jdbc:oracle:thin:@//host:port/service")
|
|
107
|
+
return ConnInfo(engine=engine, host=m["host"], port=_port(m["port"]) or DEFAULT_PORTS[engine], database=m["db"], user=m["user"] or "", password=m["pw"] or "")
|
|
108
|
+
return _uri(f"{kind}:{rest}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_ADO_KEYS = {
|
|
112
|
+
"server": "host", "data source": "host", "address": "host", "addr": "host", "host": "host",
|
|
113
|
+
"database": "database", "initial catalog": "database",
|
|
114
|
+
"user id": "user", "uid": "user", "user": "user", "username": "user",
|
|
115
|
+
"password": "password", "pwd": "password", "port": "port",
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _adonet(raw: str) -> ConnInfo:
|
|
120
|
+
info = ConnInfo()
|
|
121
|
+
params: Dict[str, str] = {}
|
|
122
|
+
for part in raw.split(";"):
|
|
123
|
+
if "=" not in part:
|
|
124
|
+
continue
|
|
125
|
+
key, _, value = part.partition("=")
|
|
126
|
+
key, value = key.strip().lower(), value.strip().strip('"')
|
|
127
|
+
target = _ADO_KEYS.get(key)
|
|
128
|
+
if target == "host":
|
|
129
|
+
info.host = value
|
|
130
|
+
elif target:
|
|
131
|
+
setattr(info, target, value)
|
|
132
|
+
else:
|
|
133
|
+
params[key] = value
|
|
134
|
+
host = re.sub(r"^tcp:", "", info.host, flags=re.IGNORECASE)
|
|
135
|
+
if "," in host:
|
|
136
|
+
host, port = host.split(",", 1)
|
|
137
|
+
info.port = _port(port.strip())
|
|
138
|
+
info.host = host.split("\\", 1)[0].strip()
|
|
139
|
+
# Npgsql (Host=...;Port=5432) and MySqlConnector strings use the same layout as SQL Server's.
|
|
140
|
+
port = info.port if isinstance(info.port, int) else _port(info.port)
|
|
141
|
+
info.engine = "postgres" if port == 5432 or "postgres" in info.host.lower() else "mysql" if port == 3306 or "mysql" in info.host.lower() else "mssql"
|
|
142
|
+
info.port = port or DEFAULT_PORTS[info.engine]
|
|
143
|
+
info.params = params
|
|
144
|
+
return info
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def parse(raw: str) -> ConnInfo:
|
|
148
|
+
text = (raw or "").strip()
|
|
149
|
+
if not text:
|
|
150
|
+
raise ValueError("The connection string is empty")
|
|
151
|
+
if text.lower().startswith("jdbc:"):
|
|
152
|
+
return _jdbc(text)
|
|
153
|
+
if re.match(r"^[a-z][a-z0-9+.-]*://", text, re.IGNORECASE):
|
|
154
|
+
return _uri(text)
|
|
155
|
+
if "=" in text and ";" in text or re.match(r"^\s*(server|data source|host)\s*=", text, re.IGNORECASE):
|
|
156
|
+
return _adonet(text)
|
|
157
|
+
raise ValueError("Not a connection string ForgeQE reads: use a URI (postgresql://...), JDBC (jdbc:...) or ADO.NET (Server=...;Database=...)")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def cloud_of(host: str) -> str:
|
|
161
|
+
"""azure, aws, gcp or "" from a host name, for TLS defaults and token sign-in."""
|
|
162
|
+
h = (host or "").lower()
|
|
163
|
+
if h.endswith((".database.windows.net", ".postgres.database.azure.com", ".mysql.database.azure.com", ".database.azure.com")):
|
|
164
|
+
return "azure"
|
|
165
|
+
if h.endswith((".rds.amazonaws.com", ".redshift.amazonaws.com", ".redshift-serverless.amazonaws.com")):
|
|
166
|
+
return "aws"
|
|
167
|
+
if h.endswith(".cloudsql.googleapis.com") or h.startswith("/cloudsql/"):
|
|
168
|
+
return "gcp"
|
|
169
|
+
return ""
|