2026-05-09 17:06:57 +02:00
|
|
|
import logging
|
|
|
|
|
|
|
|
|
|
import psycopg2
|
2026-05-10 12:37:24 +02:00
|
|
|
|
2026-05-10 15:06:36 +02:00
|
|
|
from ports import DeviceRepository
|
2026-05-10 14:55:50 +02:00
|
|
|
from domain.exceptions import DatabaseError
|
|
|
|
|
from infrastructure.db import get_conn
|
2026-05-09 17:06:57 +02:00
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PgDeviceRepository(DeviceRepository):
|
|
|
|
|
def get_or_create_device_id(self, dev_eui: str) -> str:
|
2026-05-09 17:47:37 +02:00
|
|
|
try:
|
2026-05-10 14:55:50 +02:00
|
|
|
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
|
2026-05-09 17:47:37 +02:00
|
|
|
except psycopg2.DatabaseError as e:
|
|
|
|
|
raise DatabaseError(f"Erreur de création du device {dev_eui}") from e
|