""" 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 """ from city_model_structure.city import City from persistence.models import City as ModelCity from persistence import BaseRepo from sqlalchemy.exc import SQLAlchemyError from sqlalchemy import select class CityRepo(BaseRepo): def __init__(self): super().__init__() def insert(self, city: City): model_city = ModelCity() model_city.name = city.name model_city.longitude = city.longitude model_city.latitude = city.latitude model_city.country_code = city.country_code model_city.time_zone = city.time_zone try: self.session.add(model_city) self.session.flush() self.session.commit() return model_city except SQLAlchemyError as err: print(f'Error while adding city: {err}') def get_by_id(self, city_id: int) -> ModelCity: """ Fetch a City based on the id :param city_id: the city id :return: a city """ try: return self.session.execute(select(ModelCity).where(ModelCity.id == city_id)).first()[0] except SQLAlchemyError as err: print(f'Error while fetching city: {err}') def get_by_name(self, city_name: str) -> [ModelCity]: """ 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(ModelCity).where(ModelCity.name == city_name)) return [building[0] for building in result_set] except SQLAlchemyError as err: print(f'Error while fetching city by name: {err}')