Spaces:
Paused
Paused
Download scripts/validate_supabase_setup.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/validate_supabase_setup.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/scripts/validate_supabase_setup.py
-
curl -L -o validate_supabase_setup.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/validate_supabase_setup.py
11.1 kB
| #!/usr/bin/env python3 | |
| """ | |
| Quick validation script for Supabase setup. | |
| Tests basic functionality without running full integration tests. | |
| """ | |
| import os | |
| import sys | |
| import asyncio | |
| import logging | |
| from pathlib import Path | |
| from uuid import uuid4 | |
| # Add project root to path | |
| project_root = Path(__file__).parent.parent | |
| sys.path.insert(0, str(project_root)) | |
| from shared.supabase_config import supabase_config, get_supabase_client | |
| from shared.database import SupabaseManager | |
| from shared.models import UserContext | |
| from shared.config import settings | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| async def validate_environment(): | |
| """Validate environment configuration.""" | |
| logger.info("π Validating environment configuration...") | |
| required_vars = ['supabase_url', 'supabase_anon_key', 'supabase_service_role_key'] | |
| missing_vars = [] | |
| for var in required_vars: | |
| if not getattr(settings, var, None): | |
| missing_vars.append(var.upper()) | |
| if missing_vars: | |
| logger.error(f"β Missing environment variables: {', '.join(missing_vars)}") | |
| return False | |
| logger.info("β Environment configuration is valid") | |
| return True | |
| async def validate_connection(): | |
| """Validate Supabase connection.""" | |
| logger.info("π Testing Supabase connection...") | |
| try: | |
| await supabase_config.initialize() | |
| health_status = await supabase_config.health_check() | |
| if health_status: | |
| logger.info("β Supabase connection successful") | |
| return True | |
| else: | |
| logger.error("β Supabase health check failed") | |
| return False | |
| except Exception as e: | |
| logger.error(f"β Connection failed: {e}") | |
| return False | |
| async def validate_database_schema(): | |
| """Validate that required tables exist.""" | |
| logger.info("π Validating database schema...") | |
| try: | |
| client = await get_supabase_client(use_service_role=True) | |
| required_tables = [ | |
| 'users', | |
| 'analysis_sessions', | |
| 'user_datasets', | |
| 'hypotheses', | |
| 'hypothesis_results', | |
| 'trained_models', | |
| 'progress_events', | |
| 'business_recommendations' | |
| ] | |
| missing_tables = [] | |
| for table in required_tables: | |
| try: | |
| result = await asyncio.to_thread( | |
| client.table(table).select('count').limit(1).execute | |
| ) | |
| logger.info(f"β Table '{table}' exists and is accessible") | |
| except Exception as e: | |
| logger.error(f"β Table '{table}' not accessible: {e}") | |
| missing_tables.append(table) | |
| if missing_tables: | |
| logger.error(f"β Missing or inaccessible tables: {', '.join(missing_tables)}") | |
| return False | |
| logger.info("β Database schema validation successful") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β Schema validation failed: {e}") | |
| return False | |
| async def validate_user_operations(): | |
| """Validate basic user operations.""" | |
| logger.info("π€ Testing user operations...") | |
| try: | |
| db_manager = SupabaseManager() | |
| await db_manager.initialize() | |
| # Create test user context | |
| test_user = UserContext( | |
| user_id=f"test_validation_{uuid4().hex[:8]}", | |
| email="validation@test.com", | |
| permissions=["read_data", "write_data"] | |
| ) | |
| # Test user creation | |
| created = await db_manager.create_user_if_not_exists(test_user) | |
| if created: | |
| logger.info("β User creation successful") | |
| else: | |
| logger.info("β User already exists (expected)") | |
| # Test session creation | |
| session_data = { | |
| 'name': 'Validation Test Session', | |
| 'business_context': 'Testing basic operations' | |
| } | |
| session_id = await db_manager.create_analysis_session(test_user, session_data) | |
| logger.info(f"β Analysis session created: {session_id}") | |
| # Test session retrieval | |
| session = await db_manager.get_analysis_session(test_user, session_id) | |
| if session and session['name'] == 'Validation Test Session': | |
| logger.info("β Session retrieval successful") | |
| else: | |
| logger.error("β Session retrieval failed") | |
| return False | |
| # Test session update | |
| updates = {'status': 'running', 'progress_percentage': 50} | |
| success = await db_manager.update_analysis_session(test_user, session_id, updates) | |
| if success: | |
| logger.info("β Session update successful") | |
| else: | |
| logger.error("β Session update failed") | |
| return False | |
| logger.info("β User operations validation successful") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β User operations validation failed: {e}") | |
| return False | |
| async def validate_real_time(): | |
| """Validate real-time functionality.""" | |
| logger.info("π‘ Testing real-time functionality...") | |
| try: | |
| from shared.supabase_config import broadcast_progress | |
| test_user_id = f"test_realtime_{uuid4().hex[:8]}" | |
| test_session_id = str(uuid4()) | |
| # Broadcast a test progress event | |
| await broadcast_progress( | |
| user_id=test_user_id, | |
| session_id=test_session_id, | |
| event_type="validation_test", | |
| stage="testing", | |
| progress_percentage=100, | |
| message="Real-time validation test", | |
| details={"test": True} | |
| ) | |
| # Verify the event was stored | |
| client = await get_supabase_client(use_service_role=True) | |
| result = await asyncio.to_thread( | |
| client.table('progress_events') | |
| .select('*') | |
| .eq('session_id', test_session_id) | |
| .eq('user_id', test_user_id) | |
| .execute | |
| ) | |
| if result.data and len(result.data) > 0: | |
| event = result.data[0] | |
| if (event['event_type'] == 'validation_test' and | |
| event['stage'] == 'testing' and | |
| event['progress_percentage'] == 100): | |
| logger.info("β Real-time event broadcasting successful") | |
| return True | |
| else: | |
| logger.error("β Real-time event data mismatch") | |
| return False | |
| else: | |
| logger.error("β Real-time event not found in database") | |
| return False | |
| except Exception as e: | |
| logger.error(f"β Real-time validation failed: {e}") | |
| return False | |
| async def validate_rls_policies(): | |
| """Validate Row Level Security policies.""" | |
| logger.info("π Testing Row Level Security policies...") | |
| try: | |
| # Note: Full RLS testing requires authenticated clients | |
| # This is a basic test to ensure RLS is enabled | |
| client = await get_supabase_client(use_service_role=True) | |
| # Check that RLS is enabled on key tables | |
| rls_tables = ['users', 'analysis_sessions', 'user_datasets', 'hypotheses'] | |
| for table in rls_tables: | |
| try: | |
| # This query should work with service role | |
| result = await asyncio.to_thread( | |
| client.table(table).select('count').limit(1).execute | |
| ) | |
| logger.info(f"β RLS table '{table}' accessible with service role") | |
| except Exception as e: | |
| logger.error(f"β RLS table '{table}' not accessible: {e}") | |
| return False | |
| logger.info("β RLS policies validation successful") | |
| logger.info("βΉοΈ Note: Full RLS testing requires authenticated user tokens") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β RLS validation failed: {e}") | |
| return False | |
| async def cleanup_test_data(): | |
| """Clean up test data created during validation.""" | |
| logger.info("π§Ή Cleaning up test data...") | |
| try: | |
| client = await get_supabase_client(use_service_role=True) | |
| # Clean up test users | |
| await asyncio.to_thread( | |
| client.table('users') | |
| .delete() | |
| .like('clerk_user_id', 'test_validation_%') | |
| .execute | |
| ) | |
| # Clean up test progress events | |
| await asyncio.to_thread( | |
| client.table('progress_events') | |
| .delete() | |
| .like('user_id', 'test_realtime_%') | |
| .execute | |
| ) | |
| logger.info("β Test data cleanup completed") | |
| except Exception as e: | |
| logger.warning(f"β οΈ Test data cleanup failed (non-critical): {e}") | |
| async def main(): | |
| """Main validation function.""" | |
| logger.info("π Starting Supabase setup validation") | |
| validation_steps = [ | |
| ("Environment Configuration", validate_environment), | |
| ("Database Connection", validate_connection), | |
| ("Database Schema", validate_database_schema), | |
| ("User Operations", validate_user_operations), | |
| ("Real-time Functionality", validate_real_time), | |
| ("Row Level Security", validate_rls_policies), | |
| ] | |
| passed_steps = 0 | |
| total_steps = len(validation_steps) | |
| for step_name, step_function in validation_steps: | |
| logger.info(f"\nπ Step: {step_name}") | |
| try: | |
| if await step_function(): | |
| passed_steps += 1 | |
| else: | |
| logger.error(f"β Step failed: {step_name}") | |
| except Exception as e: | |
| logger.error(f"β Step error: {step_name} - {e}") | |
| # Cleanup test data | |
| await cleanup_test_data() | |
| # Summary | |
| logger.info(f"\nπ Validation Summary:") | |
| logger.info(f"Passed: {passed_steps}/{total_steps} steps") | |
| if passed_steps == total_steps: | |
| logger.info("π All validation steps passed! Supabase setup is working correctly.") | |
| logger.info("\nNext steps:") | |
| logger.info("1. Run full integration tests: python -m pytest tests/test_supabase_integration.py") | |
| logger.info("2. Configure Clerk authentication integration") | |
| logger.info("3. Test the complete MCP pipeline") | |
| return True | |
| else: | |
| logger.error(f"β {total_steps - passed_steps} validation steps failed.") | |
| logger.error("Please check the errors above and fix the issues before proceeding.") | |
| return False | |
| if __name__ == "__main__": | |
| success = asyncio.run(main()) | |
| sys.exit(0 if success else 1) |