orcle
This commit is contained in:
1 parent
5da6c464b9
commit
13ecfc3e42
3 files changed
+153
-32
No files matched your search
@@ -2,10 +2,13 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from flask import current_app
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
_oracle_client_init_attempted = False
|
||||
_oracle_client_init_error = None
|
||||
_oracle_client_mode = "unknown"
|
||||
|
||||
@staticmethod
|
||||
def _backend_dir() -> str:
|
||||
@@ -17,22 +20,109 @@ class Text2SQLService:
|
||||
|
||||
@classmethod
|
||||
def _find_oracle_client_dir(cls) -> str | None:
|
||||
candidate_roots = [
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
candidate_roots = []
|
||||
if env_dir:
|
||||
candidate_roots.append(env_dir)
|
||||
candidate_roots.extend([
|
||||
os.path.join(cls._backend_dir(), 'oracle_client'),
|
||||
os.path.join(cls._project_root(), 'oracle_client'),
|
||||
]
|
||||
os.path.join(os.getcwd(), 'oracle_client'),
|
||||
'/app/oracle_client',
|
||||
'/opt/oracle',
|
||||
])
|
||||
library_markers = {'oci.dll', 'libclntsh.so', 'libclntsh.dylib'}
|
||||
for oracle_client_dir in candidate_roots:
|
||||
if not os.path.exists(oracle_client_dir):
|
||||
if not oracle_client_dir or not os.path.exists(oracle_client_dir):
|
||||
continue
|
||||
try:
|
||||
entries = os.listdir(oracle_client_dir)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
entry_names = {name.lower() for name in entries}
|
||||
if library_markers & entry_names:
|
||||
return oracle_client_dir
|
||||
|
||||
client_dirs = [
|
||||
os.path.join(oracle_client_dir, d)
|
||||
for d in os.listdir(oracle_client_dir)
|
||||
for d in entries
|
||||
if d.startswith('instantclient_') and os.path.isdir(os.path.join(oracle_client_dir, d))
|
||||
]
|
||||
if client_dirs:
|
||||
return client_dirs[0]
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _log(level: str, message: str):
|
||||
if has_app_context():
|
||||
getattr(current_app.logger, level, current_app.logger.info)(message)
|
||||
|
||||
@classmethod
|
||||
def _ensure_oracle_client_initialized(cls, oracledb):
|
||||
if cls._oracle_client_init_attempted:
|
||||
return cls._oracle_client_mode == "thick"
|
||||
|
||||
cls._oracle_client_init_attempted = True
|
||||
try:
|
||||
if not getattr(oracledb, "is_thin_mode", lambda: True)():
|
||||
cls._oracle_client_mode = "thick"
|
||||
return True
|
||||
|
||||
import platform
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
target_lib_dir = cls._find_oracle_client_dir()
|
||||
if platform.system() == 'Windows' and target_lib_dir and not target_lib_dir.isascii():
|
||||
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
|
||||
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
|
||||
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
shutil.copytree(target_lib_dir, safe_lib_dir)
|
||||
target_lib_dir = safe_lib_dir
|
||||
|
||||
if target_lib_dir:
|
||||
oracledb.init_oracle_client(lib_dir=target_lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
|
||||
cls._oracle_client_mode = "thin" if getattr(oracledb, "is_thin_mode", lambda: True)() else "thick"
|
||||
if cls._oracle_client_mode == "thick":
|
||||
cls._log("info", f"Oracle thick mode initialized successfully. lib_dir={target_lib_dir or 'system-default'}")
|
||||
return True
|
||||
|
||||
cls._oracle_client_init_error = "Oracle client initialized but driver is still in thin mode"
|
||||
except Exception as exc:
|
||||
cls._oracle_client_init_error = str(exc)
|
||||
cls._oracle_client_mode = "thin"
|
||||
cls._log("warning", f"Failed to init Oracle thick mode: {exc}")
|
||||
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _format_connection_error(cls, error_message: str) -> str:
|
||||
message = (error_message or "").strip()
|
||||
if "DPY-3010" in message or "DPY-6005" in message:
|
||||
init_error = cls._oracle_client_init_error or "未找到可用的 Oracle Instant Client"
|
||||
return (
|
||||
"Oracle 连接失败:当前驱动仍在 thin mode,而该 ERP Oracle 版本需要 thick mode。"
|
||||
"请在部署环境提供 Oracle Instant Client,并将项目根目录的 oracle_client 挂载到 /app/oracle_client "
|
||||
"或设置 ORACLE_CLIENT_LIB_DIR。"
|
||||
f"当前 thick mode 初始化错误:{init_error}"
|
||||
)
|
||||
return message or "未知数据库错误"
|
||||
|
||||
@staticmethod
|
||||
def _extract_invalid_identifier(error_message: str) -> str:
|
||||
match = re.search(r'ORA-00904:\s*"?(?P<name>[A-Za-z0-9_#$]+)"?\s*:\s*invalid identifier', error_message or "", re.IGNORECASE)
|
||||
return (match.group("name") if match else "").upper()
|
||||
|
||||
@staticmethod
|
||||
def _is_repairable_sql_error(error_message: str) -> bool:
|
||||
text = (error_message or "").upper()
|
||||
return any(code in text for code in ("ORA-00904", "ORA-00942", "INVALID IDENTIFIER", "TABLE OR VIEW DOES NOT EXIST"))
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
if cls._schema_text is None:
|
||||
@@ -184,6 +274,7 @@ class Text2SQLService:
|
||||
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
|
||||
- 仅允许输出单条 SELECT 或 WITH 开头的查询。
|
||||
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
|
||||
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
|
||||
- 优先选择最相关字段,避免 SELECT *。
|
||||
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
|
||||
- 如果问题无法仅依据当前 Schema 回答,请输出安全的 SELECT 语句说明原因,例如 SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL。"""
|
||||
@@ -199,6 +290,45 @@ class Text2SQLService:
|
||||
except Exception as e:
|
||||
return f"SELECT '{cls._escape_sql_message(f'LLM Error: {e}')}' AS error FROM DUAL"
|
||||
|
||||
@classmethod
|
||||
def repair_sql(cls, query: str, failed_sql: str, error_message: str) -> str:
|
||||
schema = cls.get_schema()
|
||||
invalid_identifier = cls._extract_invalid_identifier(error_message)
|
||||
invalid_hint = f"本次报错的非法字段/标识符是:{invalid_identifier}。" if invalid_identifier else ""
|
||||
|
||||
system_prompt = f"""你是一个专业的 Oracle SQL 修复助手。你的任务是根据执行失败的 SQL、数据库报错和当前 Schema,修复成一条可执行的 Oracle 查询语句。
|
||||
|
||||
数据库结构 (Schema):
|
||||
{schema}
|
||||
|
||||
修复要求:
|
||||
- 只输出 SQL,不要解释。
|
||||
- 必须保留用户问题的原始意图。
|
||||
- 必须只使用 Schema 中真实存在的表名和字段名。
|
||||
- 严禁创造 FILE_TYPE、STATUS_NAME 这类 Schema 中不存在的字段。
|
||||
- 如果当前 Schema 无法支持该问题,请输出:SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL
|
||||
- 严禁输出任何非 SELECT / WITH 语句。"""
|
||||
|
||||
user_prompt = f"""用户问题:{query}
|
||||
执行失败的 SQL:
|
||||
```sql
|
||||
{failed_sql}
|
||||
```
|
||||
|
||||
数据库错误:{error_message}
|
||||
{invalid_hint}
|
||||
|
||||
请根据上述错误修复 SQL,并确保只使用当前 Schema 中真实存在的表和字段。"""
|
||||
|
||||
try:
|
||||
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
|
||||
sql = sql.rstrip(";")
|
||||
if not cls._is_safe_query(sql):
|
||||
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
|
||||
return sql
|
||||
except Exception as e:
|
||||
return f"SELECT '{cls._escape_sql_message(f'SQL Repair Error: {e}')}' AS error FROM DUAL"
|
||||
|
||||
@classmethod
|
||||
def execute_sql(cls, sql: str):
|
||||
try:
|
||||
@@ -208,33 +338,9 @@ class Text2SQLService:
|
||||
|
||||
user = "EXT_VIEW_USER"
|
||||
password = "extviewuser"
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
try:
|
||||
# Enable thick mode to support older Oracle versions
|
||||
import platform
|
||||
import tempfile
|
||||
import shutil
|
||||
if platform.system() == 'Windows':
|
||||
target_lib_dir = cls._find_oracle_client_dir()
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
# Fix for OCI path issue with Chinese characters (like "HX工作目录")
|
||||
# OCI C-library fails to load if path contains non-ASCII
|
||||
if target_lib_dir and not target_lib_dir.isascii():
|
||||
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
|
||||
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
|
||||
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
shutil.copytree(target_lib_dir, safe_lib_dir)
|
||||
target_lib_dir = safe_lib_dir
|
||||
|
||||
if target_lib_dir:
|
||||
oracledb.init_oracle_client(lib_dir=target_lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
||||
cls._ensure_oracle_client_initialized(oracledb)
|
||||
|
||||
try:
|
||||
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
@@ -249,7 +355,7 @@ class Text2SQLService:
|
||||
|
||||
return columns, rows
|
||||
except Exception as e:
|
||||
return ["Error"], [[str(e)]]
|
||||
return ["Error"], [[cls._format_connection_error(str(e))]]
|
||||
|
||||
@classmethod
|
||||
def format_result(cls, columns, rows, sql, original_query):
|
||||
@@ -287,6 +393,14 @@ class Text2SQLService:
|
||||
|
||||
# 2. Execute SQL
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
if columns == ["Error"] and rows and rows[0]:
|
||||
error_message = str(rows[0][0] or "")
|
||||
if Text2SQLService._is_repairable_sql_error(error_message):
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n"
|
||||
repaired_sql = Text2SQLService.repair_sql(query, sql, error_message)
|
||||
if repaired_sql and repaired_sql != sql:
|
||||
sql = repaired_sql
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n"
|
||||
|
||||
Reference in new issue
Block a user