streaming-sql-engine 0.1.0__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.
@@ -0,0 +1,133 @@
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
+
15
+ def execute_plan(
16
+ plan,
17
+ sources,
18
+ source_metadata,
19
+ debug=False
20
+ ):
21
+ """
22
+ Execute a logical plan and return a generator of result rows.
23
+
24
+ Args:
25
+ plan: Logical execution plan
26
+ sources: Dictionary mapping table names to source functions
27
+ source_metadata: Dictionary with metadata about sources (e.g., ordered_by)
28
+
29
+ Returns:
30
+ Generator of result row dictionaries
31
+ """
32
+ # Start with scan of root table
33
+ if debug:
34
+ print(f" [SCAN] Scanning table: {plan.root_table}")
35
+ iterator = ScanIterator(
36
+ sources[plan.root_table],
37
+ plan.root_table,
38
+ plan.root_alias,
39
+ debug=debug
40
+ )
41
+
42
+ # Apply WHERE filter if present
43
+ if plan.where_expr:
44
+ if debug:
45
+ print(f" [FILTER] Applying WHERE clause")
46
+ iterator = FilterIterator(iterator, plan.where_expr, debug=debug)
47
+
48
+ # Apply joins in order
49
+ for i, join_info in enumerate(plan.joins, 1):
50
+ if debug:
51
+ print(f" [JOIN {i}/{len(plan.joins)}] {join_info.join_type} JOIN {join_info.table}")
52
+ iterator = _build_join_iterator(
53
+ iterator,
54
+ join_info,
55
+ sources,
56
+ source_metadata,
57
+ debug=debug
58
+ )
59
+
60
+ # Apply projection
61
+ if debug:
62
+ print(f" [PROJECT] Applying SELECT projection")
63
+ print(f"\nPipeline ready. Starting row processing...\n")
64
+ print("-" * 60)
65
+ iterator = ProjectIterator(iterator, plan.projections, debug=debug)
66
+
67
+ return iterator
68
+
69
+
70
+ def _build_join_iterator(
71
+ left_iterator,
72
+ join_info,
73
+ sources,
74
+ source_metadata,
75
+ debug=False
76
+ ):
77
+ """Build appropriate join iterator based on source capabilities."""
78
+ right_source = sources[join_info.table]
79
+ right_metadata = source_metadata.get(join_info.table, {})
80
+
81
+ # Check if both sides are ordered by join keys
82
+ left_ordered_by = _extract_table_from_key(join_info.left_key)
83
+ right_ordered_by = right_metadata.get("ordered_by")
84
+
85
+ # For merge join, we need both sides sorted on their respective join keys
86
+ # This is a simplified check - in practice, we'd need to verify the actual
87
+ # column names match
88
+ use_merge_join = (
89
+ right_ordered_by is not None and
90
+ right_ordered_by == _extract_column_from_key(join_info.right_key)
91
+ )
92
+
93
+ if use_merge_join:
94
+ if debug:
95
+ print(f" Using MERGE JOIN (sorted data)")
96
+ return MergeJoinIterator(
97
+ left_iterator,
98
+ right_source,
99
+ join_info.left_key,
100
+ join_info.right_key,
101
+ join_info.join_type,
102
+ join_info.table,
103
+ join_info.alias,
104
+ debug=debug
105
+ )
106
+ else:
107
+ if debug:
108
+ print(f" Using LOOKUP JOIN (building index...)")
109
+ return LookupJoinIterator(
110
+ left_iterator,
111
+ right_source,
112
+ join_info.left_key,
113
+ join_info.right_key,
114
+ join_info.join_type,
115
+ join_info.table,
116
+ join_info.alias,
117
+ debug=debug
118
+ )
119
+
120
+
121
+ def _extract_table_from_key(key):
122
+ """Extract table alias from a key like 'alias.column'."""
123
+ if "." in key:
124
+ return key.split(".", 1)[0]
125
+ return None
126
+
127
+
128
+ def _extract_column_from_key(key):
129
+ """Extract column name from a key like 'alias.column'."""
130
+ if "." in key:
131
+ return key.split(".", 1)[1]
132
+ return key
133
+
@@ -0,0 +1,393 @@
1
+ """
2
+ JSONL-based executor: Export tables to JSONL files, then merge them.
3
+ Simpler approach that reduces CPU usage by avoiding in-memory joins.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import tempfile
9
+ from datetime import datetime, date, time
10
+ from decimal import Decimal
11
+ from pathlib import Path
12
+ from .planner import LogicalPlan, JoinInfo
13
+ from .operators import ScanIterator, FilterIterator, ProjectIterator, LookupJoinIterator
14
+
15
+
16
+ def _json_serializer(obj):
17
+ """
18
+ Custom JSON serializer for objects not serializable by default json code.
19
+ Handles datetime, date, time, Decimal, and other common database types.
20
+ """
21
+ if isinstance(obj, (datetime, date, time)):
22
+ return obj.isoformat()
23
+ elif isinstance(obj, Decimal):
24
+ return float(obj)
25
+ elif hasattr(obj, '__dict__'):
26
+ return str(obj)
27
+ raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
28
+
29
+
30
+ def execute_plan_jsonl(
31
+ plan,
32
+ sources,
33
+ source_metadata,
34
+ output_dir=None,
35
+ debug=False
36
+ ):
37
+ """
38
+ Execute plan by exporting tables to JSONL files, then merging.
39
+
40
+ Steps:
41
+ 1. Export root table to JSONL (with WHERE filter if applicable)
42
+ 2. Export each joined table to JSONL
43
+ 3. Merge JSONL files by reading and joining them
44
+ 4. Apply projection
45
+ 5. Yield results
46
+
47
+ Args:
48
+ plan: Logical execution plan
49
+ sources: Dictionary mapping table names to source functions
50
+ source_metadata: Dictionary with metadata about sources
51
+ output_dir: Directory for temporary JSONL files (None = use temp dir)
52
+ debug: Enable debug output
53
+
54
+ Returns:
55
+ Generator of result row dictionaries
56
+ """
57
+ if output_dir is None:
58
+ output_dir = tempfile.mkdtemp(prefix="streaming_sql_")
59
+
60
+ output_path = Path(output_dir)
61
+ output_path.mkdir(parents=True, exist_ok=True)
62
+
63
+ if debug:
64
+ print("=" * 60)
65
+ print("JSONL-BASED EXECUTION MODE")
66
+ print("=" * 60)
67
+ print(f"Temporary directory: {output_dir}\n")
68
+
69
+ try:
70
+ # Step 1: Export root table to JSONL
71
+ if debug:
72
+ print(f"[STEP 1] Exporting root table '{plan.root_table}' to JSONL...")
73
+
74
+ root_jsonl = output_path / f"{plan.root_table}.jsonl"
75
+ root_count = _export_table_to_jsonl(
76
+ sources[plan.root_table],
77
+ plan.root_table,
78
+ plan.root_alias,
79
+ root_jsonl,
80
+ plan.where_expr, # Apply WHERE to root table
81
+ debug
82
+ )
83
+
84
+ if debug:
85
+ print(f" Exported {root_count:,} rows to {root_jsonl.name}\n")
86
+
87
+ # Step 2: Export joined tables to JSONL
88
+ join_jsonls = []
89
+ for i, join_info in enumerate(plan.joins, 1):
90
+ if debug:
91
+ print(f"[STEP {i+1}] Exporting joined table '{join_info.table}' to JSONL...")
92
+
93
+ join_jsonl = output_path / f"{join_info.table}.jsonl"
94
+ join_count = _export_table_to_jsonl(
95
+ sources[join_info.table],
96
+ join_info.table,
97
+ join_info.alias,
98
+ join_jsonl,
99
+ None, # No WHERE for joined tables (filtered during merge)
100
+ debug
101
+ )
102
+
103
+ join_jsonls.append((join_info, join_jsonl))
104
+
105
+ if debug:
106
+ print(f" Exported {join_count:,} rows to {join_jsonl.name}\n")
107
+
108
+ # Step 3: Merge JSONL files
109
+ if debug:
110
+ print(f"[STEP {len(plan.joins) + 2}] Merging JSONL files...")
111
+ print(f" Merging {len(join_jsonls) + 1} files...\n")
112
+
113
+ # Merge files sequentially
114
+ merged_jsonl = root_jsonl
115
+ for join_info, join_jsonl in join_jsonls:
116
+ merged_jsonl = _merge_jsonl_files(
117
+ merged_jsonl,
118
+ join_jsonl,
119
+ join_info,
120
+ output_path,
121
+ debug,
122
+ memory_limit_mb=2000 # Increase to 2GB to use fast in-memory index more often
123
+ )
124
+
125
+ # Step 4: Apply projection and yield results
126
+ if debug:
127
+ print(f"[STEP {len(plan.joins) + 3}] Applying projection and yielding results...\n")
128
+ print("-" * 60)
129
+
130
+ return _yield_from_jsonl_with_projection(merged_jsonl, plan.projections, debug)
131
+
132
+ finally:
133
+ # Cleanup: Remove temporary files
134
+ if not debug:
135
+ # Only cleanup if not debugging (keep files for inspection)
136
+ try:
137
+ import shutil
138
+ shutil.rmtree(output_dir)
139
+ except Exception:
140
+ pass
141
+
142
+
143
+ def _export_table_to_jsonl(
144
+ source_fn,
145
+ table_name,
146
+ alias,
147
+ output_file,
148
+ where_expr, # Expression for filtering
149
+ debug
150
+ ):
151
+ """
152
+ Export a table to JSONL file.
153
+ Writes incrementally (append mode) to minimize memory usage.
154
+ Each row is written immediately, not buffered in memory.
155
+ """
156
+ count = 0
157
+ alias = alias or table_name
158
+
159
+ # Open in write mode (creates new file, writes incrementally)
160
+ with open(output_file, 'w', encoding='utf-8', buffering=8192) as f:
161
+ iterator = ScanIterator(source_fn, table_name, alias, debug=False)
162
+
163
+ # Apply filter if provided
164
+ if where_expr:
165
+ from .operators import FilterIterator
166
+ iterator = FilterIterator(iterator, where_expr, debug=False)
167
+
168
+ # Write each row immediately (incremental write, low memory)
169
+ for row in iterator:
170
+ f.write(json.dumps(row, ensure_ascii=False, default=_json_serializer) + '\n')
171
+ count += 1
172
+
173
+ if debug and count % 10000 == 0:
174
+ print(f" → Exported {count:,} rows...")
175
+
176
+ return count
177
+
178
+
179
+ def _extract_column_from_key(key):
180
+ """Extract column name from a key like 'alias.column'."""
181
+ if "." in key:
182
+ return key.split(".", 1)[1]
183
+ return key
184
+
185
+
186
+ def _merge_jsonl_files(
187
+ left_jsonl,
188
+ right_jsonl,
189
+ join_info,
190
+ output_dir,
191
+ debug,
192
+ memory_limit_mb=500
193
+ ):
194
+ """
195
+ Merge two JSONL files based on join condition.
196
+ Returns path to merged JSONL file.
197
+ """
198
+
199
+ # Extract join key columns
200
+ left_key_col = join_info.left_key # e.g., "sp.sku"
201
+ right_key_col = join_info.right_key # e.g., "spo.concrete_sku"
202
+ right_table_col = _extract_column_from_key(join_info.right_key)
203
+
204
+ # Count right file size first to decide strategy
205
+ if debug:
206
+ print(f" Analyzing {right_jsonl.name}...")
207
+
208
+ right_count = 0
209
+ with open(right_jsonl, 'r', encoding='utf-8') as f:
210
+ for _ in f:
211
+ right_count += 1
212
+
213
+ # Estimate memory usage (rough: ~1KB per row average)
214
+ estimated_mb = (right_count * 1024) / (1024 * 1024)
215
+
216
+ if debug:
217
+ print(f" Right table: {right_count:,} rows (~{estimated_mb:.1f} MB estimated)")
218
+
219
+ # Strategy: If right table is small enough, use in-memory index (fast)
220
+ # Otherwise, use streaming approach (lower memory)
221
+ use_memory_index = estimated_mb < memory_limit_mb
222
+
223
+ # Initialize merged_jsonl variable (will be set in either branch)
224
+ merged_jsonl = None
225
+
226
+ if use_memory_index:
227
+ # Fast path: Build index in memory (for small right tables)
228
+ if debug:
229
+ print(f" Using in-memory index (table < {memory_limit_mb} MB)...")
230
+
231
+ lookup_index = {}
232
+
233
+ with open(right_jsonl, 'r', encoding='utf-8') as f:
234
+ for line in f:
235
+ right_row = json.loads(line)
236
+ key_value = right_row.get(right_key_col)
237
+ if key_value is None:
238
+ key_value = right_row.get(right_table_col)
239
+ if key_value is not None:
240
+ if key_value not in lookup_index:
241
+ lookup_index[key_value] = []
242
+ lookup_index[key_value].append(right_row)
243
+
244
+ if debug:
245
+ print(f" Index built: {right_count:,} rows, {len(lookup_index):,} unique keys")
246
+
247
+ # Merge using index - write incrementally
248
+ merged_jsonl = output_dir / f"merged_{left_jsonl.stem}_{right_jsonl.stem}.jsonl"
249
+ merged_count = 0
250
+
251
+ if debug:
252
+ print(f" Merging into {merged_jsonl.name}...")
253
+
254
+ with open(left_jsonl, 'r', encoding='utf-8') as left_f, \
255
+ open(merged_jsonl, 'w', encoding='utf-8') as merged_f:
256
+
257
+ for line in left_f:
258
+ left_row = json.loads(line)
259
+ left_key_value = left_row.get(left_key_col)
260
+ right_matches = lookup_index.get(left_key_value, [])
261
+
262
+ if join_info.join_type == "INNER":
263
+ if not right_matches:
264
+ continue
265
+ for right_row in right_matches:
266
+ merged_row = {**left_row, **right_row}
267
+ merged_f.write(json.dumps(merged_row, ensure_ascii=False, default=_json_serializer) + '\n')
268
+ merged_count += 1
269
+ else: # LEFT JOIN
270
+ if not right_matches:
271
+ merged_f.write(json.dumps(left_row, ensure_ascii=False, default=_json_serializer) + '\n')
272
+ merged_count += 1
273
+ else:
274
+ for right_row in right_matches:
275
+ merged_row = {**left_row, **right_row}
276
+ merged_f.write(json.dumps(merged_row, ensure_ascii=False, default=_json_serializer) + '\n')
277
+ merged_count += 1
278
+
279
+ if debug and merged_count % 10000 == 0:
280
+ print(f" Merged {merged_count:,} rows...")
281
+
282
+ else:
283
+ # For very large files: Build index anyway but warn about memory usage
284
+ # The O(n*m) streaming approach is too slow, so we use in-memory index even for large files
285
+ # User can increase memory_limit_mb if they have memory constraints
286
+ if debug:
287
+ print(f" WARNING: Right table is large ({estimated_mb:.1f} MB)")
288
+ print(f" Using in-memory index anyway (streaming mode is too slow)")
289
+ print(f" If you run out of memory, increase memory_limit_mb parameter")
290
+
291
+ lookup_index = {}
292
+
293
+ with open(right_jsonl, 'r', encoding='utf-8') as f:
294
+ for line in f:
295
+ right_row = json.loads(line)
296
+ key_value = right_row.get(right_key_col)
297
+ if key_value is None:
298
+ key_value = right_row.get(right_table_col)
299
+ if key_value is not None:
300
+ if key_value not in lookup_index:
301
+ lookup_index[key_value] = []
302
+ lookup_index[key_value].append(right_row)
303
+
304
+ if debug:
305
+ print(f" Index built: {right_count:,} rows, {len(lookup_index):,} unique keys")
306
+
307
+ # Merge using index - write incrementally
308
+ merged_jsonl = output_dir / f"merged_{left_jsonl.stem}_{right_jsonl.stem}.jsonl"
309
+ merged_count = 0
310
+
311
+ if debug:
312
+ print(f" Merging into {merged_jsonl.name}...")
313
+
314
+ with open(left_jsonl, 'r', encoding='utf-8') as left_f, \
315
+ open(merged_jsonl, 'w', encoding='utf-8') as merged_f:
316
+
317
+ for line in left_f:
318
+ left_row = json.loads(line)
319
+ left_key_value = left_row.get(left_key_col)
320
+ right_matches = lookup_index.get(left_key_value, [])
321
+
322
+ if join_info.join_type == "INNER":
323
+ if not right_matches:
324
+ continue
325
+ for right_row in right_matches:
326
+ merged_row = {**left_row, **right_row}
327
+ merged_f.write(json.dumps(merged_row, ensure_ascii=False, default=_json_serializer) + '\n')
328
+ merged_count += 1
329
+ else: # LEFT JOIN
330
+ if not right_matches:
331
+ merged_f.write(json.dumps(left_row, ensure_ascii=False, default=_json_serializer) + '\n')
332
+ merged_count += 1
333
+ else:
334
+ for right_row in right_matches:
335
+ merged_row = {**left_row, **right_row}
336
+ merged_f.write(json.dumps(merged_row, ensure_ascii=False, default=_json_serializer) + '\n')
337
+ merged_count += 1
338
+
339
+ if debug and merged_count % 10000 == 0:
340
+ print(f" Merged {merged_count:,} rows...")
341
+
342
+ if debug:
343
+ print(f" Merge complete: {merged_count:,} rows\n")
344
+
345
+ # Return the merged file path
346
+ if merged_jsonl is None:
347
+ raise RuntimeError("Failed to create merged JSONL file")
348
+
349
+ return merged_jsonl
350
+
351
+ def _yield_from_jsonl_with_projection(
352
+ jsonl_file,
353
+ projections,
354
+ debug
355
+ ):
356
+ """
357
+ Read JSONL file and apply SELECT projection.
358
+ Streams through file line-by-line (low memory usage).
359
+ Yields results incrementally, not buffered in memory.
360
+ """
361
+ from .operators import ProjectIterator
362
+ from .evaluator import evaluate_expression
363
+ from sqlglot import expressions as exp
364
+
365
+ count = 0
366
+
367
+ with open(jsonl_file, 'r', encoding='utf-8') as f:
368
+ for line in f:
369
+ row = json.loads(line)
370
+
371
+ # Apply projection
372
+ result = {}
373
+ for expr in projections:
374
+ if isinstance(expr, exp.Alias):
375
+ alias = expr.alias
376
+ value = evaluate_expression(expr.this, row)
377
+ result[alias] = value
378
+ elif isinstance(expr, exp.Column):
379
+ col_name = f"{expr.table}.{expr.name}" if expr.table else expr.name
380
+ if col_name in row:
381
+ result[expr.name] = row[col_name]
382
+ else:
383
+ raise KeyError(f"Column {col_name} not found")
384
+ else:
385
+ value = evaluate_expression(expr, row)
386
+ result[str(expr)] = value
387
+
388
+ count += 1
389
+ if debug and count % 10000 == 0:
390
+ print(f" Yielded {count:,} result rows...")
391
+
392
+ yield result
393
+