Reputation: 2363
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?
Upvotes: 19
Views: 7421
Reputation: 11665
alembic version 1.4.0 or higher supports this feature.
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"
)
Upvotes: 4
Reputation: 611
Slice them into separate nested lists, ending at the column before the inserted column ( so in this case, create a one nested list that ends at the "id" column.
Let's call that variable id_col
Now, you can either use the "extend" built-in or "append" to add the "name" column right after the id column.
You can also add the nested lists to end up with a final single data structure that has what you're looking for.
The emphasis, here, being, that you do not have to be constrained by exclusively using your SQL table format. You can convert it into a a nested list and then once combined using list methods, reconvert them back into your desired SQL table.
Upvotes: 0