Creating the Users Table
After successfully creating the posts table, the next step is implementing user functionality by creating a users table. This table will allow users to register and log in.Before proceeding, ensure that your existing posts table is functioning correctly.
Key Points in the Users Table Migration
- The
idcolumn is defined as an integer and set as non-nullable. A primary key is established using eitherprimary_key=Trueor a separatesa.PrimaryKeyConstraint('id'). - The
emailcolumn has a unique constraint to prevent duplicate entries. - The
created_atcolumn is defined with TIMESTAMP and timezone support. Its default value is set tonow()usingserver_default=sa.text('now()').

Adding a Foreign Key to the Posts Table
Next, establish a relationship between the posts and users tables by adding a foreign key to the posts table. To link the two tables, add a new columnowner_id to the posts table.
Start by introducing the column without the constraint:
posts.owner_id to users.id with cascading delete behavior:

Adding Additional Columns to the Posts Table
Your application may require extra functionality that necessitates new columns. In this case, we add a booleanpublished column and a created_at timestamp column to the posts table.
The following migration achieves this:

Downgrading and Re-Upgrading Revisions
Alembic provides the flexibility to rollback and upgrade revisions as needed. For instance, to roll back to the revision corresponding to the user table, use the following migration:Auto-Generating the Votes Table
With the posts and users tables in place, the next step is creating a votes table. Instead of writing the migration manually, leverage Alembic’s auto-generation feature. Alembic compares your SQLAlchemy models with the existing schema and creates the necessary migration. Below is the SQLAlchemy model for the Post, which includes all required columns:alembic upgrade head, verify that the votes table is created with the appropriate foreign key constraints.
Updating the User Model with a New Phone Number Column
If you wish to extend your User model with an optionalphone_number column, update your SQLAlchemy model as shown below:
phone_number column is present in the users table:

Removing models.Base.metadata.create_all from main.py
As Alembic now manages your database schema, you can remove the direct table creation command from your main application file. Although keeping it might be useful during early development, it is redundant once migrations are in place. Below is a samplemain.py file with the table creation commented out:
By following these steps, you can efficiently manage your evolving database schema with Alembic. This process minimizes manual migration work and ensures that your database stays in sync with your SQLAlchemy models as your application grows. For further reading on Alembic and database migrations, consider exploring Alembic’s official documentation.