🏷️ Adjust type annotation for Field.sa_type to support instantiated SQLAlchemy types#1345
+10 −4
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.
Note
When I was writing description for this PR, I found another discussion started for just the same issue I was experiencing with
mypy, so this changes are basically fixing the issue described hereUsing
sa_typeandsa_column_kwargsinstead of justsa_columncan benefit when using inheritance for classes derived fromSQLModelas it was suggested here.If
sa_columnis not specified andsa_typeis provided, it will be passed as a second, type argumnet tosqlalchemy.Columninstance. If you would checksqlalchemy.Columnconstruction definition, it looks as following:Note the
__type_posargument withUnion[_TypeEngineArgument[_T], SchemaEventTarget]whereSo, from technical perspective you can pass not only the subclass of
TypeEngine, e.g. SQLAlchemy's sqltype such asString,Integer,DateTime,JSONetc, but also an instance of this type.I was trying for
JSONB(none_as_null=True)andString(50)and it worked just fine,alembicmigrations were generated correctly, onlymypywas arguing for type mismatch withcall-overloadissue.To fix
mypyerror, we can update type annotation forsqlmodel.main.Field.sa_typeto support also an instantiated SQLAlchemy's sqltype to match those ofsqlalchemy.ColumnRelated discussions: