Search code examples
pythonsqlpython-3.xsqlalchemyalembic

Run alembic operations manually by code, using an sqlalchemy engine


I invested some time to understand Alemic, how I could run migrations manually without any setup. Due to some reasons we need that, we need to be able to execute operations manually without init, ini files or execution context.


Solution

  • Here is my result:

    import sqlalchemy
    
    from alembic.migration import MigrationContext
    from alembic.operations import Operations
    
    
    # Connection
    connection_string = 'postgres://xx:@localhost/xxdb'
    engine = sqlalchemy.create_engine(connection_string.replace('postgres://', 'postgresql://'))
    
    # Create migration context
    mc = MigrationContext.configure(engine.connect())
    
    # Creation operations object
    ops = Operations(mc)
    
    
    # Add column
    try:
        ops.add_column('record', sqlalchemy.Column('new_column', sqlalchemy.String))
    except Exception as ex:
        print(ex)
    
    # Create table
    try:
        ops.create_table('new_table', [
            sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
            sqlalchemy.Column('name', sqlalchemy.String)
        ])
    except Exception as ex:
        print(ex)
    

    It lets you run any alembic operation without needing all the stuff around. I just wanted to share that, since it's really hard to get complete examples about it online.