105 lines
4.1 KiB
Python
105 lines
4.1 KiB
Python
"""Model-driven schema generation.
|
|
|
|
Forty-plus tables share the same shape, so read/create/update schemas are
|
|
derived straight from the SQLAlchemy mapped columns. A module only declares the
|
|
few fields that differ from the table (labels, aggregates, write-only values).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
from typing import Any, Optional
|
|
|
|
from pydantic import BaseModel, ConfigDict, create_model
|
|
from sqlalchemy import BigInteger, Boolean, Date, DateTime, Float, Integer, JSON, Numeric, String, Text
|
|
|
|
from .common import DEFAULT_SYSTEM_FIELDS
|
|
|
|
_READ_CONFIG = ConfigDict(from_attributes=True, str_strip_whitespace=False)
|
|
|
|
|
|
def _resolve_type(col_type):
|
|
"""Unwrap ``TypeDecorator`` layers (e.g. :class:`~hrms.db.base.Money`)."""
|
|
seen = 0
|
|
while hasattr(col_type, "impl") and seen < 6:
|
|
impl = col_type.impl
|
|
col_type = impl() if isinstance(impl, type) else impl
|
|
seen += 1
|
|
return col_type
|
|
|
|
|
|
def _annotation(column) -> Any:
|
|
t = _resolve_type(column.type)
|
|
if isinstance(t, DateTime):
|
|
return dt.datetime
|
|
if isinstance(t, Date):
|
|
return dt.date
|
|
if isinstance(t, Boolean):
|
|
return bool
|
|
if isinstance(t, (Integer, BigInteger)):
|
|
return int
|
|
if isinstance(t, (Numeric, Float)):
|
|
return float # money crosses the wire as a JSON number
|
|
if isinstance(t, JSON):
|
|
return Any
|
|
if isinstance(t, (String, Text)):
|
|
return str
|
|
return Any
|
|
|
|
|
|
def read_schema(model: type, name: str | None = None, *, exclude: tuple[str, ...] = (),
|
|
include: dict[str, Any] | None = None,
|
|
optional: tuple[str, ...] = ()) -> type[BaseModel]:
|
|
"""Build an ORM-backed response model from a mapped class."""
|
|
defs: dict[str, Any] = {}
|
|
for column in model.__table__.columns:
|
|
if column.name in exclude:
|
|
continue
|
|
anno = _annotation(column)
|
|
required = (not column.nullable and column.default is None
|
|
and column.server_default is None and column.name not in optional)
|
|
# A column that is nullable / defaulted still needs an Optional annotation,
|
|
# otherwise legacy rows holding NULL fail response validation.
|
|
defs[column.name] = (anno, ...) if required else (Optional[anno], None)
|
|
for field_name, anno in (include or {}).items():
|
|
defs[field_name] = (anno, None)
|
|
|
|
base = create_model(name or f"{model.__name__}Read", __base__=BaseModel, **defs)
|
|
base.model_config = _READ_CONFIG
|
|
base.__name__ = name or f"{model.__name__}Read"
|
|
base.model_rebuild(force=True)
|
|
return base
|
|
|
|
|
|
def create_schema(model: type, name: str | None = None, *, required: tuple[str, ...] = (),
|
|
exclude: tuple[str, ...] = (), extra: dict[str, tuple[type, bool]] | None = None,
|
|
read: type[BaseModel] | None = None) -> type[BaseModel]:
|
|
read = read or read_schema(model, f"{model.__name__}Read")
|
|
from .common import make_create
|
|
|
|
return make_create(read, name or f"{model.__name__}Create", required=required,
|
|
exclude=(*DEFAULT_SYSTEM_FIELDS, *exclude), extra=extra)
|
|
|
|
|
|
def update_schema(model: type, name: str | None = None, *, exclude: tuple[str, ...] = (),
|
|
read: type[BaseModel] | None = None) -> type[BaseModel]:
|
|
read = read or read_schema(model, f"{model.__name__}Read")
|
|
from .common import make_update
|
|
|
|
return make_update(read, name or f"{model.__name__}Update",
|
|
exclude=(*DEFAULT_SYSTEM_FIELDS, *exclude))
|
|
|
|
|
|
def triple(model: type, *, required: tuple[str, ...] = (), exclude: tuple[str, ...] = (),
|
|
include: dict[str, Any] | None = None,
|
|
extra: dict[str, tuple[type, bool]] | None = None,
|
|
prefix: str | None = None) -> tuple[type[BaseModel], type[BaseModel], type[BaseModel]]:
|
|
"""``(Read, Create, Update)`` for a model in one line."""
|
|
base = prefix or model.__name__
|
|
read = read_schema(model, f"{base}Read", exclude=exclude, include=include)
|
|
return (
|
|
read,
|
|
create_schema(model, f"{base}Create", required=required, exclude=exclude, extra=extra, read=read),
|
|
update_schema(model, f"{base}Update", exclude=exclude, read=read),
|
|
)
|