add column to SQLAlchemy Table

Solution 1:

I have the same problem, and a thought of using migration library only for this trivial thing makes me
tremble. Anyway, this is my attempt so far:

def add_column(engine, table_name, column):
    column_name = column.compile(dialect=engine.dialect)
    column_type = column.type.compile(engine.dialect)
    engine.execute('ALTER TABLE %s ADD COLUMN %s %s' % (table_name, column_name, column_type))

column = Column('new_column_name', String(100), primary_key=True)
add_column(engine, table_name, column)

Still, I don't know how to insert primary_key=True into raw SQL request.

Solution 2:

This is referred to as database migration (SQLAlchemy doesn't support migration out of the box). You can look at using sqlalchemy-migrate to help in these kinds of situations, or you can just ALTER TABLE through your chosen database's command line utility,

Solution 3:

See this section of the SQLAlchemy documentation: http://docs.sqlalchemy.org/en/latest/core/metadata.html#altering-schemas-through-migrations

Alembic is the latest software to offer this type of functionality and is made by the same author as SQLAlchemy.

Solution 4:

I have a database called "ncaaf.db" built with sqlite3 and a table called "games". So I would CD into the same directory on my linux command prompt and do

sqlite3 ncaaf.db
alter table games add column q4 type float

and that is all it takes! Just make sure you update your definitions in your sqlalchemy code.