Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions sqlmodel/ext/asyncio/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@


class AsyncSession(_AsyncSession):
sync_session_class: type[Session] = Session
sync_session: Session
sync_session_class: type[Session] = Session # ty: ignore[incompatible-mutable-override]
sync_session: Session # ty: ignore[incompatible-mutable-override]
Comment on lines +32 to +33

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We attempt to narrow the attribute type in child class from SQLAlchemy.Session to SQLModel.Session.
ty correctly argues that it's still possible to assign SQLAlchemy.Session to this attribute via SQLAlchemy interface. So, this narrower type can't be enforced.
I think in this case it's fine to just ignore it and assume nobody will do it.

Original typing errors
error[incompatible-mutable-override]: Invalid override of attribute `sync_session_class`
  --> sqlmodel/ext/asyncio/session.py:32:5
   |
32 |     sync_session_class: type[Session] = Session
   |     ^^^^^^^^^^^^^^^^^^ Override does not accept writes of type `type[Session]`

error[incompatible-mutable-override]: Invalid override of attribute `sync_session`
  --> sqlmodel/ext/asyncio/session.py:33:5
   |
33 |     sync_session: Session
   |     ^^^^^^^^^^^^ Override does not accept writes of type `Session`

I's not clear from the first sight here, but type[Session] in type annotation is SQLModel's Session, but in the error message it's SQLAlchemy's Session.


@overload
async def exec(
Expand Down
25 changes: 14 additions & 11 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,13 +562,13 @@ class SQLModelMetaclass(ModelMetaclass, DeclarativeMeta):
model_fields: ClassVar[dict[str, FieldInfo]]

# Replicate SQLAlchemy
def __setattr__(cls, name: str, value: Any) -> None: # ty: ignore[invalid-method-override]
def __setattr__(cls, name: str, value: Any) -> None: # ty: ignore[lost-keyword-for-regular-parameter]
if is_table_model_class(cls):
DeclarativeMeta.__setattr__(cls, name, value)
else:
super().__setattr__(name, value)

def __delattr__(cls, name: str) -> None: # ty: ignore[invalid-method-override]
def __delattr__(cls, name: str) -> None: # ty: ignore[lost-keyword-for-regular-parameter]
Comment on lines +565 to +571

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Base class declares the parameter name as key, but here we use name.
We previously decided to keep the name and just ignore this error: #1806 (comment). So I kept this approach (just fixed the rule name).

But actually we can rename it to key and resolve the issue (I've checked CI passes). Compatibility with Object is not an issue because Object.__setattr__ declares parameters as position-only. So, there will be no name collision here:

@disjoint_base
class object:
    ...
    def __setattr__(self, name: str, value: Any, /) -> None: ...
    def __delattr__(self, name: str, /) -> None: ...
Original errors
error[lost-keyword-for-regular-parameter]: Override of method `__setattr__` disallows keyword arguments allowed by the method on the base class
   --> sqlmodel/main.py:565:9
    |
565 |     def __setattr__(cls, name: str, value: Any) -> None:  # ty: ignore[invalid-method-override]
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definition is incompatible with `_DynamicAttributesType.__setattr__`
    |
   ::: .venv/lib/python3.11/site-packages/sqlalchemy/orm/decl_api.py:138:9
    |
138 |     def __setattr__(cls, key: str, value: Any) -> None:
    |         ---------------------------------------------- `_DynamicAttributesType.__setattr__` defined here
info: the parameter named `name` does not match `key` (and can be used as a keyword parameter)
info: This violates the Liskov Substitution Principle

warning[unused-ignore-comment]: Unused `ty: ignore` directive
   --> sqlmodel/main.py:565:59
    |
565 |     def __setattr__(cls, name: str, value: Any) -> None:  # ty: ignore[invalid-method-override]
    |                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: Remove the unused suppression comment
    |
564 |     # Replicate SQLAlchemy
    -     def __setattr__(cls, name: str, value: Any) -> None:  # ty: ignore[invalid-method-override]
565 +     def __setattr__(cls, name: str, value: Any) -> None:
566 |         if is_table_model_class(cls):
    |

warning[renamed-rule-in-ignore-comment]: Rule `invalid-method-override` has been renamed to `incompatible-method-override`
   --> sqlmodel/main.py:565:72
    |
565 |     def __setattr__(cls, name: str, value: Any) -> None:  # ty: ignore[invalid-method-override]
    |                                                                        ^^^^^^^^^^^^^^^^^^^^^^^
help: Replace `invalid-method-override` with `incompatible-method-override`
    |
564 |     # Replicate SQLAlchemy
    -     def __setattr__(cls, name: str, value: Any) -> None:  # ty: ignore[invalid-method-override]
565 +     def __setattr__(cls, name: str, value: Any) -> None:  # ty: ignore[incompatible-method-override]
566 |         if is_table_model_class(cls):
    |

error[lost-keyword-for-regular-parameter]: Override of method `__delattr__` disallows keyword arguments allowed by the method on the base class
   --> sqlmodel/main.py:571:9
    |
571 |     def __delattr__(cls, name: str) -> None:  # ty: ignore[invalid-method-override]
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definition is incompatible with `_DynamicAttributesType.__delattr__`
    |
   ::: .venv/lib/python3.11/site-packages/sqlalchemy/orm/decl_api.py:144:9
    |
144 |     def __delattr__(cls, key: str) -> None:
    |         ---------------------------------- `_DynamicAttributesType.__delattr__` defined here
info: the parameter named `name` does not match `key` (and can be used as a keyword parameter)
info: This violates the Liskov Substitution Principle

warning[unused-ignore-comment]: Unused `ty: ignore` directive
   --> sqlmodel/main.py:571:47
    |
571 |     def __delattr__(cls, name: str) -> None:  # ty: ignore[invalid-method-override]
    |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: Remove the unused suppression comment
    |
570 |
    -     def __delattr__(cls, name: str) -> None:  # ty: ignore[invalid-method-override]
571 +     def __delattr__(cls, name: str) -> None:
572 |         if is_table_model_class(cls):
    |

warning[renamed-rule-in-ignore-comment]: Rule `invalid-method-override` has been renamed to `incompatible-method-override`
   --> sqlmodel/main.py:571:60
    |
571 |     def __delattr__(cls, name: str) -> None:  # ty: ignore[invalid-method-override]
    |                                                            ^^^^^^^^^^^^^^^^^^^^^^^
help: Replace `invalid-method-override` with `incompatible-method-override`
    |
570 |
    -     def __delattr__(cls, name: str) -> None:  # ty: ignore[invalid-method-override]
571 +     def __delattr__(cls, name: str) -> None:  # ty: ignore[incompatible-method-override]
572 |         if is_table_model_class(cls):
    |

if is_table_model_class(cls):
DeclarativeMeta.__delattr__(cls, name)
else:
Expand Down Expand Up @@ -624,9 +624,10 @@ def __new__(
**pydantic_annotations,
**new_cls.__annotations__,
}
new_cls_model_config = cast(SQLModelConfig, new_cls.model_config)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

In base class model_config attribute has type Pydantic.ConfigDict. Even if we assign SQLModelConfig in child, the type remains Pydantic.ConfigDict (it's still possible to assign Pydantic.ConfigDict via base class interface).

So, when the code below attempts to access table and registry keys, ty correctly argues (these keys are not declared for Pydantic.ConfigDict).

To fix this we assume that nobody will re-assign it this way and just cast it here for type checking to pass.


def get_config(name: str) -> Any:
config_class_value = new_cls.model_config.get(name, Undefined)
config_class_value = new_cls_model_config.get(name, Undefined)
if config_class_value is not Undefined:
return config_class_value
kwarg_value = kwargs.get(name, Undefined)
Expand All @@ -637,7 +638,7 @@ def get_config(name: str) -> Any:
config_table = get_config("table")
if config_table is True:
# If it was passed by kwargs, ensure it's also set in config
new_cls.model_config["table"] = config_table
new_cls_model_config["table"] = config_table
for k, v in get_model_fields(new_cls).items():
col = get_column_from_field(v)
setattr(new_cls, k, col)
Expand All @@ -646,16 +647,16 @@ def get_config(name: str) -> Any:
# This could be done by reading new_cls.model_config['table'] in FastAPI, but
# that's very specific about SQLModel, so let's have another config that
# other future tools based on Pydantic can use.
new_cls.model_config["read_from_attributes"] = True # ty: ignore[invalid-key]
new_cls_model_config["read_from_attributes"] = True # ty: ignore[invalid-typed-dict-key]
# For compatibility with older versions
# TODO: remove this in the future
new_cls.model_config["read_with_orm_mode"] = True # ty: ignore[invalid-key]
new_cls_model_config["read_with_orm_mode"] = True # ty: ignore[invalid-typed-dict-key]
Comment on lines 647 to +653

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think we can remove these two assignments - they were needed for compatibility with Pydantic V1 and are not used since we dropped Pydantic V1 support.


config_registry = get_config("registry")
if config_registry is not Undefined:
config_registry = cast(registry, config_registry)
# If it was passed by kwargs, ensure it's also set in config
new_cls.model_config["registry"] = config_table
new_cls_model_config["registry"] = config_table
setattr(new_cls, "_sa_registry", config_registry) # noqa: B010
setattr(new_cls, "metadata", config_registry.metadata) # noqa: B010
setattr(new_cls, "__abstract__", True) # noqa: B010
Expand Down Expand Up @@ -686,7 +687,7 @@ def __init__(
# Plain forward references, for models not yet defined, are not
# handled well by SQLAlchemy without Mapped, so, wrap the
# annotations in Mapped here
cls.__annotations__[rel_name] = Mapped[ann]
cls.__annotations__[rel_name] = Mapped[ann] # ty: ignore[invalid-type-form]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ty correctly argues on this.
Before switching from mypy to ty we had # type: ignore[valid-type] ignore comment here (see PR). Now ty also started arguing on this, so we need to add this ignore comment back.

Original error
error[invalid-type-form]: Variable `ann` cannot be used as a type
   --> sqlmodel/main.py:690:60
    |
690 |                     cls.__annotations__[rel_name] = Mapped[ann]
    |                                                            ^^^
info: `ann` is not a valid type alias
info: Invalid subscript of object of type `dict[str, Any]` in a type alias definition
   --> sqlmodel/main.py:681:27
    |
681 |                 raw_ann = cls.__annotations__[rel_name]
    |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
info: See the following page for a reference on valid type expressions:
info: https://typing.python.org/en/latest/spec/annotations.html#type-and-annotation-expressions

relationship_to = get_relationship_to(
name=rel_name, rel_info=rel_info, annotation=ann
)
Expand Down Expand Up @@ -742,7 +743,7 @@ def get_sqlalchemy_type(field: Any) -> Any:
ipaddress.IPv6Address,
ipaddress.IPv6Network,
Path,
EmailStr,
cast(type, EmailStr),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

With TYPE_CHECKING Pydantic declares EmailStr, AwareDatetime and NaiveDatetime as Annotated[str, ...] (ref).

So, they are not types and ty correctly argues that we can pass them to isinstance. But in runtime they are classes.
So, it's Ok to cast them here.

Original error
error[invalid-argument-type]: Argument to function `issubclass` is incorrect
   --> sqlmodel/main.py:739:9
    |
739 | /         (
740 | |             str,
741 | |             ipaddress.IPv4Address,
742 | |             ipaddress.IPv4Network,
743 | |             ipaddress.IPv6Address,
744 | |             ipaddress.IPv6Network,
745 | |             Path,
746 | |             EmailStr,
747 | |         ),
    | |_________^ Expected `_ClassInfo`, found `tuple[<class 'str'>, <class 'IPv4Address'>, <class 'IPv4Network'>, <class 'IPv6Address'>, <class 'IPv6Network'>, <class 'Path'>, <special-form 'typing.Annotated[str,<metadata>]'>]`
info: Function defined here
    --> stdlib/builtins.pyi:4193:5
     |
4193 | def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool:
     |     ^^^^^^^^^^            -------------------------- Parameter declared here

error[invalid-argument-type]: Argument to function `issubclass` is incorrect
   --> sqlmodel/main.py:760:16
    |
760 |         type_, (datetime, AwareDatetime, NaiveDatetime)
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Expected `_ClassInfo`, found `tuple[<class 'datetime'>, <special-form 'typing.Annotated[datetime, <metadata>]'>, <special-form 'typing.Annotated[datetime, <metadata>]'>]`
info: Function defined here
    --> stdlib/builtins.pyi:4193:5
     |
4193 | def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool:
     |     ^^^^^^^^^^            -------------------------- Parameter declared here

),
):
max_length = getattr(metadata, "max_length", None)
Expand All @@ -755,7 +756,9 @@ def get_sqlalchemy_type(field: Any) -> Any:
return Boolean
if issubclass(type_, int):
return Integer
if issubclass(type_, (datetime, AwareDatetime, NaiveDatetime)):
if issubclass(
type_, (datetime, cast(type, AwareDatetime), cast(type, NaiveDatetime))
):
Comment on lines +759 to +761

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

See comment above

if issubclass(type_, cast(type, NaiveDatetime)):
return DateTime(timezone=False)
return UTCDateTime()
Expand Down Expand Up @@ -909,7 +912,7 @@ def __tablename__(cls) -> str:
return cls.__name__.lower()

@classmethod
def model_validate( # ty: ignore[invalid-method-override]
def model_validate( # ty: ignore[incompatible-method-override]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ty renamed this rule

cls: type[_TSQLModel],
obj: Any,
*,
Expand Down
42 changes: 21 additions & 21 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading