mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
commit
336f1e8456
@ -1,5 +1,6 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from asyncpg import UniqueViolationError
|
||||||
from fastapi import HTTPException, status
|
from fastapi import HTTPException, status
|
||||||
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
|
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
@ -68,17 +69,16 @@ class Base:
|
|||||||
await self.save(db_session)
|
await self.save(db_session)
|
||||||
|
|
||||||
async def save_or_update(self, db: AsyncSession):
|
async def save_or_update(self, db: AsyncSession):
|
||||||
# TODO: this will be successor of update meth
|
|
||||||
_success = False
|
|
||||||
try:
|
try:
|
||||||
db.add(self)
|
db.add(self)
|
||||||
_success = await db.commit()
|
return await db.commit()
|
||||||
return _success
|
|
||||||
except IntegrityError as exception:
|
except IntegrityError as exception:
|
||||||
if not _success:
|
if isinstance(exception.orig, UniqueViolationError):
|
||||||
# TODO: check if exception is instance of class 'asyncpg.exceptions.UniqueViolationError'
|
|
||||||
return await db.merge(self)
|
return await db.merge(self)
|
||||||
else:
|
else:
|
||||||
raise exception
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail=repr(exception),
|
||||||
|
) from exception
|
||||||
finally:
|
finally:
|
||||||
await db.close()
|
await db.close()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user