I am using the sqlalchemy Table class to load up a data schema I am provided.
Once loaded into sqlalchemy, I want to use some of the existing extensions like:
- ERD plots - eralchemy
- Auto finding relationships using automap
etc.
I am not using any actual DB connection under the table though - i.e. not really going to be generating SQL statements (as of now)
My schema comes from different operations that are fed into the system - like create table, add column, rename column, delete column.
While I was trying to mimic these operations in sqlalchemy, I realized that I need to:
1. Create a MetaData
2. Create the table with a name and add columns to the arguments
3. To add a new column - I can use the extend_existing kwarg in sqlalchemy.Table
But I could not find a way to "drop" or "remove" a column I have added.
To add some code examples:
>>> import sqlalchemy as sqla
>>> mytable = sqla.Table("mytable", sqla.MetaData(), sqla.Column('col1', sqla.String()))
>>> mytable
Table('mytable',
MetaData(bind=None),
Column('col1', String(), table=<mytable>), schema=None)
>>> # Mutating the table to add a column:
>>> sqla.Table("mytable", mytable.metadata, sqla.Column('col2', sqla.String()), extend_existing=True)
Table('mytable',
MetaData(bind=None),
Column('col1', String(), table=<mytable>),
Column('col2', String(), table=<mytable>), schema=None)
>>> # Mutating the table to drop a column:
>>> # What do I do here ?
Table('mytable',
MetaData(bind=None),
Column('col1', String(), table=<mytable>), schema=None)
I can think of 2 approaches:
# Recreate the entire table
mytable.metadata.remove(mytable)
mytable = sqla.Table(
mytable.metadata,
*[i for i in mytable.columns if i.name != 'col2])
# Modify the private _columns collection
mytable._columns.remove(mytable.c['col2'])
I was wondering if there is a correct/compliant way to do this.
PS: I cannot avoid doing a drop column - have to do it as that is an operation that we want to support.