Python alembic.op.batch_alter_table() Examples

The following are 30 code examples of alembic.op.batch_alter_table(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module alembic.op , or try the search function .
Example #1
Source File: d4d2c5aa8a0_add_granularity_to_watching_repos.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def downgrade():
    op.add_column('watchers', sa.Column('watch', sa.BOOLEAN(), nullable=True))

    # This section is to update the `watch` column with the value of
    # `watch_issues`
    connection = op.get_bind()
    for watcher in connection.execute(watcher_helper.select()):
        connection.execute(
            watcher_helper.update().where(
                watcher_helper.c.id == watcher.id
            ).values(
                watch=watcher.watch_issues
            )
        )

    with op.batch_alter_table('watchers') as b:
        # Set nullable to False now that we've set values
        b.alter_column('watch', nullable=False)
        # Drop the added columns
        b.drop_column('watch_issues')
        b.drop_column('watch_commits') 
Example #2
Source File: 74effc47d867_change_datetime_to_datetime2_6_on_mssql_.py    From airflow with Apache License 2.0 6 votes vote down vote up
def modify_execution_date_with_constraint(conn, batch_operator, table_name, type_, nullable):
    """
    Helper function changes type of column execution_date by
    dropping and recreating any primary/unique constraint associated with
    the column

    :param conn: sql connection object
    :param batch_operator: batch_alter_table for the table
    :param table_name: table name
    :param type_: DB column type
    :param nullable: nullable (boolean)
    :return: a dictionary of ((constraint name, constraint type), column name) of table
    :rtype: defaultdict(list)
    """
    constraint_dict = get_table_constraints(conn, table_name)
    drop_constraint(batch_operator, constraint_dict)
    batch_operator.alter_column(
        column_name="execution_date",
        type_=type_,
        nullable=nullable,
    )
    create_constraint(batch_operator, constraint_dict) 
Example #3
Source File: 74effc47d867_change_datetime_to_datetime2_6_on_mssql_.py    From airflow with Apache License 2.0 6 votes vote down vote up
def create_constraint(operator, constraint_dict):
    """
    Create a primary key or unique constraint

    :param operator: batch_alter_table for the table
    :param constraint_dict: a dictionary of ((constraint name, constraint type), column name) of table
    """
    for constraint, columns in constraint_dict.items():
        if 'execution_date' in columns:
            if constraint[1].lower().startswith("primary"):
                operator.create_primary_key(
                    constraint_name=constraint[0],
                    columns=reorder_columns(columns)
                )
            elif constraint[1].lower().startswith("unique"):
                operator.create_unique_constraint(
                    constraint_name=constraint[0],
                    columns=reorder_columns(columns)
                ) 
Example #4
Source File: 74effc47d867_change_datetime_to_datetime2_6_on_mssql_.py    From airflow with Apache License 2.0 6 votes vote down vote up
def drop_constraint(operator, constraint_dict):
    """
    Drop a primary key or unique constraint

    :param operator: batch_alter_table for the table
    :param constraint_dict: a dictionary of ((constraint name, constraint type), column name) of table
    """
    for constraint, columns in constraint_dict.items():
        if 'execution_date' in columns:
            if constraint[1].lower().startswith("primary"):
                operator.drop_constraint(
                    constraint[0],
                    type_='primary'
                )
            elif constraint[1].lower().startswith("unique"):
                operator.drop_constraint(
                    constraint[0],
                    type_='unique'
                ) 
Example #5
Source File: beb065460c24_fixed-password-type.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def upgrade():
    connection = op.get_bind()
    if connection.engine.name != 'sqlite':
        return
    
    with op.batch_alter_table('user') as batch_op:
        batch_op.add_column(sa.Column('_password',
               sqlalchemy_utils.types.password.PasswordType(max_length=128),
               server_default='',
               nullable=False
            ))
    
    connection.execute(
            UserHelper.update().values(_password=UserHelper.c.password)
        )
    
    with op.batch_alter_table('user') as batch_op:
        batch_op.drop_column('password')
        batch_op.alter_column('_password', server_default=None, new_column_name='password') 
Example #6
Source File: e360c56bcf8c_.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def upgrade():
    try:
        with op.batch_alter_table("smsgatewayoption") as batch_op:
            batch_op.drop_constraint('sgix_1', type_='unique')
            batch_op.create_unique_constraint('sgix_1', ['gateway_id', 'Key', 'Type'])
    except Exception as exx:
        print("Cannot change constraint 'sgix_1' in table smsgatewayoption.")
        print(exx)

    try:
        bind = op.get_bind()
        session = orm.Session(bind=bind)
        # add default type 'option' for all rows
        for row in session.query(SMSGatewayOption):
            if not row.Type:
                row.Type = "option"

    except Exception as exx:
        session.rollback()
        print("Failed to add option type for all existing entries in table smsgatewayoption!")
        print(exx)

    session.commit() 
Example #7
Source File: 6e96a59344a4_make_taskinstance_pool_not_nullable.py    From airflow with Apache License 2.0 6 votes vote down vote up
def upgrade():
    """
    Make TaskInstance.pool field not nullable.
    """
    with create_session() as session:
        session.query(TaskInstance) \
            .filter(TaskInstance.pool.is_(None)) \
            .update({TaskInstance.pool: 'default_pool'},
                    synchronize_session=False)  # Avoid select updated rows
        session.commit()

    conn = op.get_bind()
    if conn.dialect.name == "mssql":
        op.drop_index('ti_pool', table_name='task_instance')

    # use batch_alter_table to support SQLite workaround
    with op.batch_alter_table('task_instance') as batch_op:
        batch_op.alter_column(
            column_name='pool',
            type_=sa.String(50),
            nullable=False,
        )

    if conn.dialect.name == "mssql":
        op.create_index('ti_pool', 'task_instance', ['pool', 'state', 'priority_weight']) 
Example #8
Source File: beb065460c24_fixed-password-type.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def downgrade():
    connection = op.get_bind()
    if connection.engine.name != 'sqlite':
        return
    
    with op.batch_alter_table('user') as batch_op:
        batch_op.add_column(sa.Column('_password',
               type_=sa.NUMERIC(precision=128),
               server_default='',
               nullable=False
            ))
    
    connection.execute(
            UserHelper.update().values(_password=UserHelper.c.password)
        )
    
    with op.batch_alter_table('user') as batch_op:
        batch_op.drop_column('password')
        batch_op.alter_column('_password', server_default=None, new_column_name='password') 
Example #9
Source File: 36954739c63_.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('user', sa.Column('created', sa.DateTime(), nullable=True))
    op.add_column('user', sa.Column('updated', sa.DateTime(), nullable=True))
    with op.batch_alter_table('user') as batch_op:
        batch_op.alter_column('password',
               existing_type=sa.VARCHAR(length=128),
               type_=sqlalchemy_utils.types.password.PasswordType(max_length=128),
               existing_nullable=False,
               postgresql_using='password::bytea')
    ### end Alembic commands ###

    user = sa.Table('user',
        sa.MetaData(),
        sa.Column('created', sa.DateTime()),
        sa.Column('updated', sa.DateTime()),
    )

    op.execute(
        user.update().values({'created': datetime.now(), 'updated': datetime.now()})
    ) 
Example #10
Source File: 26b4c36c11e_create_database.py    From spkrepo with MIT License 6 votes vote down vote up
def downgrade():
    op.drop_table("download")
    op.drop_table("build_architecture")
    op.drop_table("displayname")
    op.drop_table("description")
    op.drop_table("icon")
    sa.Enum(name="icon_size").drop(op.get_bind(), checkfirst=False)
    op.drop_table("build")
    op.drop_table("version_service_dependency")
    op.drop_table("package_user_maintainer")
    with op.batch_alter_table("version", schema=None) as batch_op:
        batch_op.drop_index(batch_op.f("ix_version_version"))
    op.drop_table("version")
    op.drop_table("screenshot")
    op.drop_table("user_role")
    op.drop_table("package")
    op.drop_table("service")
    op.drop_table("firmware")
    op.drop_table("language")
    op.drop_table("architecture")
    op.drop_table("role")
    op.drop_table("user") 
Example #11
Source File: d4d2c5aa8a0_add_granularity_to_watching_repos.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def upgrade():
    op.add_column('watchers', sa.Column('watch_commits', sa.Boolean(),
                                        nullable=True))
    op.add_column('watchers', sa.Column('watch_issues', sa.Boolean(),
                                        nullable=True))
    # This section is to update the `watch_issues` and `watch_commits` columns
    # with the value of `watch`
    connection = op.get_bind()
    for watcher in connection.execute(watcher_helper.select()):
        connection.execute(
            watcher_helper.update().where(
                watcher_helper.c.id == watcher.id
            ).values(
                watch_issues=watcher.watch,
                watch_commits=False
            )
        )

    with op.batch_alter_table('watchers') as b:
        # Set nullable to False now that we've set values
        b.alter_column('watch_issues', nullable=False)
        b.alter_column('watch_commits', nullable=False)
        # Remove the watch column
        b.drop_column('watch') 
Example #12
Source File: 8f966b9c467a_set_conn_type_as_non_nullable.py    From airflow with Apache License 2.0 6 votes vote down vote up
def upgrade():
    """Apply Set conn_type as non-nullable"""

    Base = declarative_base()

    class Connection(Base):
        __tablename__ = "connection"

        id = sa.Column(sa.Integer(), primary_key=True)
        conn_id = sa.Column(sa.String(250))
        conn_type = sa.Column(sa.String(500))

    # Generate run type for existing records
    connection = op.get_bind()
    sessionmaker = sa.orm.sessionmaker()
    session = sessionmaker(bind=connection)

    # imap_default was missing it's type, let's fix that up
    session.query(Connection).filter_by(conn_id="imap_default", conn_type=None).update(
        {Connection.conn_type: "imap"}, synchronize_session=False
    )
    session.commit()

    with op.batch_alter_table("connection", schema=None) as batch_op:
        batch_op.alter_column("conn_type", existing_type=sa.VARCHAR(length=500), nullable=False) 
Example #13
Source File: 55f89221fc55_email_index.py    From kansha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def upgrade():
    # first, find and merge duplicates
    # then, set unique index
    bind = op.get_bind()
    select = sa.text('select email from "user" where email is not null group by email having count(*) > 1')
    for email in bind.execute(select):
        same_users = bind.execute(users.select().where(users.c.email == email[0]).order_by('registration_date')).fetchall()
        kept_user = same_users.pop()
        for obsolete_user in same_users:
            merge_users(bind, obsolete_user, kept_user)
            bind.execute(users.delete().where(
                and_(
                    users.c.username == obsolete_user.username,
                    users.c.source == obsolete_user.source)))
    # phantom users, lost forever...
    bind.execute(users.update().where(users.c.email == None).values(email_to_confirm=None))
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_email'), ['email'], unique=True)
        batch_op.create_index(batch_op.f('ix_email_to_confirm'), ['email_to_confirm'], unique=True) 
Example #14
Source File: 26341fb32054_add_custom_puppet_support.py    From mautrix-facebook with GNU Affero General Public License v3.0 5 votes vote down vote up
def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('puppet') as batch_op:
        batch_op.drop_column('custom_mxid')
        batch_op.drop_column('access_token')
    # ### end Alembic commands ### 
Example #15
Source File: 2e9d99288cd_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user') as batch_op:
        batch_op.alter_column('created',
               existing_type=sa.DATETIME(),
               nullable=False)
        batch_op.alter_column('updated',
               existing_type=sa.DATETIME(),
               nullable=False)
    ### end Alembic commands ### 
Example #16
Source File: 2e9d99288cd_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user') as batch_op:
        batch_op.alter_column('updated',
               existing_type=sa.DATETIME(),
               nullable=True)
        batch_op.alter_column('created',
               existing_type=sa.DATETIME(),
               nullable=True)
    ### end Alembic commands ### 
Example #17
Source File: 8e0f1142c8d5_store_custom_puppet_next_batch_in_.py    From mautrix-facebook with GNU Affero General Public License v3.0 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table("puppet") as batch_op:
        batch_op.drop_column("next_batch") 
Example #18
Source File: 244273a86d81_re_add_user_agent_to_db.py    From mautrix-facebook with GNU Affero General Public License v3.0 5 votes vote down vote up
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.add_column(sa.Column('user_agent', sa.String(length=255), nullable=True))

    # ### end Alembic commands ### 
Example #19
Source File: c56c9a30b228_add_end_to_bridge_encryption_fields.py    From mautrix-facebook with GNU Affero General Public License v3.0 5 votes vote down vote up
def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('portal') as batch_op:
        batch_op.drop_column('encrypted')
    op.drop_table('nio_outgoing_key_request')
    op.drop_table('nio_olm_session')
    op.drop_table('nio_megolm_inbound_session')
    op.drop_table('nio_device_key')
    op.drop_table('nio_account')
    # ### end Alembic commands ### 
Example #20
Source File: 20160831125422_add_drug_name_active_ingredients_and_company_to_fda_dap.py    From collectors with MIT License 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table('fda_dap') as batch_op:
        batch_op.drop_column('drug_name')
        batch_op.drop_column('active_ingredients')
        batch_op.drop_column('company') 
Example #21
Source File: 82184d7d1e88_altered-OAuth2Token-token_type-to-Enum.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def downgrade():
    connection = op.get_bind()

    with op.batch_alter_table('oauth2_token') as batch_op:
        batch_op.alter_column('token_type',
               existing_type=sa.Enum('Bearer', name='tokentypes'),
               type_=sa.VARCHAR(length=40),
               existing_nullable=False)

    tokentypes = sa.dialects.postgresql.ENUM('Bearer', name='tokentypes')
    tokentypes.drop(connection) 
Example #22
Source File: 357c2809db4_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table('team_member') as batch_op:
        batch_op.alter_column('is_leader',
               existing_type=sa.BOOLEAN(),
               nullable=True) 
Example #23
Source File: 357c2809db4_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def upgrade():
    with op.batch_alter_table('team_member') as batch_op:
        batch_op.alter_column('is_leader',
               existing_type=sa.BOOLEAN(),
               nullable=False) 
Example #24
Source File: 4754e1427ac_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table('team_member') as batch_op:
        batch_op.drop_column('is_leader')
    op.rename_table('team_member', 'team_members') 
Example #25
Source File: 8c8b2d23a5_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table('team_member') as batch_op:
        batch_op.drop_constraint('_team_user_uc', type_='unique') 
Example #26
Source File: 8c8b2d23a5_.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def upgrade():
    with op.batch_alter_table('team_member') as batch_op:
        batch_op.create_unique_constraint('_team_user_uc', ['team_id', 'user_id']) 
Example #27
Source File: 361f9cbae3fc_rename_board_archive.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table('board') as batch_op:
        batch_op.alter_column('show_archive', new_column_name='archive') 
Example #28
Source File: 361f9cbae3fc_rename_board_archive.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def upgrade():
    with op.batch_alter_table('board') as batch_op:
        batch_op.alter_column('archive', new_column_name='show_archive') 
Example #29
Source File: 7fcaf5b6e9e8_add_request_and_response_to_command.py    From chainerui with MIT License 5 votes vote down vote up
def upgrade():
    with op.batch_alter_table('command') as batch_op:
        batch_op.add_column(sa.Column('request', sa.String(1024)))
        batch_op.add_column(sa.Column('response', sa.String(1024)))
        batch_op.drop_column('body') 
Example #30
Source File: 9d002f65344b_add_crawlable.py    From chainerui with MIT License 5 votes vote down vote up
def downgrade():
    with op.batch_alter_table('project') as batch_op:
        batch_op.drop_column('crawlable')

    with op.batch_alter_table('result') as batch_op:
        batch_op.drop_column('crawlable')