Adding a Column to a Database Table with Alembic and SQLAlchemy

  • Share this:

Code introduction


This function uses Alembic and SQLAlchemy to add a new column to a specified database table.


Technology Stack : Alembic, SQLAlchemy

Code Type : Function

Code Difficulty : Intermediate


                
                    
from alembic import op
from sqlalchemy import Column, Integer, String, MetaData, Table

def add_column_to_table(table_name, column_name, column_type):
    """
    This function adds a new column to a specified table using Alembic's op and sqlalchemy.
    """
    meta = MetaData()
    table = Table(table_name, meta, autoload_with=op.get_bind())
    
    op.add_column(table, Column(column_name, column_type))