SQLAlchemy and Alembic

DB migrations using Alembic

1
# 1. install alembic - time of writing current version used - alembic 1.7.5
2
​
3
pip install alembic
4
​
5
# 2. Inititiate alembic
6
alembic init alembic
7
​
8
# 3. Update alemnic.ini file with db connection details, for example:
9
sqlalchemy.url = mysql+pymysql://root:[email protected]:3306/service_dashboard
10
​
11
# 4. Edit alembic/env.py and add the following:
12
from models import Base
13
target_metadata = Base.metadata
14
# save your file
15
​
16
#5. For existing db generate first migration and add your stuff, so create migration manually, by running:
17
alembic revision -m "First migration"
18
​
19
# 6. After above commend yuo will have a new versioned fiele in versions directory, for example: bf35c09ac2e3
20
# edit file and add your changes, for example we want to add new columns:
21
​
22
def upgrade():
23
op.add_column('test_table', sa.Column('column_name', sa.String(255)))
24
​
25
​
26
def downgrade():
27
op.drop_column('test_table', 'column_name')
28
29
# 7. Run migrations with command:
30
alembic upgrade head
31
​
32
# For future you will generate new migrations with automatic migrations:
33
alembic revision --autogenerate -m "Add new columns"
Copied!
Copy link