Library cheatsheet
SQLAlchemy and Alembic 2 Cheatsheet
Define models, query and change data with SQLAlchemy 2, and manage schema changes with Alembic migrations.
Engine, models and tables
- Install SQLAlchemy — Install SQLAlchemy and a database driver, for example psycopg for PostgreSQL.
- Create an engine — An engine manages connections. SQLite is handy for tests; use your real URL in production.
- Define models — Declare tables with typed Mapped attributes.
- Create the tables — Create tables for all models. Use migrations for real schema changes.
- Open a session — A session is a unit of work. Use it as a context manager so it always closes.
Querying
- Insert rows — Add objects, then commit to write them.
- Select rows — Build a select statement and read model objects with scalars().
- Get by primary key — Look up one object by primary key; it returns None if missing.
- Get exactly one row — scalar_one() raises if there is not exactly one match; first() returns None for no match.
- Join tables — Select columns across a relationship with an explicit join.
- Group and count — Count rows per group with SQL functions.
- Paginate — Return the second page of 20 rows.
- Avoid N+1 queries — Load related rows in the same query or one extra query, instead of one query per object.
Updating and raw SQL
- Update an object — Change attributes on a loaded object and commit; SQLAlchemy tracks the change.
- Update many rows — Run one UPDATE statement for all matching rows.
- Delete a row — Delete an object and commit.
- Roll back on error — Undo pending changes when something fails.
- Run raw SQL safely — Use text() with bound parameters, never string formatting.
- Use the async API — Create an async engine and session for asyncio apps such as FastAPI. Use an async driver like asyncpg.
Alembic migrations
- Install Alembic — Install the migration tool.
- Create a migration environment — Create the alembic folder and alembic.ini. Point env.py at your models' metadata.
- Generate a migration — Compare your models with the database and write a migration. Always review the generated file.
- Apply migrations — Upgrade the database to the latest revision.
- Undo the last migration — Step back by one revision.
- Check the current revision — Show which revision the database is at.
- List migrations — Show the revision history.
- Generate SQL without running it — Print the SQL of a migration for review or for a DBA to run.
Related cheatsheets
- Hugging Face cheatsheet — The hf command line, and Transformers and Datasets code for downloading, running, training and sharing models.
- Matplotlib and seaborn 3 cheatsheet — Draw line, scatter, bar and histogram charts with Matplotlib, and statistical charts with seaborn.
- pandas and NumPy 3 cheatsheet — Load, clean, reshape, group and analyze tabular data with pandas, and work with arrays in NumPy.
- Polars 2 cheatsheet — Fast DataFrames in Python: expressions, filtering, grouping, joins, lazy queries and file formats.
- Prisma ORM cheatsheet — Model your database in a schema, run migrations, and query with the type-safe Prisma Client. Examples use the prisma-client-js generator; check the docs for newer generators.
- PyTorch 2 cheatsheet — Tensors, autograd, models, training loops, saving and speed-ups in PyTorch 2.