How to run DB migration
philipvibrant001
HOBBYOP

2 months ago

Hello I am new here, I am working on a new project.
I have a flask app and postgresSQL.

I want to know what are the steps to run a DB migration.

I appreciate your help.

Thank you.

$10 Bounty

2 Replies

fescobillguide
FREE

2 months ago

If you are using Flask with PostgreSQL, the most common and clean way to handle DB migrations is with Flask-Migrate (Alembic).

Basic steps:

1. Install dependencies:

pip install flask-migrate flask-sqlalchemy

2. Initialize migrations (one time):

flask db init

3. After creating or updating your models:

flask db migrate -m "initial migration"

4. Apply the migration to the database:

flask db upgrade

On Railway, make sure your DATABASE_URL environment variable is set correctly, then you can run the same commands using Railway CLI or in a deployment command.

This keeps schema changes versioned and avoids manual SQL changes.


2 months ago

Note that you should ideally run the migration command as a [Pre-Deploy Command](https://docs.railway.com/guides/pre-deploy-command). This ensures that if you have replicas of your app, they don't all try to migrate the database at the same time, causing lock contention and potentially corruption.


Loading...