File size: 13,207 Bytes
b336134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
MVCC Executor.
Performs lock-free versioned operations on Parquet files using Polars LazyFrames.
"""
from __future__ import annotations

import os
import polars as pl

from config import DATA_DIR, LAZY_THRESHOLD_BYTES
from services.session_manager import session_manager
from core.column_registry import column_registry
from core.execution.polars_builder import build_polars_expression

def _build_predicate(column: str, condition: str, value) -> pl.Expr:
    """Build a Polars expression from a comparison condition string."""
    col = pl.col(column)
    if condition == ">":
        return col > value
    elif condition == "<":
        return col < value
    elif condition == ">=":
        return col >= value
    elif condition == "<=":
        return col <= value
    elif condition == "!=":
        return col != value
    elif condition == "==" or condition == "=":
        if isinstance(value, (int, float)):
            return col == value
        try:
            return col == float(value)
        except (ValueError, TypeError):
            return col.cast(pl.String).str.to_lowercase() == str(value).lower()
    elif condition in ("contains", "~"):
        return col.cast(pl.String).str.contains(str(value), literal=True)
    else:
        return col.cast(pl.String).str.to_lowercase() == str(value).lower()

def _format_number(val) -> str:
    """Pretty-print numbers with commas."""
    if val is None:
        return "N/A"
    if isinstance(val, float):
        if val == int(val):
            return f"{int(val):,}"
        return f"{val:,.2f}"
    if isinstance(val, int):
        return f"{val:,}"
    return str(val)

def execute_mvcc_command(session_id: str, intent: dict) -> dict:
    """Execute the command and return a result dict.

    Updates metadata and creates a new parquet version on write.
    """
    meta = session_manager.get(session_id)
    if meta is None:
        return {
            "status": "error",
            "message": "Session nahi mila. Pehle file upload karo.",
            "diff": {}
        }

    version = getattr(meta, "current_version", 0)

    # Resolve read path
    # If version is 0, we can fall back to the initial upload path (data/sessions/{session_id}.parquet).
    v_path = os.path.join(DATA_DIR, f"{session_id}_v{version}.parquet")
    if not os.path.exists(v_path):
        if version == 0:
            v_path = os.path.join(DATA_DIR, f"{session_id}.parquet")
            if not os.path.exists(v_path):
                raise FileNotFoundError(f"Initial Parquet file not found for session {session_id}")
        else:
            raise FileNotFoundError(f"Parquet file not found for version {version} of session {session_id}")

    op = intent.get("operation")
    if not op:
        return {
            "message": "Operation specifies nahi kiya gaya",
            "diff": {}
        }

    # ── Read-only operations (Aggregates) ──
    if op in ("sum", "average", "count", "min", "max"):
        lf = pl.scan_parquet(v_path)
        if op == "sum":
            col = intent["column"]
            result = lf.select(pl.col(col).sum()).collect().item()
            return {
                "message": f"{col} ka sum = {_format_number(result)}",
                "diff": {"operation": "sum", "column": col, "result": result},
            }
        elif op == "average":
            col = intent["column"]
            result = lf.select(pl.col(col).mean()).collect().item()
            return {
                "message": f"{col} ka average = {_format_number(result)}",
                "diff": {"operation": "average", "column": col, "result": result},
            }
        elif op == "count":
            col = intent.get("column")
            if col:
                result = lf.select(pl.col(col).count()).collect().item()
                return {
                    "message": f"{col} mein {_format_number(result)} non-null values hain",
                    "diff": {"operation": "count", "column": col, "result": result},
                }
            else:
                result = lf.select(pl.len()).collect().item()
                return {
                    "message": f"Total {_format_number(result)} rows hain",
                    "diff": {"operation": "count", "column": None, "result": result},
                }
        elif op == "min":
            col = intent["column"]
            result = lf.select(pl.col(col).min()).collect().item()
            return {
                "message": f"{col} ka minimum = {_format_number(result)}",
                "diff": {"operation": "min", "column": col, "result": result},
            }
        elif op == "max":
            col = intent["column"]
            result = lf.select(pl.col(col).max()).collect().item()
            return {
                "message": f"{col} ka maximum = {_format_number(result)}",
                "diff": {"operation": "max", "column": col, "result": result},
            }

    # ── Write operations ──
    lf = pl.scan_parquet(v_path)
    new_version = version + 1
    new_path = os.path.join(DATA_DIR, f"{session_id}_v{new_version}.parquet")

    before_count = lf.select(pl.len()).collect().item()

    if op in ("increase", "decrease"):
        col = intent["column"]
        value = intent.get("value")
        if value is None:
            value = 10.0
        is_percent = intent.get("is_percent", True)
        
        expr = build_polars_expression(op, col, {"value": value, "is_percent": is_percent})
        lf = lf.with_columns(expr)

    elif op == "cast_type":
        col = intent["column"]
        target = intent["target_dtype"]
        expr = build_polars_expression("cast_type", col, {"target_dtype": target})
        lf = lf.with_columns(expr)

    elif op == "find_replace":
        col = intent["column"]
        old_val = intent["old_value"]
        new_val = intent["new_value"]
        
        schema = lf.collect_schema()
        dtype = schema[col]
        is_numeric = dtype in (pl.Float64, pl.Int64, pl.Int32, pl.Float32)
        
        if is_numeric:
            try:
                float(old_val)
                float(new_val)
            except (ValueError, TypeError):
                return {
                    "message": f"'{col}' numeric hai, replace values bhi numbers hone chahiye",
                    "diff": {},
                }
        
        expr = build_polars_expression("find_replace", col, {
            "old_value": old_val,
            "new_value": new_val,
            "is_numeric": is_numeric
        })
        lf = lf.with_columns(expr)

    elif op == "delete_column":
        col = intent["column"]
        lf = lf.drop(col)

    elif op == "rename_column":
        old = intent["column"]
        new = intent["new_name"]
        lf = lf.rename({old: new})

    elif op == "add_column":
        new_col = intent.get("new_column_name") or intent.get("column", "new_col")
        default_val = intent.get("value", 0)
        lf = lf.with_columns(pl.lit(default_val).alias(new_col))

    elif op == "remove_duplicates":
        col = intent.get("column")
        if col:
            lf = lf.unique(subset=[col], keep="first")
        else:
            lf = lf.unique(keep="first")

    elif op == "filter":
        col = intent["column"]
        condition = intent["condition"]
        filter_value = intent["filter_value"]
        predicate = _build_predicate(col, condition, filter_value)
        lf = lf.filter(predicate)

    elif op in ("sort_asc", "sort_desc"):
        col = intent["column"]
        descending = (op == "sort_desc")
        lf = lf.sort(col, descending=descending)

    else:
        return {
            "message": f"'{op}' operation supported nahi hai",
            "diff": {},
        }

    # Lock-free versioned write
    prev_size = os.path.getsize(v_path)
    try:
        if prev_size > LAZY_THRESHOLD_BYTES:
            lf.sink_parquet(new_path)
        else:
            lf.collect().write_parquet(new_path)
    except Exception:
        # Fallback to eager write if streaming sink is not supported for this query plan (e.g. sort/unique)
        lf.collect().write_parquet(new_path)

    # Read updated metadata
    lf_new = pl.scan_parquet(new_path)
    new_schema = lf_new.collect_schema()
    after_count = lf_new.select(pl.len()).collect().item()
    columns_meta = [{"name": name, "dtype": str(dtype)} for name, dtype in new_schema.items()]

    # Format result message and diff
    message = ""
    diff = {}

    if op in ("increase", "decrease"):
        col = intent["column"]
        value = intent.get("value")
        if value is None:
            value = 10.0
        is_percent = intent.get("is_percent", True)
        op_label = f"{value}% badha diya" if op == "increase" else f"{value}% ghata diya"
        if not is_percent:
            op_label = f"{value} joda" if op == "increase" else f"{value} ghata diya"
        message = f"{col} ko {op_label} ({after_count:,} rows updated)"
        diff = {
            "operation": op,
            "column": col,
            "value": value,
            "is_percent": is_percent,
            "affected_rows": after_count,
        }

    elif op == "cast_type":
        col = intent["column"]
        target = intent["target_dtype"]
        message = f"'{col}' ka type {target} mein change ho gaya"
        diff = {"operation": "cast_type", "column": col, "target_dtype": target}

    elif op == "find_replace":
        col = intent["column"]
        old_val = intent["old_value"]
        new_val = intent["new_value"]
        
        dtype = new_schema[col]
        is_numeric = dtype in (pl.Float64, pl.Int64, pl.Int32, pl.Float32)
        if is_numeric:
            try:
                count = lf_new.filter(pl.col(col) == float(new_val)).select(pl.len()).collect().item()
            except (ValueError, TypeError):
                count = "N/A"
        else:
            count = lf_new.filter(pl.col(col).cast(pl.String) == str(new_val)).select(pl.len()).collect().item()
            
        message = f"'{col}' mein '{old_val}' ko '{new_val}' se replace kiya ({count} rows changed)"
        diff = {
            "operation": "find_replace",
            "column": col,
            "old_value": old_val,
            "new_value": new_val,
            "affected_rows": count,
        }

    elif op == "delete_column":
        col = intent["column"]
        message = f"'{col}' column delete ho gaya"
        diff = {"operation": "delete_column", "column": col}

    elif op == "rename_column":
        old = intent["column"]
        new = intent["new_name"]
        message = f"'{old}' ka naam badal ke '{new}' ho gaya"
        diff = {"operation": "rename_column", "old_name": old, "new_name": new}

    elif op == "add_column":
        new_col = intent.get("new_column_name") or intent.get("column", "new_col")
        default_val = intent.get("value", 0)
        message = f"Naya column '{new_col}' add ho gaya (default: {default_val})"
        diff = {"operation": "add_column", "column": new_col}

    elif op == "remove_duplicates":
        col = intent.get("column")
        removed = before_count - after_count
        if col:
            message = f"'{col}' ke duplicate rows hata diye ({removed} rows removed, {after_count:,} remaining)"
        else:
            message = f"Duplicate rows hata diye ({removed} rows removed, {after_count:,} remaining)"
        diff = {
            "operation": "remove_duplicates",
            "column": col,
            "rows_removed": removed,
            "rows_remaining": after_count,
        }

    elif op == "filter":
        col = intent["column"]
        condition = intent["condition"]
        filter_value = intent["filter_value"]
        message = f"{col} {condition} {filter_value} β†’ {after_count:,} rows bach gaye"
        diff = {
            "operation": "filter",
            "column": col,
            "condition": condition,
            "filter_value": filter_value,
            "rows_after": after_count,
        }

    elif op in ("sort_asc", "sort_desc"):
        col = intent["column"]
        descending = (op == "sort_desc")
        order = "descending (bada se chhota)" if descending else "ascending (chhota se bada)"
        message = f"{col} ko {order} sort kiya ({after_count:,} rows)"
        diff = {
            "operation": "sort",
            "column": col,
            "descending": descending,
            "affected_rows": after_count,
        }

    # Update session metadata in session_manager
    meta.current_version = new_version
    meta.row_count = after_count
    meta.columns = columns_meta
    meta.touch()

    # Update column registry
    column_registry.register(session_id, [c["name"] for c in columns_meta])

    # Clean up the previous intermediate versioned file
    if version > 0:
        prev_version_path = os.path.join(DATA_DIR, f"{session_id}_v{version}.parquet")
        if os.path.exists(prev_version_path):
            try:
                os.remove(prev_version_path)
            except Exception as e:
                print(f"[MVCC Executor] Warning cleaning up version {version}: {e}")

    return {
        "message": message,
        "diff": diff,
    }