Skip to content

Commit

Permalink
Merge pull request #5 from Trevypants/main
Browse files Browse the repository at this point in the history
Add Literal type handling
  • Loading branch information
AntonDeMeester authored Nov 8, 2023
2 parents f926d9d + 37c4d65 commit 0532fee
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@
from .typing import SQLModelConfig

if sys.version_info >= (3, 8):
from typing import get_args, get_origin
from typing import get_args, get_origin, Literal
else:
from typing_extensions import get_args, get_origin
from typing_extensions import get_args, get_origin, Literal

from typing_extensions import Annotated, _AnnotatedAlias

Expand Down Expand Up @@ -478,6 +478,15 @@ def get_sqlalchemy_type(field: FieldInfo) -> Any:
elif org_type is pydantic.AnyUrl and type(type_) is _AnnotatedAlias:
return AutoString(type_.__metadata__[0].max_length)

# Resolve Literal fields
if get_origin(type_) is Literal:
child_types = list({type(x) for x in get_args(type_)})
if len(child_types) != 1:
raise RuntimeError(
"Cannot have a Literal with multiple types as a SQLAlchemy field"
)
type_ = child_types[0]

# The 3rd is PydanticGeneralMetadata
metadata = _get_field_metadata(field)
if type_ is None:
Expand Down

0 comments on commit 0532fee

Please sign in to comment.