Slide 1

Slide 1 text

Zero-downtime upgrades with Alembic A look at some of the power features of Alembic, the database migration tool PyCon IE 2022 @stephenfin

Slide 2

Slide 2 text

Stephen Finucane (@stephenfin) Senior Software Engineer Red Hat

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

Alembic +

Slide 5

Slide 5 text

Background

Slide 6

Slide 6 text

class User(Base): __tablename__ = "user_account" id = Column(Integer, primary_key=True) first_name = Column(String(30)) last_name = Column(String(30)) addresses = relationship( "Address", back_populates="user", cascade="all, delete-orphan" ) def __repr__(self): return f"User(id={self.id!r})" models.py

Slide 7

Slide 7 text

❯ alembic revision --autogenerate ...

Slide 8

Slide 8 text

# revision identifiers, used by Alembic. revision = '6cb93d555e2b' down_revision = None branch_labels = None depends_on = None def upgrade() -> None: op.create_table( 'user_account', sa.Column('id', sa.Integer(), nullable=False), sa.Column('first_name', sa.String(length=30), nullable=True), sa.Column('last_name', sa.String(length=30), nullable=True), sa.PrimaryKeyConstraint('id'), ) 6cb93d555e2b_initial_migration.py

Slide 9

Slide 9 text

❯ alembic upgrade head

Slide 10

Slide 10 text

. ├── alembic_expand_contract_demo │ ├── __init__.py │ ├── migrations │ │ ├── env.py │ │ ├── README │ │ ├── script.py.mako │ │ └── versions │ │ └── 6cb93d555e2b_initial_migration.py │ ├── models.py ├── alembic.ini ├── README.md └── requirements.txt

Slide 11

Slide 11 text

. ├── alembic_expand_contract_demo │ ├── __init__.py │ ├── migrations │ │ ├── env.py │ │ ├── README │ │ ├── script.py.mako │ │ └── versions │ │ └── 6cb93d555e2b_initial_migration.py │ ├── models.py ├── alembic.ini ├── README.md └── requirements.txt

Slide 12

Slide 12 text

The Problem

Slide 13

Slide 13 text

class User(Base): __tablename__ = "user_account" id = Column(Integer, primary_key=True) first_name = Column(String(30)) last_name = Column(String(30)) addresses = relationship( "Address", back_populates="user", cascade="all, delete-orphan" ) def __repr__(self): return f"User(id={self.id!r})" models.py

Slide 14

Slide 14 text

class User(Base): __tablename__ = "user_account" id = Column(Integer, primary_key=True) name = Column(String) addresses = relationship( "Address", back_populates="user", cascade="all, delete-orphan" ) def __repr__(self): return f"User(id={self.id!r})" models.py

Slide 15

Slide 15 text

❯ alembic revision --autogenerate ...

Slide 16

Slide 16 text

def upgrade() -> None: # schema migration - add new columns op.add_column( 'user_account', sa.Column('name', sa.String(), nullable=True), ) # ...some (manually added) data migrations... # schema migration - drop old columns op.drop_column('user_account', 'first_name') op.drop_column('user_account', 'last_name') 0585005489f0_merge_user_names.py

Slide 17

Slide 17 text

To do the schema and data migrations in one go, we’d need to shut down our instances…

Slide 18

Slide 18 text

To do the schema and data migrations in one go, we’d need to shut down our instances… How do we avoid downtime? 🤔

Slide 19

Slide 19 text

A Solution

Slide 20

Slide 20 text

Expand - Contract

Slide 21

Slide 21 text

Expand - Migrate - Contract

Slide 22

Slide 22 text

first_name last_name first_name last_name name name expand migrate contract

Slide 23

Slide 23 text

Let’s split up those migrations (manually, for now)

Slide 24

Slide 24 text

revision = '9c36df1b3f62' down_revision = '6cb93d555e2b' branch_labels = None depends_on = None def upgrade() -> None: # schema migration - add new columns op.add_column( 'user_account', sa.Column('name', sa.String(), nullable=True), ) 9c36df1b3f62_merge_user_names_expand.py

Slide 25

Slide 25 text

revision = 'e629a4ea0677' down_revision = '9c36df1b3f62' branch_labels = None depends_on = None def upgrade() -> None: # schema migrations - contract op.drop_column('user_account', 'first_name') op.drop_column('user_account', 'last_name') 9c36df1b3f62_merge_user_names_contract.py

Slide 26

Slide 26 text

❯ alembic upgrade 9c36df1b3f62 # expand hash ❯ alembic upgrade e629a4ea0677 # contract hash

Slide 27

Slide 27 text

That’s kind of ugly, no? 🤮

Slide 28

Slide 28 text

A Better Solution

Slide 29

Slide 29 text

“A branch describes a point in a migration stream when two or more versions refer to the same parent migration as their ancestor.” Alembic Documentation

Slide 30

Slide 30 text

revision = '9c36df1b3f62' down_revision = '6cb93d555e2b' branch_labels = None depends_on = None def upgrade() -> None: # schema migration - add new columns op.add_column( 'user_account', sa.Column('name', sa.String(), nullable=True), ) 9c36df1b3f62_merge_user_names_expand.py (before)

Slide 31

Slide 31 text

revision = '9c36df1b3f62' down_revision = '6cb93d555e2b' branch_labels = ('expand',) depends_on = None def upgrade() -> None: # schema migration - add new columns op.add_column( 'user_account', sa.Column('name', sa.String(), nullable=True), ) 9c36df1b3f62_merge_user_names_expand.py (after)

Slide 32

Slide 32 text

revision = 'e629a4ea0677' down_revision = '9c36df1b3f62' branch_labels = None depends_on = None def upgrade() -> None: # schema migrations - contract op.drop_column('user_account', 'first_name') op.drop_column('user_account', 'last_name') 9c36df1b3f62_merge_user_names_contract.py (before)

Slide 33

Slide 33 text

revision = 'e629a4ea0677' down_revision = '9c36df1b3f62' branch_labels = ('contract',) depends_on = None def upgrade() -> None: # schema migrations - contract op.drop_column('user_account', 'first_name') op.drop_column('user_account', 'last_name') 9c36df1b3f62_merge_user_names_contract.py (after)

Slide 34

Slide 34 text

❯ alembic upgrade expand ❯ alembic upgrade contract

Slide 35

Slide 35 text

Much better! .

Slide 36

Slide 36 text

Much better! But we can do more…

Slide 37

Slide 37 text

The “Best” Solution

Slide 38

Slide 38 text

❯ alembic revision --autogenerate ...

Slide 39

Slide 39 text

def run_migrations_online() -> None: connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, ) with context.begin_transaction(): context.run_migrations() env.py

Slide 40

Slide 40 text

def run_migrations_online() -> None: connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, process_revision_directives=autogen.process_revision_directives, ) with context.begin_transaction(): context.run_migrations() env.py

Slide 41

Slide 41 text

process_revision_directives - a callable function that will be passed a structure representing the end result of an autogenerate or plain “revision” operation, which can be manipulated to affect how the alembic revision command ultimately outputs new revision scripts. Alembic Documentation

Slide 42

Slide 42 text

def run_migrations_online() -> None: connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, process_revision_directives=autogen.process_revision_directives, ) with context.begin_transaction(): context.run_migrations() env.py

Slide 43

Slide 43 text

_ec_dispatcher = Dispatcher() def process_revision_directives(context, revision, directives): directives[:] = list(_assign_directives(context, directives)) def _assign_directives(context, directives, phase=None): for directive in directives: decider = _ec_dispatcher.dispatch(directive) if phase is None: phases = ('expand', 'contract') else: phases = (phase,) for phase in phases: decided = decider(context, directive, phase) if decided: yield decided autogen.py (part 1)

Slide 44

Slide 44 text

@_ec_dispatcher.dispatch_for(ops.MigrationScript) def _migration_script_ops(context, directive, phase): op = ops.MigrationScript( new_rev_id(), ops.UpgradeOps( ops=list( _assign_directives(context, directive.upgrade_ops.ops, phase) ) ), ops.DowngradeOps(ops=[]), message=directive.message, head=f'{phase}@head', ) if not op.upgrade_ops.is_empty(): return op autogen.py (part 2)

Slide 45

Slide 45 text

@_ec_dispatcher.dispatch_for(ops.AddConstraintOp) @_ec_dispatcher.dispatch_for(ops.CreateIndexOp) @_ec_dispatcher.dispatch_for(ops.CreateTableOp) @_ec_dispatcher.dispatch_for(ops.AddColumnOp) def _expands(context, directive, phase): if phase == 'expand': return directive else: return None autogen.py (part 3)

Slide 46

Slide 46 text

@_ec_dispatcher.dispatch_for(ops.DropConstraintOp) @_ec_dispatcher.dispatch_for(ops.DropIndexOp) @_ec_dispatcher.dispatch_for(ops.DropTableOp) @_ec_dispatcher.dispatch_for(ops.DropColumnOp) def _contracts(context, directive, phase): if phase == 'contract': return directive else: return None autogen.py (part 4)

Slide 47

Slide 47 text

@_ec_dispatcher.dispatch_for(ops.AlterColumnOp) def _alter_column(context, directive, phase): is_expand = phase == 'expand' if is_expand and directive.modify_nullable is True: return directive elif not is_expand and directive.modify_nullable is False: return directive else: raise NotImplementedError( "Don't know if operation is an expand or contract at the moment: " "%s" % directive ) autogen.py (part 5)

Slide 48

Slide 48 text

@_ec_dispatcher.dispatch_for(ops.ModifyTableOps) def _modify_table_ops(context, directive, phase): op = ops.ModifyTableOps( directive.table_name, ops=list(_assign_directives(context, directive.ops, phase)), schema=directive.schema, ) if not op.is_empty(): return op autogen.py (part 6)

Slide 49

Slide 49 text

❯ alembic revision --autogenerate ...

Slide 50

Slide 50 text

# revision identifiers, used by Alembic. revision = '1630422c66fe' down_revision = '9c36df1b3f62' branch_labels = None depends_on = None def upgrade() -> None: op.add_column( 'user_account', sa.Column('name', sa.String(), nullable=True) ) 1630422c66fe_merge_user_names.py

Slide 51

Slide 51 text

# revision identifiers, used by Alembic. revision = 'a142d030afc5' down_revision = 'e629a4ea0677' branch_labels = None depends_on = None def upgrade() -> None: op.drop_column('user_account', 'last_name') op.drop_column('user_account', 'first_name') a142d030afc5_merge_user_names.py

Slide 52

Slide 52 text

❯ alembic upgrade expand ❯ alembic upgrade contract

Slide 53

Slide 53 text

Next Steps & Wrap Up

Slide 54

Slide 54 text

We can improve this further…

Slide 55

Slide 55 text

We can improve this further… Distinguish expand/contract migrations by filename

Slide 56

Slide 56 text

❯ ls migrations/version 1630422c66fe_merge_user_names.py 6cb93d555e2b_initial_models.py 9c36df1b3f62_initial_expand.py a142d030afc5_merge_user_names.py e629a4ea0677_initial_contract.py

Slide 57

Slide 57 text

❯ ls migrations/version 1630422c66fe_merge_user_names.py 6cb93d555e2b_initial_models.py 9c36df1b3f62_initial_expand.py a142d030afc5_merge_user_names.py e629a4ea0677_initial_contract.py

Slide 58

Slide 58 text

We can improve this further… Distinguish expand/contract migrations by filename Add checkpoints (e.g. version 1.0, 1.1, …)

Slide 59

Slide 59 text

❯ alembic upgrade expand ❯ alembic upgrade contract

Slide 60

Slide 60 text

❯ neutron-db-manage --expand zed ❯ neutron-db-manage --contract zed

Slide 61

Slide 61 text

We can improve this further… Distinguish expand/contract migrations by filename Add checkpoints (e.g. version 1.0, 1.1, …) Add tests …

Slide 62

Slide 62 text

that.guru/blog/zero-downtime-upgrades-with-alembic-and-sqlalchemy/

Slide 63

Slide 63 text

Credits Cover photo by Yunus Tuğ on Unsplash Source code based OpenStack Neutron code, licensed under Apache 2.0