1"""Add a numerical position column to sort header matches.
2
3Revision ID: d4fbb4fd34ca
4Revises: bfda02ab3a9b
5Create Date: 2016-02-01 15:57:09.807678
6
7"""
8
9import sqlalchemy as sa
10
11from alembic import op
12from mailman.database.helpers import is_mysql
13
14
15# Revision identifiers, used by Alembic.
16revision = 'd4fbb4fd34ca'
17down_revision = 'bfda02ab3a9b'
18
19
20def upgrade():
21    with op.batch_alter_table('headermatch') as batch_op:
22        batch_op.add_column(
23            sa.Column('position', sa.Integer(), nullable=True))
24        batch_op.create_index(
25            op.f('ix_headermatch_position'), ['position'], unique=False)
26        if not is_mysql(op.get_bind()):
27            # MySQL automatically creates indexes for primary keys.
28            batch_op.create_index(
29                op.f('ix_headermatch_mailing_list_id'), ['mailing_list_id'],
30                unique=False)
31            # MySQL doesn't allow changing columns used in a foreign key
32            # constrains since MySQL version 5.6.  We need to drop the
33            # constraint before changing the column.  But, since the
34            # constraint name is auto-generated, we can't really hardcode the
35            # name here to use batch_op.drop_constraint().  Until we have a
36            # better fix for this, it should be safe to skip this.
37            batch_op.alter_column(
38                'mailing_list_id', existing_type=sa.INTEGER(), nullable=False)
39
40
41def downgrade():
42    with op.batch_alter_table('headermatch') as batch_op:
43        batch_op.drop_index(op.f('ix_headermatch_position'))
44        batch_op.drop_column('position')
45
46        if not is_mysql(op.get_bind()):
47            # MySQL automatically creates and removes the indexes for primary
48            # keys.  So, you cannot drop it without removing the foreign key
49            # constraint.
50            batch_op.drop_index(op.f('ix_headermatch_mailing_list_id'))
51            # MySQL doesn't allow changing columns used in foreign_key
52            # constraints.
53            batch_op.alter_column(
54                'mailing_list_id', existing_type=sa.INTEGER(), nullable=True)
55