244 lines
8.7 KiB
Python
244 lines
8.7 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from typing import Any
|
|
|
|
_ENV_VAR_PATTERN = re.compile(r"\$\{(\w+)\}")
|
|
|
|
|
|
def resolve_env_value(val: str) -> str:
|
|
if not val or "${" not in val:
|
|
return val
|
|
|
|
def _replacer(match: re.Match) -> str:
|
|
env_key = match.group(1)
|
|
return os.environ.get(env_key, match.group(0))
|
|
|
|
return _ENV_VAR_PATTERN.sub(_replacer, val)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DataSourceConfig:
|
|
db_type: str = "sqlserver"
|
|
host: str = ""
|
|
port: str = ""
|
|
database: str = ""
|
|
username: str = ""
|
|
password: str = ""
|
|
driver: str = ""
|
|
encrypt: str = ""
|
|
trust_cert: str = ""
|
|
|
|
def is_empty(self) -> bool:
|
|
return not self.host.strip()
|
|
|
|
def build_connection_string(self) -> str:
|
|
host = resolve_env_value(self.host)
|
|
port = resolve_env_value(self.port)
|
|
database = resolve_env_value(self.database)
|
|
username = resolve_env_value(self.username)
|
|
password = resolve_env_value(self.password)
|
|
|
|
if not port:
|
|
if self.db_type == "sqlserver":
|
|
port = "1433"
|
|
elif self.db_type == "postgresql":
|
|
port = "5432"
|
|
elif self.db_type == "mysql":
|
|
port = "3306"
|
|
|
|
if self.db_type == "sqlserver":
|
|
driver = resolve_env_value(self.driver) or "SQL Server"
|
|
encrypt = resolve_env_value(self.encrypt) or "no"
|
|
trust_cert = resolve_env_value(self.trust_cert) or "yes"
|
|
return (
|
|
f"DRIVER={{{driver}}};"
|
|
f"SERVER={host},{port};"
|
|
f"DATABASE={database};"
|
|
f"UID={username};"
|
|
f"PWD={password};"
|
|
f"Encrypt={encrypt};"
|
|
f"TrustServerCertificate={trust_cert};"
|
|
)
|
|
elif self.db_type == "postgresql":
|
|
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
|
|
elif self.db_type == "mysql":
|
|
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"
|
|
raise ValueError(f"Unsupported db_type: {self.db_type}")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ExternalApiConfig:
|
|
url: str = ""
|
|
method: str = "POST"
|
|
headers: dict[str, str] = field(default_factory=dict)
|
|
body_template: str = ""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ScheduleSqlConfig:
|
|
description: str = ""
|
|
row_id_key: str = "id"
|
|
log_prefix: str = ""
|
|
fetch_sql: str = ""
|
|
base_fetch_sql: str = ""
|
|
fetch_where_conditions: str = ""
|
|
fetch_order_by: str = ""
|
|
writeback_sql: str = ""
|
|
detail_sql: str = ""
|
|
alias_order: list[str] = field(default_factory=list)
|
|
detail_alias_order: list[str] = field(default_factory=list)
|
|
header_labels: dict[str, str] = field(default_factory=dict)
|
|
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
|
|
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
|
|
data_source_type: str = "database"
|
|
dify_system_prompt: str = ""
|
|
|
|
|
|
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
|
|
parts = [base.strip().rstrip(";").strip()]
|
|
if where_conds.strip():
|
|
parts.append("where")
|
|
parts.append(where_conds.strip())
|
|
if order_by.strip():
|
|
parts.append(order_by.strip())
|
|
return "\n".join(parts)
|
|
|
|
|
|
def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
|
|
from app import db
|
|
from app.models import ScheduleTask
|
|
|
|
task_id = cfg_model.schedule_task_id
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
|
|
base = str(cfg_model.base_fetch_sql or "")
|
|
where_conds = str(cfg_model.fetch_where_conditions or "")
|
|
order_by = str(cfg_model.fetch_order_by or "")
|
|
fetch_sql = _build_fetch_sql(base, where_conds, order_by) if base else ""
|
|
|
|
ds = DataSourceConfig(
|
|
db_type=str(cfg_model.ds_db_type or "sqlserver"),
|
|
host=str(cfg_model.ds_host or ""),
|
|
port=str(cfg_model.ds_port or ""),
|
|
database=str(cfg_model.ds_database or ""),
|
|
username=str(cfg_model.ds_username or ""),
|
|
password=str(cfg_model.ds_password or ""),
|
|
driver=str(cfg_model.ds_driver or ""),
|
|
encrypt=str(cfg_model.ds_encrypt or ""),
|
|
trust_cert=str(cfg_model.ds_trust_cert or ""),
|
|
)
|
|
|
|
ext = ExternalApiConfig(
|
|
url=str(cfg_model.api_url or ""),
|
|
method=str(cfg_model.api_method or "POST"),
|
|
headers=dict(cfg_model.api_headers or {}),
|
|
body_template=str(cfg_model.api_body_template or ""),
|
|
)
|
|
|
|
return ScheduleSqlConfig(
|
|
description=str(task.name if task else ""),
|
|
row_id_key=str(cfg_model.row_id_key or "id"),
|
|
log_prefix=str(cfg_model.log_prefix or ""),
|
|
fetch_sql=fetch_sql,
|
|
base_fetch_sql=base,
|
|
fetch_where_conditions=where_conds,
|
|
fetch_order_by=order_by,
|
|
writeback_sql=str(cfg_model.writeback_sql or ""),
|
|
detail_sql=str(cfg_model.detail_sql or ""),
|
|
alias_order=list(cfg_model.alias_order or []),
|
|
detail_alias_order=list(cfg_model.detail_alias_order or []),
|
|
header_labels=dict(cfg_model.header_labels or {}),
|
|
data_source=ds,
|
|
external_api=ext,
|
|
data_source_type=str(task.data_source_type if task else "database"),
|
|
dify_system_prompt=str(cfg_model.dify_system_prompt or ""),
|
|
)
|
|
|
|
|
|
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
|
|
from app import db
|
|
from app.models import ScheduleTask, ScheduleTaskConfig
|
|
|
|
key = name.strip().lower()
|
|
task = None
|
|
if key.isdigit():
|
|
task = db.session.get(ScheduleTask, int(key))
|
|
if not task:
|
|
task = ScheduleTask.query.filter(
|
|
ScheduleTask.platform_api_path.ilike(f"%{key}%")
|
|
).first()
|
|
if not task:
|
|
return None
|
|
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
|
if not cfg_model:
|
|
return None
|
|
|
|
return _config_from_model(cfg_model)
|
|
|
|
|
|
def get_schedule_sql_config_by_task_id(task_id: int) -> ScheduleSqlConfig | None:
|
|
from app import db
|
|
from app.models import ScheduleTask, ScheduleTaskConfig
|
|
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
if not cfg_model:
|
|
return None
|
|
return _config_from_model(cfg_model)
|
|
|
|
|
|
def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
|
|
from app.models import ScheduleTask, ScheduleTaskConfig
|
|
|
|
results: dict[str, ScheduleSqlConfig] = {}
|
|
configs = ScheduleTaskConfig.query.all()
|
|
for cfg_model in configs:
|
|
key = str(cfg_model.schedule_task_id)
|
|
results[key] = _config_from_model(cfg_model)
|
|
return results
|
|
|
|
|
|
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
|
|
from app import db
|
|
from app.models import ScheduleTask, ScheduleTaskConfig
|
|
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
if not cfg_model:
|
|
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
|
|
db.session.add(cfg_model)
|
|
|
|
for k, v in data.items():
|
|
if k == "data_source" and isinstance(v, dict):
|
|
cfg_model.ds_db_type = str(v.get("db_type", "sqlserver"))
|
|
cfg_model.ds_host = str(v.get("host", ""))
|
|
cfg_model.ds_port = str(v.get("port", ""))
|
|
cfg_model.ds_database = str(v.get("database", ""))
|
|
cfg_model.ds_username = str(v.get("username", ""))
|
|
cfg_model.ds_password = str(v.get("password", ""))
|
|
cfg_model.ds_driver = str(v.get("driver", "")) if v.get("driver") else None
|
|
cfg_model.ds_encrypt = str(v.get("encrypt", "")) if v.get("encrypt") else None
|
|
cfg_model.ds_trust_cert = str(v.get("trust_cert", "")) if v.get("trust_cert") else None
|
|
elif k == "external_api" and isinstance(v, dict):
|
|
cfg_model.api_url = str(v.get("url", ""))
|
|
cfg_model.api_method = str(v.get("method", "POST"))
|
|
cfg_model.api_headers = dict(v.get("headers", {}))
|
|
cfg_model.api_body_template = str(v.get("body_template", ""))
|
|
elif k in ("row_id_key", "log_prefix"):
|
|
setattr(cfg_model, k, str(v) if v is not None else "")
|
|
elif k in ("base_fetch_sql", "fetch_where_conditions", "fetch_order_by",
|
|
"writeback_sql", "detail_sql"):
|
|
setattr(cfg_model, k, str(v) if v is not None else None)
|
|
elif k in ("alias_order", "detail_alias_order"):
|
|
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
|
|
elif k == "header_labels":
|
|
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
|
|
elif k == "dify_system_prompt":
|
|
setattr(cfg_model, k, str(v) if v is not None else None)
|
|
|
|
db.session.commit()
|
|
db.session.refresh(cfg_model)
|
|
return _config_from_model(cfg_model)
|