Skip to content

Instantly share code, notes, and snippets.

@gcavalcante8808
Last active June 11, 2025 22:59
Show Gist options
  • Save gcavalcante8808/bdd4ff1497a8c21baa6a1709d99657b5 to your computer and use it in GitHub Desktop.
Save gcavalcante8808/bdd4ff1497a8c21baa6a1709d99657b5 to your computer and use it in GitHub Desktop.
Coerce pydantic model to SQLAlchemy Table **imperatively**
from sqlalchemy.orm import declarative_base
from sqlalchemy import Text, Integer, JSON, Table, Column
Base = declarative_base()
def convert_pydantic_field_to_sqlalchemy_column(field_name, field_type):
if field_type == str:
return Column(field_name, Text)
if field_type == int:
return Column(field_name, Integer)
if field_type.__origin__ == list:
return Column(field_name, JSON)
if field_type.__origin__ == typing.Union:
nullable = types.NoneType in field_type.__args__
return Column(field_name, JSON, nullable=nullable)
raise ValueError(f"Value Not Supported! {field_name}:{field_type}")
def coerce_pydantic_model_to_sqlalchemy_table(table_name: str, base, model: Type[BaseModel]):
columns = []
fields = get_type_hints(model)
columns.extend([convert_pydantic_field_to_sqlalchemy_column(field_name, field_type) for field_name, field_type in fields.items()])
return Table(
table_name,
base.metadata,
Column("id", Integer, primary_key=True),
*columns
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment