An ORM Maps Classes to Tables, and Migrations Version the Schema Those Classes Describe

In progress

An object-relational mapper (ORM) lets code work with objects while the database stores rows: a class maps to a table, an attribute to a column, a relationship to a foreign key, and method calls become SQL. Changing a class, however, doesn't change the table. Migrations close that gap: each one is a versioned, reviewable script that moves the database schema from one version of the models to the next.

What the ORM Gives

Object side Database side
class Book table book
attribute title: str column title VARCHAR
book.author relationship foreign key author_id and a join
session.add(book); session.commit() INSERT inside a transaction
  • Parameterised queries by default, which closes the usual SQL injection hole, as long as raw SQL isn't assembled from strings.
  • One vocabulary across databases: the same code runs on SQLite, PostgreSQL or MySQL, apart from vendor-specific features.
  • Objects for the rest of the app: services and templates consume Book instances rather than cursor rows.

SQLAlchemy is Python's main ORM and SQL toolkit; Flask-SQLAlchemy wraps it for Flask, and SQLModel builds Pydantic models on top of it for FastAPI. Django and Rails ship their own ORMs with the same ideas.

Alembic Versions the Schema

alembic revision --autogenerate -m "add isbn to book"   # diff models vs database
alembic upgrade head          # apply all pending migrations
alembic upgrade +1            # apply the next one
alembic downgrade -1          # undo the last one
alembic current               # revision the database is at
alembic history --verbose     # all revisions
alembic upgrade head --sql    # print the SQL instead of running it

References

Review cards

Flashcard How does an ORM close the usual SQL injection hole, and when does it reopen?

It sends parameterised queries by default, so values never become SQL. The hole reopens as soon as raw SQL is assembled from strings.

Flashcard Why read every migration Alembic autogenerates before applying it?

Autogenerate diffs the models against the live schema and guesses. A renamed column looks like "drop column, add column", which deletes its data, so renames must be fixed by hand.

Quiz Which benefit does an ORM such as SQLAlchemy actually give?
  • The same code runs on SQLite, PostgreSQL or MySQL, apart from vendor features
  • It removes the need for migrations
  • It keeps the query count low on its own
  • It turns a model change into a schema change automatically

One vocabulary across databases. Changing a class doesn't change the table (that's what migrations are for), and lazy relationships can cause N+1 queries.

Flashcard What does `alembic upgrade head` do, and why commit migrations with the models?

It applies every pending migration up to the latest revision. With the model change and its migration in the same commit, any checkout rebuilds its exact schema with that one command.