Project Structure
Below is an example of the project structure, which shows where migration scripts will be stored:Installing Alembic
Begin by installing Alembic using pip. This not only installs the package but also provides access to its command-line interface:User and Vote as follows:
In this example, you are instructed to remove the
phone_number field once Alembic is set up and you are ready to update your database schema.Preparing the Database
Before running migrations, ensure that your application is stopped to prevent automatic restarts during the migration process. If required, drop any existing tables—usingDROP CASCADE if there are foreign key constraints—to start with a clean slate.
To check the current data in your database, you can run the following SQL query:
Initializing Alembic
Initialize Alembic to create the necessary directory structure and configuration files. The Alembic CLI provides several subcommands, which you can review using:alembic.ini configuration file. Next, you need to update both the env.py and alembic.ini files to connect Alembic with your SQLAlchemy models and database settings.
Configuring env.py for SQLAlchemy
Theenv.py file is the main configuration file for Alembic. It must be updated to import your SQLAlchemy models and set the target metadata for autogeneration. An initial snippet might look like this:
env.py file to import Base from your application’s database file. Replace the original metadata configuration with:
app.models), ensure the import reflects that. For instance, to detect changes in a Post model:
env.py accordingly:
Configuring alembic.ini
Within thealembic.ini file, specify your SQLAlchemy database URL. Initially, it might appear as follows:
While the above example hardcodes credentials for demonstration purposes, it is advisable to manage sensitive information using environment variables in production.
Overriding the Database URL in env.py
To avoid hardcoding credentials withinalembic.ini, you can override the SQLAlchemy URL directly in env.py using values from your configuration file. For example:
config.py might resemble: