JhHardwareWRS_BackPoint/scripts/migrate_product_erp_aux_fields.py
2026-06-24 15:19:14 +08:00

42 lines
1.2 KiB
Python

from pathlib import Path
import sys
from sqlalchemy import text
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.database import engine # noqa: E402
FIELDS = [
("product_net_weight_kg", "DECIMAL(12,4) NULL", "material_name"),
("product_gross_weight_kg", "DECIMAL(12,4) NULL", "product_net_weight_kg"),
("scrap_loss_rate", "DECIMAL(10,6) NULL", "product_gross_weight_kg"),
("waste_price_yuan_per_kg", "DECIMAL(12,4) NULL", "scrap_loss_rate"),
]
def column_exists(conn, column_name: str) -> bool:
return bool(conn.execute(text("""
SELECT COUNT(1)
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'products'
AND column_name = :column_name
"""), {"column_name": column_name}).scalar())
def main() -> None:
with engine.begin() as conn:
for column_name, column_type, after_column in FIELDS:
if not column_exists(conn, column_name):
conn.execute(text(
f"ALTER TABLE products ADD COLUMN {column_name} {column_type} AFTER {after_column}"
))
print("product ERP auxiliary fields migrated")
if __name__ == "__main__":
main()