agreg-server/server/backend/adapters/postgres/device_repository.py

31 lines
1,018 B
Python
Raw Normal View History

import logging
import psycopg2
from ports import DeviceRepository
from domain.exceptions import DatabaseError
from infrastructure.db import get_conn
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