"""Small production-schema compatibility helpers. The project has legacy production databases where some columns may not exist yet. Use these helpers before introducing optional-column SQL in UI/services. """ from __future__ import annotations from functools import lru_cache from sqlalchemy import text from app.db import engine @lru_cache(maxsize=256) def has_column(table_name: str, column_name: str, schema_name: str = "public") -> bool: table_name = str(table_name or "").strip() column_name = str(column_name or "").strip() schema_name = str(schema_name or "public").strip() or "public" if not table_name or not column_name: return False with engine.begin() as conn: return bool(conn.execute(text(""" SELECT 1 FROM information_schema.columns WHERE table_schema = :schema_name AND table_name = :table_name AND column_name = :column_name LIMIT 1 """), { "schema_name": schema_name, "table_name": table_name, "column_name": column_name, }).scalar()) def opportunity_customer_column() -> str: """Return the customer link column supported by this deployment.""" if has_column("opportunities", "fiscal_customer_id"): return "fiscal_customer_id" return "local_customer_id"