BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.9k stars 201 forks source link

Provide any information about transactions in documentation #536

Open roman-right opened 1 year ago

roman-right commented 1 year ago

Discussed in https://github.com/roman-right/beanie/discussions/529

Originally posted by **Phobos-Programmer** April 5, 2023 Unfortunately, there is no any information in https://beanie-odm.dev/ about transaction and how to use them with beanie. Please add notes that it is possible to have transactions with beanie and provide some example. Thx!
devandreassimmeth commented 9 months ago

Hi @roman-right

First of all thanks for all the work you put into the library. I'm working with it over a year now coming from years of development in .NET and I think it is a very good object-document mapper library!

Until today I did not need any transactions, but now I'm on a point, where I really need them, so I searched and found that thread. Really nice that it's already implemented, so I don't have to do it on myself. Is there a possibility to provide some information and maybe an example in the near future? That would make my work even easier!

Thanks a lot guy!

Rocking greetings from germany, Andreas :)

MahmudulHassan5809 commented 9 months ago

Hi @roman-right .

Thanks for this awesome library. I am using this one of my current project . i did not notice any information about how to handle transaction.

can you please give me a basic example if possible . Thanks .

k1ng commented 4 months ago

I found example of using the transaction from @roman-right in Discord.

import motor.motor_asyncio
from pydantic import BaseSettings

from beanie import Document, init_beanie

class Settings(BaseSettings):
    mongodb_dsn: str = "mongodb://localhost:27017"
    mongodb_db_name: str = "beanie_db"

class Sample(Document):
    name: str

async def main():
    settings = Settings()
    cli = motor.motor_asyncio.AsyncIOMotorClient(settings.mongodb_dsn)
    db = cli[settings.mongodb_db_name]
    await init_beanie(database=db, document_models=[Sample])

    async with await cli.start_session() as s:
        async with s.start_transaction():
            await Sample.find(
                Sample.name == "smth",
                session=s
            ).set(
                {Sample.name: "new_val"}
            )

Session could be provided as an argument to any method of the query builder. To set, istead of find for example:

         await Sample.find(
                Sample.name == "smth"
            ).set(
                {Sample.name: "new_val"},
                session=s
            )

Or it can be set in a separated method even:

        await Sample.find(
                Sample.name == "smth"
            ).set(
                {Sample.name: "new_val"}
            ).set_session(s)