This guide walks you through the steps to migrate your codebase from SQLAlchemy 1.6 to 2.0 using Codegen. Follow along to modernize your imports, relationships, and query syntax while ensuring compatibility with SQLAlchemy 2.0. Each step includes a direct link to the appropriate codemod for easy implementation.
The migration focuses on these key updates:
-
Import Adjustments Aligns your code with the updated SQLAlchemy 2.0 module structure. Run the Import Codemod
-
Relationship Updates Refines relationship definitions by replacing
backrefwithback_populatesfor explicitness and better readability. Run the Relationship Codemod -
Query Syntax Modernization Updates queries to leverage the latest syntax like
select()andwhere(), removing deprecated methods. Run the Query Syntax Codemod -
Relationship Lazy Loading SQLAlchemy 2.0 introduces a new
lazyparameter for relationship definitions. Update your relationships to use the newlazyparameter for improved performance. Run the Relationship Lazy Loading Codemod -
Type Annotations SQLAlchemy 2.0 has improved type annotation support. Update your models to include type hints for better IDE support and runtime type checking.
- Add type annotations to model attributes and relationships
- Leverage SQLAlchemy's typing module for proper type hints
- Enable better IDE autocompletion and type checking
SQLAlchemy 2.0 introduces a refined import structure. Use the import codemod to:
- Replace wildcard imports (
*) with explicit imports for better clarity. - Update
declarative_basetoDeclarativeBase.
In SQLAlchemy 2.0, relationships require more explicit definitions. This includes:
- Transitioning from
backreftoback_populatesfor consistency. - Explicitly specifying
back_populatesfor all relationship definitions.
👉 Run the Relationship Codemod
The query API has been revamped in SQLAlchemy 2.0. Key updates include:
- Switching to
select()andwhere()for query construction. - Replacing any deprecated methods with their modern equivalents.
👉 Run the Query Syntax Codemod
SQLAlchemy 2.0 introduces a new lazy parameter for relationship definitions. Update your relationships to use the new lazy parameter for improved performance.
👉 Run the Relationship Lazy Loading Codemod
SQLAlchemy 2.0 has improved type annotation support. Update your models to include type hints for better IDE support and runtime type checking.
- Add type annotations to model attributes and relationships
- Leverage SQLAlchemy's typing module for proper type hints
- Enable better IDE autocompletion and type checking
👉 Run the Type Annotations Codemod
If you encounter issues or have specific edge cases not addressed by the codemods, reach out to the Codegen support team or visit the Codegen Documentation for detailed guidance.
Start your SQLAlchemy 2.0 migration today and enjoy the benefits of a cleaner, modern codebase!