新增内部查询方法,替换simulation中scada设备查询方法

This commit is contained in:
JIANG
2025-12-09 15:10:10 +08:00
parent 357bacbf8a
commit 1d55bf4992
5 changed files with 102 additions and 42 deletions

View File

@@ -1,6 +1,6 @@
from typing import List, Any
from datetime import datetime
from psycopg import AsyncConnection, sql
from psycopg import AsyncConnection, Connection, sql
class ScadaRepository:
@@ -25,36 +25,53 @@ class ScadaRepository:
)
@staticmethod
async def get_scada_by_id_time_range(
conn: AsyncConnection, device_id: str, start_time: datetime, end_time: datetime
async def get_scada_by_ids_time_range(
conn: AsyncConnection,
device_ids: List[str],
start_time: datetime,
end_time: datetime,
) -> List[dict]:
async with conn.cursor() as cur:
await cur.execute(
"SELECT * FROM scada.scada_data WHERE device_id = %s AND time >= %s AND time <= %s",
(device_id, start_time, end_time),
"SELECT * FROM scada.scada_data WHERE device_id = ANY(%s) AND time >= %s AND time <= %s",
(device_ids, start_time, end_time),
)
return await cur.fetchall()
@staticmethod
def get_scada_by_ids_time_range_sync(
conn: Connection,
device_ids: List[str],
start_time: datetime,
end_time: datetime,
) -> List[dict]:
with conn.cursor() as cur:
cur.execute(
"SELECT * FROM scada.scada_data WHERE device_id = ANY(%s) AND time >= %s AND time <= %s",
(device_ids, start_time, end_time),
)
return cur.fetchall()
@staticmethod
async def get_scada_field_by_id_time_range(
conn: AsyncConnection,
device_id: str,
device_ids: List[str],
start_time: datetime,
end_time: datetime,
field: str,
) -> Any:
) -> List[dict]:
valid_fields = {"monitored_value", "cleaned_value"}
if field not in valid_fields:
raise ValueError(f"Invalid field: {field}")
query = sql.SQL(
"SELECT {} FROM scada.scada_data WHERE time >= %s AND time <= %s AND device_id = %s"
"SELECT device_id, {} FROM scada.scada_data WHERE time >= %s AND time <= %s AND device_id = ANY(%s)"
).format(sql.Identifier(field))
async with conn.cursor() as cur:
await cur.execute(query, (start_time, end_time, device_id))
row = await cur.fetchone()
return row[field] if row else None
await cur.execute(query, (start_time, end_time, device_ids))
rows = await cur.fetchall()
return [{"device_id": row["device_id"], field: row[field]} for row in rows]
@staticmethod
async def update_scada_field(