Skip to content

Commit

Permalink
Alchemy: Actually save the objects in db
Browse files Browse the repository at this point in the history
  • Loading branch information
nadege committed Jan 13, 2024
1 parent 5f2582d commit 4ece4ba
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
19 changes: 16 additions & 3 deletions factory/alchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,21 @@ class Meta:
@classmethod
async def _create_model_async(cls, model_class, *args, **kwargs):
session = cls._meta.sqlalchemy_session

if session is None:
raise RuntimeError("No session provided.")

async with session.begin():
model = model_class(**kwargs)
session.add(model)
return await cls._save(model_class, session, args, kwargs)

@classmethod
async def _save(cls, model_class, session, args, kwargs):
session_persistence = cls._meta.sqlalchemy_session_persistence

return model
obj = model_class(*args, **kwargs)
session.add(obj)
if session_persistence == SESSION_PERSISTENCE_FLUSH:
await session.flush()
elif session_persistence == SESSION_PERSISTENCE_COMMIT:
await session.commit()
return obj
1 change: 1 addition & 0 deletions tests/test_alchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ class NoteFactory(SQLAlchemyModelAsyncFactory):
class Meta:
model = models.NoteModel
sqlalchemy_session = models.async_session
sqlalchemy_session_persistence = 'commit'

text = factory.Sequence(lambda n: f"Text {n}")
completed = factory.Faker('boolean')
Expand Down

0 comments on commit 4ece4ba

Please sign in to comment.