The solution to allowing nulls in a unique field is:
- Don't create the unique constraint when defining the column
op.add_column(
'TABLE', sa.Column('reference', sa.Integer(), nullable=True), # No unique=True
)
- Create a unique index manually
op.create_index(
'uq_reference_allow_nulls', table_name='TABLE', columns=['reference'],
mssql_where=sa.text('reference IS NOT NULL'), unique=True,
)
- Remove the index when downgrading.
op.drop_index('uq_reference_allow_nulls', table_name='TABLE')
This also solves the problem of having a randomized unique constraint on the table because the unique
parameter is removed. All together the alembic revision looks like this:
from alembic import op
import sqlalchemy as sa
#...
def upgrade():
op.add_column(
'TABLE', sa.Column('reference', sa.Integer(), nullable=True), # Do not include unique here
)
op.create_index(
'uq_reference_allow_nulls', table_name='TABLE', columns=['reference'],
mssql_where=sa.text('reference IS NOT NULL'), unique=True,
)
def downgrade():
op.drop_index('uq_reference_allow_nulls', table_name='TABLE')
op.drop_column('TABLE', 'reference')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…