streaming-sql-engine 0.1.3__py3-none-any.whl → 0.1.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- streaming_sql_engine/__init__.py +21 -20
- streaming_sql_engine/engine.py +20 -16
- streaming_sql_engine/executor.py +131 -40
- streaming_sql_engine/optimizer.py +121 -0
- streaming_sql_engine/polars_operators.py +280 -0
- streaming_sql_engine/protocol_helpers.py +493 -0
- streaming_sql_engine/setup.py +70 -0
- streaming_sql_engine-0.1.4.dist-info/METADATA +582 -0
- streaming_sql_engine-0.1.4.dist-info/RECORD +19 -0
- streaming_sql_engine/db_connector.py +0 -377
- streaming_sql_engine/jsonl_executor.py +0 -393
- streaming_sql_engine-0.1.3.dist-info/METADATA +0 -320
- streaming_sql_engine-0.1.3.dist-info/RECORD +0 -18
- {streaming_sql_engine-0.1.3.dist-info → streaming_sql_engine-0.1.4.dist-info}/WHEEL +0 -0
- {streaming_sql_engine-0.1.3.dist-info → streaming_sql_engine-0.1.4.dist-info}/top_level.txt +0 -0
streaming_sql_engine/__init__.py
CHANGED
|
@@ -6,25 +6,26 @@ without loading full tables into memory.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
from .engine import Engine
|
|
9
|
-
from .db_connector import (
|
|
10
|
-
PostgreSQLPool,
|
|
11
|
-
MySQLPool,
|
|
12
|
-
create_pool_from_env,
|
|
13
|
-
create_mysql_pool_from_env,
|
|
14
|
-
create_postgresql_pool_from_env,
|
|
15
|
-
stream_query,
|
|
16
|
-
create_table_source
|
|
17
|
-
)
|
|
18
9
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
10
|
+
# Protocol helpers for easy source creation
|
|
11
|
+
try:
|
|
12
|
+
from .protocol_helpers import (
|
|
13
|
+
add_protocol_support,
|
|
14
|
+
wrap_simple_source,
|
|
15
|
+
create_protocol_source,
|
|
16
|
+
register_file_source,
|
|
17
|
+
register_api_source,
|
|
18
|
+
)
|
|
19
|
+
__all__ = [
|
|
20
|
+
"Engine",
|
|
21
|
+
"add_protocol_support",
|
|
22
|
+
"wrap_simple_source",
|
|
23
|
+
"create_protocol_source",
|
|
24
|
+
"register_file_source",
|
|
25
|
+
"register_api_source",
|
|
26
|
+
]
|
|
27
|
+
except ImportError:
|
|
28
|
+
__all__ = ["Engine"]
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.4"
|
|
30
31
|
|
streaming_sql_engine/engine.py
CHANGED
|
@@ -6,7 +6,6 @@ from typing import Any
|
|
|
6
6
|
from .parser import parse_sql
|
|
7
7
|
from .planner import build_logical_plan
|
|
8
8
|
from .executor import execute_plan
|
|
9
|
-
from .jsonl_executor import execute_plan_jsonl
|
|
10
9
|
|
|
11
10
|
|
|
12
11
|
class Engine:
|
|
@@ -21,20 +20,17 @@ class Engine:
|
|
|
21
20
|
print(row)
|
|
22
21
|
"""
|
|
23
22
|
|
|
24
|
-
def __init__(self, debug=False,
|
|
23
|
+
def __init__(self, debug=False, use_polars=True):
|
|
25
24
|
"""
|
|
26
25
|
Initialize a new engine instance.
|
|
27
26
|
|
|
28
27
|
Args:
|
|
29
28
|
debug: If True, enables verbose logging of execution stages
|
|
30
|
-
use_jsonl_mode: If True, uses JSONL-based execution (export tables to JSONL, then merge)
|
|
31
|
-
This is simpler and can reduce CPU usage for complex queries
|
|
32
29
|
use_polars: If True, uses Polars for optimizations when available (default: True)
|
|
33
30
|
"""
|
|
34
31
|
self._sources = {}
|
|
35
32
|
self._source_metadata = {}
|
|
36
33
|
self.debug = debug
|
|
37
|
-
self.use_jsonl_mode = use_jsonl_mode
|
|
38
34
|
self.use_polars = use_polars
|
|
39
35
|
|
|
40
36
|
def register(
|
|
@@ -42,7 +38,6 @@ class Engine:
|
|
|
42
38
|
table_name,
|
|
43
39
|
source_fn,
|
|
44
40
|
ordered_by=None,
|
|
45
|
-
is_database_source=False,
|
|
46
41
|
filename=None
|
|
47
42
|
):
|
|
48
43
|
"""
|
|
@@ -50,13 +45,28 @@ class Engine:
|
|
|
50
45
|
|
|
51
46
|
Args:
|
|
52
47
|
table_name: Name of the table as used in SQL queries
|
|
53
|
-
source_fn: Function that returns an iterator of row dictionaries
|
|
48
|
+
source_fn: Function that returns an iterator of row dictionaries.
|
|
49
|
+
If the function accepts `dynamic_where` and/or `dynamic_columns` parameters,
|
|
50
|
+
optimizations (filter pushdown and column pruning) will be applied automatically.
|
|
54
51
|
ordered_by: Optional column name if the source is sorted by this column
|
|
55
52
|
(enables merge joins)
|
|
56
|
-
is_database_source: If True, indicates this is a database source that supports
|
|
57
|
-
column pruning and filter pushdown optimizations
|
|
58
53
|
filename: Optional filename if source is file-based (enables mmap-based joins
|
|
59
54
|
for 90-99% memory reduction)
|
|
55
|
+
|
|
56
|
+
Example:
|
|
57
|
+
# Simple source (no optimizations)
|
|
58
|
+
def simple_source():
|
|
59
|
+
return iter([{"id": 1, "name": "Alice"}])
|
|
60
|
+
engine.register("users", simple_source)
|
|
61
|
+
|
|
62
|
+
# Optimized source (with protocol)
|
|
63
|
+
def optimized_source(dynamic_where=None, dynamic_columns=None):
|
|
64
|
+
# Build query with optimizations
|
|
65
|
+
query = build_query(dynamic_where, dynamic_columns)
|
|
66
|
+
for row in execute(query):
|
|
67
|
+
yield row
|
|
68
|
+
engine.register("products", optimized_source)
|
|
69
|
+
# Optimizations apply automatically!
|
|
60
70
|
"""
|
|
61
71
|
if not callable(source_fn):
|
|
62
72
|
raise ValueError(f"source_fn must be callable, got {type(source_fn)}")
|
|
@@ -64,7 +74,6 @@ class Engine:
|
|
|
64
74
|
self._sources[table_name] = source_fn
|
|
65
75
|
self._source_metadata[table_name] = {
|
|
66
76
|
"ordered_by": ordered_by,
|
|
67
|
-
"is_database_source": is_database_source,
|
|
68
77
|
"filename": filename # Enable mmap-based joins
|
|
69
78
|
}
|
|
70
79
|
|
|
@@ -111,9 +120,4 @@ class Engine:
|
|
|
111
120
|
print(f"Building execution pipeline...\n")
|
|
112
121
|
|
|
113
122
|
# Execute plan
|
|
114
|
-
|
|
115
|
-
if self.debug:
|
|
116
|
-
print(f"\nUsing JSONL-based execution mode (simpler, lower CPU)\n")
|
|
117
|
-
return execute_plan_jsonl(logical_plan, self._sources, self._source_metadata, debug=self.debug)
|
|
118
|
-
else:
|
|
119
|
-
return execute_plan(logical_plan, self._sources, self._source_metadata, debug=self.debug, use_polars=self.use_polars)
|
|
123
|
+
return execute_plan(logical_plan, self._sources, self._source_metadata, debug=self.debug, use_polars=self.use_polars)
|
streaming_sql_engine/executor.py
CHANGED
|
@@ -56,7 +56,7 @@ def execute_plan(
|
|
|
56
56
|
root_required_columns = plan.required_columns.get(plan.root_table)
|
|
57
57
|
|
|
58
58
|
# Handle pushable WHERE clause (filter pushdown)
|
|
59
|
-
# For
|
|
59
|
+
# For sources that support the protocol, we can push WHERE to the source
|
|
60
60
|
# For other sources, we'll apply it after scanning
|
|
61
61
|
root_source_fn = sources[plan.root_table]
|
|
62
62
|
pushable_where_sql = None
|
|
@@ -73,31 +73,33 @@ def execute_plan(
|
|
|
73
73
|
print(f" [OPTIMIZATION] Could not push WHERE clause: {e}")
|
|
74
74
|
pushable_where_sql = None
|
|
75
75
|
|
|
76
|
-
# Check if source supports optimization
|
|
77
|
-
# If
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
76
|
+
# Check if source supports optimization via protocol
|
|
77
|
+
# Protocol: If function accepts dynamic_where or dynamic_columns parameters, optimizations apply
|
|
78
|
+
import inspect
|
|
79
|
+
|
|
80
|
+
def source_supports_optimizations(source_fn):
|
|
81
|
+
"""Check if source implements optimization protocol."""
|
|
82
|
+
try:
|
|
83
|
+
sig = inspect.signature(source_fn)
|
|
84
|
+
params = list(sig.parameters.keys())
|
|
85
|
+
return 'dynamic_where' in params or 'dynamic_columns' in params
|
|
86
|
+
except (ValueError, TypeError):
|
|
87
|
+
# Can't inspect signature, assume no protocol
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
# Apply optimizations if protocol is supported
|
|
91
|
+
if source_supports_optimizations(root_source_fn) and (root_required_columns or pushable_where_sql):
|
|
82
92
|
if debug:
|
|
83
|
-
print(f" [OPTIMIZATION]
|
|
93
|
+
print(f" [OPTIMIZATION] Source supports protocol - applying column pruning and filter pushdown")
|
|
84
94
|
|
|
85
95
|
original_source_fn = root_source_fn
|
|
86
96
|
|
|
87
97
|
def optimized_source_fn():
|
|
88
|
-
#
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
# Source accepts parameters - pass optimizations
|
|
94
|
-
return original_source_fn(
|
|
95
|
-
dynamic_where=pushable_where_sql,
|
|
96
|
-
dynamic_columns=list(root_required_columns) if root_required_columns else None
|
|
97
|
-
)
|
|
98
|
-
else:
|
|
99
|
-
# Source doesn't accept parameters - use original
|
|
100
|
-
return original_source_fn()
|
|
98
|
+
# Call source with optimization parameters
|
|
99
|
+
return original_source_fn(
|
|
100
|
+
dynamic_where=pushable_where_sql,
|
|
101
|
+
dynamic_columns=list(root_required_columns) if root_required_columns else None
|
|
102
|
+
)
|
|
101
103
|
|
|
102
104
|
root_source_fn = optimized_source_fn
|
|
103
105
|
|
|
@@ -116,25 +118,12 @@ def execute_plan(
|
|
|
116
118
|
debug=debug
|
|
117
119
|
)
|
|
118
120
|
|
|
119
|
-
# Apply WHERE filter if present (non-pushable conditions)
|
|
120
|
-
if plan.where_expr:
|
|
121
|
-
if debug:
|
|
122
|
-
print(f" [FILTER] Applying WHERE clause (non-pushable conditions)")
|
|
123
|
-
|
|
124
|
-
# Use Polars batch filtering if available and beneficial
|
|
125
|
-
if (use_polars and POLARS_AVAILABLE and PolarsBatchFilterIterator is not None):
|
|
126
|
-
try:
|
|
127
|
-
iterator = PolarsBatchFilterIterator(iterator, plan.where_expr, batch_size=10000, debug=debug)
|
|
128
|
-
if debug:
|
|
129
|
-
print(f" [OPTIMIZATION] Using Polars vectorized filtering (SIMD)")
|
|
130
|
-
except Exception as e:
|
|
131
|
-
if debug:
|
|
132
|
-
print(f" [OPTIMIZATION] Polars filtering failed: {e}, using Python")
|
|
133
|
-
iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
|
|
134
|
-
else:
|
|
135
|
-
iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
|
|
136
|
-
|
|
137
121
|
# Apply joins in order
|
|
122
|
+
# Track WHERE clauses that have been pushed to sources
|
|
123
|
+
remaining_where_expr = plan.where_expr
|
|
124
|
+
if debug and remaining_where_expr:
|
|
125
|
+
print(f" [DEBUG] Initial remaining_where_expr: {remaining_where_expr}")
|
|
126
|
+
|
|
138
127
|
for i, join_info in enumerate(plan.joins, 1):
|
|
139
128
|
if debug:
|
|
140
129
|
# Get required columns for joined table
|
|
@@ -143,16 +132,113 @@ def execute_plan(
|
|
|
143
132
|
print(f" [JOIN {i}/{len(plan.joins)}] {join_info.join_type} JOIN {join_info.table} (columns: {len(join_required_columns)})")
|
|
144
133
|
else:
|
|
145
134
|
print(f" [JOIN {i}/{len(plan.joins)}] {join_info.join_type} JOIN {join_info.table}")
|
|
135
|
+
|
|
136
|
+
# Check if we can push WHERE clauses to this joined table
|
|
137
|
+
right_source_fn = sources[join_info.table]
|
|
138
|
+
join_where_sql = None
|
|
139
|
+
table_where_expr = None
|
|
140
|
+
|
|
141
|
+
# Extract WHERE clauses that reference this joined table
|
|
142
|
+
if remaining_where_expr:
|
|
143
|
+
from .optimizer import extract_table_where_clauses, expression_to_sql_string, remove_expression_from_where
|
|
144
|
+
if debug:
|
|
145
|
+
print(f" [DEBUG] remaining_where_expr is not None: {remaining_where_expr}")
|
|
146
|
+
try:
|
|
147
|
+
# Try both alias and table name (WHERE clause might use either)
|
|
148
|
+
table_alias = join_info.alias or join_info.table
|
|
149
|
+
table_name = join_info.table
|
|
150
|
+
|
|
151
|
+
if debug:
|
|
152
|
+
print(f" [DEBUG] Checking WHERE clauses for alias '{table_alias}' or table '{table_name}'")
|
|
153
|
+
print(f" [DEBUG] Remaining WHERE expr: {remaining_where_expr}")
|
|
154
|
+
|
|
155
|
+
# Try alias first, then table name
|
|
156
|
+
table_where_expr = extract_table_where_clauses(remaining_where_expr, table_alias)
|
|
157
|
+
if not table_where_expr and table_alias != table_name:
|
|
158
|
+
# If alias didn't match and it's different from table name, try table name
|
|
159
|
+
table_where_expr = extract_table_where_clauses(remaining_where_expr, table_name)
|
|
160
|
+
|
|
161
|
+
if table_where_expr:
|
|
162
|
+
join_where_sql = expression_to_sql_string(table_where_expr)
|
|
163
|
+
if debug:
|
|
164
|
+
print(f" [OPTIMIZATION] Pushing WHERE clause to {join_info.table}: {join_where_sql}")
|
|
165
|
+
# Remove pushed clauses from remaining WHERE
|
|
166
|
+
remaining_where_expr = remove_expression_from_where(remaining_where_expr, table_where_expr)
|
|
167
|
+
if debug:
|
|
168
|
+
print(f" [DEBUG] Remaining WHERE after removal: {remaining_where_expr}")
|
|
169
|
+
else:
|
|
170
|
+
if debug:
|
|
171
|
+
print(f" [DEBUG] No WHERE clauses found for alias '{table_alias}' or table '{table_name}'")
|
|
172
|
+
except Exception as e:
|
|
173
|
+
if debug:
|
|
174
|
+
print(f" [OPTIMIZATION] Could not push WHERE to {join_info.table}: {e}")
|
|
175
|
+
import traceback
|
|
176
|
+
traceback.print_exc()
|
|
177
|
+
else:
|
|
178
|
+
# Even if not debug, log the error so we can see what's wrong
|
|
179
|
+
import traceback
|
|
180
|
+
print(f" [ERROR] Could not push WHERE to {join_info.table}: {e}")
|
|
181
|
+
traceback.print_exc()
|
|
182
|
+
join_where_sql = None
|
|
183
|
+
|
|
184
|
+
# Apply protocol optimizations to joined table source if supported
|
|
185
|
+
import inspect
|
|
186
|
+
def source_supports_optimizations(source_fn):
|
|
187
|
+
"""Check if source implements optimization protocol."""
|
|
188
|
+
try:
|
|
189
|
+
sig = inspect.signature(source_fn)
|
|
190
|
+
params = list(sig.parameters.keys())
|
|
191
|
+
return 'dynamic_where' in params or 'dynamic_columns' in params
|
|
192
|
+
except (ValueError, TypeError):
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
optimized_right_source_fn = right_source_fn
|
|
196
|
+
if source_supports_optimizations(right_source_fn) and (join_required_columns or join_where_sql):
|
|
197
|
+
if debug:
|
|
198
|
+
print(f" [OPTIMIZATION] Source {join_info.table} supports protocol - applying optimizations")
|
|
199
|
+
|
|
200
|
+
original_right_source_fn = right_source_fn
|
|
201
|
+
|
|
202
|
+
def optimized_right_source_fn():
|
|
203
|
+
# Call source with optimization parameters
|
|
204
|
+
return original_right_source_fn(
|
|
205
|
+
dynamic_where=join_where_sql,
|
|
206
|
+
dynamic_columns=list(join_required_columns) if join_required_columns else None
|
|
207
|
+
)
|
|
208
|
+
|
|
146
209
|
iterator = _build_join_iterator(
|
|
147
210
|
iterator,
|
|
148
211
|
join_info,
|
|
149
212
|
sources,
|
|
150
213
|
source_metadata,
|
|
151
214
|
plan.required_columns.get(join_info.table), # Pass required columns
|
|
215
|
+
optimized_right_source_fn=optimized_right_source_fn, # Pass optimized source
|
|
152
216
|
debug=debug,
|
|
153
217
|
use_polars=use_polars # Pass Polars flag
|
|
154
218
|
)
|
|
155
219
|
|
|
220
|
+
# Update plan.where_expr to only include clauses not pushed to sources
|
|
221
|
+
plan.where_expr = remaining_where_expr
|
|
222
|
+
|
|
223
|
+
# Apply WHERE filter if present (non-pushable conditions)
|
|
224
|
+
# Must be applied AFTER joins since remaining WHERE conditions may reference joined tables
|
|
225
|
+
if plan.where_expr:
|
|
226
|
+
if debug:
|
|
227
|
+
print(f" [FILTER] Applying WHERE clause (non-pushable conditions)")
|
|
228
|
+
|
|
229
|
+
# Use Polars batch filtering if available and beneficial
|
|
230
|
+
if (use_polars and POLARS_AVAILABLE and PolarsBatchFilterIterator is not None):
|
|
231
|
+
try:
|
|
232
|
+
iterator = PolarsBatchFilterIterator(iterator, plan.where_expr, batch_size=10000, debug=debug)
|
|
233
|
+
if debug:
|
|
234
|
+
print(f" [OPTIMIZATION] Using Polars vectorized filtering (SIMD)")
|
|
235
|
+
except Exception as e:
|
|
236
|
+
if debug:
|
|
237
|
+
print(f" [OPTIMIZATION] Polars filtering failed: {e}, using Python")
|
|
238
|
+
iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
|
|
239
|
+
else:
|
|
240
|
+
iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
|
|
241
|
+
|
|
156
242
|
# Apply projection
|
|
157
243
|
if debug:
|
|
158
244
|
print(f" [PROJECT] Applying SELECT projection")
|
|
@@ -189,8 +275,13 @@ def _build_join_iterator(
|
|
|
189
275
|
|
|
190
276
|
Args:
|
|
191
277
|
required_columns: Set of column names needed from right table (for column pruning)
|
|
278
|
+
optimized_right_source_fn: Optional optimized source function (with protocol applied)
|
|
192
279
|
"""
|
|
193
|
-
|
|
280
|
+
# Use optimized source if provided, otherwise use original
|
|
281
|
+
if optimized_right_source_fn is not None:
|
|
282
|
+
right_source = optimized_right_source_fn
|
|
283
|
+
else:
|
|
284
|
+
right_source = sources[join_info.table]
|
|
194
285
|
right_metadata = source_metadata.get(join_info.table, {})
|
|
195
286
|
|
|
196
287
|
# Apply column pruning to right source if needed
|
|
@@ -347,3 +347,124 @@ def expression_to_sql_string(expr: exp.Expression) -> str:
|
|
|
347
347
|
except:
|
|
348
348
|
return str(expr)
|
|
349
349
|
|
|
350
|
+
|
|
351
|
+
def extract_table_where_clauses(where_expr, table_alias: str) -> Optional[exp.Expression]:
|
|
352
|
+
"""
|
|
353
|
+
Extract WHERE clauses that reference a specific table.
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
where_expr: WHERE expression (may be None)
|
|
357
|
+
table_alias: Table alias to extract clauses for
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
Expression containing only clauses referencing the specified table, or None
|
|
361
|
+
"""
|
|
362
|
+
if not where_expr:
|
|
363
|
+
return None
|
|
364
|
+
|
|
365
|
+
# Extract clauses that reference this table
|
|
366
|
+
matching_parts = []
|
|
367
|
+
|
|
368
|
+
def _extract_for_table(expr):
|
|
369
|
+
"""Recursively extract expressions referencing the table."""
|
|
370
|
+
if isinstance(expr, exp.And):
|
|
371
|
+
# AND: check both sides
|
|
372
|
+
left = _extract_for_table(expr.this)
|
|
373
|
+
right = _extract_for_table(expr.expression)
|
|
374
|
+
|
|
375
|
+
if left and right:
|
|
376
|
+
return exp.And(this=left, expression=right)
|
|
377
|
+
elif left:
|
|
378
|
+
return left
|
|
379
|
+
elif right:
|
|
380
|
+
return right
|
|
381
|
+
else:
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
elif isinstance(expr, exp.Or):
|
|
385
|
+
# OR: both sides must reference the table
|
|
386
|
+
left = _extract_for_table(expr.this)
|
|
387
|
+
right = _extract_for_table(expr.expression)
|
|
388
|
+
|
|
389
|
+
if left and right:
|
|
390
|
+
return exp.Or(this=left, expression=right)
|
|
391
|
+
else:
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
elif isinstance(expr, exp.Not):
|
|
395
|
+
# NOT: check inner expression
|
|
396
|
+
inner = _extract_for_table(expr.this)
|
|
397
|
+
if inner:
|
|
398
|
+
return exp.Not(this=inner)
|
|
399
|
+
else:
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
else:
|
|
403
|
+
# Leaf expression - check if it references the table
|
|
404
|
+
referenced_aliases = set()
|
|
405
|
+
_extract_table_aliases_from_expr(expr, referenced_aliases)
|
|
406
|
+
|
|
407
|
+
if table_alias in referenced_aliases and len(referenced_aliases) == 1:
|
|
408
|
+
# Only references this table
|
|
409
|
+
return expr
|
|
410
|
+
else:
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
result = _extract_for_table(where_expr)
|
|
414
|
+
return result
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def remove_expression_from_where(where_expr: Optional[exp.Expression], expr_to_remove: exp.Expression) -> Optional[exp.Expression]:
|
|
418
|
+
"""
|
|
419
|
+
Remove a specific expression from a WHERE clause.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
where_expr: Original WHERE expression
|
|
423
|
+
expr_to_remove: Expression to remove
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
Updated WHERE expression with the expression removed, or None if nothing remains
|
|
427
|
+
"""
|
|
428
|
+
if not where_expr:
|
|
429
|
+
return None
|
|
430
|
+
|
|
431
|
+
# Simple approach: if expressions are equal, return None
|
|
432
|
+
# For AND expressions, try to remove one side
|
|
433
|
+
if isinstance(where_expr, exp.And):
|
|
434
|
+
left = where_expr.this
|
|
435
|
+
right = where_expr.expression
|
|
436
|
+
|
|
437
|
+
# Check if left or right matches what we want to remove
|
|
438
|
+
if (isinstance(left, type(expr_to_remove)) and
|
|
439
|
+
hasattr(left, 'sql') and hasattr(expr_to_remove, 'sql') and
|
|
440
|
+
left.sql() == expr_to_remove.sql()):
|
|
441
|
+
# Remove left side
|
|
442
|
+
return right if right else None
|
|
443
|
+
|
|
444
|
+
if (isinstance(right, type(expr_to_remove)) and
|
|
445
|
+
hasattr(right, 'sql') and hasattr(expr_to_remove, 'sql') and
|
|
446
|
+
right.sql() == expr_to_remove.sql()):
|
|
447
|
+
# Remove right side
|
|
448
|
+
return left if left else None
|
|
449
|
+
|
|
450
|
+
# Try recursively
|
|
451
|
+
new_left = remove_expression_from_where(left, expr_to_remove)
|
|
452
|
+
new_right = remove_expression_from_where(right, expr_to_remove)
|
|
453
|
+
|
|
454
|
+
if new_left and new_right:
|
|
455
|
+
return exp.And(this=new_left, expression=new_right)
|
|
456
|
+
elif new_left:
|
|
457
|
+
return new_left
|
|
458
|
+
elif new_right:
|
|
459
|
+
return new_right
|
|
460
|
+
else:
|
|
461
|
+
return None
|
|
462
|
+
|
|
463
|
+
# For other expressions, check if they match
|
|
464
|
+
if (isinstance(where_expr, type(expr_to_remove)) and
|
|
465
|
+
hasattr(where_expr, 'sql') and hasattr(expr_to_remove, 'sql') and
|
|
466
|
+
where_expr.sql() == expr_to_remove.sql()):
|
|
467
|
+
return None
|
|
468
|
+
|
|
469
|
+
# Doesn't match, return original
|
|
470
|
+
return where_expr
|