Getting sqlalchemy.migrate to rename a column with primary key

2.2k views Asked by At

I am trying to rename a column in a table which has the primary key constraint to an another name and add a new column with a new type becoming the primary key.

So currently I have :

  TABLE (
     `id` VARCHAR(36) PRIMARY_KEY,
  ) table;

I want to rename id to uuid and add a new id as a integer which would become the primary key :

 TABLE (
   `id` integer PRIMARY_KEY, AUTO_INCRREMENT,
   `uuid` VARCHAR(36)
 ) table;

Trying to do that with sqlalchemy.migrate :

table = sqlalchemy.Table('table', meta, autoload=True)
event.c.id.alter(name='uuid')
id = sqlalchemy.Column('id', sqlalchemy.Integer(),
                        primary_key=True)
event_uuid.create(event)

result with this error in postgres since the primary key constraint wasn't removed from the old id :

ERROR: Column.create() accepts index_name, primary_key_name and unique_name to generate constraints

If somebody have an idea how to do that

1

There are 1 answers

0
Chmouel Boudjnah On BEST ANSWER

It was actually not too hard after reading the source code of sqlalchemy.migrate , you need first to drop the constraints simply by accessing it directly :

pk = constraint.PrimaryKeyConstraint('id',
                                     table=table,
                                     name="table_pkey")

pk.drop()

and when creating just add primary_key_name to the create method :

primary_id.create(table=table, primary_key_name='table_pkey')

which would get you the primary key on the newly created id column