|
| 1 | +from datetime import datetime |
| 2 | + |
| 3 | +from fastapi import Depends |
| 4 | +from sqlalchemy import select |
| 5 | +from sqlalchemy.orm import Session |
| 6 | + |
| 7 | +from wacruit.src.apps.history.models import History |
| 8 | +from wacruit.src.database.connection import get_db_session |
| 9 | +from wacruit.src.database.connection import Transaction |
| 10 | + |
| 11 | + |
| 12 | +class HistoryRepository: |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + session: Session = Depends(get_db_session), |
| 16 | + transaction: Transaction = Depends(), |
| 17 | + ): |
| 18 | + self.session = session |
| 19 | + self.transaction = transaction |
| 20 | + |
| 21 | + def get_history(self) -> list[History]: |
| 22 | + query = select(History) |
| 23 | + return list(self.session.execute(query).scalars().all()) |
| 24 | + |
| 25 | + def update_history(self, history: History) -> History: |
| 26 | + history_key = history.history_key |
| 27 | + history_value = history.history_value |
| 28 | + |
| 29 | + with self.transaction: |
| 30 | + query = select(History).where(History.history_key == history_key) |
| 31 | + result = self.session.execute(query).scalar_one_or_none() |
| 32 | + if result: |
| 33 | + result.history_value = history_value |
| 34 | + else: |
| 35 | + result = History(history_key=history_key, history_value=history_value) |
| 36 | + self.session.add(result) |
| 37 | + |
| 38 | + return history |
| 39 | + |
| 40 | + def get_start_date(self) -> datetime | None: |
| 41 | + query = select(History).where(History.history_key == "start_date") |
| 42 | + result = self.session.execute(query).scalar_one_or_none() |
| 43 | + |
| 44 | + if result is None: |
| 45 | + return None |
| 46 | + return datetime.strptime(result.history_value, "%Y-%m-%d") |
0 commit comments