sqlalchemyfastapiariadne-graphql

How to pass database session to Ariadne in Fastapi


I'm new to python, trying to learn and use Fastapi, Ariadne and SQLAlchemy. I'm following the docs and I'm stuck.

I have my dependency injection get_db() for normal REST requests, which provides a Session object, which I pass through few different modules from the request start until I actually do the db work, and honestly I don't get this design. But I left it there.

Then, another problem come up. How can I pass db to Ariadne GraphQL? Should I use context_value or are there any other options?


Solution

  • You need to create a session of SQLAlchemy from ariadne resolvers. And don't forget to close the connection after resolvers finished.

    Let's say your database file like following,

    import os
    
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    
    SQLALCHEMY_DATABASE_URL = os.getenv("DB_CONN_STRING")
    
    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    LocalSession = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    
    def get_db():
        db = None
        try:
            db = LocalSession()
            yield db
        finally:
            if db:
                db.close()
    
    # Import the local session from local database file
    from app.database import LocalSession
    
    db = LocalSession()
    # Do whatever you need to do
    db.close()