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

Use SQLModel Session for better typehinting #124

Merged
merged 3 commits into from
Aug 21, 2024

Conversation

piercefreeman
Copy link
Owner

@piercefreeman piercefreeman commented Aug 21, 2024

Mountaineer's database support has focused on using a SQLAlchemy AsyncSession for database connections alongside SQLModel for query construction. This was due to some initial limitations in the async session provided by SQLModel and SQLAlchemy2.

Mixing the sessions works but can result in some clunky code. Each database request has to explicitly get the scalars for typehinting to resolve in mypy:

query_result = await db_session.execute(query)
result = query_result.scalars().all()

Additionally, there are some cases where this approach results in the wrong typehints - like when we're trying to fetch a tuple of field:

query = select(models.ModelA, models.ModelB)

We expect this would result in a tuple of (model_a, model_b) as the typehint suggests, but it only gathers the first object since scalars() just arbitrarily takes the first value.

To address these shortcomings, we switch to using the typehints provided by SQLModel. Technically we use a thin wrapper on top of AsyncSession in order to support text queries like discussed here:
fastapi/sqlmodel#909

Old .execute requests are still supported, but clients are advised to switch to .exec to get the proper typehints and to avoid the deprecation warning.

@piercefreeman piercefreeman force-pushed the feature/sqlmodel-async-wrapper branch from f4494d1 to bc4676a Compare August 21, 2024 19:10
@piercefreeman piercefreeman force-pushed the feature/sqlmodel-async-wrapper branch from d34e6a9 to 4b10e9f Compare August 21, 2024 22:26
@piercefreeman piercefreeman merged commit f4fa45d into main Aug 21, 2024
22 checks passed
@piercefreeman piercefreeman deleted the feature/sqlmodel-async-wrapper branch August 21, 2024 22:53
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.

1 participant