Merge branch 'runny&xinxin' into dev
This commit is contained in:
commit
8d73343bd8
77 files changed
+17955
-274
No files matched your search
@@ -2,13 +2,13 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from flask import current_app, has_app_context
|
||||
from pathlib import Path
|
||||
from flask import current_app
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
_oracle_client_init_attempted = False
|
||||
_oracle_client_init_error = None
|
||||
_oracle_client_mode = "unknown"
|
||||
_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:
|
||||
@@ -151,6 +151,122 @@ class Text2SQLService:
|
||||
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_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:
|
||||
@@ -392,9 +508,14 @@ class Text2SQLService:
|
||||
|
||||
user = "EXT_VIEW_USER"
|
||||
password = "extviewuser"
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
cls._ensure_oracle_client_initialized(oracledb)
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
try:
|
||||
# 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}")
|
||||
|
||||
try:
|
||||
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
@@ -409,7 +530,15 @@ class Text2SQLService:
|
||||
|
||||
return columns, rows
|
||||
except Exception as e:
|
||||
return ["Error"], [[cls._format_connection_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):
|
||||
|
||||
Reference in new issue
Block a user