交付三种引擎登记、草稿/已保存连接测试、可逆启用、每源熔断与 Cron 巡检,以及控制台页面;用户确认收尾后标 DONE_LOCAL。 Co-authored-by: Cursor <cursoragent@cursor.com>
130 lines
4.0 KiB
Python
130 lines
4.0 KiB
Python
"""Create the isolated probe-test databases for PostgreSQL, MySQL and SQL Server.
|
|
|
|
Why: connector tests must never touch the platform database, so each engine gets its own
|
|
empty database plus one harmless table. This is the only place CREATE DATABASE runs; the
|
|
probe function itself stays read-only.
|
|
Boundary: creates a database only if missing and never drops anything. Prints engine names
|
|
and ok/failed words only -- no hosts, users, passwords or driver error text.
|
|
Depends on .env.local through watchman.core.config.merge_layered_env.
|
|
|
|
Usage (from services/watchman): uv run python scripts/setup_probe_test_sources.py [engine ...]
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import sys
|
|
|
|
import psycopg
|
|
import pymssql
|
|
import pymysql
|
|
from psycopg import sql
|
|
|
|
from watchman.core.config import merge_layered_env
|
|
|
|
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
|
|
_TIMEOUT = 10
|
|
|
|
|
|
def _env(prefix: str) -> dict[str, str]:
|
|
env = merge_layered_env()
|
|
keys = ("HOST", "PORT", "USER", "PASSWORD", "DATABASE")
|
|
missing = [f"{prefix}_{k}" for k in keys if not env.get(f"{prefix}_{k}")]
|
|
if missing:
|
|
raise RuntimeError("missing env: " + ", ".join(missing))
|
|
values = {k.lower(): env[f"{prefix}_{k}"] for k in keys}
|
|
if not _IDENT.match(values["database"]):
|
|
# Identifier is interpolated into CREATE DATABASE; keep it to a safe charset.
|
|
raise RuntimeError(f"{prefix}_DATABASE is not a plain identifier")
|
|
return values
|
|
|
|
|
|
def _setup_postgresql() -> None:
|
|
cfg = _env("WATCHMAN_TEST_PG")
|
|
common = dict(
|
|
host=cfg["host"],
|
|
port=int(cfg["port"]),
|
|
user=cfg["user"],
|
|
password=cfg["password"],
|
|
connect_timeout=_TIMEOUT,
|
|
autocommit=True,
|
|
)
|
|
with psycopg.connect(dbname="postgres", **common) as conn:
|
|
exists = conn.execute(
|
|
"SELECT 1 FROM pg_database WHERE datname = %s", (cfg["database"],)
|
|
).fetchone()
|
|
if not exists:
|
|
conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(cfg["database"])))
|
|
with psycopg.connect(dbname=cfg["database"], **common) as conn:
|
|
conn.execute("CREATE TABLE IF NOT EXISTS probe (id int)")
|
|
|
|
|
|
def _setup_mysql() -> None:
|
|
cfg = _env("WATCHMAN_TEST_MYSQL")
|
|
conn = pymysql.connect(
|
|
host=cfg["host"],
|
|
port=int(cfg["port"]),
|
|
user=cfg["user"],
|
|
password=cfg["password"],
|
|
connect_timeout=_TIMEOUT,
|
|
autocommit=True,
|
|
)
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(f"CREATE DATABASE IF NOT EXISTS `{cfg['database']}`")
|
|
cur.execute(f"CREATE TABLE IF NOT EXISTS `{cfg['database']}`.probe (id int)")
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _setup_sqlserver() -> None:
|
|
cfg = _env("WATCHMAN_TEST_SQLSERVER")
|
|
conn = pymssql.connect(
|
|
server=cfg["host"],
|
|
port=cfg["port"],
|
|
user=cfg["user"],
|
|
password=cfg["password"],
|
|
database="master",
|
|
login_timeout=_TIMEOUT,
|
|
timeout=60,
|
|
autocommit=True,
|
|
)
|
|
try:
|
|
cur = conn.cursor()
|
|
db = cfg["database"]
|
|
cur.execute(f"IF DB_ID(N'{db}') IS NULL CREATE DATABASE [{db}]")
|
|
cur.execute(
|
|
f"USE [{db}]; IF OBJECT_ID(N'dbo.probe', N'U') IS NULL CREATE TABLE dbo.probe (id int)"
|
|
)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
_ENGINES = {
|
|
"postgresql": _setup_postgresql,
|
|
"mysql": _setup_mysql,
|
|
"sqlserver": _setup_sqlserver,
|
|
}
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
wanted = argv or list(_ENGINES)
|
|
unknown = [e for e in wanted if e not in _ENGINES]
|
|
if unknown:
|
|
print("unknown engine name(s); choose from: " + ", ".join(_ENGINES))
|
|
return 2
|
|
failed = 0
|
|
for name in wanted:
|
|
try:
|
|
_ENGINES[name]()
|
|
print(f"{name}: ok")
|
|
except Exception as exc: # noqa: BLE001
|
|
# Class name only: driver messages can embed user, host or password hints.
|
|
print(f"{name}: failed ({type(exc).__name__})")
|
|
failed += 1
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|