emcp/backend/app/repositories/alarm_repo.py

72 lines
2.2 KiB
Python
Raw Normal View History

2026-05-18 09:12:14 +08:00
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict, List, Optional
2026-05-18 09:12:14 +08:00
from app.db.sqlite import get_connection
from app.schemas.platform import AlarmEvent
class AlarmRepository:
def save_alarm(self, alarm: AlarmEvent) -> int:
with get_connection() as connection:
cursor = connection.execute(
"""
INSERT INTO alarm_event (alarm_type, time, no, type, content, level)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
alarm.alarm_type,
alarm.time.isoformat(sep=" ", timespec="seconds"),
alarm.no,
alarm.type,
alarm.content,
alarm.level,
),
)
connection.commit()
return int(cursor.lastrowid)
def list_alarms(
self,
page: int = 1,
size: int = 20,
no: str = "",
alarm_type: str = "",
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
) -> List[Dict[str, Any]]:
2026-05-18 09:12:14 +08:00
offset = (page - 1) * size
conditions = []
params: List[Any] = []
if no:
conditions.append("no = ?")
params.append(no)
if alarm_type:
conditions.append("type = ?")
params.append(alarm_type)
if start_time is not None:
conditions.append("time >= ?")
params.append(start_time.isoformat(sep=" ", timespec="seconds"))
if end_time is not None:
conditions.append("time <= ?")
params.append(end_time.isoformat(sep=" ", timespec="seconds"))
where_clause = ""
if conditions:
where_clause = "WHERE " + " AND ".join(conditions)
2026-05-18 09:12:14 +08:00
with get_connection() as connection:
cursor = connection.execute(
f"""
2026-05-18 09:12:14 +08:00
SELECT id, alarm_type, time, no, type, content, level
FROM alarm_event
{where_clause}
2026-05-18 09:12:14 +08:00
ORDER BY id DESC
LIMIT ? OFFSET ?
""",
tuple(params + [size, offset]),
2026-05-18 09:12:14 +08:00
)
return [dict(row) for row in cursor.fetchall()]