|
| 1 | +from sqlalchemy import create_engine, select, delete, engine |
| 2 | +from sqlalchemy.orm import Session |
| 3 | +from dotenv import load_dotenv |
| 4 | +from os import environ |
| 5 | +from typing import Optional, Union |
| 6 | + |
| 7 | +from app.database.models.DevicePlant import DevicePlant |
| 8 | +from app.database.models.Measurement import Measurement |
| 9 | + |
| 10 | +load_dotenv() |
| 11 | + |
| 12 | + |
| 13 | +class SQLAlchemyClient(): |
| 14 | + |
| 15 | + db_url = engine.URL.create( |
| 16 | + "postgresql", |
| 17 | + database=environ["POSTGRES_DB"], |
| 18 | + username=environ["POSTGRES_USER"], |
| 19 | + password=environ["POSTGRES_PASSWORD"], |
| 20 | + host=environ["POSTGRES_HOST"], |
| 21 | + port=environ["POSTGRES_PORT"] |
| 22 | + ) |
| 23 | + |
| 24 | + engine = create_engine(db_url) |
| 25 | + |
| 26 | + def __init__(self): |
| 27 | + self.conn = self.engine.connect() |
| 28 | + self.session = Session(self.engine) |
| 29 | + |
| 30 | + def shutdown(self): |
| 31 | + self.conn.close() |
| 32 | + self.session.close() |
| 33 | + |
| 34 | + def rollback(self): |
| 35 | + self.session.rollback() |
| 36 | + |
| 37 | + def clean_table(self, table: Union[DevicePlant, Measurement]): |
| 38 | + query = delete(table) |
| 39 | + self.session.execute(query) |
| 40 | + self.session.commit() |
| 41 | + |
| 42 | + def add_new(self, record: Union[DevicePlant, Measurement]): |
| 43 | + self.session.add(record) |
| 44 | + self.session.commit() |
| 45 | + |
| 46 | + def find_device_plant(self, id_device: str) -> DevicePlant: |
| 47 | + query = select(DevicePlant).where(DevicePlant.id_device == id_device) |
| 48 | + result = self.session.scalars(query).one() |
| 49 | + return result |
| 50 | + |
| 51 | + def update_device_plant(self, |
| 52 | + id_device: str, |
| 53 | + id_plant: Optional[int], |
| 54 | + plant_type: Optional[int], |
| 55 | + id_user: Optional[int]): |
| 56 | + |
| 57 | + query = select(DevicePlant).where(DevicePlant.id_device == id_device) |
| 58 | + |
| 59 | + device_plant = self.session.scalars(query).one() |
| 60 | + if id_plant: |
| 61 | + device_plant.id_plant = id_plant |
| 62 | + if plant_type: |
| 63 | + device_plant.id_plant = plant_type |
| 64 | + if id_user: |
| 65 | + device_plant.id_user = id_user |
| 66 | + self.session.commit() |
| 67 | + |
| 68 | + def get_last_measurement(self, id_plant: int) -> Measurement: |
| 69 | + query = select(Measurement).where( |
| 70 | + Measurement.id_plant == id_plant |
| 71 | + ).order_by(Measurement.id.desc()).limit(1) |
| 72 | + |
| 73 | + result: Measurement = self.session.scalars(query).one() |
| 74 | + |
| 75 | + return result |
0 commit comments