fix: support StringConstraints metadata in SQLAlchemy type generation#2001
fix: support StringConstraints metadata in SQLAlchemy type generation#2001Sujit-1509 wants to merge 2 commits into
Conversation
|
@Sujit-1509, do you have specific use case there it's required to use You marked it as |
|
@YuriiMotov Thanks for the feedback. The use case I had in mind is projects migrating to Pydantic v2 patterns and reusing constrained types across multiple models. For example: from typing import Annotated
from pydantic import StringConstraints
Name = Annotated[str, StringConstraints(max_length=50)]
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: NameIn this case validation correctly enforces My assumption was that this was an inconsistency because SQLModel already extracts length-related metadata to configure SQLAlchemy column types, but currently ignores That said, I understand your point that SQLModel's documented approach is |
Summary
When using Pydantic v2's
StringConstraintsinsideAnnotated, SQLModel correctly applies validation constraints but does not propagatemax_lengthto the generated SQLAlchemy column type.For example:
currently generates a column with no length constraint, even though
max_length=50is declared.Root Cause
get_field_metadata()recognizesPydanticMetadataandMaxLenmetadata objects, but does not recognizeStringConstraints, causing the metadata extractor to returnFakeMetadata()instead of the constraint object.As a result,
get_sqlalchemy_type()cannot readmax_lengthand falls back to an unconstrained string type.Changes
StringConstraintsinget_field_metadata().Annotated[str, StringConstraints(max_length=50)]produces a SQLAlchemy column withlength == 50.Testing
Added a regression test that fails on the current implementation and passes with this change.