"""order_items name snapshots (product_name, category_id, category_name) (D-18, step 1.12) Hand-edited: product_name is added nullable, back-filled from the CURRENT catalogue (the best a v2 DB can know; v1 history comes through the migration tool, plan 7.1), then made NOT NULL. Items of deleted products get "#". Revision ID: 0011_order_item_names Revises: 0010_notifications Create Date: 2026-11-13 11:29:59.346931 """ from alembic import op import sqlalchemy as sa revision = '0011_order_item_names' down_revision = '0010_notifications' branch_labels = None depends_on = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('order_items', schema=None) as batch_op: batch_op.add_column(sa.Column('product_name', sa.String(), nullable=True)) batch_op.add_column(sa.Column('category_id', sa.Integer(), nullable=True)) batch_op.add_column(sa.Column('category_name', sa.String(), nullable=True)) batch_op.create_index(batch_op.f('ix_order_items_category_id'), ['category_id'], unique=False) # ### end Alembic commands ### op.execute(""" UPDATE order_items SET product_name = COALESCE((SELECT p.name FROM products p WHERE p.id = order_items.product_id), '#' || order_items.product_id), category_id = (SELECT p.category_id FROM products p WHERE p.id = order_items.product_id) """) op.execute(""" UPDATE order_items SET category_name = (SELECT c.name FROM categories c WHERE c.id = order_items.category_id) WHERE category_id IS NOT NULL """) with op.batch_alter_table('order_items', schema=None) as batch_op: batch_op.alter_column('product_name', existing_type=sa.String(), nullable=False) def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('order_items', schema=None) as batch_op: batch_op.drop_index(batch_op.f('ix_order_items_category_id')) batch_op.drop_column('category_name') batch_op.drop_column('category_id') batch_op.drop_column('product_name') # ### end Alembic commands ###