import uuid from typing import Any, Type from sqlalchemy.orm import Session def short_id(prefix: str, size: int = 8) -> str: return f"{prefix}_{uuid.uuid4().hex[:size]}" def unique_short_id(prefix: str, db: Session, model_cls: Type[Any], size: int = 8) -> str: for _ in range(10): candidate = short_id(prefix, size=size) exists = db.query(model_cls.id).filter(model_cls.id == candidate).first() if not exists: return candidate raise RuntimeError(f"failed to generate unique id for {model_cls.__name__}")