3

I have a table where I need to add column say a_1 after column a and the table structure is like column a,b,c,d? How can i add this?

Below query adds column after d but I want to add column after a?

def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('sample_table', sa.Column('a_1', mysql.JSON(), nullable=True, ))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('sample_table', 'a_1')
# ### end Alembic commands ###
  • 3
    Class `alembic.operations.BatchOperations` has a method `add_column(column, insert_before=None, insert_after=None)`. https://alembic.sqlalchemy.org/en/latest/ops.html – Akina Mar 19 '21 at 07:59

1 Answers1

-4
add_column(table_name, column, schema=None)

Issue an “add column” instruction using the current migration context.

e.g.:

from alembic import op
from sqlalchemy import Column, String

op.add_column('organization',
    Column('name', String())
)

The provided Column object can also specify a ForeignKey, referencing a remote table name. Alembic will automatically generate a stub “referenced” table and emit a second ALTER statement in order to add the constraint separately:

from alembic import op
from sqlalchemy import Column, INTEGER, ForeignKey

op.add_column('organization',
    Column('account_id', INTEGER, ForeignKey('accounts.id'))
)

Note that this statement uses the Column construct as is from the SQLAlchemy library. In particular, default values to be created on the database side are specified using the server_default parameter, and not default which only specifies Python-side defaults:

from alembic import op
from sqlalchemy import Column, TIMESTAMP, func

# specify "DEFAULT NOW" along with the column add
op.add_column('account',
    Column('timestamp', TIMESTAMP, server_default=func.now())
)

Parameters table_name – String name of the parent table.

column – a sqlalchemy.schema.Column object representing the new column.

schema – Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct quoted_name.

Source https://alembic.sqlalchemy.org/en/latest/ops.html

Biobo
  • 1
  • 2