I need to alter the type of a column with alembic. Currently my code looks like this:
with op.batch_alter_table('annotations', schema=None) as batch_op:
batch_op.alter_column('anno_id', existing_type=sa.Integer(), type_=sa.String(36))
My issue is that anno_id is the table's primary key, and while the code works fine with sqlite, MS SQL rejects the command:
The object 'PK__annotati__2CC37C988C804EF7' is dependent on column 'anno_id'.DB-Lib error message 20018, severity 16
The PK constraint was auto-generated so I can't know in advance what its name is. What do I need to do to identify the constraint and remove and then recreate it after altering the column?
UPDATE, based on Aaron Bertrand's answer below, I was able to do the following in alembic. Unfortunately, as he notes, I couldn't directly alter the column to change it to string type, so I dropped/recreated it.
if context.get_impl().bind.dialect.name == "mssql":
batch_op.execute("""
DECLARE @sql nvarchar(max) = N'',
@table nvarchar(513) = QUOTENAME(N'annotations'),
@column nvarchar(128) = QUOTENAME(N'anno_id');
SELECT @sql += N'ALTER TABLE dbo.'
+ @table + N' DROP CONSTRAINT '
+ QUOTENAME(name) + N';'
FROM sys.key_constraints
WHERE type = N'PK' AND parent_object_id = OBJECT_ID(N'dbo.' + @table);
EXEC sys.sp_executesql @sql;
""")
batch_op.drop_column('anno_id')
batch_op.add_column(sa.Column('anno_id', sa.String(36), nullable=False))
batch_op.create_primary_key('annotations_pkey', ['anno_id'])