Repository navigation
Closed
Labels
bugSomething isn't working
Description
Priority: medium. dynamoxy checks values outside instances with FieldSpec.validate, and the fields of a PydanticModel carry no dynamoxy constraints or validators (pydantic validates instances), so for pydantic models that check is the codec's type check only. Two places skip pydantic's validation:
- Key values of reads and writes by key. The fix of Key and index lookups skip the field's validators #80 runs a native field's constraints and validators on them, but a pydantic validator that normalizes a key or index key field still makes items unreachable (example below).
docs/guides/pydantic.mddocuments it: normalize the value before the lookup. - Values that
update()sets (repository.py,_plan_updateand_upsert_completion). The writing guide says they are validated like constructor arguments before any I/O. For a pydantic model,cards.update(Card.key("c1"), attr(Card.name).set("x"))withname: str = Field(min_length=3)writes"x"to DynamoDB and then raisesItemDecodeError("the update was applied, but the item it returned does not decode"); a value anAfterValidator(str.lower)would normalize is stored as given.
class Member(dynamoxy.PydanticModel, table="members"):
handle: Annotated[str, dynamoxy.PartitionKey(), AfterValidator(str.lower)]
email: Annotated[str, dynamoxy.Unique()]
by_email = dynamoxy.GlobalIndex(partition_key="email")
@field_validator("email")
@classmethod
def lower(cls, value: str) -> str:
return value.lower()After members.create(Member(handle="Ada", email="[email protected]")), members.get("Ada") returns None and members.query(index=Member.by_email, email="[email protected]") returns [].
Pydantic has no public API that validates the value of one field with the model's validators. Options:
- Build a validator per field from that field's schema in
__pydantic_core_schema__(with the schema's definitions), and use it whereFieldSpec.validateruns for native models. It runsAnnotatedvalidators,Fieldconstraints and@field_validators, but not validators that read other fields (info.data), and it relies on the layout of the core schema. __pydantic_validator__.validate_assignment(Model.model_construct(), name, value)runs the field's validators, but also the model validators, on an instance whose other fields are missing: amode="after"model validator that reads them fails. Not safe.- Document both as limitations.
Found while fixing #80 (fctl session).
Metadata
Metadata
Assignees
Labels
bugSomething isn't working
Activity
[-]Key and index lookups of pydantic models skip pydantic's validators[/-][+]Pydantic models: key lookups and update values skip pydantic's validators[/+]fix(models): key and index lookups run the field's validators, as wri…
fix(pydantic): key values and update values run the field's pydantic …
fix(pydantic): key values and update values run the field's pydantic …