streaming-sql-engine 0.1.6__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/DEPLOYMENT.md +154 -0
- streaming_sql_engine/QUICK_DEPLOY.md +82 -0
- streaming_sql_engine/QUICK_FIX.md +53 -0
- streaming_sql_engine/README.md +533 -0
- streaming_sql_engine/__init__.py +31 -0
- streaming_sql_engine/engine.py +123 -0
- streaming_sql_engine/evaluator.py +218 -0
- streaming_sql_engine/executor.py +410 -0
- streaming_sql_engine/mmap_index.py +386 -0
- streaming_sql_engine/operators.py +507 -0
- streaming_sql_engine/operators_mmap.py +269 -0
- streaming_sql_engine/operators_polars.py +581 -0
- streaming_sql_engine/optimizer.py +470 -0
- streaming_sql_engine/parser.py +93 -0
- streaming_sql_engine/planner.py +172 -0
- streaming_sql_engine/polars_expression_translator.py +177 -0
- streaming_sql_engine/polars_operators.py +280 -0
- streaming_sql_engine/protocol_helpers.py +493 -0
- streaming_sql_engine/requirements.txt +7 -0
- streaming_sql_engine/setup.py +69 -0
- streaming_sql_engine-0.1.6.dist-info/METADATA +581 -0
- streaming_sql_engine-0.1.6.dist-info/RECORD +24 -0
- streaming_sql_engine-0.1.6.dist-info/WHEEL +5 -0
- streaming_sql_engine-0.1.6.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Expression evaluator for WHERE clauses and SELECT projections.
|
|
3
|
+
Optimized to reduce isinstance() checks using expression type caching.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from sqlglot import expressions as exp
|
|
7
|
+
|
|
8
|
+
# Cache expression type classes for faster isinstance checks
|
|
9
|
+
_COLUMN_TYPE = exp.Column
|
|
10
|
+
_LITERAL_TYPE = exp.Literal
|
|
11
|
+
_EQ_TYPE = exp.EQ
|
|
12
|
+
_NEQ_TYPE = exp.NEQ
|
|
13
|
+
_LT_TYPE = exp.LT
|
|
14
|
+
_GT_TYPE = exp.GT
|
|
15
|
+
_LTE_TYPE = exp.LTE
|
|
16
|
+
_GTE_TYPE = exp.GTE
|
|
17
|
+
_AND_TYPE = exp.And
|
|
18
|
+
_OR_TYPE = exp.Or
|
|
19
|
+
_NOT_TYPE = exp.Not
|
|
20
|
+
_IS_TYPE = exp.Is
|
|
21
|
+
_ALIAS_TYPE = exp.Alias
|
|
22
|
+
_PAREN_TYPE = exp.Paren
|
|
23
|
+
_IN_TYPE = exp.In
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _coerce_comparable_types(left, right):
|
|
27
|
+
"""
|
|
28
|
+
Coerce two values to comparable types for comparison operations.
|
|
29
|
+
|
|
30
|
+
Handles cases where one value is a number (int/float) and the other is a string
|
|
31
|
+
that can be converted to a number.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
left: Left operand
|
|
35
|
+
right: Right operand
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Tuple of (left, right) with coerced types
|
|
39
|
+
"""
|
|
40
|
+
# If both are same type or both None, no coercion needed
|
|
41
|
+
if type(left) == type(right) or (left is None and right is None):
|
|
42
|
+
return left, right
|
|
43
|
+
|
|
44
|
+
# If one is None, comparisons are False (except !=)
|
|
45
|
+
if left is None or right is None:
|
|
46
|
+
return left, right
|
|
47
|
+
|
|
48
|
+
# Try to coerce string to number if one is numeric
|
|
49
|
+
if isinstance(left, (int, float)) and isinstance(right, str):
|
|
50
|
+
try:
|
|
51
|
+
# Try to convert string to number
|
|
52
|
+
if '.' in right or 'e' in right.lower() or 'E' in right:
|
|
53
|
+
right = float(right)
|
|
54
|
+
else:
|
|
55
|
+
right = int(right)
|
|
56
|
+
except (ValueError, TypeError):
|
|
57
|
+
# Can't convert, keep as string (will raise TypeError on comparison)
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
elif isinstance(right, (int, float)) and isinstance(left, str):
|
|
61
|
+
try:
|
|
62
|
+
# Try to convert string to number
|
|
63
|
+
if '.' in left or 'e' in left.lower() or 'E' in left:
|
|
64
|
+
left = float(left)
|
|
65
|
+
else:
|
|
66
|
+
left = int(left)
|
|
67
|
+
except (ValueError, TypeError):
|
|
68
|
+
# Can't convert, keep as string (will raise TypeError on comparison)
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
return left, right
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def evaluate_expression(expr, row):
|
|
75
|
+
"""
|
|
76
|
+
Evaluate a SQL expression against a row.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
expr: SQL expression AST node
|
|
80
|
+
row: Row dictionary with prefixed column names (e.g., "alias.column")
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
Evaluated value
|
|
84
|
+
"""
|
|
85
|
+
# Use cached type references for faster isinstance checks
|
|
86
|
+
expr_type = type(expr)
|
|
87
|
+
|
|
88
|
+
if expr_type is _COLUMN_TYPE:
|
|
89
|
+
# Column reference
|
|
90
|
+
col_name = f"{expr.table}.{expr.name}" if expr.table else expr.name
|
|
91
|
+
if col_name in row:
|
|
92
|
+
return row[col_name]
|
|
93
|
+
# Try without table prefix
|
|
94
|
+
if expr.name in row:
|
|
95
|
+
return row[expr.name]
|
|
96
|
+
raise KeyError(f"Column {col_name} not found in row")
|
|
97
|
+
|
|
98
|
+
elif expr_type is _LITERAL_TYPE:
|
|
99
|
+
# Literal value
|
|
100
|
+
return expr.this
|
|
101
|
+
|
|
102
|
+
elif expr_type is _EQ_TYPE:
|
|
103
|
+
# Equality: left = right
|
|
104
|
+
left = evaluate_expression(expr.this, row)
|
|
105
|
+
right = evaluate_expression(expr.expression, row)
|
|
106
|
+
return left == right
|
|
107
|
+
|
|
108
|
+
elif expr_type is _NEQ_TYPE:
|
|
109
|
+
# Inequality: left != right
|
|
110
|
+
left = evaluate_expression(expr.this, row)
|
|
111
|
+
right = evaluate_expression(expr.expression, row)
|
|
112
|
+
return left != right
|
|
113
|
+
|
|
114
|
+
elif expr_type is _LT_TYPE:
|
|
115
|
+
# Less than: left < right
|
|
116
|
+
left = evaluate_expression(expr.this, row)
|
|
117
|
+
right = evaluate_expression(expr.expression, row)
|
|
118
|
+
left, right = _coerce_comparable_types(left, right)
|
|
119
|
+
return left < right
|
|
120
|
+
|
|
121
|
+
elif expr_type is _GT_TYPE:
|
|
122
|
+
# Greater than: left > right
|
|
123
|
+
left = evaluate_expression(expr.this, row)
|
|
124
|
+
right = evaluate_expression(expr.expression, row)
|
|
125
|
+
left, right = _coerce_comparable_types(left, right)
|
|
126
|
+
return left > right
|
|
127
|
+
|
|
128
|
+
elif expr_type is _LTE_TYPE:
|
|
129
|
+
# Less than or equal: left <= right
|
|
130
|
+
left = evaluate_expression(expr.this, row)
|
|
131
|
+
right = evaluate_expression(expr.expression, row)
|
|
132
|
+
left, right = _coerce_comparable_types(left, right)
|
|
133
|
+
return left <= right
|
|
134
|
+
|
|
135
|
+
elif expr_type is _GTE_TYPE:
|
|
136
|
+
# Greater than or equal: left >= right
|
|
137
|
+
left = evaluate_expression(expr.this, row)
|
|
138
|
+
right = evaluate_expression(expr.expression, row)
|
|
139
|
+
left, right = _coerce_comparable_types(left, right)
|
|
140
|
+
return left >= right
|
|
141
|
+
|
|
142
|
+
elif expr_type is _AND_TYPE:
|
|
143
|
+
# AND: left AND right
|
|
144
|
+
left = evaluate_expression(expr.this, row)
|
|
145
|
+
if not left:
|
|
146
|
+
return False
|
|
147
|
+
right = evaluate_expression(expr.expression, row)
|
|
148
|
+
return bool(right)
|
|
149
|
+
|
|
150
|
+
elif expr_type is _OR_TYPE:
|
|
151
|
+
# OR: left OR right
|
|
152
|
+
left = evaluate_expression(expr.this, row)
|
|
153
|
+
if left:
|
|
154
|
+
return True
|
|
155
|
+
right = evaluate_expression(expr.expression, row)
|
|
156
|
+
return bool(right)
|
|
157
|
+
|
|
158
|
+
elif expr_type is _NOT_TYPE:
|
|
159
|
+
# NOT: NOT expr
|
|
160
|
+
value = evaluate_expression(expr.this, row)
|
|
161
|
+
return not value
|
|
162
|
+
|
|
163
|
+
elif expr_type is _IS_TYPE:
|
|
164
|
+
# IS NULL / IS NOT NULL
|
|
165
|
+
value = evaluate_expression(expr.this, row)
|
|
166
|
+
if expr.expression is None:
|
|
167
|
+
# IS NULL
|
|
168
|
+
return value is None
|
|
169
|
+
elif isinstance(expr.expression, exp.Null):
|
|
170
|
+
# IS NULL
|
|
171
|
+
return value is None
|
|
172
|
+
elif isinstance(expr.expression, exp.Not) and isinstance(expr.expression.this, exp.Null):
|
|
173
|
+
# IS NOT NULL
|
|
174
|
+
return value is not None
|
|
175
|
+
else:
|
|
176
|
+
raise ValueError(f"Unsupported IS expression: {expr}")
|
|
177
|
+
|
|
178
|
+
elif expr_type is _ALIAS_TYPE:
|
|
179
|
+
# Alias - evaluate the inner expression
|
|
180
|
+
return evaluate_expression(expr.this, row)
|
|
181
|
+
|
|
182
|
+
elif expr_type is _PAREN_TYPE:
|
|
183
|
+
# Parentheses - evaluate inner expression
|
|
184
|
+
return evaluate_expression(expr.this, row)
|
|
185
|
+
|
|
186
|
+
elif expr_type is _IN_TYPE:
|
|
187
|
+
# IN clause: column IN (value1, value2, ...)
|
|
188
|
+
left = evaluate_expression(expr.this, row)
|
|
189
|
+
# Get the list of values from the expression
|
|
190
|
+
if isinstance(expr.expression, exp.Tuple):
|
|
191
|
+
values = [evaluate_expression(e, row) for e in expr.expression.expressions]
|
|
192
|
+
elif isinstance(expr.expression, (list, tuple)):
|
|
193
|
+
values = [evaluate_expression(e, row) for e in expr.expression]
|
|
194
|
+
else:
|
|
195
|
+
# Could be a subquery (not supported)
|
|
196
|
+
raise ValueError("IN clause with subqueries is not supported")
|
|
197
|
+
return left in values
|
|
198
|
+
|
|
199
|
+
elif isinstance(expr, exp.Not) and isinstance(expr.this, exp.In):
|
|
200
|
+
# NOT IN clause
|
|
201
|
+
in_expr = expr.this
|
|
202
|
+
left = evaluate_expression(in_expr.this, row)
|
|
203
|
+
if isinstance(in_expr.expression, exp.Tuple):
|
|
204
|
+
values = [evaluate_expression(e, row) for e in in_expr.expression.expressions]
|
|
205
|
+
elif isinstance(in_expr.expression, (list, tuple)):
|
|
206
|
+
values = [evaluate_expression(e, row) for e in in_expr.expression]
|
|
207
|
+
else:
|
|
208
|
+
raise ValueError("NOT IN clause with subqueries is not supported")
|
|
209
|
+
return left not in values
|
|
210
|
+
|
|
211
|
+
elif isinstance(expr, exp.Where):
|
|
212
|
+
# Where node should be unwrapped before reaching evaluator
|
|
213
|
+
# If it reaches here, unwrap it and evaluate the inner expression
|
|
214
|
+
return evaluate_expression(expr.this, row)
|
|
215
|
+
|
|
216
|
+
else:
|
|
217
|
+
raise ValueError(f"Unsupported expression type: {type(expr).__name__}")
|
|
218
|
+
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Execution engine - builds iterator pipeline from logical plan.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .planner import LogicalPlan, JoinInfo
|
|
6
|
+
from .operators import (
|
|
7
|
+
ScanIterator,
|
|
8
|
+
FilterIterator,
|
|
9
|
+
ProjectIterator,
|
|
10
|
+
LookupJoinIterator,
|
|
11
|
+
MergeJoinIterator
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
# Try importing Polars operators (optional)
|
|
15
|
+
try:
|
|
16
|
+
from .operators_polars import (
|
|
17
|
+
PolarsLookupJoinIterator,
|
|
18
|
+
PolarsBatchFilterIterator,
|
|
19
|
+
PolarsBatchProjectIterator,
|
|
20
|
+
should_use_polars
|
|
21
|
+
)
|
|
22
|
+
POLARS_AVAILABLE = True
|
|
23
|
+
except ImportError:
|
|
24
|
+
POLARS_AVAILABLE = False
|
|
25
|
+
PolarsBatchFilterIterator = None
|
|
26
|
+
PolarsBatchProjectIterator = None
|
|
27
|
+
|
|
28
|
+
# Try importing mmap operators (optional)
|
|
29
|
+
try:
|
|
30
|
+
from .operators_mmap import MmapLookupJoinIterator
|
|
31
|
+
MMAP_AVAILABLE = True
|
|
32
|
+
except ImportError:
|
|
33
|
+
MMAP_AVAILABLE = False
|
|
34
|
+
MmapLookupJoinIterator = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def execute_plan(
|
|
38
|
+
plan,
|
|
39
|
+
sources,
|
|
40
|
+
source_metadata,
|
|
41
|
+
debug=False,
|
|
42
|
+
use_polars=True
|
|
43
|
+
):
|
|
44
|
+
"""
|
|
45
|
+
Execute a logical plan and return a generator of result row dictionaries.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
plan: Logical execution plan (with optimizations: required_columns, pushable_where_expr)
|
|
49
|
+
sources: Dictionary mapping table names to source functions
|
|
50
|
+
source_metadata: Dictionary with metadata about sources (e.g., ordered_by)
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
Generator of result row dictionaries
|
|
54
|
+
"""
|
|
55
|
+
# Get required columns for root table (column pruning)
|
|
56
|
+
root_required_columns = plan.required_columns.get(plan.root_table)
|
|
57
|
+
|
|
58
|
+
# Handle pushable WHERE clause (filter pushdown)
|
|
59
|
+
# For sources that support the protocol, we can push WHERE to the source
|
|
60
|
+
# For other sources, we'll apply it after scanning
|
|
61
|
+
root_source_fn = sources[plan.root_table]
|
|
62
|
+
pushable_where_sql = None
|
|
63
|
+
|
|
64
|
+
if plan.pushable_where_expr:
|
|
65
|
+
# Convert pushable WHERE expression to SQL string
|
|
66
|
+
from .optimizer import expression_to_sql_string
|
|
67
|
+
try:
|
|
68
|
+
pushable_where_sql = expression_to_sql_string(plan.pushable_where_expr)
|
|
69
|
+
if debug:
|
|
70
|
+
print(f" [OPTIMIZATION] Pushing WHERE clause to source: {pushable_where_sql}")
|
|
71
|
+
except Exception as e:
|
|
72
|
+
if debug:
|
|
73
|
+
print(f" [OPTIMIZATION] Could not push WHERE clause: {e}")
|
|
74
|
+
pushable_where_sql = None
|
|
75
|
+
|
|
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):
|
|
92
|
+
if debug:
|
|
93
|
+
print(f" [OPTIMIZATION] Source supports protocol - applying column pruning and filter pushdown")
|
|
94
|
+
|
|
95
|
+
original_source_fn = root_source_fn
|
|
96
|
+
|
|
97
|
+
def optimized_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
|
+
)
|
|
103
|
+
|
|
104
|
+
root_source_fn = optimized_source_fn
|
|
105
|
+
|
|
106
|
+
# Start with scan of root table
|
|
107
|
+
if debug:
|
|
108
|
+
if root_required_columns:
|
|
109
|
+
print(f" [SCAN] Scanning table: {plan.root_table} (columns: {len(root_required_columns)})")
|
|
110
|
+
else:
|
|
111
|
+
print(f" [SCAN] Scanning table: {plan.root_table}")
|
|
112
|
+
|
|
113
|
+
iterator = ScanIterator(
|
|
114
|
+
root_source_fn,
|
|
115
|
+
plan.root_table,
|
|
116
|
+
plan.root_alias,
|
|
117
|
+
required_columns=root_required_columns,
|
|
118
|
+
debug=debug
|
|
119
|
+
)
|
|
120
|
+
|
|
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
|
+
|
|
127
|
+
for i, join_info in enumerate(plan.joins, 1):
|
|
128
|
+
# Get required columns for joined table (needed for optimizations)
|
|
129
|
+
join_required_columns = plan.required_columns.get(join_info.table)
|
|
130
|
+
|
|
131
|
+
if debug:
|
|
132
|
+
if join_required_columns:
|
|
133
|
+
print(f" [JOIN {i}/{len(plan.joins)}] {join_info.join_type} JOIN {join_info.table} (columns: {len(join_required_columns)})")
|
|
134
|
+
else:
|
|
135
|
+
print(f" [JOIN {i}/{len(plan.joins)}] {join_info.join_type} JOIN {join_info.table}")
|
|
136
|
+
|
|
137
|
+
# Check if we can push WHERE clauses to this joined table
|
|
138
|
+
right_source_fn = sources[join_info.table]
|
|
139
|
+
join_where_sql = None
|
|
140
|
+
table_where_expr = None
|
|
141
|
+
|
|
142
|
+
# Extract WHERE clauses that reference this joined table
|
|
143
|
+
if remaining_where_expr:
|
|
144
|
+
from .optimizer import extract_table_where_clauses, expression_to_sql_string, remove_expression_from_where
|
|
145
|
+
if debug:
|
|
146
|
+
print(f" [DEBUG] remaining_where_expr is not None: {remaining_where_expr}")
|
|
147
|
+
try:
|
|
148
|
+
# Try both alias and table name (WHERE clause might use either)
|
|
149
|
+
table_alias = join_info.alias or join_info.table
|
|
150
|
+
table_name = join_info.table
|
|
151
|
+
|
|
152
|
+
if debug:
|
|
153
|
+
print(f" [DEBUG] Checking WHERE clauses for alias '{table_alias}' or table '{table_name}'")
|
|
154
|
+
print(f" [DEBUG] Remaining WHERE expr: {remaining_where_expr}")
|
|
155
|
+
|
|
156
|
+
# Try alias first, then table name
|
|
157
|
+
table_where_expr = extract_table_where_clauses(remaining_where_expr, table_alias)
|
|
158
|
+
if not table_where_expr and table_alias != table_name:
|
|
159
|
+
# If alias didn't match and it's different from table name, try table name
|
|
160
|
+
table_where_expr = extract_table_where_clauses(remaining_where_expr, table_name)
|
|
161
|
+
|
|
162
|
+
if table_where_expr:
|
|
163
|
+
join_where_sql = expression_to_sql_string(table_where_expr)
|
|
164
|
+
if debug:
|
|
165
|
+
print(f" [OPTIMIZATION] Pushing WHERE clause to {join_info.table}: {join_where_sql}")
|
|
166
|
+
# Remove pushed clauses from remaining WHERE
|
|
167
|
+
remaining_where_expr = remove_expression_from_where(remaining_where_expr, table_where_expr)
|
|
168
|
+
if debug:
|
|
169
|
+
print(f" [DEBUG] Remaining WHERE after removal: {remaining_where_expr}")
|
|
170
|
+
else:
|
|
171
|
+
if debug:
|
|
172
|
+
print(f" [DEBUG] No WHERE clauses found for alias '{table_alias}' or table '{table_name}'")
|
|
173
|
+
except Exception as e:
|
|
174
|
+
if debug:
|
|
175
|
+
print(f" [OPTIMIZATION] Could not push WHERE to {join_info.table}: {e}")
|
|
176
|
+
import traceback
|
|
177
|
+
traceback.print_exc()
|
|
178
|
+
else:
|
|
179
|
+
# Even if not debug, log the error so we can see what's wrong
|
|
180
|
+
import traceback
|
|
181
|
+
print(f" [ERROR] Could not push WHERE to {join_info.table}: {e}")
|
|
182
|
+
traceback.print_exc()
|
|
183
|
+
join_where_sql = None
|
|
184
|
+
|
|
185
|
+
# Apply protocol optimizations to joined table source if supported
|
|
186
|
+
import inspect
|
|
187
|
+
def source_supports_optimizations(source_fn):
|
|
188
|
+
"""Check if source implements optimization protocol."""
|
|
189
|
+
try:
|
|
190
|
+
sig = inspect.signature(source_fn)
|
|
191
|
+
params = list(sig.parameters.keys())
|
|
192
|
+
return 'dynamic_where' in params or 'dynamic_columns' in params
|
|
193
|
+
except (ValueError, TypeError):
|
|
194
|
+
return False
|
|
195
|
+
|
|
196
|
+
optimized_right_source_fn = right_source_fn
|
|
197
|
+
if source_supports_optimizations(right_source_fn) and (join_required_columns or join_where_sql):
|
|
198
|
+
if debug:
|
|
199
|
+
print(f" [OPTIMIZATION] Source {join_info.table} supports protocol - applying optimizations")
|
|
200
|
+
|
|
201
|
+
original_right_source_fn = right_source_fn
|
|
202
|
+
|
|
203
|
+
def optimized_right_source_fn():
|
|
204
|
+
# Call source with optimization parameters
|
|
205
|
+
return original_right_source_fn(
|
|
206
|
+
dynamic_where=join_where_sql,
|
|
207
|
+
dynamic_columns=list(join_required_columns) if join_required_columns else None
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
iterator = _build_join_iterator(
|
|
211
|
+
iterator,
|
|
212
|
+
join_info,
|
|
213
|
+
sources,
|
|
214
|
+
source_metadata,
|
|
215
|
+
plan.required_columns.get(join_info.table), # Pass required columns
|
|
216
|
+
optimized_right_source_fn=optimized_right_source_fn, # Pass optimized source
|
|
217
|
+
debug=debug,
|
|
218
|
+
use_polars=use_polars # Pass Polars flag
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
# Update plan.where_expr to only include clauses not pushed to sources
|
|
222
|
+
plan.where_expr = remaining_where_expr
|
|
223
|
+
|
|
224
|
+
# Apply WHERE filter if present (non-pushable conditions)
|
|
225
|
+
# Must be applied AFTER joins since remaining WHERE conditions may reference joined tables
|
|
226
|
+
if plan.where_expr:
|
|
227
|
+
if debug:
|
|
228
|
+
print(f" [FILTER] Applying WHERE clause (non-pushable conditions)")
|
|
229
|
+
|
|
230
|
+
# Use Polars batch filtering if available and beneficial
|
|
231
|
+
if (use_polars and POLARS_AVAILABLE and PolarsBatchFilterIterator is not None):
|
|
232
|
+
try:
|
|
233
|
+
iterator = PolarsBatchFilterIterator(iterator, plan.where_expr, batch_size=10000, debug=debug)
|
|
234
|
+
if debug:
|
|
235
|
+
print(f" [OPTIMIZATION] Using Polars vectorized filtering (SIMD)")
|
|
236
|
+
except Exception as e:
|
|
237
|
+
if debug:
|
|
238
|
+
print(f" [OPTIMIZATION] Polars filtering failed: {e}, using Python")
|
|
239
|
+
iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
|
|
240
|
+
else:
|
|
241
|
+
iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
|
|
242
|
+
|
|
243
|
+
# Apply projection
|
|
244
|
+
if debug:
|
|
245
|
+
print(f" [PROJECT] Applying SELECT projection")
|
|
246
|
+
print(f"\nPipeline ready. Starting row processing...\n")
|
|
247
|
+
print("-" * 60)
|
|
248
|
+
|
|
249
|
+
# Use Polars batch projection if available and beneficial
|
|
250
|
+
if (use_polars and POLARS_AVAILABLE and PolarsBatchProjectIterator is not None):
|
|
251
|
+
try:
|
|
252
|
+
iterator = PolarsBatchProjectIterator(iterator, plan.projections, batch_size=10000, debug=debug)
|
|
253
|
+
if debug:
|
|
254
|
+
print(f" [OPTIMIZATION] Using Polars vectorized projection")
|
|
255
|
+
except Exception as e:
|
|
256
|
+
if debug:
|
|
257
|
+
print(f" [OPTIMIZATION] Polars projection failed: {e}, using Python")
|
|
258
|
+
iterator = ProjectIterator(iterator, plan.projections, debug=debug)
|
|
259
|
+
else:
|
|
260
|
+
iterator = ProjectIterator(iterator, plan.projections, debug=debug)
|
|
261
|
+
|
|
262
|
+
return iterator
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _build_join_iterator(
|
|
266
|
+
left_iterator,
|
|
267
|
+
join_info,
|
|
268
|
+
sources,
|
|
269
|
+
source_metadata,
|
|
270
|
+
required_columns=None,
|
|
271
|
+
debug=False,
|
|
272
|
+
use_polars=True
|
|
273
|
+
):
|
|
274
|
+
"""
|
|
275
|
+
Build appropriate join iterator based on source capabilities.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
required_columns: Set of column names needed from right table (for column pruning)
|
|
279
|
+
optimized_right_source_fn: Optional optimized source function (with protocol applied)
|
|
280
|
+
"""
|
|
281
|
+
# Use optimized source if provided, otherwise use original
|
|
282
|
+
if optimized_right_source_fn is not None:
|
|
283
|
+
right_source = optimized_right_source_fn
|
|
284
|
+
else:
|
|
285
|
+
right_source = sources[join_info.table]
|
|
286
|
+
right_metadata = source_metadata.get(join_info.table, {})
|
|
287
|
+
|
|
288
|
+
# Apply column pruning to right source if needed
|
|
289
|
+
# For database sources, this would be handled at source creation
|
|
290
|
+
# For other sources, LookupJoinIterator will handle it via ScanIterator
|
|
291
|
+
|
|
292
|
+
# Check if both sides are ordered by join keys
|
|
293
|
+
left_ordered_by = _extract_table_from_key(join_info.left_key)
|
|
294
|
+
right_ordered_by = right_metadata.get("ordered_by")
|
|
295
|
+
|
|
296
|
+
# For merge join, we need both sides sorted on their respective join keys
|
|
297
|
+
# This is a simplified check - in practice, we'd need to verify the actual
|
|
298
|
+
# column names match
|
|
299
|
+
use_merge_join = (
|
|
300
|
+
right_ordered_by is not None and
|
|
301
|
+
right_ordered_by == _extract_column_from_key(join_info.right_key)
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
if use_merge_join:
|
|
305
|
+
if debug:
|
|
306
|
+
print(f" Using MERGE JOIN (sorted data)")
|
|
307
|
+
return MergeJoinIterator(
|
|
308
|
+
left_iterator,
|
|
309
|
+
right_source,
|
|
310
|
+
join_info.left_key,
|
|
311
|
+
join_info.right_key,
|
|
312
|
+
join_info.join_type,
|
|
313
|
+
join_info.table,
|
|
314
|
+
join_info.alias,
|
|
315
|
+
debug=debug
|
|
316
|
+
)
|
|
317
|
+
else:
|
|
318
|
+
# Check if we can use mmap-based join (lowest memory - PRIORITY for large tables)
|
|
319
|
+
right_metadata = source_metadata.get(join_info.table, {})
|
|
320
|
+
right_table_filename = right_metadata.get("filename")
|
|
321
|
+
|
|
322
|
+
# For very large tables, prefer mmap over Polars (memory is critical)
|
|
323
|
+
if (MMAP_AVAILABLE and MmapLookupJoinIterator is not None and
|
|
324
|
+
right_table_filename):
|
|
325
|
+
if debug:
|
|
326
|
+
if required_columns:
|
|
327
|
+
print(f" Using MMAP LOOKUP JOIN (low memory, columns: {len(required_columns)})...")
|
|
328
|
+
else:
|
|
329
|
+
print(f" Using MMAP LOOKUP JOIN (low memory, position-based index)...")
|
|
330
|
+
try:
|
|
331
|
+
return MmapLookupJoinIterator(
|
|
332
|
+
left_iterator,
|
|
333
|
+
right_source,
|
|
334
|
+
join_info.left_key,
|
|
335
|
+
join_info.right_key,
|
|
336
|
+
join_info.join_type,
|
|
337
|
+
join_info.table,
|
|
338
|
+
join_info.alias,
|
|
339
|
+
right_table_filename=right_table_filename,
|
|
340
|
+
required_columns=required_columns,
|
|
341
|
+
debug=debug
|
|
342
|
+
)
|
|
343
|
+
except Exception as e:
|
|
344
|
+
if debug:
|
|
345
|
+
print(f" ⚠️ Mmap join failed: {e}")
|
|
346
|
+
import traceback
|
|
347
|
+
traceback.print_exc()
|
|
348
|
+
print(f" Falling back to Polars/Python")
|
|
349
|
+
# Fallback to Polars or Python
|
|
350
|
+
pass
|
|
351
|
+
|
|
352
|
+
# Decide between Polars and Python implementation
|
|
353
|
+
# NOTE: Only use Polars if mmap not available (mmap is better for memory)
|
|
354
|
+
if (use_polars and POLARS_AVAILABLE and
|
|
355
|
+
should_use_polars(right_source, threshold=10000)):
|
|
356
|
+
if debug:
|
|
357
|
+
if required_columns:
|
|
358
|
+
print(f" Using POLARS LOOKUP JOIN (fast, columns: {len(required_columns)})...")
|
|
359
|
+
else:
|
|
360
|
+
print(f" Using POLARS LOOKUP JOIN (fast, vectorized)...")
|
|
361
|
+
try:
|
|
362
|
+
return PolarsLookupJoinIterator(
|
|
363
|
+
left_iterator,
|
|
364
|
+
right_source,
|
|
365
|
+
join_info.left_key,
|
|
366
|
+
join_info.right_key,
|
|
367
|
+
join_info.join_type,
|
|
368
|
+
join_info.table,
|
|
369
|
+
join_info.alias,
|
|
370
|
+
batch_size=10000,
|
|
371
|
+
required_columns=required_columns,
|
|
372
|
+
debug=debug
|
|
373
|
+
)
|
|
374
|
+
except Exception as e:
|
|
375
|
+
if debug:
|
|
376
|
+
print(f" Polars join failed: {e}, falling back to Python")
|
|
377
|
+
# Fallback to Python implementation
|
|
378
|
+
pass
|
|
379
|
+
|
|
380
|
+
if debug:
|
|
381
|
+
if required_columns:
|
|
382
|
+
print(f" Using LOOKUP JOIN (building index, columns: {len(required_columns)})...")
|
|
383
|
+
else:
|
|
384
|
+
print(f" Using LOOKUP JOIN (building index...)")
|
|
385
|
+
return LookupJoinIterator(
|
|
386
|
+
left_iterator,
|
|
387
|
+
right_source,
|
|
388
|
+
join_info.left_key,
|
|
389
|
+
join_info.right_key,
|
|
390
|
+
join_info.join_type,
|
|
391
|
+
join_info.table,
|
|
392
|
+
join_info.alias,
|
|
393
|
+
required_columns=required_columns,
|
|
394
|
+
debug=debug
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _extract_table_from_key(key):
|
|
399
|
+
"""Extract table alias from a key like 'alias.column'."""
|
|
400
|
+
if "." in key:
|
|
401
|
+
return key.split(".", 1)[0]
|
|
402
|
+
return None
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _extract_column_from_key(key):
|
|
406
|
+
"""Extract column name from a key like 'alias.column'."""
|
|
407
|
+
if "." in key:
|
|
408
|
+
return key.split(".", 1)[1]
|
|
409
|
+
return key
|
|
410
|
+
|