db.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. """PG 连接基建:连 open_aigc(Greenplum / PG12 内核),供只读查询复用。
  2. 目前唯一用途是分类树 dump(scripts/dump_trees.py 查 public.global_category)。
  3. 连接 / 参数化风格对齐 ContentFindAgentNew 的 database_runtime.py。
  4. """
  5. from __future__ import annotations
  6. from typing import Any
  7. import psycopg2
  8. import psycopg2.extras
  9. from core.config import PgConfig
  10. def connect(cfg: PgConfig, schema: str | None = None) -> Any:
  11. """建连;schema 缺省用 cfg.schema,可显式传 public 查全局分类树。"""
  12. return psycopg2.connect(
  13. host=cfg.host,
  14. port=cfg.port,
  15. user=cfg.user,
  16. password=cfg.password,
  17. dbname=cfg.database,
  18. connect_timeout=cfg.timeout,
  19. options=f"-c search_path={schema or cfg.schema}",
  20. )
  21. def fetch_all(cfg: PgConfig, sql: str, params: tuple = (), schema: str | None = None) -> list[dict]:
  22. """只读查询,返回 dict 列表。"""
  23. conn = connect(cfg, schema)
  24. try:
  25. with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
  26. cur.execute(sql, params)
  27. return [dict(r) for r in cur.fetchall()]
  28. finally:
  29. conn.close()