forked from s_ranjbar/city_retrofit
135 lines
4.4 KiB
Python
135 lines
4.4 KiB
Python
"""
|
|
City repository with database CRUD operations
|
|
SPDX - License - Identifier: LGPL - 3.0 - or -later
|
|
Copyright © 2022 Concordia CERC group
|
|
Project Coder Peter Yefi peteryefi@gmail.com
|
|
"""
|
|
|
|
import datetime
|
|
import pickle
|
|
from typing import Union, Dict
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
from hub.city_model_structure.city import City
|
|
from hub.hub_logger import logger
|
|
from hub.persistence import BaseRepo
|
|
from hub.persistence.models import City as DBCity
|
|
from hub.version import __version__
|
|
|
|
|
|
class CityRepo(BaseRepo):
|
|
_instance = None
|
|
|
|
def __init__(self, db_name: str, dotenv_path: str, app_env: str):
|
|
super().__init__(db_name, dotenv_path, app_env)
|
|
|
|
def __new__(cls, db_name, dotenv_path, app_env):
|
|
"""
|
|
Implemented for a singleton pattern
|
|
"""
|
|
if cls._instance is None:
|
|
cls._instance = super(CityRepo, cls).__new__(cls)
|
|
return cls._instance
|
|
|
|
def insert(self, city: City, application_id, user_id: int) -> Union[City, Dict]:
|
|
"""
|
|
Insert a city
|
|
:param city: The complete city instance
|
|
:param application_id: Application id owning the instance
|
|
:param user_id: User id owning the instance
|
|
:return: City and Dictionary
|
|
"""
|
|
try:
|
|
release = __version__
|
|
db_city = DBCity(pickle.dumps(city), city.name, city.level_of_detail, city.climate_file, application_id, user_id,
|
|
release)
|
|
|
|
self.session.add(db_city)
|
|
self.session.flush()
|
|
self.session.commit()
|
|
return db_city
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'An error occurred while creating city: {err}')
|
|
|
|
def get_by_id(self, city_id: int) -> DBCity:
|
|
"""
|
|
Fetch a City based on the id
|
|
:param city_id: the city id
|
|
:return: a city
|
|
"""
|
|
try:
|
|
return self.session.execute(select(DBCity).where(DBCity.id == city_id)).first()[0]
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'Error while fetching city: {err}')
|
|
|
|
def _get_by_hub_version(self, hub_release: str, city_name: str) -> City:
|
|
"""
|
|
Fetch a City based on the name and hub project
|
|
:param hub_release: the hub release
|
|
:param city_name: the name of the city
|
|
:return: a city
|
|
"""
|
|
try:
|
|
return self.session.execute(select(DBCity)
|
|
.where(DBCity.hub_release == hub_release, DBCity.name == city_name)).first()
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'Error while fetching city: {err}')
|
|
|
|
def update(self, city_id: int, city: City):
|
|
"""
|
|
Updates a city
|
|
:param city_id: the id of the city to be updated
|
|
:param city: the city object
|
|
:return:
|
|
"""
|
|
try:
|
|
self.session.query(DBCity).filter(DBCity.id == city_id) \
|
|
.update({
|
|
'name': city.name, 'srs_name': city.srs_name, 'country_code': city.country_code, 'longitude': city.longitude,
|
|
'latitude': city.latitude, 'time_zone': city.time_zone, 'lower_corner': city.lower_corner.tolist(),
|
|
'upper_corner': city.upper_corner.tolist(), 'climate_reference_city': city.climate_reference_city,
|
|
'updated': datetime.datetime.utcnow()
|
|
})
|
|
|
|
self.session.commit()
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'Error while updating city: {err}')
|
|
|
|
def get_by_name(self, city_name: str) -> [DBCity]:
|
|
"""
|
|
Fetch city based on the name
|
|
:param city_name: the name of the building
|
|
:return: [ModelCity] with the provided name
|
|
"""
|
|
try:
|
|
result_set = self.session.execute(select(DBCity).where(DBCity.name == city_name))
|
|
return [building[0] for building in result_set]
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'Error while fetching city by name: {err}')
|
|
|
|
def get_by_user(self, user_id: int) -> [DBCity]:
|
|
"""
|
|
Fetch city based on the user who created it
|
|
:param user_id: the id of the user
|
|
:return: [ModelCity] with the provided name
|
|
"""
|
|
try:
|
|
result_set = self.session.execute(select(DBCity).where(DBCity.user_id == user_id))
|
|
return [building[0] for building in result_set]
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'Error while fetching city by name: {err}')
|
|
|
|
def delete_city(self, city_id: int):
|
|
"""
|
|
Deletes a City with the id
|
|
:param city_id: the city id
|
|
:return: a city
|
|
"""
|
|
try:
|
|
self.session.query(DBCity).filter(DBCity.id == city_id).delete()
|
|
self.session.commit()
|
|
except SQLAlchemyError as err:
|
|
logger.error(f'Error while fetching city: {err}')
|