User Guides: Database Migrations¶
DuoORM provides a command-line tool, duo-orm, to manage your database schema evolution. This tool is a wrapper around the powerful Alembic library, providing an opinionated and streamlined workflow.
The Migration Workflow¶
The core workflow for database migrations consists of three steps:
- Initialize: Set up the migration environment in your project. You only need to do this once.
- Create: After you change your models, you generate a new migration script that contains the Python code to apply those changes to your database schema.
- Upgrade/Downgrade: You apply (or revert) these migration scripts to your database to bring its schema up-to-date.
1. Initializing Your Project (init)¶
The duo-orm init command bootstraps your entire database setup.
This command does several things:
- Creates a directory structure: By default, it creates a
db/directory with subdirectories formodels,schemas, andmigrations(each with__init__.pyso you can import cleanly). - Generates configuration: It creates an
alembic.iniandenv.pyfile insidedb/migrations/that are pre-configured to work with DuoORM. - Creates a database entrypoint: It generates a
db/database.pyfile where you will configure yourDatabaseinstance. - Updates
pyproject.toml: It saves your configuration to your project'spyproject.tomlfile, so you don't have to specify it again. - Points you to next steps: Define ORM models in
db/models/and matching Pydantic schemas indb/schemas/for request/response DTOs.
You can customize the directory using the --dir option:
2. Creating Migrations (migration create)¶
After you have created or modified your models in the db/models/ directory, you can generate a migration script.
This command will:
1. Connect to your database to inspect its current schema.
2. Inspect your db.Model classes to determine the desired schema.
3. Compare the two and generate a new Python script in the db/migrations/versions/ directory containing the upgrade() and downgrade() functions to bridge the difference.
It's good practice to give your migrations a short, descriptive message.
Important
For migration create to work, it needs to be able to connect to your database. Make sure the URL in your db/database.py file is valid and points to a running database instance.
3. Applying and Reverting Migrations¶
Once you have a migration script, you can apply it to your database.
upgrade¶
The upgrade command applies migrations.
You can also specify a target revision:
The special keywordhead refers to the latest migration.
downgrade¶
The downgrade command reverts migrations.
By default, this reverts a single level. You can also specify a target revision to revert to.
history¶
To see a list of all migrations and their status, use the history command.