Unfortunately there's no RENAME CONSTRAINT directive, so dropping and
recreating is how it has to go.
Alembic and SQLAlchemy together do have the ability to return lists of
constraints and produce CREATE instructions for them. Recently I did
some of this related to foreign keys, and the same idea would apply to
indexes, unique constraints, CHECK constraints. Here's two ways to
do that to give you some ideas:
from alembic.operations.ops import CreateForeignKeyOp
from alembic.migration import MigrationContext
from alembic.operations import Operations
with engine.connect() as conn:
ctx = MigrationContext.configure(conn)
op = Operations(ctx)
m = MetaData(naming_convention={...})
t = Table(table_name, m, autoload_with=conn)
for fk in t.foreign_keys:
op.drop_constraint(
fk.name, table_name, type_="foreignkey")
# give fk the name we want
fk.name = "somename"
# or name it None to get the naming convention
#
fk.name = None
create_fk = CreateForeignKeyOp.from_constraint(fk)
op.invoke(create_fk)
or using the inspector, more manual / explicit:
from sqlalchemy import inspect
with engine.connect() as conn:
ctx = MigrationContext.configure(conn)
op = Operations(ctx)
insp = inspect(conn)
for fk in insp.get_foreign_keys(table_name):
for fk in fks:
op.drop_constraint(
fk['name'], fk['source_table'], type_="foreignkey")
for fk in fks:
op.create_foreign_key(
fk['name'], fk['source_table'],
fk['referred_table'],
fk['constrained_columns'],
fk['referred_columns'],
onupdate=fk['options'].get('onupdate'),
ondelete=fk['options'].get('ondelete'),
deferrable=fk['options'].get('deferrable'),
initially=fk['options'].get('initially'),
)
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy-alembic" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to
sqlalchemy-alem...@googlegroups.com.
> For more options, visit
https://groups.google.com/d/optout.