@@ -20,64 +20,46 @@ def __tablename__(self) -> str:
2020 return self .__name__ .lower ()
2121
2222 async def save (self , db_session : AsyncSession ):
23- """
24-
25- :param db_session:
26- :return:
27- """
2823 try :
2924 db_session .add (self )
30- await db_session .commit ()
25+ await db_session .flush ()
3126 await db_session .refresh (self )
3227 return self
3328 except SQLAlchemyError as ex :
3429 await logger .aerror (f"Error inserting instance of { self } : { repr (ex )} " )
35- raise HTTPException (
36- status_code = status .HTTP_422_UNPROCESSABLE_ENTITY , detail = repr (ex )
37- ) from ex
30+ raise # This will make the exception handler catch it
3831
3932 async def delete (self , db_session : AsyncSession ):
40- """
41-
42- :param db_session:
43- :return:
44- """
4533 try :
4634 await db_session .delete (self )
47- await db_session .commit ()
4835 return True
4936 except SQLAlchemyError as ex :
5037 raise HTTPException (
5138 status_code = status .HTTP_422_UNPROCESSABLE_ENTITY , detail = repr (ex )
5239 ) from ex
5340
54- async def update (self , db : AsyncSession , ** kwargs ):
55- """
56-
57- :param db:
58- :param kwargs
59- :return:
60- """
41+ async def update (self , ** kwargs ):
6142 try :
6243 for k , v in kwargs .items ():
6344 setattr (self , k , v )
64- return await db . commit ()
45+ return True
6546 except SQLAlchemyError as ex :
6647 raise HTTPException (
6748 status_code = status .HTTP_422_UNPROCESSABLE_ENTITY , detail = repr (ex )
6849 ) from ex
6950
70- async def save_or_update (self , db : AsyncSession ):
51+ async def save_or_update (self , db_session : AsyncSession ):
7152 try :
72- db .add (self )
73- return await db .commit ()
53+ db_session .add (self )
54+ await db_session .flush ()
55+ return True
7456 except IntegrityError as exception :
7557 if isinstance (exception .orig , UniqueViolationError ):
76- return await db .merge (self )
58+ return await db_session .merge (self )
7759 else :
7860 raise HTTPException (
7961 status_code = status .HTTP_422_UNPROCESSABLE_ENTITY ,
8062 detail = repr (exception ),
8163 ) from exception
8264 finally :
83- await db .close ()
65+ await db_session .close ()
0 commit comments