Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(backend): replace db.query() with select() #213

Merged
merged 4 commits into from
Dec 2, 2024

Conversation

eatyourgreens
Copy link
Contributor

@eatyourgreens eatyourgreens commented Dec 2, 2024

Replace the legacy SQLAlchemy Query API with select() in the backend API.

@eatyourgreens
Copy link
Contributor Author

@tomalrussell @mz8i I think these changes can also be applied to https://github.com/nismod/infra-risk-vis.



# pass empty connection string to use PG* environment variables
# (see https://www.postgresql.org/docs/current/libpq-envars.html)
engine = create_engine("postgresql+psycopg2://", future=True)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = Session(engine)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of queries here (and with deleting app/dependencies.py)

First, if we drop the use sessionmaker, do we also want to go back to default autoflush=True? I think dropping the other arguments wouldn't make a difference: autocommit=False is already the default, and bind can be replaced by passing engine as the first parameter.

https://docs.sqlalchemy.org/en/20/orm/session_basics.html#using-a-sessionmaker

Second, as I read the docs, it's not thread-safe to create a single module-level session variable, and for FastAPI these should be constructed once per request. FastAPI have a slightly lighter recommendation now, where we can pass in session: SessionDep as a parameter instead of db: Session = Depends(get_db):

# in backend.db.database:
def get_session():
    with Session(engine) as session:
        yield session


SessionDep = Annotated[Session, Depends(get_session)]

# in e.g. backend.app.routers.features:
@router.get("/{feature_id}", response_model=schemas.FeatureOut)
def read_feature(feature_id: int, session: SessionDep):

https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-session-dependency

Copy link
Contributor Author

@eatyourgreens eatyourgreens Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking a look. I've updated this to follow the changes in nismod/infra-risk-vis#190, and added sessionmaker back in with autoFlush=False for all sessions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmmm, might have spoken too soon. I'm now seeing this in the backend logs on this branch.

TypeError: Session.__init__() got an unexpected keyword argument 'autoFlush'

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My mistake, there's a typo in autoFlush.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should all be working now.

Replace the legacy SQLAlchemy Query API with `select()` in the backend API.
- replace `parse_obj` with `model_validate_json`.
- use per-request sessions.
@eatyourgreens eatyourgreens merged commit a11052e into main Dec 2, 2024
2 checks passed
@eatyourgreens eatyourgreens deleted the backend-select-api branch December 2, 2024 20:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

The query API is legacy in SQLAlchemy 2
2 participants