43 lines
No EOL
1.5 KiB
Python
43 lines
No EOL
1.5 KiB
Python
import logging
|
|
|
|
import psycopg2
|
|
|
|
from ports import DeviceRepository
|
|
from domain.exceptions import DatabaseError
|
|
from infrastructure.db import get_conn
|
|
from domain.entities import Device
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
class PgDeviceRepository(DeviceRepository):
|
|
def get_or_create_device_id(self, dev_eui: str) -> str:
|
|
try:
|
|
with get_conn() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO device (device_eui)
|
|
VALUES (%s)
|
|
ON CONFLICT (device_eui) DO NOTHING
|
|
""",
|
|
(dev_eui,),
|
|
)
|
|
cur.execute(
|
|
"SELECT device_id FROM device WHERE device_eui = %s", (dev_eui,)
|
|
)
|
|
return str(cur.fetchone()[0]) # type: ignore
|
|
except psycopg2.DatabaseError as e:
|
|
raise DatabaseError(f"Erreur de création du device {dev_eui}") from e
|
|
|
|
def get_all(self) -> list[Device]:
|
|
query = "SELECT device_id, device_eui FROM device ORDER BY device_eui ASC"
|
|
try:
|
|
with get_conn() as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute(query)
|
|
rows = cur.fetchall()
|
|
except psycopg2.DatabaseError as e:
|
|
raise DatabaseError(f"Erreur d'accès aux devices : {e}") from e
|
|
|
|
return [Device(device_id=r[0], device_eui=r[1]) for r in rows] |