2022-11-11 16:16:31 -05:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
"""
|
|
|
|
|
2023-01-24 10:51:50 -05:00
|
|
|
from hub.city_model_structure.city import City
|
|
|
|
from hub.persistence import BaseRepo
|
2022-11-11 16:16:31 -05:00
|
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
from sqlalchemy import select
|
2023-01-24 10:51:50 -05:00
|
|
|
from hub.persistence.models import City as DBCity
|
2022-11-11 16:16:31 -05:00
|
|
|
import pickle
|
|
|
|
import requests
|
|
|
|
from urllib3.exceptions import HTTPError
|
|
|
|
from typing import Union, Dict
|
2023-01-24 10:51:50 -05:00
|
|
|
from hub.hub_logger import logger
|
2023-01-10 12:26:08 -05:00
|
|
|
import datetime
|
2022-11-11 16:16:31 -05:00
|
|
|
|
|
|
|
|
|
|
|
class CityRepo(BaseRepo):
|
2022-11-15 20:48:42 -05:00
|
|
|
_instance = None
|
|
|
|
|
2022-12-07 19:06:17 -05:00
|
|
|
def __init__(self, db_name: str, dotenv_path: str, app_env: str):
|
2022-12-14 17:49:29 -05:00
|
|
|
super().__init__(db_name, dotenv_path, app_env)
|
2022-11-11 16:16:31 -05:00
|
|
|
|
2022-12-07 19:06:17 -05:00
|
|
|
def __new__(cls, db_name, dotenv_path, app_env):
|
2022-11-15 20:48:42 -05:00
|
|
|
"""
|
|
|
|
Implemented for a singleton pattern
|
|
|
|
"""
|
|
|
|
if cls._instance is None:
|
|
|
|
cls._instance = super(CityRepo, cls).__new__(cls)
|
|
|
|
return cls._instance
|
|
|
|
|
2023-01-11 16:02:33 -05:00
|
|
|
def insert(self, city: City, user_id: int) -> Union[City, Dict]:
|
2022-11-25 18:21:09 -05:00
|
|
|
db_city = DBCity(pickle.dumps(city), city.name, city.srs_name, city.country_code, city.lower_corner,
|
2023-01-11 16:02:33 -05:00
|
|
|
city.upper_corner, user_id)
|
2022-11-15 20:48:42 -05:00
|
|
|
db_city.climate_reference_city = city.climate_reference_city
|
|
|
|
db_city.longitude = city.longitude
|
|
|
|
db_city.latitude = city.latitude
|
|
|
|
db_city.time_zone = city.time_zone
|
2022-11-11 16:16:31 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
# Retrieve hub project latest release
|
|
|
|
response = requests.get("https://rs-loy-gitlab.concordia.ca/api/v4/projects/2/repository/branches/master",
|
|
|
|
headers={"PRIVATE-TOKEN": self.config.hub_token})
|
|
|
|
recent_commit = response.json()["commit"]["id"]
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.info(f'Current commit of hub is {recent_commit}')
|
2022-11-11 16:16:31 -05:00
|
|
|
exiting_city = self._get_by_hub_version(recent_commit, city.name)
|
|
|
|
|
|
|
|
# Do not persist the same city for the same version of Hub
|
|
|
|
if exiting_city is None:
|
2022-11-15 20:48:42 -05:00
|
|
|
db_city.hub_release = recent_commit
|
2022-11-11 16:16:31 -05:00
|
|
|
cities = self.get_by_name(city.name)
|
|
|
|
# update version for the same city but different hub versions
|
2022-11-15 20:48:42 -05:00
|
|
|
|
2022-11-11 16:16:31 -05:00
|
|
|
if len(cities) == 0:
|
2022-11-15 20:48:42 -05:00
|
|
|
db_city.city_version = 0
|
2022-11-11 16:16:31 -05:00
|
|
|
else:
|
2022-11-15 20:48:42 -05:00
|
|
|
db_city.city_version = cities[-1].city_version + 1
|
2022-11-11 16:16:31 -05:00
|
|
|
|
|
|
|
# Persist city
|
2022-11-15 20:48:42 -05:00
|
|
|
self.session.add(db_city)
|
2022-11-11 16:16:31 -05:00
|
|
|
self.session.flush()
|
|
|
|
self.session.commit()
|
2022-11-15 20:48:42 -05:00
|
|
|
return db_city
|
2022-11-11 16:16:31 -05:00
|
|
|
else:
|
|
|
|
return {'message': f'Same version of {city.name} exist'}
|
|
|
|
except SQLAlchemyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error while adding city: {err}')
|
2022-11-11 16:16:31 -05:00
|
|
|
except HTTPError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error retrieving Hub latest release: {err}')
|
2022-11-11 16:16:31 -05:00
|
|
|
|
2022-11-15 20:48:42 -05:00
|
|
|
def get_by_id(self, city_id: int) -> DBCity:
|
2022-11-11 16:16:31 -05:00
|
|
|
"""
|
|
|
|
Fetch a City based on the id
|
|
|
|
:param city_id: the city id
|
|
|
|
:return: a city
|
|
|
|
"""
|
|
|
|
try:
|
2022-11-15 20:48:42 -05:00
|
|
|
return self.session.execute(select(DBCity).where(DBCity.id == city_id)).first()[0]
|
2022-11-11 16:16:31 -05:00
|
|
|
except SQLAlchemyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error while fetching city: {err}')
|
2022-11-11 16:16:31 -05:00
|
|
|
|
|
|
|
def _get_by_hub_version(self, hub_commit: str, city_name: str) -> City:
|
|
|
|
"""
|
|
|
|
Fetch a City based on the name and hub project recent commit
|
|
|
|
:param hub_commit: the latest hub commit
|
|
|
|
:param city_name: the name of the city
|
|
|
|
:return: a city
|
|
|
|
"""
|
|
|
|
try:
|
2022-11-15 20:48:42 -05:00
|
|
|
return self.session.execute(select(DBCity)
|
|
|
|
.where(DBCity.hub_release == hub_commit, DBCity.name == city_name)).first()
|
2022-11-11 16:16:31 -05:00
|
|
|
except SQLAlchemyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error while fetching city: {err}')
|
2022-11-11 16:16:31 -05:00
|
|
|
|
|
|
|
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:
|
2022-11-15 20:48:42 -05:00
|
|
|
self.session.query(DBCity).filter(DBCity.id == city_id) \
|
2022-11-11 16:16:31 -05:00
|
|
|
.update({
|
2023-01-10 12:26:08 -05:00
|
|
|
'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,
|
2023-01-10 20:30:55 -05:00
|
|
|
'updated': datetime.datetime.utcnow()
|
2023-01-10 12:26:08 -05:00
|
|
|
})
|
2022-11-11 16:16:31 -05:00
|
|
|
|
|
|
|
self.session.commit()
|
|
|
|
except SQLAlchemyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error while updating city: {err}')
|
2022-11-11 16:16:31 -05:00
|
|
|
|
2022-11-15 20:48:42 -05:00
|
|
|
def get_by_name(self, city_name: str) -> [DBCity]:
|
2022-11-11 16:16:31 -05:00
|
|
|
"""
|
|
|
|
Fetch city based on the name
|
|
|
|
:param city_name: the name of the building
|
|
|
|
:return: [ModelCity] with the provided name
|
|
|
|
"""
|
|
|
|
try:
|
2022-11-15 20:48:42 -05:00
|
|
|
result_set = self.session.execute(select(DBCity).where(DBCity.name == city_name))
|
2022-11-11 16:16:31 -05:00
|
|
|
return [building[0] for building in result_set]
|
|
|
|
except SQLAlchemyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error while fetching city by name: {err}')
|
2022-11-15 20:48:42 -05:00
|
|
|
|
2023-01-11 16:02:33 -05:00
|
|
|
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}')
|
|
|
|
|
2022-11-15 20:48:42 -05:00
|
|
|
def delete_city(self, city_id: int):
|
|
|
|
"""
|
|
|
|
Deletes a City with the id
|
|
|
|
:param city_id: the city id
|
|
|
|
:return: a city
|
|
|
|
"""
|
|
|
|
try:
|
2022-11-25 18:21:09 -05:00
|
|
|
self.session.query(DBCity).filter(DBCity.id == city_id).delete()
|
|
|
|
self.session.commit()
|
2022-11-15 20:48:42 -05:00
|
|
|
except SQLAlchemyError as err:
|
2022-12-14 17:49:29 -05:00
|
|
|
logger.error(f'Error while fetching city: {err}')
|