"""Products and categories point at the media library (plan step 5.2). products.media_id and categories.media_id (a picture in `media`). The old product photos (products.image_url = /static/product_images/) are copied into the library: each file is processed like an upload (sizes made, kept once by hash, display name = the product's name) and the product points at it. The old folder is left on disk untouched. A file that is missing or unreadable is logged and skipped (the product just has no photo). Then products.image_url goes; apps read `image` / `image_url` (the card size) from the API. Revision ID: 0027_product_media Revises: 0026_media Create Date: 2026-11-17 15:00:00 """ import logging import os from alembic import op import sqlalchemy as sa revision = '0027_product_media' down_revision = '0026_media' branch_labels = None depends_on = None log = logging.getLogger("alembic.0027") OLD_DIR = os.environ.get("XENIA_PRODUCT_IMAGE_DIR", "/app/data/product_images") def upgrade() -> None: with op.batch_alter_table('categories', schema=None) as batch_op: batch_op.add_column(sa.Column('media_id', sa.Integer(), nullable=True)) batch_op.create_index(batch_op.f('ix_categories_media_id'), ['media_id'], unique=False) batch_op.create_foreign_key('fk_categories_media_id_media', 'media', ['media_id'], ['id'], ondelete='SET NULL') with op.batch_alter_table('products', schema=None) as batch_op: batch_op.add_column(sa.Column('media_id', sa.Integer(), nullable=True)) batch_op.create_index(batch_op.f('ix_products_media_id'), ['media_id'], unique=False) batch_op.create_foreign_key('fk_products_media_id_media', 'media', ['media_id'], ['id'], ondelete='SET NULL') _move_photos(op.get_bind()) with op.batch_alter_table('products', schema=None) as batch_op: batch_op.drop_column('image_url') def _move_photos(conn) -> None: rows = conn.execute(sa.text("SELECT id, name, image_url FROM products WHERE image_url IS NOT NULL AND image_url != ''")).fetchall() if not rows: return from core.timeutil import DB_FORMAT, utcnow from services import media as store moved = 0 for pid, name, url in rows: path = os.path.join(OLD_DIR, os.path.basename(url)) if not os.path.isfile(path): log.warning("product %s: photo %s not found, skipped", pid, path) continue try: sha, size, info = store.ingest_path(path) except Exception as e: # refused (type, size) or unreadable log.warning("product %s: photo %s not moved (%s)", pid, path, getattr(e, "code", e)) continue mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar() if mid is None: if not info: # files there from an earlier try, no row store.delete_files(sha) sha, size, info = store.ingest_path(path) conn.execute(sa.text( "INSERT INTO media (kind, name, original_name, content_type, sha256, bytes, width, height, duration_ms, created_at) " "VALUES (:kind, :name, :orig, :ctype, :sha, :bytes, :w, :h, :d, :at)"), {"kind": info["kind"], "name": (name or "photo")[:120], "orig": os.path.basename(path), "ctype": info["content_type"], "sha": sha, "bytes": size, "w": info.get("width"), "h": info.get("height"), "d": info.get("duration_ms"), "at": utcnow().strftime(DB_FORMAT)}) mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar() conn.execute(sa.text("UPDATE products SET media_id = :m WHERE id = :p"), {"m": mid, "p": pid}) moved += 1 log.info("product photos moved into the media library: %d of %d", moved, len(rows)) def downgrade() -> None: with op.batch_alter_table('products', schema=None) as batch_op: batch_op.add_column(sa.Column('image_url', sa.VARCHAR(), nullable=True)) batch_op.drop_constraint('fk_products_media_id_media', type_='foreignkey') batch_op.drop_index(batch_op.f('ix_products_media_id')) batch_op.drop_column('media_id') with op.batch_alter_table('categories', schema=None) as batch_op: batch_op.drop_constraint('fk_categories_media_id_media', type_='foreignkey') batch_op.drop_index(batch_op.f('ix_categories_media_id')) batch_op.drop_column('media_id')