Use SQLModel Session for better typehinting #124
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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:
Additionally, there are some cases where this approach results in the wrong typehints - like when we're trying to fetch a tuple of field:
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.