Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set column order in alembic when adding a new column

I'm struggling to find a clean way (without raw SQL) to set the column order in alembic. For example, I would like to put a new column called 'name' after the 'id' column, something like this:

from alembic import op
import sqlalchemy as sa

...

op.add_column(
    'people',
    sa.Column(
        'name',
        sa.String(),
        nullable=False
    ),
    after='id'
)

But of course, alembic does not have the 'after' parameter, therefore this code fails and I have not found an equivalent to this 'after' parameter in the docs. I'm only able to append the column at the end of the table.

Can anybody suggest how to achieve in alembic/sqlalchemy what I want? Is it possible without raw SQL?

like image 250
Rafael K. Avatar asked Dec 01 '25 01:12

Rafael K.


1 Answers

alembic version 1.4.0 or higher supports this feature.

use the batch operation to achieve it.

from alembic import op
import sqlalchemy as sa

with op.batch_alter_table("people") as batch_op:
  batch_op.add_column(
    Column("name", sa.String(50)),
    insert_after="id"
  )

Reference: https://alembic.sqlalchemy.org/en/latest/ops.html?highlight=insert_after#alembic.operations.BatchOperations.add_column

like image 151
anjaneyulubatta505 Avatar answered Dec 02 '25 14:12

anjaneyulubatta505



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!