"""将客户身份事实迁移到 ShippingNotice。 用途:支持 Notice 在不依赖 ShippingCase 的情况下完成客户确认、业务编号和履约。 依赖:shipping_notices、shipping_customers、shipping_cases。 逻辑:新增 Notice 客户字段并从历史 Case 回填;旧 Case 外键暂留只读兼容。 """ from __future__ import annotations import sqlalchemy as sa from alembic import op revision = 'ho8p9q0r1s2t' down_revision = 'hn7o8p9q0r1s' branch_labels = None depends_on = None def upgrade() -> None: """新增 Notice 客户字段并回填历史 Case 客户事实。""" inspector = sa.inspect(op.get_bind()) columns = {item['name'] for item in inspector.get_columns('shipping_notices')} with op.batch_alter_table('shipping_notices') as batch: if 'customer_id' not in columns: batch.add_column(sa.Column('customer_id', sa.Integer(), nullable=True)) if 'customer_name_snapshot' not in columns: batch.add_column(sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True)) if 'customer_short_code_snapshot' not in columns: batch.add_column(sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True)) indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} if 'ix_shipping_notices_customer_id' not in indexes: batch.create_index('ix_shipping_notices_customer_id', ['customer_id'], unique=False) foreign_keys = {item.get('name') for item in inspector.get_foreign_keys('shipping_notices')} if 'fk_shipping_notices_customer_id' not in foreign_keys: batch.create_foreign_key( 'fk_shipping_notices_customer_id', 'shipping_customers', ['customer_id'], ['id'], ) bind = op.get_bind() bind.execute(sa.text(""" UPDATE shipping_notices AS n SET customer_id = c.customer_id, customer_name_snapshot = c.customer_name_snapshot, customer_short_code_snapshot = c.customer_short_code_snapshot FROM shipping_cases AS c WHERE n.shipping_case_id = c.id AND n.customer_id IS NULL AND c.customer_id IS NOT NULL """)) def downgrade() -> None: """回滚 Notice 客户字段;历史 Case 字段不受影响。""" with op.batch_alter_table('shipping_notices') as batch: batch.drop_constraint('fk_shipping_notices_customer_id', type_='foreignkey') batch.drop_index('ix_shipping_notices_customer_id') batch.drop_column('customer_short_code_snapshot') batch.drop_column('customer_name_snapshot') batch.drop_column('customer_id')