Complete worked example
python
from sqlalchemy import create_engine, select, text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Role(Base):
__tablename__ = "roles"
id: Mapped[int] = mapped_column(primary_key=True)
score: Mapped[int]
def inspect_example(scores, minimum, limit):
if type(limit) is not int or not 1 <= limit <= 3:
raise ValueError("limit must be an integer between one and three")
engine = create_engine("sqlite+pysqlite://", connect_args={"autocommit": False})
try:
Base.metadata.create_all(engine)
with Session(engine) as session, session.begin():
session.add_all(Role(id=i, score=value) for i, value in enumerate(scores, 1))
with Session(engine) as session:
statement = (select(Role.id).where(Role.score >= minimum)
.order_by(Role.score.desc(), Role.id).limit(limit))
return list(session.scalars(statement))
finally:
engine.dispose()- Reasoning
- The statement builds its WHERE from a column expression, orders by score descending and ID ascending, and applies the validated limit. For [3, 9, 9, 1], minimum 3 and limit 2, the expected IDs are [2, 3]. The exact tied order is part of the declared result. Input values become bound parameters through SQLAlchemy’s expression system. The code does not splice a caller-controlled SQL fragment into ORDER BY. It creates only the rows needed for this owned example; a production page must additionally define how concurrent changes affect later requests and which cursor or snapshot semantics it promises.