80 lines
1.5 KiB
Python
80 lines
1.5 KiB
Python
|
"""
|
||
|
Pydantic representation of database contents.
|
||
|
"""
|
||
|
|
||
|
from __future__ import annotations
|
||
|
|
||
|
from datetime import datetime
|
||
|
|
||
|
from pydantic import BaseModel
|
||
|
from sqlalchemy.exc import IntegrityError
|
||
|
from sqlalchemy.orm import Session
|
||
|
|
||
|
from .. import models
|
||
|
|
||
|
|
||
|
class DeviceBase(BaseModel):
|
||
|
name: str
|
||
|
type: str
|
||
|
expiry: datetime
|
||
|
|
||
|
|
||
|
class DeviceCreate(DeviceBase):
|
||
|
owner_name: str
|
||
|
|
||
|
|
||
|
class Device(DeviceBase):
|
||
|
class Config:
|
||
|
orm_mode = True
|
||
|
|
||
|
@classmethod
|
||
|
def create(
|
||
|
cls,
|
||
|
db: Session,
|
||
|
device: DeviceCreate,
|
||
|
) -> Device | None:
|
||
|
"""
|
||
|
Create a new device in the database.
|
||
|
"""
|
||
|
|
||
|
try:
|
||
|
db_device = models.Device(
|
||
|
owner_name=device.owner_name,
|
||
|
|
||
|
name=device.name,
|
||
|
type=device.type,
|
||
|
expiry=device.expiry,
|
||
|
)
|
||
|
|
||
|
db.add(db_device)
|
||
|
db.commit()
|
||
|
db.refresh(db_device)
|
||
|
|
||
|
return cls.from_orm(db_device)
|
||
|
|
||
|
except IntegrityError:
|
||
|
# device already existed
|
||
|
return None
|
||
|
|
||
|
def delete(
|
||
|
self,
|
||
|
db: Session,
|
||
|
) -> bool:
|
||
|
"""
|
||
|
Delete this device from the database.
|
||
|
"""
|
||
|
|
||
|
db_device = models.Device(
|
||
|
# owner_name=
|
||
|
name=self.name,
|
||
|
)
|
||
|
db.refresh(db_device)
|
||
|
|
||
|
if db_device is None:
|
||
|
# nonexistent device
|
||
|
return False
|
||
|
|
||
|
db.delete(db_device)
|
||
|
db.commit()
|
||
|
return True
|