Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Database migrations with SQLAlchemy, Flask, Elixir, SQLite
I have a project that was built 3 years ago, back before Elixir stopped being maintained. As projects have a tendancy to do, it's now time for an update. I've learned a lot in the last 3 years, and am looking forward to adding database migrations to the project. At the same time, if it aint broke don't fix it. I'm keeping Elixir in place, as it works well for our needs. However, Flask-Migrate relies on direct access to an SQLAlchemy object. I'm keeping is simple and going directly to the source: alembic.
The nice thing about this is that I can do the migrations directly on the db, without needing Elixir or any of our app logic.
``` bash
$ alembic init alembic
$ alembic revision -m "adding fields to media: id, filename_uploaded, and tags"
Generating /data/cliftonlabs/sportsvision/alembic/versions/4b7eedb40b12_adding_fields_to_media_id_filename_.py ... done
```
Now, updating the migration file with my new columns (using SQLAlchemy directly):
``` python
"""adding fields to media: id, filename_uploaded, and tags
Revision ID: 4b7eedb40b12
Revises:
Create Date: 2015-04-09 14:48:51.845299
"""
# revision identifiers, used by Alembic.
revision = '4b7eedb40b12'
down_revision = None
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('media', sa.Column('id', sa.Integer, primary_key=True))
op.add_column('media', sa.Column('tags', sa.String))
def downgrade():
op.drop_column('media', 'id')
op.drop_column('media', 'tags')
```
Update the environment file (alembic.ini) with our SQL connection (sqlite for me) and run the migration. My connection string looks like:
sqlalchemy.url = sqlite:///~/.app/database.db
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment