Skip to content

Commit

Permalink
🐛 fix: async mutations
Browse files Browse the repository at this point in the history
  • Loading branch information
MDoreto committed Jan 18, 2024
1 parent d89fc13 commit 73940af
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 17 deletions.
59 changes: 43 additions & 16 deletions graphemy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

import strawberry
from sqlmodel import SQLModel, literal

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import sessionmaker
from .setup import Setup


Expand Down Expand Up @@ -471,26 +472,52 @@ async def put_item(model: 'Graphemy', item, id='id', engine=engine):
id = [getattr(item, i) for i in id]
kwargs = vars(item)
engine = Setup.engine
with Session(engine) as session:
if not id or None in id:
new_item = model(**kwargs)
else:
new_item = session.get(model, id)
if not new_item:
if Setup.async_engine:
async_session = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
async with async_session() as session:
if not id or None in id:
new_item = model(**kwargs)
for key, value in kwargs.items():
setattr(new_item, key, value)
session.add(new_item)
session.commit()
session.refresh(new_item)
else:
new_item = await session.get(model, id)
if not new_item:
new_item = model(**kwargs)
for key, value in kwargs.items():
setattr(new_item, key, value)
session.add(new_item)
await session.commit()
await session.refresh(new_item)
else:
with Session(engine) as session:
if not id or None in id:
new_item = model(**kwargs)
else:
new_item = session.get(model, id)
if not new_item:
new_item = model(**kwargs)
for key, value in kwargs.items():
setattr(new_item, key, value)
session.add(new_item)
session.commit()
session.refresh(new_item)
return new_item


async def delete_item(model: 'Graphemy', item, id='id', engine=engine):
id = [getattr(item, i) for i in id]
engine = Setup.engine
with Session(engine) as session:
item = session.get(model, id)
session.delete(item)
session.commit()
if Setup.async_engine:
async_session = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
async with async_session() as session:
item = await session.get(model, id)
await session.delete(item)
await session.commit()
else:
with Session(engine) as session:
item = session.get(model, id)
session.delete(item)
session.commit()
return item
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "graphemy"
version = "0.3.3"
version = "0.3.4"
description = "A Python library for integrating SQLModel and Strawberry, providing a seamless GraphQL integration with FastAPI and advanced features for database interactions."
authors = ["Matheus Doreto <[email protected]>"]
readme = "README.md"
Expand Down

0 comments on commit 73940af

Please sign in to comment.