Buckets:

download
raw
6.78 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse, inspect, importlib, pkgutil, re
from pathlib import Path
from typing import Any, Optional, Tuple, Dict, List
from datetime import date, datetime
from decimal import Decimal
import uuid
from sqlalchemy.inspection import inspect as sa_inspect
from sqlalchemy.orm import DeclarativeMeta
from sqlalchemy import Integer, BigInteger, SmallInteger, String, Text, Boolean, Date, DateTime, Float, Numeric, JSON
try:
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
except Exception:
PG_UUID = None
HEADER = '''# Auto-generated by OSSS.schemas.codegen — DO NOT EDIT BY HAND
from __future__ import annotations
from typing import Optional, Any, List
from datetime import date, datetime
from decimal import Decimal
import uuid
from pydantic import Field
from OSSS.schemas.base import APIModel
'''
def snake(name: str) -> str:
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def map_type(col) -> str:
t = col.type
# Column nullability handled in field optionality
if isinstance(t, (Integer, SmallInteger, BigInteger)):
return "int"
if isinstance(t, (Float,)):
return "float"
if isinstance(t, (Numeric,)):
return "Decimal"
if isinstance(t, (Boolean,)):
return "bool"
if isinstance(t, (Date,)):
return "date"
if isinstance(t, (DateTime,)):
return "datetime"
if isinstance(t, (String, Text)):
return "str"
if PG_UUID is not None and isinstance(t, PG_UUID):
return "uuid.UUID"
if isinstance(t, JSON):
return "dict | list | Any"
# Fallback
return "Any"
def has_default(col) -> bool:
return bool(col.default is not None or col.server_default is not None)
def is_autoincrement_pk(col) -> bool:
try:
return bool(col.primary_key and (getattr(col, "autoincrement", "auto") in (True, "auto")))
except Exception:
return bool(col.primary_key)
def gen_classes(model) -> Tuple[str, str]:
mapper = sa_inspect(model)
cols = list(mapper.columns)
name = model.__name__
snake_name = snake(name)
# Build fields for Out/Create/Replace/Patch
out_lines: List[str] = [f"class {name}Out(APIModel):"]
create_lines: List[str] = [f"class {name}Create(APIModel):"]
replace_lines: List[str] = [f"class {name}Replace(APIModel):"]
patch_lines: List[str] = [f"class {name}Patch(APIModel):"]
for c in cols:
py = map_type(c)
# Out: include PK and all fields; optional if nullable
if c.nullable:
out_lines.append(f" {c.key}: {py} | None = None")
else:
out_lines.append(f" {c.key}: {py}")
if c.primary_key:
# Payloads: exclude PK to avoid conflicts with path param
continue
# Create/Replace: required if not nullable and no default; else Optional
required = (not c.nullable) and (not has_default(c))
if required:
create_lines.append(f" {c.key}: {py}")
replace_lines.append(f" {c.key}: {py}")
else:
create_lines.append(f" {c.key}: {py} | None = None")
replace_lines.append(f" {c.key}: {py} | None = None")
# Patch: all optional
patch_lines.append(f" {c.key}: {py} | None = None")
# List envelope for this model
list_lines = [
f"class {name}List(APIModel):",
f" items: list[{name}Out]",
" total: int | None = None",
" skip: int = 0",
" limit: int = 100",
]
body = "\n".join(out_lines + [""] + create_lines + [""] + replace_lines + [""] + patch_lines + [""] + list_lines) + "\n"
return HEADER, body
def import_all(package: str) -> Any:
pkg = importlib.import_module(package)
if hasattr(pkg, "__path__"):
for m in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + "."):
try:
importlib.import_module(m.name)
except Exception:
pass
return importlib.import_module(package)
def iter_models(base) -> List[Any]:
# SQLAlchemy 2.x registry path
models = []
reg = getattr(base, "registry", None)
if reg and getattr(reg, "mappers", None):
for mapper in reg.mappers:
cls = mapper.class_
if getattr(cls, "__abstract__", False):
continue
models.append(cls)
return models
# Fallback older style
reg = getattr(base, "_decl_class_registry", {})
for cls in reg.values():
if isinstance(cls, type) and not getattr(cls, "__abstract__", False):
models.append(cls)
return models
def main():
ap = argparse.ArgumentParser(description="Generate per-model Pydantic v2 schemas from SQLAlchemy models.")
ap.add_argument("--models-package", default="OSSS.db.models", help="Import path to the models package")
ap.add_argument("--base-object", default="OSSS.db.base:Base", help="Import path to the declarative Base (module:attr)")
ap.add_argument("--out", default="src/OSSS/schemas/generated", help="Output directory for generated .py files")
ap.add_argument("--include-list", nargs="*", default=None, help="Optional list of model class names to include")
ap.add_argument("--exclude-list", nargs="*", default=None, help="Optional list of model class names to exclude")
args = ap.parse_args()
# Import models to register them
import_all(args.models_package)
mod_name, attr = args.base_object.split(":")
Base = getattr(importlib.import_module(mod_name), attr)
outdir = Path(args.out)
outdir.mkdir(parents=True, exist_ok=True)
models = iter_models(Base)
includes = set(args.include_list or [])
excludes = set(args.exclude_list or [])
index_lines = ["# Auto-generated index for per-model schemas", "from __future__ import annotations", "__all__ = []"]
for m in models:
if includes and m.__name__ not in includes:
continue
if excludes and m.__name__ in excludes:
continue
head, body = gen_classes(m)
fname = outdir / f"{snake(m.__name__)}.py"
with open(fname, "w") as f:
f.write(head)
f.write("\n\n")
f.write(body)
index_lines.append(f"from .{snake(m.__name__)} import {m.__name__}Out, {m.__name__}Create, {m.__name__}Replace, {m.__name__}Patch, {m.__name__}List")
index_lines.append(f"__all__ += ['{m.__name__}Out','{m.__name__}Create','{m.__name__}Replace','{m.__name__}Patch','{m.__name__}List']")
with open(outdir / "__init__.py", "w") as f:
f.write("\n".join(index_lines) + "\n")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
6.78 kB
·
Xet hash:
afac78d0a30854578029693e8b72340e5a4b9197aae5c78fdb01885e4c763c3d

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.