"""Удаление lab_component_nutrients — только EAV lab_component_nutrient_value. Revision ID: drop_lab_component_nutrients Revises: org_settings_normalize Create Date: 2026-06-08 """ from __future__ import annotations import uuid import sqlalchemy as sa from alembic import op revision = "drop_lab_component_nutrients" down_revision = "org_settings_normalize" branch_labels = None depends_on = None _SUMMARY_TO_HEADER = { "crude_protein": "Сыр. Протеин", "usp": "уСП", "bra": "БРА", "nel_cattle": "ЧЭЛ- КРС", "oe_cattle": "ОЭ-КРС", "ndf": "Сырая клетч", "structural_fiber": "Структур клетч", "crude_fat": "Сырой жир", } def _migrate_summary_to_eav(bind) -> None: insp = sa.inspect(bind) if "lab_component_nutrients" not in insp.get_table_names(): return if "lab_component_nutrient_value" not in insp.get_table_names(): return rows = bind.execute( sa.text( """ SELECT component_id, crude_protein, usp, bra, nel_cattle, oe_cattle, ndf, structural_fiber, crude_fat FROM lab_component_nutrients """ ) ).fetchall() for row in rows: comp_id = row[0] for i, header in enumerate(_SUMMARY_TO_HEADER.values()): val = row[i + 1] if val is None: continue bind.execute( sa.text( """ INSERT INTO lab_component_nutrient_value (id, component_id, nutrient_key, value) VALUES (:id, :component_id, :nutrient_key, :value) ON CONFLICT(component_id, nutrient_key) DO NOTHING """ ), { "id": str(uuid.uuid4()), "component_id": comp_id, "nutrient_key": header, "value": val, }, ) def upgrade(**kw) -> None: if kw.get("tag") == "reports": return bind = op.get_bind() _migrate_summary_to_eav(bind) insp = sa.inspect(bind) if "lab_component_nutrients" in insp.get_table_names(): op.drop_table("lab_component_nutrients") def downgrade(**kw) -> None: if kw.get("tag") == "reports": return bind = op.get_bind() if "lab_component_nutrients" not in sa.inspect(bind).get_table_names(): op.create_table( "lab_component_nutrients", sa.Column("component_id", sa.String(length=36), primary_key=True), sa.Column("crude_protein", sa.Float(), nullable=True), sa.Column("usp", sa.Float(), nullable=True), sa.Column("bra", sa.Float(), nullable=True), sa.Column("nel_cattle", sa.Float(), nullable=True), sa.Column("oe_cattle", sa.Float(), nullable=True), sa.Column("ndf", sa.Float(), nullable=True), sa.Column("structural_fiber", sa.Float(), nullable=True), sa.Column("crude_fat", sa.Float(), nullable=True), )