from src.logging.get_logger import get_logger
from src.model.db.ultmarc_sosiety import UltmarcSosietyDBModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('COM_学会取得')


class UltmarcSosietyRepository(BaseRepository):

    FETCH_SQL = """\
        SELECT com_sosiety.sosiety_cd, com_sosiety.sosiety_name
        FROM src05.com_dr
        LEFT JOIN src05.com_dr_sosiety ON com_dr.dcf_pcf_dr_cd = com_dr_sosiety.dcf_pcf_dr_cd
        LEFT JOIN src05.com_sosiety ON com_dr_sosiety.sosiety_cd = com_sosiety.sosiety_cd
        WHERE com_dr.dcf_pcf_dr_cd = :id
        ORDER BY com_sosiety.sosiety_cd
    """

    def fetch_many(self, id) -> list[UltmarcSosietyDBModel]:
        try:
            self._database.connect()
            query = self.FETCH_SQL
            result = self._database.execute_select(query, {'id': id})
            models = [UltmarcSosietyDBModel(**r) for r in result]
            if len(models) == 0:
                return None
            return models
        except Exception as e:
            logger.exception(f"DB Error : Exception={e.args}")
            raise e
        finally:
            self._database.disconnect()
