postgres.py 8.6 KB
"""PostgreSQL 连接器(驱动 psycopg2,按需安装:pip install psycopg2-binary)。

和 MySQL 一样三层防护:只读事务 + statement_timeout + fetchmany 硬截断;SQL 只读性在 guard.py。
内省走 information_schema(只看 extra.schema 指定的 schema,默认 public)。
"""
from __future__ import annotations

import logging
import time

from sqlalchemy import create_engine, text as sa_text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError

from .base import (
    ColumnInfo, ConnectionFailed, Connector, ForeignKeyInfo, Introspection,
    QueryFailed, QueryResult, TableInfo,
)
from .mysql import _clean, _is_pii, _jsonable, _short

log = logging.getLogger(__name__)


def _q(name: str) -> str:
    return '"' + str(name).replace('"', '""') + '"'


class PostgresConnector(Connector):
    dialect = "postgres"

    def __init__(self, ds: dict, password: str):
        super().__init__(ds, password)
        self._engine: Engine | None = None

    @property
    def schema(self) -> str:
        return str((self.ds.get("extra") or {}).get("schema") or "public")

    @property
    def engine(self) -> Engine:
        if self._engine is None:
            try:
                import psycopg2  # noqa: F401
            except ImportError as e:
                raise ConnectionFailed("服务器没有安装 PostgreSQL 驱动:pip install psycopg2-binary") from e
            from urllib.parse import quote_plus
            url = (f"postgresql+psycopg2://{quote_plus(self.ds['username'])}:{quote_plus(self.password)}"
                   f"@{self.ds['host']}:{int(self.ds['port'] or 5432)}/{self.ds['db_name']}")
            self._engine = create_engine(url, pool_pre_ping=True, pool_recycle=1800, pool_size=3,
                                         max_overflow=2, future=True,
                                         connect_args={"connect_timeout": 10,
                                                       "options": "-c default_transaction_read_only=on"})
        return self._engine

    def dispose(self) -> None:
        if self._engine is not None:
            self._engine.dispose()
            self._engine = None

    def test(self) -> dict:
        try:
            with self.engine.connect() as c:
                version = c.execute(sa_text("SELECT version()")).scalar_one()
                db = c.execute(sa_text("SELECT current_database()")).scalar_one()
                n = c.execute(sa_text("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = :s"),
                              {"s": self.schema}).scalar_one()
                writable = c.execute(sa_text(
                    "SELECT has_database_privilege(current_user, current_database(), 'CREATE')")).scalar_one()
        except SQLAlchemyError as e:
            raise ConnectionFailed(_clean(e)) from e
        return {"version": str(version).split(",")[0], "database": str(db), "table_count": int(n),
                "account_writable": bool(writable)}

    def introspect(self) -> Introspection:
        try:
            with self.engine.connect() as c:
                tables: dict[str, TableInfo] = {}
                for name, ttype in c.execute(sa_text(
                        "SELECT table_name, table_type FROM information_schema.tables "
                        "WHERE table_schema = :s ORDER BY table_name"), {"s": self.schema}).fetchall():
                    tables[name] = TableInfo(name=name, kind="view" if "VIEW" in str(ttype) else "table")
                for name, comment, rows in c.execute(sa_text(
                        "SELECT c.relname, obj_description(c.oid), c.reltuples::bigint FROM pg_class c "
                        "JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :s"),
                        {"s": self.schema}).fetchall():
                    if name in tables:
                        tables[name].comment = comment or ""
                        tables[name].row_count_est = max(0, int(rows or 0))
                for t, col, dtype, nullable, default, comment in c.execute(sa_text(
                        "SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default, "
                        "col_description((quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass, "
                        "c.ordinal_position) FROM information_schema.columns c WHERE c.table_schema = :s "
                        "ORDER BY c.table_name, c.ordinal_position"), {"s": self.schema}).fetchall():
                    if t in tables:
                        tables[t].columns.append(ColumnInfo(name=col, data_type=str(dtype), nullable=nullable == "YES",
                                                            comment=comment or "",
                                                            default="" if default is None else str(default)))
                fks = []
                for kind, t, col, rt, rc in c.execute(sa_text(
                        "SELECT tc.constraint_type, kcu.table_name, kcu.column_name, ccu.table_name, ccu.column_name "
                        "FROM information_schema.table_constraints tc "
                        "JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name "
                        "AND tc.table_schema = kcu.table_schema "
                        "LEFT JOIN information_schema.constraint_column_usage ccu "
                        "ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema "
                        "WHERE tc.table_schema = :s AND tc.constraint_type IN ('PRIMARY KEY','FOREIGN KEY')"),
                        {"s": self.schema}).fetchall():
                    if kind == "PRIMARY KEY" and t in tables and col not in tables[t].primary_key:
                        tables[t].primary_key.append(col)
                    elif kind == "FOREIGN KEY" and rt:
                        fks.append(ForeignKeyInfo(from_table=t, from_column=col, to_table=rt, to_column=rc))
        except SQLAlchemyError as e:
            raise ConnectionFailed(_clean(e)) from e
        return Introspection(tables=list(tables.values()), foreign_keys=fks)

    def sample_values(self, table: str, column: str, limit: int, max_distinct: int) -> tuple[list[str], int]:
        if limit <= 0 or _is_pii(column):
            return [], 0
        t, c_ = f"{_q(self.schema)}.{_q(table)}", _q(column)
        try:
            with self.engine.connect() as c:
                c.execute(sa_text("SET statement_timeout = 5000"))
                total = int(c.execute(sa_text(
                    f"SELECT COUNT(*) FROM (SELECT DISTINCT {c_} FROM {t} WHERE {c_} IS NOT NULL "
                    f"LIMIT {int(max_distinct) + 1}) x")).scalar_one() or 0)
                if total == 0 or total > max_distinct:
                    return [], total
                rows = c.execute(sa_text(f"SELECT {c_}, COUNT(*) AS n FROM {t} WHERE {c_} IS NOT NULL "
                                         f"GROUP BY {c_} ORDER BY n DESC LIMIT {int(limit)}")).fetchall()
        except SQLAlchemyError:
            return [], 0
        return [_short(r[0]) for r in rows], total

    def null_ratios(self, table: str, columns: list[str], sample: int = 50000) -> dict[str, float]:
        if not columns:
            return {}
        parts = ", ".join(f"SUM(CASE WHEN {_q(c)} IS NULL THEN 1 ELSE 0 END)" for c in columns)
        try:
            with self.engine.connect() as c:
                c.execute(sa_text("SET statement_timeout = 30000"))
                row = c.execute(sa_text(f"SELECT COUNT(*), {parts} FROM (SELECT * FROM "
                                        f"{_q(self.schema)}.{_q(table)} LIMIT {int(sample)}) x")).fetchone()
        except SQLAlchemyError:
            return {}
        total = int((row or [0])[0] or 0)
        return {col: float(row[i + 1] or 0) / total for i, col in enumerate(columns)} if total else {}

    def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
        started = time.time()
        try:
            with self.engine.connect() as c:
                c.execute(sa_text(f"SET statement_timeout = {int(timeout_ms)}"))
                c.execute(sa_text(f"SET search_path TO {_q(self.schema)}"))
                cur = c.execute(sa_text(sql))
                cols = list(cur.keys())
                rows = cur.fetchmany(row_limit + 1)
        except SQLAlchemyError as e:
            raise QueryFailed(_clean(e)) from e
        truncated = len(rows) > row_limit
        rows = rows[:row_limit]
        return QueryResult(columns=cols, rows=[[_jsonable(v) for v in r] for r in rows],
                           row_count=len(rows), duration_ms=int((time.time() - started) * 1000),
                           truncated=truncated)