Coverage for src/counter_os/infrastructure/persistence/postgres_counter_repository.py: 84%

45 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-29 05:31 -0600

1import sqlalchemy as sa 

2import sqlalchemy.orm 

3 

4from counter_os.domain.entities.counter import Counter 

5from counter_os.domain.repositories.counter_repository import CounterRepository 

6from counter_os.domain.value_objects.count import Count 

7from counter_os.infrastructure.persistence.counter_repository_type import ( 

8 CounterRepositoryType, 

9) 

10 

11 

12class PostgresCounterRepository(CounterRepository): 

13 _session_factory: sa.orm.sessionmaker 

14 _repository_location: str 

15 

16 def __init__(self, location: str): 

17 self._repository_location = location 

18 self._configure_sql_alchemy(location) 

19 

20 def _configure_sql_alchemy(self, location: str): 

21 sa_engine_config_url = "postgresql+psycopg://" + location 

22 engine = sa.create_engine(sa_engine_config_url) 

23 Base.metadata.create_all(engine) 

24 self._session_factory = sa.orm.sessionmaker(bind=engine) 

25 with self._session_factory() as session: 

26 record = session.get(PostgresCounter, 1) 

27 if record is None: 27 ↛ exitline 27 didn't jump to the function exit

28 session.add(PostgresCounter(id=1, count=0)) 

29 session.commit() 

30 

31 def save(self, counter: Counter) -> None: 

32 with self._session_factory() as session: 

33 record = session.get(PostgresCounter, 1) 

34 if record is not None: 34 ↛ 37line 34 didn't jump to line 37 because the condition on line 34 was always true

35 record.count = counter.count.value 

36 else: 

37 session.add(PostgresCounter(id=1, count=counter.count.value)) 

38 session.commit() 

39 

40 def get(self) -> Counter: 

41 with self._session_factory() as session: 

42 record = session.get(PostgresCounter, 1) 

43 if record is not None: 43 ↛ 46line 43 didn't jump to line 46 because the condition on line 43 was always true

44 return Counter(Count(record.count)) 

45 

46 new_record = PostgresCounter(id=1, count=0) 

47 session.add(new_record) 

48 session.commit() 

49 return Counter(Count(new_record.count)) 

50 

51 def repository_type(self) -> str: 

52 return CounterRepositoryType.POSTGRES_LOCAL 

53 

54 def repository_location(self) -> str: 

55 return self._repository_location 

56 

57 

58class Base(sa.orm.DeclarativeBase): 

59 pass 

60 

61 

62class PostgresCounter(Base): 

63 """SQL Alchemy ORM class for "counters" table""" 

64 

65 __tablename__ = "counters" 

66 

67 id: sa.orm.Mapped[int] = sa.orm.mapped_column(primary_key=True) 

68 count: sa.orm.Mapped[int]