from sqlalchemy import text from app.core.database import async_engine as engine import asyncio import logging # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def patch_schema(): logger.info("🔧 Starting manual schema patch...") async with engine.begin() as conn: # 1. Add Stripe Fields to Tenants logger.info("Checking/Adding Stripe fields...") await conn.execute(text(""" DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='stripe_customer_id') THEN ALTER TABLE tenants ADD COLUMN stripe_customer_id TEXT; CREATE INDEX ix_tenants_stripe_customer_id ON tenants (stripe_customer_id); RAISE NOTICE 'Added stripe_customer_id'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='stripe_subscription_id') THEN ALTER TABLE tenants ADD COLUMN stripe_subscription_id TEXT; RAISE NOTICE 'Added stripe_subscription_id'; END IF; END $$; """)) # 2. Fix Embedding Dimension # Note: This might fail if data is incompatible, but intended for fixing schema mismatch. logger.info("Fixing Embedding dimension (384 -> 1536)...") try: await conn.execute(text(""" ALTER TABLE knowledge_base ALTER COLUMN embedding TYPE vector(1536) USING embedding::vector(1536); """)) logger.info("✅ Embedding dimension updated to 1536.") except Exception as e: logger.warning(f"⚠️ Could not update embedding dimension (might already be 1536 or PGVector issue): {e}") # 3. Add Meta Config Columns (from failed migration) # meta_wa_config, meta_ig_config logger.info("Checking/Adding Meta Config fields...") await conn.execute(text(""" DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='meta_wa_config') THEN ALTER TABLE tenants ADD COLUMN meta_wa_config JSON; RAISE NOTICE 'Added meta_wa_config'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='meta_ig_config') THEN ALTER TABLE tenants ADD COLUMN meta_ig_config JSON; RAISE NOTICE 'Added meta_ig_config'; END IF; IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='google_calendar_config') THEN ALTER TABLE tenants ADD COLUMN google_calendar_config JSON; RAISE NOTICE 'Added google_calendar_config'; END IF; END $$; """)) logger.info("🎉 Schema patch completed successfully.") if __name__ == "__main__": asyncio.run(patch_schema())