新增 timescaledb 的 CRUD 方法、fastapi 路由
This commit is contained in:
39
timescaledb/schemas/scada.py
Normal file
39
timescaledb/schemas/scada.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from typing import List, Any
|
||||
from datetime import datetime
|
||||
from psycopg import AsyncConnection, sql
|
||||
|
||||
class ScadaRepository:
|
||||
|
||||
@staticmethod
|
||||
async def insert_batch(conn: AsyncConnection, data: List[dict]):
|
||||
if not data:
|
||||
return
|
||||
|
||||
async with conn.cursor() as cur:
|
||||
async with cur.copy(
|
||||
"COPY scada.scada_data (time, device_id, monitored_value, cleaned_value) FROM STDIN"
|
||||
) as copy:
|
||||
for item in data:
|
||||
await copy.write_row((
|
||||
item['time'], item['device_id'], item.get('monitored_value'), item.get('cleaned_value')
|
||||
))
|
||||
|
||||
@staticmethod
|
||||
async def get_data_by_time(conn: AsyncConnection, device_id: 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)
|
||||
)
|
||||
return await cur.fetchall()
|
||||
|
||||
@staticmethod
|
||||
async def update_field(conn: AsyncConnection, time: datetime, device_id: str, field: str, value: Any):
|
||||
valid_fields = {"monitored_value", "cleaned_value"}
|
||||
if field not in valid_fields:
|
||||
raise ValueError(f"Invalid field: {field}")
|
||||
|
||||
query = sql.SQL("UPDATE scada.scada_data SET {} = %s WHERE time = %s AND device_id = %s").format(sql.Identifier(field))
|
||||
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(query, (value, time, device_id))
|
||||
Reference in New Issue
Block a user