aiteamutils 0.2.53__tar.gz → 0.2.54__tar.gz

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiteamutils
3
- Version: 0.2.53
3
+ Version: 0.2.54
4
4
  Summary: AI Team Utilities
5
5
  Project-URL: Homepage, https://github.com/yourusername/aiteamutils
6
6
  Project-URL: Issues, https://github.com/yourusername/aiteamutils/issues
@@ -0,0 +1,207 @@
1
+ """데이터베이스 유틸리티 모듈."""
2
+ from typing import Any, Dict, Optional, Type, List, Union
3
+ from sqlalchemy import select, and_
4
+ from sqlalchemy.ext.asyncio import AsyncSession
5
+ from sqlalchemy.exc import IntegrityError, SQLAlchemyError
6
+
7
+ from .exceptions import ErrorCode, CustomException
8
+ from .base_model import Base
9
+
10
+ class DatabaseService:
11
+ def __init__(self, session: AsyncSession):
12
+ """DatabaseService 초기화
13
+
14
+ Args:
15
+ session (AsyncSession): 외부에서 주입받은 데이터베이스 세션
16
+ """
17
+ self._session = session
18
+
19
+ @property
20
+ def session(self) -> AsyncSession:
21
+ """현재 세션을 반환합니다."""
22
+ if self._session is None:
23
+ raise CustomException(
24
+ ErrorCode.DB_CONNECTION_ERROR,
25
+ detail="session",
26
+ source_function="DatabaseService.session"
27
+ )
28
+ return self._session
29
+
30
+ async def create_entity(
31
+ self,
32
+ model: Type[Base],
33
+ entity_data: Dict[str, Any]
34
+ ) -> Any:
35
+ """엔티티를 생성합니다.
36
+
37
+ Args:
38
+ model: 모델 클래스
39
+ entity_data: 생성할 엔티티 데이터
40
+
41
+ Returns:
42
+ 생성된 엔티티
43
+
44
+ Raises:
45
+ CustomException: 엔티티 생성 실패 시
46
+ """
47
+ try:
48
+ entity = model(**entity_data)
49
+ self.session.add(entity)
50
+ await self.session.flush()
51
+ await self.session.refresh(entity)
52
+ return entity
53
+ except IntegrityError as e:
54
+ await self.session.rollback()
55
+ raise CustomException(
56
+ ErrorCode.DB_INTEGRITY_ERROR,
57
+ detail=str(e),
58
+ source_function="DatabaseService.create_entity",
59
+ original_error=e
60
+ )
61
+ except Exception as e:
62
+ await self.session.rollback()
63
+ raise CustomException(
64
+ ErrorCode.DB_CREATE_ERROR,
65
+ detail=str(e),
66
+ source_function="DatabaseService.create_entity",
67
+ original_error=e
68
+ )
69
+
70
+ async def get_entity(
71
+ self,
72
+ model: Type[Base],
73
+ filters: Dict[str, Any]
74
+ ) -> Optional[Any]:
75
+ """필터 조건으로 엔티티를 조회합니다.
76
+
77
+ Args:
78
+ model: 모델 클래스
79
+ filters: 필터 조건
80
+
81
+ Returns:
82
+ 조회된 엔티티 또는 None
83
+
84
+ Raises:
85
+ CustomException: 조회 실패 시
86
+ """
87
+ try:
88
+ stmt = select(model).filter_by(**filters)
89
+ result = await self.session.execute(stmt)
90
+ return result.scalars().first()
91
+ except Exception as e:
92
+ raise CustomException(
93
+ ErrorCode.DB_QUERY_ERROR,
94
+ detail=str(e),
95
+ source_function="DatabaseService.get_entity",
96
+ original_error=e
97
+ )
98
+
99
+ async def list_entities(
100
+ self,
101
+ model: Type[Base],
102
+ filters: Optional[Dict[str, Any]] = None,
103
+ skip: int = 0,
104
+ limit: int = 100
105
+ ) -> List[Any]:
106
+ """엔티티 목록을 조회합니다.
107
+
108
+ Args:
109
+ model: 모델 클래스
110
+ filters: 필터 조건
111
+ skip: 건너뛸 레코드 수
112
+ limit: 조회할 최대 레코드 수
113
+
114
+ Returns:
115
+ 엔티티 목록
116
+
117
+ Raises:
118
+ CustomException: 조회 실패 시
119
+ """
120
+ try:
121
+ stmt = select(model)
122
+ if filters:
123
+ stmt = stmt.filter_by(**filters)
124
+ stmt = stmt.offset(skip).limit(limit)
125
+ result = await self.session.execute(stmt)
126
+ return result.scalars().all()
127
+ except Exception as e:
128
+ raise CustomException(
129
+ ErrorCode.DB_QUERY_ERROR,
130
+ detail=str(e),
131
+ source_function="DatabaseService.list_entities",
132
+ original_error=e
133
+ )
134
+
135
+ async def update_entity(
136
+ self,
137
+ entity: Base,
138
+ update_data: Dict[str, Any]
139
+ ) -> Any:
140
+ """엔티티를 수정합니다.
141
+
142
+ Args:
143
+ entity: 수정할 엔티티
144
+ update_data: 수정할 데이터
145
+
146
+ Returns:
147
+ 수정된 엔티티
148
+
149
+ Raises:
150
+ CustomException: 수정 실패 시
151
+ """
152
+ try:
153
+ for key, value in update_data.items():
154
+ setattr(entity, key, value)
155
+ await self.session.flush()
156
+ await self.session.refresh(entity)
157
+ return entity
158
+ except IntegrityError as e:
159
+ await self.session.rollback()
160
+ raise CustomException(
161
+ ErrorCode.DB_INTEGRITY_ERROR,
162
+ detail=str(e),
163
+ source_function="DatabaseService.update_entity",
164
+ original_error=e
165
+ )
166
+ except Exception as e:
167
+ await self.session.rollback()
168
+ raise CustomException(
169
+ ErrorCode.DB_UPDATE_ERROR,
170
+ detail=str(e),
171
+ source_function="DatabaseService.update_entity",
172
+ original_error=e
173
+ )
174
+
175
+ async def delete_entity(
176
+ self,
177
+ entity: Base,
178
+ soft_delete: bool = True
179
+ ) -> bool:
180
+ """엔티티를 삭제합니다.
181
+
182
+ Args:
183
+ entity: 삭제할 엔티티
184
+ soft_delete: 소프트 삭제 여부
185
+
186
+ Returns:
187
+ 삭제 성공 여부
188
+
189
+ Raises:
190
+ CustomException: 삭제 실패 시
191
+ """
192
+ try:
193
+ if soft_delete:
194
+ entity.is_deleted = True
195
+ await self.session.flush()
196
+ else:
197
+ await self.session.delete(entity)
198
+ await self.session.flush()
199
+ return True
200
+ except Exception as e:
201
+ await self.session.rollback()
202
+ raise CustomException(
203
+ ErrorCode.DB_DELETE_ERROR,
204
+ detail=str(e),
205
+ source_function="DatabaseService.delete_entity",
206
+ original_error=e
207
+ )
@@ -9,33 +9,13 @@ from .exceptions import CustomException, ErrorCode
9
9
  from .config import get_settings
10
10
  from .base_service import BaseService
11
11
  from .base_repository import BaseRepository
12
- from .database import db_manager
12
+ from .database import DatabaseService
13
13
 
14
14
  T = TypeVar("T", bound=BaseService)
15
15
  R = TypeVar("R", bound=BaseRepository)
16
16
 
17
17
  _service_registry: Dict[str, Dict[str, Any]] = {}
18
18
 
19
- async def get_db() -> AsyncGenerator[AsyncSession, None]:
20
- """데이터베이스 세션을 반환합니다.
21
-
22
- Yields:
23
- AsyncSession: 데이터베이스 세션
24
-
25
- Raises:
26
- CustomException: 세션 생성 실패 시
27
- """
28
- try:
29
- async with db_manager.get_session() as session:
30
- yield session
31
- except Exception as e:
32
- raise CustomException(
33
- ErrorCode.DATABASE_ERROR,
34
- detail=str(e),
35
- source_function="dependencies.get_db",
36
- original_error=e
37
- )
38
-
39
19
  def register_service(
40
20
  service_class: Type[T],
41
21
  repository_class: Optional[Type[R]] = None,
@@ -86,6 +66,9 @@ async def _get_service(
86
66
  repository_class = service_info["repository_class"]
87
67
  dependencies = service_info["dependencies"]
88
68
 
69
+ # 데이터베이스 서비스 생성
70
+ db_service = DatabaseService(session=session)
71
+
89
72
  # 저장소 인스턴스 생성
90
73
  repository = None
91
74
  if repository_class:
@@ -93,8 +76,8 @@ async def _get_service(
93
76
 
94
77
  # 서비스 인스턴스 생성
95
78
  service = service_class(
79
+ db=db_service,
96
80
  repository=repository,
97
- session=session,
98
81
  request=request,
99
82
  **dependencies
100
83
  )
@@ -122,14 +105,14 @@ def get_service(service_name: str) -> Callable:
122
105
  """
123
106
  async def _get_service_dependency(
124
107
  request: Request,
125
- session: AsyncSession = Depends(get_db)
108
+ session: AsyncSession
126
109
  ) -> BaseService:
127
110
  return await _get_service(service_name, session, request)
128
111
  return _get_service_dependency
129
112
 
130
113
  async def get_current_user(
131
114
  request: Request,
132
- session: AsyncSession = Depends(get_db),
115
+ session: AsyncSession,
133
116
  auth_service: BaseService = Depends(get_service("AuthService"))
134
117
  ) -> Dict[str, Any]:
135
118
  """현재 사용자 정보를 반환합니다.
@@ -0,0 +1,2 @@
1
+ """버전 정보"""
2
+ __version__ = "0.2.54"