""" 数据库操作引擎 ============== 【功能说明】 基于 SQLAlchemy 对目标数据库执行 SQL CRUD 操作。 支持 MySQL / PostgreSQL / SQLite 三种数据库。 【技术选型理由】 1. 选 SQLAlchemy:统一抽象多种数据库,改类型只改连接串; 2. 参数化查询:防 SQL 注入(硬约束 5 安全兜底); 3. 连接池 + 短连接:每次操作独立连接,避免连接泄漏。 【实现思路】 - create_engine():按连接配置创建 SQLAlchemy 引擎; - execute_sql():通用 SQL 执行(INSERT/UPDATE/DELETE/SELECT); - query_with_pagination():SELECT 分页查询; - test_connection():连接测试。 【潜在风险与应对】 风险1:SQL 注入。 应对:强制使用参数化查询,不拼接用户输入。 风险2:大批量数据操作。 应对:分页 + LIMIT 限制,防止全表扫描。 风险3:数据库连接泄漏。 应对:每次操作用 context manager 确保关闭连接。 """ from __future__ import annotations import logging import re from typing import Any from urllib.parse import quote_plus from app.schemas.database import SqlExecuteResult logger = logging.getLogger("agent.db_engine") # 合法表名/列名(防 SQL 注入) _IDENTIFIER_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$") def _validate_identifier(name: str, kind: str = "表名") -> str: """校验 SQL 标识符(表名/列名)合法性,防注入。""" if not name or not _IDENTIFIER_RE.match(name): raise ValueError(f"非法{kind}:{name!r}(只允许字母、数字、下划线,且不以数字开头)") return name def _build_engine(conn_info: dict): """按连接配置创建 SQLAlchemy 引擎。""" from sqlalchemy import create_engine db_type = conn_info.get("db_type", "sqlite").lower() if db_type == "sqlite": db_path = conn_info.get("database", ":memory:") url = f"sqlite:///{db_path}" elif db_type == "mysql": # URL 编码用户名和密码,防止特殊字符(@ : / # 等)破坏连接串 user = quote_plus(str(conn_info.get("username", ""))) pwd = quote_plus(str(conn_info.get("password", ""))) url = ( f"mysql+pymysql://{user}:{pwd}" f"@{conn_info['host']}:{conn_info['port']}/{conn_info['database']}" ) elif db_type == "postgresql": user = quote_plus(str(conn_info.get("username", ""))) pwd = quote_plus(str(conn_info.get("password", ""))) url = ( f"postgresql://{user}:{pwd}" f"@{conn_info['host']}:{conn_info['port']}/{conn_info['database']}" ) else: raise ValueError(f"不支持的数据库类型:{db_type}") return create_engine(url, pool_pre_ping=True, pool_recycle=3600) def list_tables(conn_info: dict) -> list[str]: """列出数据库中的所有表名(多数据库适配)。""" db_type = conn_info.get("db_type", "sqlite").lower() engine = _build_engine(conn_info) try: with engine.connect() as conn: from sqlalchemy import text if db_type == "mysql": result = conn.execute(text("SHOW TABLES")) return [row[0] for row in result] elif db_type == "postgresql": result = conn.execute( text( "SELECT tablename FROM pg_tables " "WHERE schemaname = 'public' ORDER BY tablename" ) ) return [row[0] for row in result] else: # sqlite result = conn.execute( text("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") ) return [row[0] for row in result] except Exception as exc: # noqa: BLE001 logger.error("列出表失败:%s", exc) return [] finally: engine.dispose() def get_table_structure(conn_info: dict, table_name: str) -> dict: """ 查询表结构(列名、类型、可空、主键、默认值、注释)。 【多数据库适配】 - MySQL:SHOW FULL COLUMNS FROM {table} - PostgreSQL:information_schema.columns - SQLite:PRAGMA table_info({table}) """ _validate_identifier(table_name, "表名") db_type = conn_info.get("db_type", "sqlite").lower() engine = _build_engine(conn_info) try: with engine.connect() as conn: from sqlalchemy import text if db_type == "mysql": result = conn.execute(text(f"SHOW FULL COLUMNS FROM {table_name}")) columns = [] for row in result.mappings(): columns.append({ "name": row.get("Field", ""), "type": row.get("Type", ""), "nullable": row.get("Null", "") == "YES", "key": row.get("Key", ""), "default": row.get("Default", ""), "comment": row.get("Comment", ""), }) elif db_type == "postgresql": result = conn.execute( text( "SELECT column_name, data_type, is_nullable, column_default " "FROM information_schema.columns WHERE table_name = :tname " "ORDER BY ordinal_position" ), {"tname": table_name}, ) columns = [ { "name": r["column_name"], "type": r["data_type"], "nullable": r["is_nullable"] == "YES", "key": "", "default": r["column_default"] or "", "comment": "", } for r in result.mappings() ] else: # sqlite result = conn.execute(text(f"PRAGMA table_info({table_name})")) columns = [ { "name": r["name"], "type": r["type"], "nullable": not r["notnull"], "key": "PRI" if r["pk"] else "", "default": r["dflt_value"] or "", "comment": "", } for r in result.mappings() ] return {"success": True, "table": table_name, "columns": columns} except Exception as exc: # noqa: BLE001 return {"success": False, "message": f"查询表结构失败:{exc}", "columns": []} finally: engine.dispose() def alter_table( conn_info: dict, table_name: str, action: str, column_name: str, column_type: str = "", nullable: bool = True, default: str = "", comment: str = "", ) -> dict: """ 修改表结构(加列/改列/删列)。 【参数】 action: add / modify / drop column_name: 列名 column_type: 列类型(如 VARCHAR(255)) nullable: 是否可空 default: 默认值 comment: 注释 """ _validate_identifier(table_name, "表名") _validate_identifier(column_name, "列名") # 校验列类型(只允许合法 SQL 类型表达式) if action in ("add", "modify") and column_type: if not re.match(r"^[a-zA-Z][a-zA-Z0-9_()]*$", column_type): return {"success": False, "message": f"非法列类型:{column_type}"} db_type = conn_info.get("db_type", "sqlite").lower() engine = _build_engine(conn_info) try: with engine.begin() as conn: from sqlalchemy import text if action == "add": if db_type == "mysql": null_str = "NULL" if nullable else "NOT NULL" default_str = f" DEFAULT {default}" if default else "" comment_str = f" COMMENT '{comment}'" if comment else "" sql = ( f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} " f"{null_str}{default_str}{comment_str}" ) elif db_type == "postgresql": null_str = "NULL" if nullable else "NOT NULL" default_str = f" DEFAULT {default}" if default else "" sql = ( f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} " f"{null_str}{default_str}" ) else: # sqlite null_str = "" if nullable else " NOT NULL" default_str = f" DEFAULT {default}" if default else "" sql = ( f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}" f"{null_str}{default_str}" ) elif action == "modify": if db_type == "mysql": null_str = "NULL" if nullable else "NOT NULL" default_str = f" DEFAULT {default}" if default else "" comment_str = f" COMMENT '{comment}'" if comment else "" sql = ( f"ALTER TABLE {table_name} MODIFY COLUMN {column_name} {column_type} " f"{null_str}{default_str}{comment_str}" ) elif db_type == "postgresql": # PG 需要拆成多条 conn.execute(text( f"ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {column_type}" )) null_str = "DROP NOT NULL" if nullable else "SET NOT NULL" conn.execute(text( f"ALTER TABLE {table_name} ALTER COLUMN {column_name} {null_str}" )) if default: conn.execute(text( f"ALTER TABLE {table_name} ALTER COLUMN {column_name} SET DEFAULT {default}" )) return {"success": True, "message": f"列 {column_name} 修改成功"} else: # sqlite return {"success": False, "message": "SQLite 不支持 MODIFY COLUMN,请通过重建表修改"} elif action == "drop": sql = f"ALTER TABLE {table_name} DROP COLUMN {column_name}" else: return {"success": False, "message": f"不支持的操作:{action}"} conn.execute(text(sql)) return {"success": True, "message": f"列 {column_name} {action} 成功"} except Exception as exc: # noqa: BLE001 return {"success": False, "message": f"修改表结构失败:{exc}"} finally: engine.dispose() def test_connection(conn_info: dict) -> dict: """测试数据库连接是否成功。""" engine = None try: engine = _build_engine(conn_info) with engine.connect() as conn: from sqlalchemy import text result = conn.execute(text("SELECT 1")) result.fetchone() return {"success": True, "message": "连接成功"} except Exception as exc: # noqa: BLE001 return {"success": False, "message": f"连接失败:{exc}"} finally: if engine is not None: engine.dispose() def _normalize_sql(sql: str) -> str: """ 规范化 SQL:去掉尾部空白与分号。 【踩坑】用户习惯写 `SELECT * FROM t;` 带分号,但分页查询会包 `SELECT COUNT(*) FROM (sql) AS _sub`,分号嵌在括号里导致语法错误。 """ return sql.strip().rstrip(";").strip() def execute_sql( conn_info: dict, sql: str, params: list | dict | None = None, ) -> SqlExecuteResult: """ 执行 SQL(INSERT/UPDATE/DELETE/SELECT 通用)。 【安全】强制参数化查询,防 SQL 注入。 """ from sqlalchemy import create_engine, text sql = _normalize_sql(sql) if not sql: return SqlExecuteResult(success=False, message="SQL 不能为空", affected_rows=0) engine = _build_engine(conn_info) try: with engine.begin() as conn: if params: result = conn.execute(text(sql), params) else: result = conn.execute(text(sql)) # SELECT:返回数据 if result.returns_rows: columns = list(result.keys()) if result.keys() else [] rows = [dict(row) for row in result.mappings().all()] return SqlExecuteResult( success=True, message=f"查询返回 {len(rows)} 条记录", affected_rows=len(rows), data=rows, columns=columns, total=len(rows), ) # INSERT/UPDATE/DELETE:返回影响行数 affected = result.rowcount if result.rowcount >= 0 else 0 return SqlExecuteResult( success=True, message=f"操作成功,影响 {affected} 行", affected_rows=affected, ) except Exception as exc: # noqa: BLE001 logger.error("SQL 执行失败:%s | %s", sql[:200], exc) return SqlExecuteResult( success=False, message=f"SQL 执行失败:{exc}", affected_rows=0 ) finally: engine.dispose() def query_with_pagination( conn_info: dict, sql: str, params: list | dict | None = None, page: int = 1, page_size: int = 20, ) -> SqlExecuteResult: """ SELECT 分页查询。 【实现】在原始 SQL 外包一层 LIMIT/OFFSET,自动补 COUNT 总数。 【修复】 1. list 参数转为 dict(SQLAlchemy text() 不支持位置参数); 2. 内部参数名加 __ 前缀,防止与用户 SQL 参数冲突; 3. 非 SELECT 语句自动走 execute_sql(不包 COUNT/LIMIT)。 """ from sqlalchemy import create_engine, text sql = _normalize_sql(sql) if not sql: return SqlExecuteResult(success=False, message="SQL 不能为空", affected_rows=0) # 非 SELECT 语句走通用执行(不包分页) first_word = sql.split()[0].upper() if sql.split() else "" if first_word not in ("SELECT", "WITH"): return execute_sql(conn_info, sql, params) engine = _build_engine(conn_info) try: offset = (page - 1) * page_size # 统一参数为 dict(SQLAlchemy text() 只支持命名参数) if params and isinstance(params, list): return SqlExecuteResult( success=False, message="分页查询暂不支持位置参数(list),请使用命名参数(dict)", affected_rows=0, ) base_params: dict[str, Any] = dict(params) if isinstance(params, dict) else {} # 内部参数名加 __ 前缀,防止与用户参数冲突 paged_sql = f"SELECT * FROM ({sql}) AS _sub LIMIT :__limit OFFSET :__offset" count_sql = f"SELECT COUNT(*) as cnt FROM ({sql}) AS _sub" paged_params = {**base_params, "__limit": page_size, "__offset": offset} with engine.connect() as conn: # 查总数 total_row = conn.execute(text(count_sql), base_params).fetchone() total = total_row[0] if total_row else 0 # 查分页数据 result = conn.execute(text(paged_sql), paged_params) columns = list(result.keys()) if result.keys() else [] rows = [dict(row) for row in result.mappings().all()] return SqlExecuteResult( success=True, message=f"查询返回 {len(rows)} 条(共 {total} 条)", affected_rows=len(rows), data=rows, columns=columns, total=total, page=page, page_size=page_size, ) except Exception as exc: # noqa: BLE001 logger.error("分页查询失败:%s | %s", sql[:200], exc) return SqlExecuteResult( success=False, message=f"查询失败:{exc}", affected_rows=0 ) finally: engine.dispose()