This commit is contained in:
runny committed 2026-05-12 14:33:48 +08:00
1 parent 08a19ebe96
commit dea3b39048
6 files changed
+240 -33

No files matched your search

+130 -22
View File
@@ -2,10 +2,13 @@ import json
import os
import re
import time
from pathlib import Path
from flask import current_app
class Text2SQLService:
_schema_text = None
_oracle_client_initialized = False
_jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar"
@staticmethod
def _backend_dir() -> str:
@@ -33,6 +36,122 @@ class Text2SQLService:
return client_dirs[0]
return None
@classmethod
def _get_oracle_client_dir(cls) -> str | None:
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
if env_dir and os.path.exists(env_dir):
return env_dir
linux_candidates = [
"/opt/oracle/instantclient",
"/opt/oracle/instantclient_19_28",
"/opt/oracle/instantclient_19_27",
]
for path in linux_candidates:
if os.path.exists(path):
return path
return cls._find_oracle_client_dir()
@classmethod
def _init_oracle_client(cls, oracledb) -> None:
if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
return
import platform
import shutil
import tempfile
target_lib_dir = cls._get_oracle_client_dir()
if platform.system() == 'Windows' and target_lib_dir:
# OCI C-library fails to load if path contains non-ASCII.
if 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_initialized = True
@classmethod
def _jdbc_dir(cls) -> Path:
return Path(cls._backend_dir()) / "jdbc"
@classmethod
def _ensure_jdbc_driver_jar(cls) -> str:
env_path = (os.getenv("ERP_JDBC_JAR") or "").strip()
if env_path and os.path.exists(env_path):
return env_path
jar_dir = cls._jdbc_dir()
jar_dir.mkdir(parents=True, exist_ok=True)
jar_path = jar_dir / "ojdbc8-19.25.0.0.jar"
if jar_path.exists():
return str(jar_path)
import requests
driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url
with requests.get(driver_url, stream=True, timeout=120) as resp:
resp.raise_for_status()
with open(jar_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=1024 * 256):
if chunk:
f.write(chunk)
return str(jar_path)
@staticmethod
def _dsn_to_jdbc_url(dsn: str) -> str:
dsn = (dsn or "").strip()
if not dsn:
raise ValueError("ERP_DB_DSN is empty")
if dsn.startswith("jdbc:oracle:thin:@"):
return dsn
if dsn.startswith("("):
return f"jdbc:oracle:thin:@{dsn}"
match = re.match(r"^(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", dsn)
if match:
host = match.group("host")
port = match.group("port") or "1521"
service = match.group("service")
return f"jdbc:oracle:thin:@//{host}:{port}/{service}"
return f"jdbc:oracle:thin:@{dsn}"
@classmethod
def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str):
import jaydebeapi
jar_path = cls._ensure_jdbc_driver_jar()
jdbc_url = cls._dsn_to_jdbc_url(dsn)
connection = jaydebeapi.connect(
"oracle.jdbc.OracleDriver",
jdbc_url,
{
"user": user,
"password": password,
"oracle.jdbc.timezoneAsRegion": "false",
},
jar_path,
)
cursor = connection.cursor()
try:
cursor.execute(sql)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchall() if columns else []
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_schema(cls):
if cls._schema_text is None:
@@ -211,27 +330,8 @@ class Text2SQLService:
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()
# 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()
# Old ERP Oracle versions require python-oracledb thick mode.
cls._init_oracle_client(oracledb)
except Exception as e:
if current_app:
current_app.logger.warning(f"Failed to init thick mode: {e}")
@@ -249,7 +349,15 @@ class Text2SQLService:
return columns, rows
except Exception as e:
return ["Error"], [[str(e)]]
error_text = str(e)
if current_app:
current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}")
if "DPY-3010" in error_text or "DPI-1047" in error_text:
try:
return cls._execute_sql_via_jdbc(sql, user, password, dsn)
except Exception as jdbc_error:
return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]]
return ["Error"], [[error_text]]
@classmethod
def format_result(cls, columns, rows, sql, original_query):