Complete worked example
python
from sqlalchemy import create_engine, text, Column, String
from alembic.migration import MigrationContext
from alembic.operations import Operations
def migrate_country(country):
if country not in ('US', 'IL', 'UA'):
raise ValueError('unsupported fixture country')
engine = create_engine('sqlite:///:memory:')
try:
with engine.begin() as connection:
connection.execute(text('CREATE TABLE role (id INTEGER PRIMARY KEY, title TEXT NOT NULL)'))
connection.execute(text("INSERT INTO role VALUES (1, 'Saved')"))
operations = Operations(MigrationContext.configure(connection))
operations.add_column('role', Column('country', String(2), nullable=False, server_default=country))
row = connection.execute(text('SELECT title, country FROM role WHERE id=1')).one()
return list(row)
finally:
engine.dispose()- Reasoning
- The fixture first creates an old table and inserts a saved row. It then adds a non-null country column with an explicit server default and reads back the original title beside its new value.