Spaces:
Paused
Paused
File size: 46,901 Bytes
56c063a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 | """
Supabase database connection utilities with user isolation.
Provides secure database operations with row-level security.
"""
import asyncio
import logging
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from datetime import datetime
from supabase import Client
from postgrest.exceptions import APIError
from .config import settings
from .models import UserContext, AnalysisSession, DatasetInfo, Hypothesis, HypothesisResult
from .supabase_config import get_supabase_client, get_authenticated_supabase_client
logger = logging.getLogger(__name__)
async def test_database_connection() -> bool:
"""Test database connectivity."""
try:
client = await get_supabase_client(use_service_role=True)
# Simple health check - try to query a system table
result = await asyncio.to_thread(
client.table('information_schema.tables').select('table_name').limit(1).execute
)
return result.data is not None
except Exception as e:
logger.error(f"Database connection test failed: {e}")
return False
async def get_database_connection():
"""Get database connection context manager."""
# For Supabase, we return the client directly
# This is a compatibility function for the integration tests
client = await get_supabase_client(use_service_role=True)
class DatabaseConnection:
def __init__(self, client):
self.client = client
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
async def fetchval(self, query: str, *args):
"""Execute a query and return a single value."""
# This is a simplified implementation for testing
# In real usage, we'd use Supabase's query methods
if "EXISTS" in query and "information_schema.tables" in query:
# Mock table existence check
table_name = args[0] if args else ""
# Return True for common tables that should exist
return table_name in ['users', 'analysis_sessions', 'user_datasets']
return None
async def fetchrow(self, query: str, *args):
"""Execute a query and return a single row."""
return None
async def execute(self, query: str, *args):
"""Execute a query."""
pass
return DatabaseConnection(client)
class DatabaseError(Exception):
"""Custom database error."""
pass
class UserIsolationError(DatabaseError):
"""Error related to user data isolation."""
pass
class SupabaseManager:
"""
Manages Supabase connections and provides user-isolated database operations.
Implements row-level security to ensure users can only access their own data.
"""
def __init__(self):
self._initialized = False
async def initialize(self):
"""Initialize Supabase clients."""
if self._initialized:
return
try:
# Test connection
client = await get_supabase_client(use_service_role=True)
# Simple health check
await asyncio.to_thread(
client.table('users').select('count').limit(1).execute
)
self._initialized = True
logger.info("Supabase manager initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize Supabase manager: {e}")
raise DatabaseError(f"Database initialization failed: {e}")
async def _get_client(self, use_service_role: bool = False, user_token: Optional[str] = None) -> Client:
"""Get the appropriate Supabase client."""
if not self._initialized:
await self.initialize()
if user_token:
return await get_authenticated_supabase_client(user_token)
else:
return await get_supabase_client(use_service_role)
async def set_user_context(self, user_context: UserContext, use_service_role: bool = False):
"""
Set user context for row-level security.
This ensures all subsequent operations are isolated to the user.
"""
client = self._get_client(use_service_role)
try:
# Set the user context for RLS
await asyncio.to_thread(
client.rpc,
'set_user_context',
{'user_id': user_context.user_id}
)
logger.debug(f"User context set for user: {user_context.user_id}")
except Exception as e:
logger.error(f"Failed to set user context: {e}")
raise UserIsolationError(f"Failed to set user context: {e}")
async def create_user_if_not_exists(self, user_context: UserContext) -> bool:
"""Create user record if it doesn't exist."""
client = self._get_client(use_service_role=True)
try:
# Check if user exists
result = await asyncio.to_thread(
client.table('users').select('id').eq('clerk_user_id', user_context.user_id).execute
)
if result.data:
return False # User already exists
# Create new user
user_data = {
'clerk_user_id': user_context.user_id,
'email': user_context.email,
'created_at': datetime.utcnow().isoformat()
}
await asyncio.to_thread(
client.table('users').insert(user_data).execute
)
logger.info(f"Created new user: {user_context.user_id}")
return True
except Exception as e:
logger.error(f"Failed to create user: {e}")
raise DatabaseError(f"User creation failed: {e}")
async def create_analysis_session(
self,
user_context: UserContext,
session_data: Dict[str, Any]
) -> str:
"""Create a new analysis session."""
await self.set_user_context(user_context)
client = self._get_client()
try:
session_record = {
'user_id': user_context.user_id,
'name': session_data.get('name', 'Untitled Analysis'),
'business_context': session_data.get('business_context', ''),
'status': 'pending',
'started_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('analysis_sessions').insert(session_record).execute
)
if not result.data:
raise DatabaseError("Failed to create analysis session")
session_id = result.data[0]['id']
logger.info(f"Created analysis session: {session_id}")
return session_id
except Exception as e:
logger.error(f"Failed to create analysis session: {e}")
raise DatabaseError(f"Analysis session creation failed: {e}")
async def update_analysis_session(
self,
user_context: UserContext,
session_id: str,
updates: Dict[str, Any]
) -> bool:
"""Update an analysis session."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('analysis_sessions')
.update(updates)
.eq('id', session_id)
.eq('user_id', user_context.user_id) # Ensure user isolation
.execute
)
if not result.data:
raise UserIsolationError(f"Session not found or access denied: {session_id}")
logger.debug(f"Updated analysis session: {session_id}")
return True
except UserIsolationError:
# Re-raise UserIsolationError as-is
raise
except Exception as e:
logger.error(f"Failed to update analysis session: {e}")
raise DatabaseError(f"Analysis session update failed: {e}")
async def get_analysis_session(
self,
user_context: UserContext,
session_id: str
) -> Optional[Dict[str, Any]]:
"""Get an analysis session by ID."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('analysis_sessions')
.select('*')
.eq('id', session_id)
.eq('user_id', user_context.user_id) # Ensure user isolation
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get analysis session: {e}")
raise DatabaseError(f"Failed to retrieve analysis session: {e}")
async def create_dataset(
self,
user_context: UserContext,
dataset_info: DatasetInfo
) -> str:
"""Create a dataset record."""
await self.set_user_context(user_context)
client = self._get_client()
try:
dataset_record = {
'id': str(dataset_info.id),
'user_id': user_context.user_id,
'name': dataset_info.name,
'file_path': dataset_info.file_path,
'metadata': dataset_info.metadata,
'created_at': dataset_info.created_at.isoformat()
}
result = await asyncio.to_thread(
client.table('user_datasets').insert(dataset_record).execute
)
if not result.data:
raise DatabaseError("Failed to create dataset record")
dataset_id = result.data[0]['id']
logger.info(f"Created dataset record: {dataset_id}")
return dataset_id
except Exception as e:
logger.error(f"Failed to create dataset: {e}")
raise DatabaseError(f"Dataset creation failed: {e}")
async def get_dataset(
self,
user_context: UserContext,
dataset_id: str
) -> Optional[Dict[str, Any]]:
"""Get a dataset by ID."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('user_datasets')
.select('*')
.eq('id', dataset_id)
.eq('user_id', user_context.user_id) # Ensure user isolation
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get dataset: {e}")
raise DatabaseError(f"Failed to retrieve dataset: {e}")
async def create_hypothesis(
self,
user_context: UserContext,
hypothesis: Hypothesis
) -> str:
"""Create a hypothesis record."""
await self.set_user_context(user_context)
client = self._get_client()
try:
hypothesis_record = {
'id': str(hypothesis.id),
'user_id': user_context.user_id,
'dataset_id': str(hypothesis.dataset_id),
'text': hypothesis.text,
'test_type': hypothesis.test_type.value,
'variables': hypothesis.variables,
'expected_outcome': hypothesis.expected_outcome,
'python_code': hypothesis.python_code,
'business_relevance': hypothesis.business_relevance,
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('hypotheses').insert(hypothesis_record).execute
)
if not result.data:
raise DatabaseError("Failed to create hypothesis")
hypothesis_id = result.data[0]['id']
logger.info(f"Created hypothesis: {hypothesis_id}")
return hypothesis_id
except Exception as e:
logger.error(f"Failed to create hypothesis: {e}")
raise DatabaseError(f"Hypothesis creation failed: {e}")
async def get_hypothesis(
self,
user_context: UserContext,
hypothesis_id: str
) -> Optional[Dict[str, Any]]:
"""Get a hypothesis by ID."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('hypotheses')
.select('*')
.eq('id', hypothesis_id)
.eq('user_id', user_context.user_id)
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get hypothesis: {e}")
raise DatabaseError(f"Failed to retrieve hypothesis: {e}")
async def get_hypotheses_by_dataset(
self,
user_context: UserContext,
dataset_id: str
) -> List[Dict[str, Any]]:
"""Get all hypotheses for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('hypotheses')
.select('*')
.eq('dataset_id', dataset_id)
.eq('user_id', user_context.user_id)
.order('created_at')
.execute
)
return result.data or []
except Exception as e:
logger.error(f"Failed to get hypotheses: {e}")
raise DatabaseError(f"Failed to retrieve hypotheses: {e}")
async def create_hypothesis_result(
self,
user_context: UserContext,
result: HypothesisResult
) -> str:
"""Create a hypothesis test result."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result_record = {
'hypothesis_id': str(result.hypothesis_id),
'user_id': user_context.user_id,
'p_value': result.p_value,
'is_significant': result.is_significant,
'confidence_interval': list(result.confidence_interval) if result.confidence_interval else None,
'effect_size': result.effect_size,
'interpretation': result.interpretation,
'test_statistic': result.test_statistic,
'created_at': datetime.utcnow().isoformat()
}
result_db = await asyncio.to_thread(
client.table('hypothesis_results').insert(result_record).execute
)
if not result_db.data:
raise DatabaseError("Failed to create hypothesis result")
result_id = result_db.data[0]['id']
logger.info(f"Created hypothesis result: {result_id}")
return result_id
except Exception as e:
logger.error(f"Failed to create hypothesis result: {e}")
raise DatabaseError(f"Hypothesis result creation failed: {e}")
async def get_hypothesis_result(
self,
user_context: UserContext,
hypothesis_id: str
) -> Optional[Dict[str, Any]]:
"""Get hypothesis test result by hypothesis ID."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('hypothesis_results')
.select('*')
.eq('hypothesis_id', hypothesis_id)
.eq('user_id', user_context.user_id)
.order('created_at', desc=True)
.limit(1)
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get hypothesis result: {e}")
raise DatabaseError(f"Failed to retrieve hypothesis result: {e}")
async def get_validated_hypotheses(
self,
user_context: UserContext,
dataset_id: str
) -> List[Dict[str, Any]]:
"""Get all validated (significant) hypotheses for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
# Join hypotheses with their results to get only significant ones
result = await asyncio.to_thread(
client.table('hypotheses')
.select('*, hypothesis_results!inner(*)')
.eq('dataset_id', dataset_id)
.eq('user_id', user_context.user_id)
.eq('hypothesis_results.is_significant', True)
.order('created_at')
.execute
)
return result.data or []
except Exception as e:
logger.error(f"Failed to get validated hypotheses: {e}")
raise DatabaseError(f"Failed to retrieve validated hypotheses: {e}")
async def store_model_result(
self,
user_context: UserContext,
model_data: Dict[str, Any]
) -> str:
"""Store a trained model result."""
await self.set_user_context(user_context)
client = self._get_client()
try:
model_record = {
**model_data,
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('trained_models').insert(model_record).execute
)
if not result.data:
raise DatabaseError("Failed to store model result")
model_id = result.data[0]['id']
logger.info(f"Stored model result: {model_id}")
return model_id
except Exception as e:
logger.error(f"Failed to store model result: {e}")
raise DatabaseError(f"Model result storage failed: {e}")
async def health_check(self) -> bool:
"""Check database connection health."""
try:
client = self._get_client(use_service_role=True)
result = await asyncio.to_thread(
client.table('users').select('count').execute
)
return True
except Exception as e:
logger.error(f"Database health check failed: {e}")
return False
async def store_data_quality_report(
self,
user_context: UserContext,
dataset_id: str,
quality_report: Dict[str, Any]
) -> str:
"""Store a data quality report."""
await self.set_user_context(user_context)
client = self._get_client()
try:
report_record = {
'dataset_id': dataset_id,
'user_id': user_context.user_id,
'missing_values': quality_report.get('missing_values', {}),
'outliers': quality_report.get('outliers', {}),
'data_types': quality_report.get('data_types', {}),
'statistics': quality_report.get('statistics', {}),
'recommendations': quality_report.get('recommendations', []),
'total_rows': quality_report.get('total_rows', 0),
'total_columns': quality_report.get('total_columns', 0),
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('data_quality_reports').insert(report_record).execute
)
if not result.data:
raise DatabaseError("Failed to store data quality report")
report_id = result.data[0]['id']
logger.info(f"Stored data quality report: {report_id}")
return report_id
except Exception as e:
logger.error(f"Failed to store data quality report: {e}")
raise DatabaseError(f"Data quality report storage failed: {e}")
async def get_data_quality_report(
self,
user_context: UserContext,
dataset_id: str
) -> Optional[Dict[str, Any]]:
"""Get the latest data quality report for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('data_quality_reports')
.select('*')
.eq('dataset_id', dataset_id)
.eq('user_id', user_context.user_id)
.order('created_at', desc=True)
.limit(1)
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get data quality report: {e}")
raise DatabaseError(f"Failed to retrieve data quality report: {e}")
async def store_cleaning_operations(
self,
user_context: UserContext,
dataset_id: str,
operations: List[Dict[str, Any]]
) -> List[str]:
"""Store cleaning operations for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
operation_records = []
for op in operations:
record = {
'dataset_id': dataset_id,
'user_id': user_context.user_id,
'operation_type': op.get('operation_type'),
'column_name': op.get('column'),
'parameters': op.get('parameters', {}),
'applied_at': datetime.utcnow().isoformat()
}
operation_records.append(record)
result = await asyncio.to_thread(
client.table('cleaning_operations').insert(operation_records).execute
)
if not result.data:
raise DatabaseError("Failed to store cleaning operations")
operation_ids = [record['id'] for record in result.data]
logger.info(f"Stored {len(operation_ids)} cleaning operations")
return operation_ids
except Exception as e:
logger.error(f"Failed to store cleaning operations: {e}")
raise DatabaseError(f"Cleaning operations storage failed: {e}")
async def store_cleaning_summary(
self,
user_context: UserContext,
original_dataset_id: str,
cleaned_dataset_id: str,
summary_data: Dict[str, Any]
) -> str:
"""Store a cleaning summary."""
await self.set_user_context(user_context)
client = self._get_client()
try:
summary_record = {
'original_dataset_id': original_dataset_id,
'cleaned_dataset_id': cleaned_dataset_id,
'user_id': user_context.user_id,
'operations_applied': summary_data.get('operations_applied', []),
'rows_before': summary_data.get('rows_before', 0),
'rows_after': summary_data.get('rows_after', 0),
'columns_before': summary_data.get('columns_before', 0),
'columns_after': summary_data.get('columns_after', 0),
'transformations': summary_data.get('transformations', []),
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('cleaning_summaries').insert(summary_record).execute
)
if not result.data:
raise DatabaseError("Failed to store cleaning summary")
summary_id = result.data[0]['id']
logger.info(f"Stored cleaning summary: {summary_id}")
return summary_id
except Exception as e:
logger.error(f"Failed to store cleaning summary: {e}")
raise DatabaseError(f"Cleaning summary storage failed: {e}")
async def get_cleaning_operations(
self,
user_context: UserContext,
dataset_id: str
) -> List[Dict[str, Any]]:
"""Get all cleaning operations for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('cleaning_operations')
.select('*')
.eq('dataset_id', dataset_id)
.eq('user_id', user_context.user_id)
.order('applied_at')
.execute
)
return result.data or []
except Exception as e:
logger.error(f"Failed to get cleaning operations: {e}")
raise DatabaseError(f"Failed to retrieve cleaning operations: {e}")
async def store_preprocessing_plan(
self,
user_context: UserContext,
plan_id: str,
dataset_id: str,
plan_data: Dict[str, Any]
) -> str:
"""Store a preprocessing plan."""
await self.set_user_context(user_context)
client = self._get_client()
try:
plan_record = {
'id': plan_id,
'dataset_id': dataset_id,
'user_id': user_context.user_id,
'scaling_operations': plan_data.get('scaling_operations', []),
'encoding_operations': plan_data.get('encoding_operations', []),
'feature_selection': plan_data.get('feature_selection', []),
'target_column': plan_data.get('target_column'),
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('preprocessing_plans').insert(plan_record).execute
)
if not result.data:
raise DatabaseError("Failed to store preprocessing plan")
stored_plan_id = result.data[0]['id']
logger.info(f"Stored preprocessing plan: {stored_plan_id}")
return stored_plan_id
except Exception as e:
logger.error(f"Failed to store preprocessing plan: {e}")
raise DatabaseError(f"Preprocessing plan storage failed: {e}")
async def get_preprocessing_plan(
self,
user_context: UserContext,
plan_id: str
) -> Optional[Dict[str, Any]]:
"""Get a preprocessing plan by ID."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('preprocessing_plans')
.select('*')
.eq('id', plan_id)
.eq('user_id', user_context.user_id)
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get preprocessing plan: {e}")
raise DatabaseError(f"Failed to retrieve preprocessing plan: {e}")
async def store_feature_mappings(
self,
user_context: UserContext,
preprocessed_dataset_id: str,
feature_mappings: List[Any]
) -> List[str]:
"""Store feature mappings for a preprocessed dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
mapping_records = []
for mapping in feature_mappings:
# Handle both FeatureMapping objects and dictionaries
if hasattr(mapping, 'model_dump'):
mapping_data = mapping.model_dump()
else:
mapping_data = mapping
record = {
'preprocessed_dataset_id': preprocessed_dataset_id,
'user_id': user_context.user_id,
'original_name': mapping_data['original_name'],
'transformed_name': mapping_data['transformed_name'],
'transformation_type': mapping_data['transformation_type'],
'parameters': mapping_data.get('parameters', {}),
'created_at': datetime.utcnow().isoformat()
}
mapping_records.append(record)
result = await asyncio.to_thread(
client.table('feature_mappings').insert(mapping_records).execute
)
if not result.data:
raise DatabaseError("Failed to store feature mappings")
mapping_ids = [record['id'] for record in result.data]
logger.info(f"Stored {len(mapping_ids)} feature mappings")
return mapping_ids
except Exception as e:
logger.error(f"Failed to store feature mappings: {e}")
raise DatabaseError(f"Feature mappings storage failed: {e}")
async def get_feature_mappings(
self,
user_context: UserContext,
preprocessed_dataset_id: str
) -> List[Dict[str, Any]]:
"""Get feature mappings for a preprocessed dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('feature_mappings')
.select('*')
.eq('preprocessed_dataset_id', preprocessed_dataset_id)
.eq('user_id', user_context.user_id)
.order('created_at')
.execute
)
return result.data or []
except Exception as e:
logger.error(f"Failed to get feature mappings: {e}")
raise DatabaseError(f"Failed to retrieve feature mappings: {e}")
async def store_preprocessing_validation(
self,
user_context: UserContext,
original_dataset_id: str,
preprocessed_dataset_id: str,
validation_results: Dict[str, Any]
) -> str:
"""Store preprocessing validation results."""
await self.set_user_context(user_context)
client = self._get_client()
try:
validation_record = {
'original_dataset_id': original_dataset_id,
'preprocessed_dataset_id': preprocessed_dataset_id,
'user_id': user_context.user_id,
'is_valid': validation_results.get('is_valid', True),
'warnings': validation_results.get('warnings', []),
'errors': validation_results.get('errors', []),
'statistics': validation_results.get('statistics', {}),
'validated_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('preprocessing_validations').insert(validation_record).execute
)
if not result.data:
raise DatabaseError("Failed to store preprocessing validation")
validation_id = result.data[0]['id']
logger.info(f"Stored preprocessing validation: {validation_id}")
return validation_id
except Exception as e:
logger.error(f"Failed to store preprocessing validation: {e}")
raise DatabaseError(f"Preprocessing validation storage failed: {e}")
async def cleanup_expired_sessions(self, hours: int = 24) -> int:
"""Clean up expired analysis sessions."""
client = self._get_client(use_service_role=True)
try:
from datetime import timedelta
cutoff_time = datetime.utcnow() - timedelta(hours=hours)
result = await asyncio.to_thread(
client.table('analysis_sessions')
.delete()
.lt('started_at', cutoff_time.isoformat())
.eq('status', 'pending')
.execute
)
cleaned_count = len(result.data) if result.data else 0
logger.info(f"Cleaned up {cleaned_count} expired sessions")
return cleaned_count
except Exception as e:
logger.error(f"Failed to cleanup expired sessions: {e}")
return 0
async def store_feature_engineering_plan(
self,
user_context: UserContext,
plan_id: str,
dataset_id: str,
plan_data: Dict[str, Any]
) -> str:
"""Store a feature engineering plan."""
await self.set_user_context(user_context)
client = self._get_client()
try:
plan_record = {
'id': plan_id,
'dataset_id': dataset_id,
'user_id': user_context.user_id,
'hypotheses_used': plan_data.get('hypotheses_used', []),
'interaction_features': plan_data.get('interaction_features', []),
'transformation_features': plan_data.get('transformation_features', []),
'aggregation_features': plan_data.get('aggregation_features', []),
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('feature_engineering_plans').insert(plan_record).execute
)
if not result.data:
raise DatabaseError("Failed to store feature engineering plan")
stored_plan_id = result.data[0]['id']
logger.info(f"Stored feature engineering plan: {stored_plan_id}")
return stored_plan_id
except Exception as e:
logger.error(f"Failed to store feature engineering plan: {e}")
raise DatabaseError(f"Feature engineering plan storage failed: {e}")
async def store_engineered_features(
self,
user_context: UserContext,
engineered_dataset_id: str,
features_info: List[Dict[str, Any]]
) -> List[str]:
"""Store engineered features information."""
await self.set_user_context(user_context)
client = self._get_client()
try:
feature_records = []
for feature_info in features_info:
record = {
'engineered_dataset_id': engineered_dataset_id,
'user_id': user_context.user_id,
'feature_name': feature_info['feature_name'],
'feature_type': feature_info['feature_type'],
'source_columns': feature_info.get('source_columns', []),
'formula': feature_info.get('formula', ''),
'hypothesis_basis': feature_info.get('hypothesis_basis', ''),
'description': feature_info.get('description', ''),
'importance_score': feature_info.get('importance_score'),
'created_at': datetime.utcnow().isoformat()
}
feature_records.append(record)
result = await asyncio.to_thread(
client.table('engineered_features').insert(feature_records).execute
)
if not result.data:
raise DatabaseError("Failed to store engineered features")
feature_ids = [record['id'] for record in result.data]
logger.info(f"Stored {len(feature_ids)} engineered features")
return feature_ids
except Exception as e:
logger.error(f"Failed to store engineered features: {e}")
raise DatabaseError(f"Engineered features storage failed: {e}")
async def get_engineered_features(
self,
user_context: UserContext,
engineered_dataset_id: str
) -> List[Dict[str, Any]]:
"""Get engineered features for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('engineered_features')
.select('*')
.eq('engineered_dataset_id', engineered_dataset_id)
.eq('user_id', user_context.user_id)
.order('created_at')
.execute
)
return result.data or []
except Exception as e:
logger.error(f"Failed to get engineered features: {e}")
raise DatabaseError(f"Failed to retrieve engineered features: {e}")
async def store_feature_complexity_metrics(
self,
user_context: UserContext,
engineered_dataset_id: str,
metrics: Dict[str, Any]
) -> str:
"""Store feature complexity metrics."""
await self.set_user_context(user_context)
client = self._get_client()
try:
metrics_record = {
'engineered_dataset_id': engineered_dataset_id,
'user_id': user_context.user_id,
'total_features': metrics.get('total_features', 0),
'original_features': metrics.get('original_features', 0),
'engineered_features': metrics.get('engineered_features', 0),
'interaction_features': metrics.get('interaction_features', 0),
'transformation_features': metrics.get('transformation_features', 0),
'aggregation_features': metrics.get('aggregation_features', 0),
'complexity_score': metrics.get('complexity_score', 0.0),
'dimensionality_reduction_applied': metrics.get('dimensionality_reduction_applied', False),
'created_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('feature_complexity_metrics').insert(metrics_record).execute
)
if not result.data:
raise DatabaseError("Failed to store feature complexity metrics")
metrics_id = result.data[0]['id']
logger.info(f"Stored feature complexity metrics: {metrics_id}")
return metrics_id
except Exception as e:
logger.error(f"Failed to store feature complexity metrics: {e}")
raise DatabaseError(f"Feature complexity metrics storage failed: {e}")
async def get_feature_complexity_metrics(
self,
user_context: UserContext,
engineered_dataset_id: str
) -> Optional[Dict[str, Any]]:
"""Get feature complexity metrics for a dataset."""
await self.set_user_context(user_context)
client = self._get_client()
try:
result = await asyncio.to_thread(
client.table('feature_complexity_metrics')
.select('*')
.eq('engineered_dataset_id', engineered_dataset_id)
.eq('user_id', user_context.user_id)
.order('created_at', desc=True)
.limit(1)
.execute
)
if result.data:
return result.data[0]
return None
except Exception as e:
logger.error(f"Failed to get feature complexity metrics: {e}")
raise DatabaseError(f"Failed to retrieve feature complexity metrics: {e}")
async def store_feature_validation(
self,
user_context: UserContext,
engineered_dataset_id: str,
validation_results: Dict[str, Any]
) -> str:
"""Store feature validation results."""
await self.set_user_context(user_context)
client = self._get_client()
try:
validation_record = {
'engineered_dataset_id': engineered_dataset_id,
'user_id': user_context.user_id,
'has_data_leakage': validation_results.get('has_data_leakage', False),
'leakage_warnings': validation_results.get('leakage_warnings', []),
'validation_errors': validation_results.get('validation_errors', []),
'validation_passed': validation_results.get('validation_passed', True),
'validated_at': datetime.utcnow().isoformat()
}
result = await asyncio.to_thread(
client.table('feature_validations').insert(validation_record).execute
)
if not result.data:
raise DatabaseError("Failed to store feature validation")
validation_id = result.data[0]['id']
logger.info(f"Stored feature validation: {validation_id}")
return validation_id
except Exception as e:
logger.error(f"Failed to store feature validation: {e}")
raise DatabaseError(f"Feature validation storage failed: {e}")
# Model Training Methods
async def execute_query(self, query: str, *params) -> Any:
"""Execute a raw SQL query with parameters."""
client = self._get_client(use_service_role=True)
try:
# For INSERT/UPDATE/DELETE operations
if query.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE')):
result = await asyncio.to_thread(
client.rpc,
'execute_sql',
{'sql_query': query, 'params': list(params)}
)
return result
else:
# For SELECT operations
result = await asyncio.to_thread(
client.rpc,
'execute_sql_select',
{'sql_query': query, 'params': list(params)}
)
return result
except Exception as e:
logger.error(f"Failed to execute query: {e}")
raise DatabaseError(f"Query execution failed: {e}")
async def fetch_one(self, query: str, *params) -> Optional[Dict[str, Any]]:
"""Fetch one row from a query."""
client = self._get_client(use_service_role=True)
try:
result = await asyncio.to_thread(
client.rpc,
'fetch_one_sql',
{'sql_query': query, 'params': list(params)}
)
return result.data if result.data else None
except Exception as e:
logger.error(f"Failed to fetch one: {e}")
raise DatabaseError(f"Fetch one failed: {e}")
async def fetch_all(self, query: str, *params) -> List[Dict[str, Any]]:
"""Fetch all rows from a query."""
client = self._get_client(use_service_role=True)
try:
result = await asyncio.to_thread(
client.rpc,
'fetch_all_sql',
{'sql_query': query, 'params': list(params)}
)
return result.data if result.data else []
except Exception as e:
logger.error(f"Failed to fetch all: {e}")
raise DatabaseError(f"Fetch all failed: {e}")
# Global database manager instance
_db_manager: Optional[SupabaseManager] = None
async def get_database() -> SupabaseManager:
"""Get the global database manager instance."""
global _db_manager
if _db_manager is None:
_db_manager = SupabaseManager()
await _db_manager.initialize()
return _db_manager
# Global database manager instance
_db_manager: Optional[SupabaseManager] = None
async def get_database() -> SupabaseManager:
"""Get the global database manager instance."""
global _db_manager
if _db_manager is None:
_db_manager = SupabaseManager()
await _db_manager.initialize()
return _db_manager
async def close_database():
"""Close the database connection."""
global _db_manager
if _db_manager is not None:
# Supabase client doesn't need explicit closing
_db_manager = None
logger.info("Database connection closed") |