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

fix: handle nullable SQLA constraints #602

Merged
merged 5 commits into from
Nov 24, 2024
Merged
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
6 changes: 3 additions & 3 deletions polyfactory/factories/sqlalchemy_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
from datetime import date, datetime
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, List, TypeVar, Union

from sqlalchemy import ARRAY, Numeric, String
from typing_extensions import Annotated

from polyfactory.exceptions import MissingDependencyException
from polyfactory.factories.base import BaseFactory
from polyfactory.field_meta import Constraints, FieldMeta
from polyfactory.persistence import AsyncPersistenceProtocol, SyncPersistenceProtocol
from polyfactory.utils.types import Frozendict

try:
from sqlalchemy import Column, inspect, types
from sqlalchemy import ARRAY, Column, Numeric, String, inspect, types
from sqlalchemy.dialects import mssql, mysql, postgresql, sqlite
from sqlalchemy.exc import NoInspectionAvailable
from sqlalchemy.orm import InstanceState, Mapper
Expand Down Expand Up @@ -170,7 +170,7 @@ def _get_type_from_type_engine(cls, type_engine: TypeEngine) -> type:
if (value := getattr(type_engine, sqlalchemy_field, None)) is not None:
constraints[constraint_field] = value # type: ignore[literal-required]
if constraints:
annotation = Annotated[annotation, constraints] # type: ignore[assignment]
annotation = Annotated[annotation, Frozendict(constraints)] # type: ignore[assignment]

return annotation

Expand Down
23 changes: 21 additions & 2 deletions polyfactory/utils/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Union
from typing import TYPE_CHECKING, Any, NoReturn, Union

try:
from types import NoneType, UnionType
Expand All @@ -9,4 +9,23 @@

NoneType = type(None) # type: ignore[misc]

__all__ = ("NoneType", "UNION_TYPES")

class Frozendict(dict):
def _immutable_error(self, *_: Any, **__: Any) -> NoReturn:
msg = f"Unable to mutate {type(self).__name__}"
raise TypeError(msg)

# Override all mutation methods to prevent changes
if not TYPE_CHECKING:
__setitem__ = _immutable_error
__delitem__ = _immutable_error
clear = _immutable_error
pop = _immutable_error
popitem = _immutable_error
update = _immutable_error

def __hash__(self) -> int: # type: ignore[override]
return hash(tuple(self.items()))


__all__ = ("NoneType", "UNION_TYPES", "Frozendict")
6 changes: 6 additions & 0 deletions tests/sqlalchemy_factory/test_sqlalchemy_factory_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,16 +464,22 @@ class Model(Base):

id: Any = Column(Integer(), primary_key=True)
constrained_string: Any = Column(String(length=1), nullable=False)
constrained_nullable_string: Any = Column(String(length=1), nullable=True)
constrainted_number: Any = Column(
Numeric(precision=2, scale=1),
nullable=False,
)
constrainted_nullable_number: Any = Column(
Numeric(precision=2, scale=1),
nullable=True,
)

class ModelFactory(SQLAlchemyFactory[Model]):
__model__ = Model

instance = ModelFactory.build()
assert len(instance.constrained_string) <= 1
assert instance.constrained_nullable_string is None or len(instance.constrained_nullable_string) <= 1

constrained_number: Decimal = instance.constrainted_number
assert isinstance(constrained_number, Decimal)
Expand Down
13 changes: 13 additions & 0 deletions tests/utils/test_frozendict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import pytest

from polyfactory.utils.types import Frozendict


def test_frozendict_immutable() -> None:
instance = Frozendict({"bar": "foo"})
with pytest.raises(TypeError, match="Unable to mutate Frozendict"):
instance["foo"] = "bar"


def test_frozendict_hashable() -> None:
assert isinstance(hash(Frozendict()), int)
Loading