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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
# MCP SQL Executor Module
"""
SQL execution tools for MCP integration using DuckDB.

Features:
- In-memory SQL execution
- DataFrame to table conversion
- Query result formatting
- Aggregation support
"""

from typing import Dict, List, Optional, Any
import json


# Global DuckDB connection
_connection = None


def _get_connection():
    """Get or create DuckDB connection"""
    global _connection
    
    if _connection is None:
        try:
            import duckdb
            _connection = duckdb.connect(':memory:')
        except ImportError:
            return None
    
    return _connection


def execute_sql(
    query: str,
    data: Optional[Dict[str, Any]] = None
) -> Dict:
    """
    Execute SQL query on data.
    
    Args:
        query: SQL query string
        data: Dict mapping table names to DataFrames
        
    Returns:
        Query results
    """
    try:
        conn = _get_connection()
        
        if conn is None:
            # Fallback to pandas-based execution
            return _execute_sql_pandas(query, data)
        
        import duckdb
        
        # Register DataFrames as tables
        if data:
            for table_name, df_data in data.items():
                import pandas as pd
                
                if isinstance(df_data, pd.DataFrame):
                    df = df_data
                elif isinstance(df_data, list):
                    df = pd.DataFrame(df_data)
                elif isinstance(df_data, dict):
                    df = pd.DataFrame(df_data)
                else:
                    continue
                
                conn.register(table_name, df)
        
        # Execute query
        result = conn.execute(query)
        
        # Get column names
        columns = [desc[0] for desc in result.description] if result.description else []
        
        # Fetch results
        rows = result.fetchall()
        
        # Convert to list of dicts
        records = []
        for row in rows:
            record = {}
            for i, col in enumerate(columns):
                val = row[i]
                # Convert to JSON-serializable types
                if hasattr(val, 'item'):  # numpy types
                    val = val.item()
                record[col] = val
            records.append(record)
        
        return {
            "success": True,
            "columns": columns,
            "data": records,
            "row_count": len(records)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "data": []
        }


def _execute_sql_pandas(query: str, data: Optional[Dict] = None) -> Dict:
    """Fallback SQL execution using pandas and sqlite"""
    try:
        import pandas as pd
        import sqlite3
        
        # Create in-memory SQLite connection
        conn = sqlite3.connect(':memory:')
        
        # Load DataFrames as tables
        if data:
            for table_name, df_data in data.items():
                if isinstance(df_data, pd.DataFrame):
                    df = df_data
                elif isinstance(df_data, list):
                    df = pd.DataFrame(df_data)
                elif isinstance(df_data, dict):
                    df = pd.DataFrame(df_data)
                else:
                    continue
                
                df.to_sql(table_name, conn, index=False, if_exists='replace')
        
        # Execute query
        result_df = pd.read_sql_query(query, conn)
        
        conn.close()
        
        return {
            "success": True,
            "columns": list(result_df.columns),
            "data": result_df.to_dict(orient='records'),
            "row_count": len(result_df)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "data": []
        }


def create_table_from_df(
    name: str,
    df: Any,
    replace: bool = True
) -> Dict:
    """
    Create virtual table from DataFrame.
    
    Args:
        name: Table name
        df: DataFrame to register
        replace: Whether to replace existing table
        
    Returns:
        Table creation result
    """
    try:
        conn = _get_connection()
        
        if conn is None:
            return {
                "success": False,
                "error": "DuckDB not available",
                "table_name": None
            }
        
        import pandas as pd
        
        if not isinstance(df, pd.DataFrame):
            if isinstance(df, list):
                df = pd.DataFrame(df)
            elif isinstance(df, dict):
                df = pd.DataFrame(df)
            else:
                return {
                    "success": False,
                    "error": "Invalid data type",
                    "table_name": None
                }
        
        conn.register(name, df)
        
        return {
            "success": True,
            "table_name": name,
            "columns": list(df.columns),
            "row_count": len(df)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "table_name": None
        }


def query_to_dataframe(query: str) -> Dict:
    """
    Execute query and return DataFrame result.
    
    Args:
        query: SQL query string
        
    Returns:
        Query result as DataFrame dict
    """
    try:
        conn = _get_connection()
        
        if conn is None:
            return {
                "success": False,
                "error": "DuckDB not available",
                "dataframe": None
            }
        
        import pandas as pd
        
        result_df = conn.execute(query).fetchdf()
        
        return {
            "success": True,
            "dataframe": result_df.to_dict(orient='records'),
            "columns": list(result_df.columns),
            "row_count": len(result_df)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "dataframe": None
        }


def aggregate_data(
    table_or_df: Any,
    group_by: List[str],
    aggregations: Dict[str, str]
) -> Dict:
    """
    Perform aggregation on data.
    
    Args:
        table_or_df: Table name (str) or DataFrame
        group_by: Columns to group by
        aggregations: Dict of {column: agg_function}
            agg_function: "sum", "avg", "count", "min", "max"
        
    Returns:
        Aggregated results
    """
    try:
        import pandas as pd
        
        if isinstance(table_or_df, str):
            # It's a table name, query it
            conn = _get_connection()
            if conn is None:
                return {
                    "success": False,
                    "error": "DuckDB not available",
                    "data": None
                }
            
            df = conn.execute(f"SELECT * FROM {table_or_df}").fetchdf()
        elif isinstance(table_or_df, pd.DataFrame):
            df = table_or_df
        else:
            df = pd.DataFrame(table_or_df)
        
        # Build aggregation dict for pandas
        agg_map = {
            "sum": "sum",
            "avg": "mean",
            "count": "count",
            "min": "min",
            "max": "max",
            "mean": "mean"
        }
        
        pandas_agg = {}
        for col, func in aggregations.items():
            if col in df.columns:
                pandas_agg[col] = agg_map.get(func.lower(), func)
        
        # Perform aggregation
        if group_by:
            result = df.groupby(group_by).agg(pandas_agg).reset_index()
        else:
            result = df.agg(pandas_agg).to_frame().T
        
        return {
            "success": True,
            "data": result.to_dict(orient='records'),
            "columns": list(result.columns),
            "row_count": len(result)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "data": None
        }


def join_tables(
    left_table: Any,
    right_table: Any,
    left_on: str,
    right_on: str,
    how: str = "inner"
) -> Dict:
    """
    Join two tables.
    
    Args:
        left_table: Left table name or DataFrame
        right_table: Right table name or DataFrame
        left_on: Left join column
        right_on: Right join column
        how: Join type ("inner", "left", "right", "outer")
        
    Returns:
        Joined table
    """
    try:
        import pandas as pd
        
        # Convert to DataFrames
        if isinstance(left_table, str):
            conn = _get_connection()
            left_df = conn.execute(f"SELECT * FROM {left_table}").fetchdf()
        else:
            left_df = pd.DataFrame(left_table)
        
        if isinstance(right_table, str):
            conn = _get_connection()
            right_df = conn.execute(f"SELECT * FROM {right_table}").fetchdf()
        else:
            right_df = pd.DataFrame(right_table)
        
        # Perform join
        result = pd.merge(left_df, right_df, left_on=left_on, right_on=right_on, how=how)
        
        return {
            "success": True,
            "data": result.to_dict(orient='records'),
            "columns": list(result.columns),
            "row_count": len(result)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "data": None
        }


def filter_data(
    table_or_df: Any,
    conditions: List[Dict]
) -> Dict:
    """
    Filter data based on conditions.
    
    Args:
        table_or_df: Table name or DataFrame
        conditions: List of {column, operator, value}
            operator: "=", "!=", ">", "<", ">=", "<=", "in", "like"
        
    Returns:
        Filtered data
    """
    try:
        import pandas as pd
        
        if isinstance(table_or_df, str):
            conn = _get_connection()
            df = conn.execute(f"SELECT * FROM {table_or_df}").fetchdf()
        else:
            df = pd.DataFrame(table_or_df)
        
        result = df.copy()
        
        for cond in conditions:
            col = cond.get("column")
            op = cond.get("operator", "=")
            val = cond.get("value")
            
            if col not in result.columns:
                continue
            
            if op == "=" or op == "==":
                result = result[result[col] == val]
            elif op == "!=":
                result = result[result[col] != val]
            elif op == ">":
                result = result[result[col] > val]
            elif op == "<":
                result = result[result[col] < val]
            elif op == ">=":
                result = result[result[col] >= val]
            elif op == "<=":
                result = result[result[col] <= val]
            elif op == "in":
                result = result[result[col].isin(val)]
            elif op == "like":
                result = result[result[col].str.contains(val, case=False, na=False)]
        
        return {
            "success": True,
            "data": result.to_dict(orient='records'),
            "columns": list(result.columns),
            "row_count": len(result),
            "original_count": len(df)
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "data": None
        }


def reset_connection():
    """Reset the DuckDB connection"""
    global _connection
    _connection = None
    return {"success": True, "message": "Connection reset"}