Files
tdEngine_mqtt_mock/db/orm.py
wsy182 6557479a2f refactor(config): 重构配置模块并优化应用依赖注入
- 将配置相关类移动到model模块
- 实现依赖注入容器管理各组件依赖关系
- 重构配置加载逻辑支持多层级键值查找
- 更新主应用入口支持命令行参数解析
- 统一日志输出格式替换原有打印语句
- 引入钻井实时数据模型简化数据处理
- 移除硬编码字段映射改用动态配置方式
- 优化数据库写入逻辑基于新的数据模型
2026-03-12 10:41:26 +08:00

102 lines
2.6 KiB
Python

import re
from model import DrillingRealtimeData
DB_COLUMNS = [
"ts",
"stknum",
"recid",
"seqid",
"actual_date",
"actual_time",
"actcod",
"deptbitm",
"deptbitv",
"deptmeas",
"deptvert",
"blkpos",
"ropa",
"hkla",
"hklx",
"woba",
"wobx",
"torqa",
"torqx",
"rpma",
"sppa",
"chkp",
"spm1",
"spm2",
"spm3",
"tvolact",
"tvolcact",
"mfop",
"mfoa",
"mfia",
"mdoa",
"mdia",
"mtoa",
"mtia",
"mcoa",
"mcia",
"stkc",
"lagstks",
"deptretm",
"gasa",
"space1",
"space2",
"space3",
"space4",
"space5",
]
INT_COLUMNS = {"stknum", "recid", "seqid", "actcod", "rpma", "spm1", "spm2", "spm3", "mfop", "stkc", "lagstks"}
def sanitize_identifier(value, fallback):
cleaned = re.sub(r"[^A-Za-z0-9_]", "_", str(value or ""))
if not cleaned:
cleaned = fallback
if cleaned[0].isdigit():
cleaned = f"t_{cleaned}"
return cleaned.lower()
def sql_quote(value):
return "'" + str(value).replace("'", "''") + "'"
class DrillingRealtimeORM:
def __init__(self, database, stable="drilling_realtime_st", default_device_code="GJ-304-0088"):
self.database = database
self.stable = stable
self.default_device_code = default_device_code or "GJ-304-0088"
def build_insert_sql(self, payload):
if not isinstance(payload, dict):
raise ValueError("payload is not JSON object")
entity = DrillingRealtimeData.from_payload(payload)
meta = payload.get("meta") if isinstance(payload.get("meta"), dict) else {}
equipment_code = (
str(self.default_device_code).strip()
or str(meta.get("equipment_code", "")).strip()
or str(meta.get("equipment_sn", "")).strip()
or entity.wellid
or "GJ-304-0088"
)
table_name = sanitize_identifier(f"drilling_realtime_{equipment_code}", "drilling_realtime_default")
values = []
for column in DB_COLUMNS:
raw = getattr(entity, column)
if column in INT_COLUMNS or column == "ts":
values.append(str(int(raw)))
else:
values.append(str(float(raw)))
columns_sql = ", ".join([f"`{column}`" for column in DB_COLUMNS])
values_sql = ", ".join(values)
return (
f"INSERT INTO `{self.database}`.`{table_name}` USING `{self.database}`.`{self.stable}` "
f"TAGS ({sql_quote(equipment_code)}) ({columns_sql}) VALUES ({values_sql})"
)