select in Python
The 2.0 query API: build a select, execute it, read scalars or rows.
from sqlalchemy import create_engine, func, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Run(Base):
__tablename__ = "runs"
id: Mapped[int] = mapped_column(primary_key=True)
lang: Mapped[str]
tpm: Mapped[float]
engine = create_engine("sqlite+pysqlite:///:memory:")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([Run(lang="python", tpm=104.0),
Run(lang="python", tpm=91.0),
Run(lang="rust", tpm=98.0)])
session.commit()
fast = session.scalars(
select(Run).where(Run.tpm > 95).order_by(Run.tpm.desc())).all()
print([(r.lang, r.tpm) for r in fast])
per_lang = session.execute(
select(Run.lang, func.avg(Run.tpm)).group_by(Run.lang)).all()
print([(lang, round(avg, 1)) for lang, avg in per_lang])
How it works
select(Model)returns whole objects.where,order_byandlimitchain onto it.scalars()unwraps single-column rows.
Keywords and builtins used here
BaseRunasclassfloatforidintpassprintroundstrwith
The run, in numbers
- Lines
- 31
- Characters to type
- 813
- Tokens
- 244
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 133 seconds.
Step 4 of 5 in SQLAlchemy, step 16 of 19 in Web services & data access.