File size: 9,646 Bytes
1273036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
from datetime import datetime
from typing import Dict, List, Any

class DatabaseManager:
    """Simple file-based database manager for storing analysis history"""
    
    def __init__(self, db_file: str = "analysis_history.json"):
        """Initialize the database manager
        
        Args:
            db_file: Path to the JSON file to store analysis history
        """
        self.db_file = db_file
        self.ensure_db_file_exists()
    
    def ensure_db_file_exists(self):
        """Ensure the database file exists"""
        if not os.path.exists(self.db_file):
            with open(self.db_file, 'w') as f:
                json.dump([], f)
    
    def save_analysis(self, analysis_record: Dict[str, Any]) -> bool:
        """Save an analysis record to the database
        
        Args:
            analysis_record: Dictionary containing analysis data
            
        Returns:
            bool: True if successful, False otherwise
        """
        try:
            # Read existing data
            existing_data = self.load_all_data()
            
            # Add timestamp if not present
            if 'timestamp' not in analysis_record:
                analysis_record['timestamp'] = datetime.now().isoformat()
            
            # Append new record
            existing_data.append(analysis_record)
            
            # Write back to file
            with open(self.db_file, 'w') as f:
                json.dump(existing_data, f, indent=2, default=str)
            
            return True
            
        except Exception as e:
            print(f"Error saving analysis: {e}")
            return False
    
    def get_history(self, session_id: str = None, limit: int = 100) -> List[Dict[str, Any]]:
        """Get analysis history
        
        Args:
            session_id: Optional session ID to filter by
            limit: Maximum number of records to return
            
        Returns:
            List of analysis records
        """
        try:
            data = self.load_all_data()
            
            # Filter by session_id if provided
            if session_id:
                data = [record for record in data if record.get('session_id') == session_id]
            
            # Sort by timestamp (newest first)
            data.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
            
            # Apply limit
            return data[:limit]
            
        except Exception as e:
            print(f"Error getting history: {e}")
            return []
    
    def clear_history(self, session_id: str = None) -> bool:
        """Clear analysis history
        
        Args:
            session_id: Optional session ID to clear specific session data
            
        Returns:
            bool: True if successful, False otherwise
        """
        try:
            if session_id:
                # Clear only specific session data
                data = self.load_all_data()
                filtered_data = [record for record in data if record.get('session_id') != session_id]
                
                with open(self.db_file, 'w') as f:
                    json.dump(filtered_data, f, indent=2, default=str)
            else:
                # Clear all data
                with open(self.db_file, 'w') as f:
                    json.dump([], f)
            
            return True
            
        except Exception as e:
            print(f"Error clearing history: {e}")
            return False
    
    def load_all_data(self) -> List[Dict[str, Any]]:
        """Load all data from the database file
        
        Returns:
            List of all records
        """
        try:
            with open(self.db_file, 'r') as f:
                data = json.load(f)
                return data if isinstance(data, list) else []
        except (FileNotFoundError, json.JSONDecodeError):
            return []
    
    def get_analysis_by_type(self, analysis_type: str, session_id: str = None) -> List[Dict[str, Any]]:
        """Get analyses by type
        
        Args:
            analysis_type: Type of analysis (e.g., 'EDA', 'Single Query Analysis')
            session_id: Optional session ID to filter by
            
        Returns:
            List of matching analysis records
        """
        try:
            data = self.load_all_data()
            
            # Filter by type
            filtered_data = [record for record in data if record.get('type') == analysis_type]
            
            # Filter by session_id if provided
            if session_id:
                filtered_data = [record for record in filtered_data if record.get('session_id') == session_id]
            
            # Sort by timestamp (newest first)
            filtered_data.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
            
            return filtered_data
            
        except Exception as e:
            print(f"Error getting analysis by type: {e}")
            return []
    
    def get_stats(self) -> Dict[str, Any]:
        """Get database statistics
        
        Returns:
            Dictionary with database statistics
        """
        try:
            data = self.load_all_data()
            
            stats = {
                'total_records': len(data),
                'unique_sessions': len(set(record.get('session_id', '') for record in data)),
                'analysis_types': {},
                'oldest_record': None,
                'newest_record': None
            }
            
            # Count analysis types
            for record in data:
                analysis_type = record.get('type', 'Unknown')
                stats['analysis_types'][analysis_type] = stats['analysis_types'].get(analysis_type, 0) + 1
            
            # Find oldest and newest records
            if data:
                timestamps = [record.get('timestamp', '') for record in data if record.get('timestamp')]
                if timestamps:
                    timestamps.sort()
                    stats['oldest_record'] = timestamps[0]
                    stats['newest_record'] = timestamps[-1]
            
            return stats
            
        except Exception as e:
            print(f"Error getting stats: {e}")
            return {
                'total_records': 0,
                'unique_sessions': 0,
                'analysis_types': {},
                'oldest_record': None,
                'newest_record': None,
                'error': str(e)
            }
    
    def backup_database(self, backup_file: str = None) -> bool:
        """Create a backup of the database
        
        Args:
            backup_file: Path for backup file. If None, uses timestamp-based name
            
        Returns:
            bool: True if successful, False otherwise
        """
        try:
            if backup_file is None:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                backup_file = f"analysis_history_backup_{timestamp}.json"
            
            data = self.load_all_data()
            
            with open(backup_file, 'w') as f:
                json.dump(data, f, indent=2, default=str)
            
            return True
            
        except Exception as e:
            print(f"Error creating backup: {e}")
            return False
    
    def restore_from_backup(self, backup_file: str) -> bool:
        """Restore database from backup
        
        Args:
            backup_file: Path to backup file
            
        Returns:
            bool: True if successful, False otherwise
        """
        try:
            if not os.path.exists(backup_file):
                print(f"Backup file not found: {backup_file}")
                return False
            
            with open(backup_file, 'r') as f:
                data = json.load(f)
            
            # Validate data format
            if not isinstance(data, list):
                print("Invalid backup file format")
                return False
            
            # Write to main database file
            with open(self.db_file, 'w') as f:
                json.dump(data, f, indent=2, default=str)
            
            return True
            
        except Exception as e:
            print(f"Error restoring from backup: {e}")
            return False
    
    def delete_old_records(self, days_old: int = 30) -> int:
        """Delete records older than specified days
        
        Args:
            days_old: Number of days to keep records
            
        Returns:
            int: Number of records deleted
        """
        try:
            from datetime import datetime, timedelta
            
            cutoff_date = datetime.now() - timedelta(days=days_old)
            cutoff_str = cutoff_date.isoformat()
            
            data = self.load_all_data()
            original_count = len(data)
            
            # Filter out old records
            filtered_data = []
            for record in data:
                record_time = record.get('timestamp', '')
                if record_time >= cutoff_str:
                    filtered_data.append(record)
            
            # Write filtered data back
            with open(self.db_file, 'w') as f:
                json.dump(filtered_data, f, indent=2, default=str)
            
            deleted_count = original_count - len(filtered_data)
            return deleted_count
            
        except Exception as e:
            print(f"Error deleting old records: {e}")
            return 0