SQLAlchemy 2.0 has been widely adopted and introduces significant changes from its predecessors. Code written for older versions (like 1.3) requires updates to comply with the new rules and best practices introduced in version 2.0 and later.
However, the official SQLAlchemy migration documentation has an encyclopedic structure that can be overwhelming for average users and lacks tutorial-style examples. In this article, I will provide a concise, practical example of what you need to do to update your code from version 1.3 to 2.0 or later.
What is SQLAlchemy?
SQLAlchemy is an Object-Relational Mapper (ORM) that allows you to map your Python classes and objects to a relational database. It enables seamless integration of SQL with Python code while maintaining database independence. If you need more information about this popular and complex framework, you can start with its official documentation or explore the many introductory resources available. However, most of these resources focus on older versions, which differ significantly from the latest release.
SQLAlchemy 1.3 Code Example
I assume you have legacy code written for SQLAlchemy 1.3 or earlier. The example below creates a simple database with one table, adds two records, and retrieves them. We declare a users table with three columns: id (user identifier), name (user name), and first_seen (registration date). To map this relational table to an object-oriented structure, we wrap it in a User class. We can add custom methods or override existing ones—for example, I overrode the repr method to customize how records are displayed when printed.
Migrating to SQLAlchemy 2.0
To upgrade the code to SQLAlchemy 2.0 style, we need to make the following key changes:
- Replace the declarative_base() function with a DeclarativeBase superclass. This new approach supersedes the old function-based method and integrates better with PEP 484 type hints without requiring plugins.
- Update column declarations to use Mapped type hints and the mapped_column function instead of the old Column approach.
- Note that session.flush is no longer supported in the new API.
- Use the new session management syntax with Session.begin() or the with Session() as session: context manager structure.
The updated SQLAlchemy 2.0 code is shown below:
Summary
In this post, I presented a step-by-step migration procedure for updating SQLAlchemy 1.3 code to SQLAlchemy 2.0. The example is intentionally simple, featuring a single table without relationships to other tables. Given the extensive and complex official documentation on this topic, I believe a concise, practical tutorial like this will help users get started with their code upgrades.