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,479 @@
1
+ """
2
+ Iterator operators for the execution pipeline.
3
+ """
4
+
5
+ from sqlglot import expressions as exp
6
+ from .evaluator import evaluate_expression
7
+
8
+
9
+ class ScanIterator:
10
+ """Scans rows from a source function."""
11
+
12
+ def __init__(
13
+ self,
14
+ source_fn,
15
+ table_name,
16
+ alias,
17
+ debug=False
18
+ ):
19
+ self.source_fn = source_fn
20
+ self.table_name = table_name
21
+ self.alias = alias or table_name
22
+ self._iterator = None
23
+ self.debug = debug
24
+ self._row_count = 0
25
+
26
+ def __iter__(self):
27
+ return self
28
+
29
+ def __next__(self):
30
+ if self._iterator is None:
31
+ self._iterator = iter(self.source_fn())
32
+ if self.debug:
33
+ print(f" Started reading from {self.table_name}")
34
+
35
+ row = next(self._iterator)
36
+ self._row_count += 1
37
+
38
+ # Prefix all columns with table alias (optimized: use dict comprehension)
39
+ prefixed_row = {f"{self.alias}.{key}": value for key, value in row.items()}
40
+
41
+ if self.debug and self._row_count % 10000 == 0:
42
+ print(f" Scanned {self._row_count:,} rows from {self.table_name}")
43
+
44
+ return prefixed_row
45
+
46
+
47
+ class FilterIterator:
48
+ """Filters rows based on WHERE expression."""
49
+
50
+ def __init__(
51
+ self,
52
+ source,
53
+ where_expr,
54
+ debug=False
55
+ ):
56
+ self.source = source
57
+ self.where_expr = where_expr
58
+ self.debug = debug
59
+ self._rows_processed = 0
60
+ self._rows_passed = 0
61
+
62
+ def __iter__(self):
63
+ return self
64
+
65
+ def __next__(self):
66
+ while True:
67
+ row = next(self.source)
68
+ self._rows_processed += 1
69
+
70
+ if evaluate_expression(self.where_expr, row):
71
+ self._rows_passed += 1
72
+ if self.debug and self._rows_passed % 10000 == 0:
73
+ print(f" Filter: {self._rows_passed:,} passed / {self._rows_processed:,} processed")
74
+ return row
75
+ # Row filtered out - continue loop
76
+
77
+
78
+ class ProjectIterator:
79
+ """Applies SELECT projection to rows."""
80
+
81
+ def __init__(
82
+ self,
83
+ source,
84
+ projections,
85
+ debug=False
86
+ ):
87
+ self.source = source
88
+ self.projections = projections
89
+ self.debug = debug
90
+ self._row_count = 0
91
+
92
+ def __iter__(self):
93
+ return self
94
+
95
+ def __next__(self):
96
+ row = next(self.source)
97
+ self._row_count += 1
98
+
99
+ if self.debug and self._row_count % 10000 == 0:
100
+ print(f" Projected {self._row_count:,} result rows")
101
+
102
+ result = {}
103
+
104
+ for expr in self.projections:
105
+ if isinstance(expr, exp.Alias):
106
+ # SELECT col AS alias
107
+ alias = expr.alias
108
+ value = evaluate_expression(expr.this, row)
109
+ result[alias] = value
110
+ elif isinstance(expr, exp.Column):
111
+ # SELECT alias.col
112
+ col_name = f"{expr.table}.{expr.name}" if expr.table else expr.name
113
+ if col_name in row:
114
+ # Use column name as key (or last part if no alias)
115
+ key = expr.name
116
+ result[key] = row[col_name]
117
+ else:
118
+ raise KeyError(f"Column {col_name} not found in row")
119
+ else:
120
+ # Simple expression - use string representation as key
121
+ value = evaluate_expression(expr, row)
122
+ key = str(expr)
123
+ result[key] = value
124
+
125
+ return result
126
+
127
+
128
+ class LookupJoinIterator:
129
+ """
130
+ Performs join by building a lookup index on the right side.
131
+ """
132
+
133
+ def __init__(
134
+ self,
135
+ left_source,
136
+ right_source_fn,
137
+ left_key,
138
+ right_key,
139
+ join_type,
140
+ right_table,
141
+ right_alias,
142
+ debug=False
143
+ ):
144
+ self.left_source = left_source
145
+ self.right_source_fn = right_source_fn
146
+ self.left_key = left_key
147
+ self.right_key = right_key
148
+ self.join_type = join_type
149
+ self.right_table = right_table
150
+ self.right_alias = right_alias or right_table
151
+ self.debug = debug
152
+
153
+ # Build lookup index
154
+ self.lookup_index = {}
155
+ if self.debug:
156
+ print(f" Building lookup index for {right_table}...")
157
+ self._build_index()
158
+
159
+ self._left_row = None
160
+ self._right_matches = []
161
+ self._match_index = 0
162
+ self._join_count = 0
163
+
164
+ def _build_index(self):
165
+ """Build lookup index from right side table."""
166
+ right_table_col = _extract_column_from_key(self.right_key)
167
+ index_size = 0
168
+
169
+ for row in self.right_source_fn():
170
+ # Skip None or invalid rows
171
+ if not row or not isinstance(row, dict):
172
+ continue
173
+
174
+ # Prefix columns with right alias (optimized: use dict comprehension)
175
+ prefixed_row = {f"{self.right_alias}.{key}": value for key, value in row.items()}
176
+
177
+ # Index by join key value
178
+ key_value = row.get(right_table_col)
179
+ # Skip rows with None join keys (can't join on None)
180
+ if key_value is None:
181
+ continue
182
+ if key_value not in self.lookup_index:
183
+ self.lookup_index[key_value] = []
184
+ self.lookup_index[key_value].append(prefixed_row)
185
+ index_size += 1
186
+
187
+ if self.debug:
188
+ print(f" Index built: {index_size:,} rows, {len(self.lookup_index):,} unique keys")
189
+
190
+ def __iter__(self):
191
+ return self
192
+
193
+ def __next__(self):
194
+ while True:
195
+ # Get next left row if needed
196
+ if self._left_row is None:
197
+ try:
198
+ self._left_row = next(self.left_source)
199
+ except StopIteration:
200
+ raise StopIteration
201
+
202
+ # Get join key value from left row
203
+ try:
204
+ left_key_value = self._get_key_value(self._left_row, self.left_key)
205
+ except KeyError:
206
+ # Join key not found in left row, skip this row
207
+ self._left_row = None
208
+ continue
209
+
210
+ # Skip rows with None join keys (can't join on None)
211
+ if left_key_value is None:
212
+ if self.join_type == "INNER":
213
+ # INNER JOIN: skip rows with None keys
214
+ self._left_row = None
215
+ continue
216
+ else:
217
+ # LEFT JOIN: yield left row with no match
218
+ result = self._left_row.copy()
219
+ self._left_row = None
220
+ self._join_count += 1
221
+ return result
222
+
223
+ # Get matching right rows
224
+ if self._match_index == 0:
225
+ matches = self.lookup_index.get(left_key_value, [])
226
+ # Filter out None or invalid rows
227
+ self._right_matches = [m for m in matches if m is not None and isinstance(m, dict)]
228
+
229
+ # Handle INNER JOIN
230
+ if self.join_type == "INNER":
231
+ if not self._right_matches:
232
+ # No match, skip this left row
233
+ self._left_row = None
234
+ continue
235
+
236
+ # Yield current match
237
+ if self._match_index < len(self._right_matches):
238
+ right_row = self._right_matches[self._match_index]
239
+
240
+ # Safety check: skip None or invalid rows
241
+ if right_row is None or not isinstance(right_row, dict):
242
+ self._match_index += 1
243
+ continue
244
+
245
+ # Safety check: ensure left_row is still valid
246
+ if self._left_row is None or not isinstance(self._left_row, dict):
247
+ # Left row became invalid, skip to next
248
+ self._left_row = None
249
+ self._match_index = 0
250
+ continue
251
+
252
+ # Store left_row before potentially resetting it
253
+ left_row_copy = self._left_row.copy()
254
+ self._match_index += 1
255
+
256
+ # If we've exhausted matches, reset for next left row
257
+ if self._match_index >= len(self._right_matches):
258
+ self._left_row = None
259
+ self._match_index = 0
260
+
261
+ self._join_count += 1
262
+ if self.debug and self._join_count % 10000 == 0:
263
+ print(f" Merge join: {self._join_count:,} rows matched")
264
+ return {**left_row_copy, **right_row}
265
+
266
+ # Handle LEFT JOIN
267
+ else: # LEFT JOIN
268
+ if not self._right_matches:
269
+ # No match, yield left row with NULLs
270
+ result = self._left_row.copy()
271
+ self._left_row = None
272
+ self._join_count += 1
273
+ if self.debug and self._join_count % 10000 == 0:
274
+ print(f" Join {self._join_count:,} rows (LEFT JOIN with NULLs)")
275
+ return result
276
+
277
+ # Yield current match
278
+ if self._match_index < len(self._right_matches):
279
+ right_row = self._right_matches[self._match_index]
280
+
281
+ # Safety check: skip None or invalid rows
282
+ if right_row is None or not isinstance(right_row, dict):
283
+ self._match_index += 1
284
+ continue
285
+
286
+ # Safety check: ensure left_row is still valid
287
+ if self._left_row is None or not isinstance(self._left_row, dict):
288
+ # Left row became invalid, skip to next
289
+ self._left_row = None
290
+ self._match_index = 0
291
+ continue
292
+
293
+ # Store left_row before potentially resetting it
294
+ left_row_copy = self._left_row.copy()
295
+ self._match_index += 1
296
+
297
+ # If we've exhausted matches, reset for next left row
298
+ if self._match_index >= len(self._right_matches):
299
+ self._left_row = None
300
+ self._match_index = 0
301
+
302
+ self._join_count += 1
303
+ if self.debug and self._join_count % 10000 == 0:
304
+ print(f" Merge join: {self._join_count:,} rows matched")
305
+ return {**left_row_copy, **right_row}
306
+
307
+ def _get_key_value(self, row, key):
308
+ """Extract join key value from a row."""
309
+ if key in row:
310
+ return row[key]
311
+ raise KeyError(f"Join key {key} not found in row")
312
+
313
+
314
+ class MergeJoinIterator:
315
+ """
316
+ Performs join using merge algorithm when both sides are sorted.
317
+ Note: This is a simplified implementation that works best when keys are unique.
318
+ For duplicate keys, it may not produce all combinations efficiently.
319
+ """
320
+
321
+ def __init__(
322
+ self,
323
+ left_source,
324
+ right_source_fn,
325
+ left_key,
326
+ right_key,
327
+ join_type,
328
+ right_table,
329
+ right_alias,
330
+ debug=False
331
+ ):
332
+ self.left_source = left_source
333
+ self.right_source_fn = right_source_fn
334
+ self.left_key = left_key
335
+ self.right_key = right_key
336
+ self.join_type = join_type
337
+ self.right_table = right_table
338
+ self.right_alias = right_alias or right_table
339
+ self.debug = debug
340
+
341
+ # Initialize right iterator
342
+ self.right_iterator = iter(self.right_source_fn())
343
+ self._right_row = None
344
+ self._join_count = 0
345
+ self._left_row = None
346
+
347
+ # Buffer for right rows with same key (handles duplicates)
348
+ self._right_buffer = []
349
+ self._right_buffer_index = 0
350
+ self._current_right_key = None
351
+
352
+ def __iter__(self):
353
+ return self
354
+
355
+ def _advance_right(self) -> bool:
356
+ """Advance right iterator and return True if successful."""
357
+ try:
358
+ raw_right = next(self.right_iterator)
359
+ # Prefix columns
360
+ self._right_row = {}
361
+ for key, value in raw_right.items():
362
+ prefixed_key = f"{self.right_alias}.{key}"
363
+ self._right_row[prefixed_key] = value
364
+ return True
365
+ except StopIteration:
366
+ self._right_row = None
367
+ return False
368
+
369
+ def _fill_right_buffer(self, target_key):
370
+ """Fill right buffer with all rows matching target_key."""
371
+ self._right_buffer = []
372
+ self._right_buffer_index = 0
373
+
374
+ if self._right_row is None:
375
+ if not self._advance_right():
376
+ return
377
+
378
+ right_key_value = self._get_key_value(self._right_row, self.right_key)
379
+
380
+ # Collect all right rows with matching key
381
+ while right_key_value == target_key:
382
+ self._right_buffer.append(self._right_row)
383
+ if not self._advance_right():
384
+ break
385
+ right_key_value = self._get_key_value(self._right_row, self.right_key)
386
+
387
+ def __next__(self):
388
+ while True:
389
+ # Get next left row if needed
390
+ if self._left_row is None:
391
+ try:
392
+ self._left_row = next(self.left_source)
393
+ except StopIteration:
394
+ # For LEFT JOIN, check if we have any remaining unmatched rows
395
+ # (simplified - full implementation would track these)
396
+ raise StopIteration
397
+
398
+ left_key_value = self._get_key_value(self._left_row, self.left_key)
399
+
400
+ # Advance right until we're at or past left key
401
+ while True:
402
+ if self._right_row is None:
403
+ if not self._advance_right():
404
+ # Right exhausted
405
+ if self.join_type == "LEFT":
406
+ # Yield left with NULLs
407
+ result = self._left_row.copy()
408
+ self._left_row = None
409
+ return result
410
+ # For INNER, skip remaining left rows
411
+ raise StopIteration
412
+
413
+ right_key_value = self._get_key_value(self._right_row, self.right_key)
414
+
415
+ if right_key_value < left_key_value:
416
+ # Right is behind, advance
417
+ if not self._advance_right():
418
+ # Right exhausted
419
+ if self.join_type == "LEFT":
420
+ result = self._left_row.copy()
421
+ self._left_row = None
422
+ return result
423
+ raise StopIteration
424
+ continue
425
+ elif right_key_value > left_key_value:
426
+ # Right has passed, no match for this left
427
+ if self.join_type == "LEFT":
428
+ result = self._left_row.copy()
429
+ self._left_row = None
430
+ return result
431
+ # For INNER, skip this left row
432
+ self._left_row = None
433
+ break
434
+ else:
435
+ # Keys match
436
+ if self._current_right_key != left_key_value:
437
+ # New key, fill buffer
438
+ self._fill_right_buffer(left_key_value)
439
+ self._current_right_key = left_key_value
440
+
441
+ if not self._right_buffer:
442
+ # No matches (shouldn't happen, but handle it)
443
+ if self.join_type == "LEFT":
444
+ result = self._left_row.copy()
445
+ self._left_row = None
446
+ return result
447
+ self._left_row = None
448
+ break
449
+
450
+ # Yield current combination
451
+ right_row = self._right_buffer[self._right_buffer_index]
452
+ self._right_buffer_index += 1
453
+
454
+ # Save left_row before potentially clearing it
455
+ result = {**self._left_row, **right_row}
456
+
457
+ # If we've exhausted right buffer, move to next left row
458
+ if self._right_buffer_index >= len(self._right_buffer):
459
+ self._right_buffer_index = 0
460
+ self._left_row = None
461
+
462
+ self._join_count += 1
463
+ if self.debug and self._join_count % 10000 == 0:
464
+ print(f" Merge join: {self._join_count:,} rows matched")
465
+ return result
466
+
467
+ def _get_key_value(self, row, key):
468
+ """Extract join key value from a row."""
469
+ if key in row:
470
+ return row[key]
471
+ raise KeyError(f"Join key {key} not found in row")
472
+
473
+
474
+ def _extract_column_from_key(key):
475
+ """Extract column name from a key like 'alias.column'."""
476
+ if "." in key:
477
+ return key.split(".", 1)[1]
478
+ return key
479
+
@@ -0,0 +1,93 @@
1
+ """
2
+ SQL parsing using sqlglot to extract query structure.
3
+ """
4
+
5
+ import sqlglot
6
+ from sqlglot import expressions as exp
7
+
8
+
9
+ class ParseError(Exception):
10
+ """Raised when SQL parsing fails or unsupported constructs are detected."""
11
+ pass
12
+
13
+
14
+ def parse_sql(sql, dialect=None):
15
+ """
16
+ Parse SQL string into an AST.
17
+
18
+ Args:
19
+ sql: SQL query string
20
+ dialect: Optional SQL dialect ('mysql', 'postgres', 'sqlite', etc.)
21
+ If None, tries multiple dialects automatically
22
+
23
+ Returns:
24
+ sqlglot Select expression AST
25
+
26
+ Raises:
27
+ ParseError: If parsing fails or unsupported constructs are found
28
+ """
29
+ if dialect:
30
+ # Use specified dialect
31
+ dialects_to_try = [dialect]
32
+ else:
33
+ # Try common dialects in order
34
+ dialects_to_try = ["mysql", "postgres", "sqlite"]
35
+
36
+ last_error = None
37
+ for dialect_name in dialects_to_try:
38
+ try:
39
+ parsed = sqlglot.parse_one(sql, dialect=dialect_name)
40
+ if isinstance(parsed, exp.Select):
41
+ # Check for unsupported constructs
42
+ _validate_query(parsed)
43
+ return parsed
44
+ else:
45
+ raise ParseError(f"Only SELECT queries are supported, got {type(parsed).__name__}")
46
+ except Exception as e:
47
+ last_error = e
48
+ continue
49
+
50
+ # If all dialects failed, raise the last error
51
+ raise ParseError(f"Failed to parse SQL with any dialect. Last error: {last_error}") from last_error
52
+
53
+
54
+ def _validate_query(select):
55
+ """Validate that query only contains supported constructs."""
56
+ # Check for GROUP BY
57
+ if select.args.get("group"):
58
+ raise ParseError("GROUP BY is not supported")
59
+
60
+ # Check for ORDER BY
61
+ if select.args.get("order"):
62
+ raise ParseError("ORDER BY is not supported")
63
+
64
+ # Check for HAVING
65
+ if select.args.get("having"):
66
+ raise ParseError("HAVING is not supported")
67
+
68
+ # Check for UNION
69
+ if select.args.get("union"):
70
+ raise ParseError("UNION is not supported")
71
+
72
+ # Check for LIMIT (we could support this but it's not in the spec)
73
+ if select.args.get("limit"):
74
+ raise ParseError("LIMIT is not supported")
75
+
76
+ # Check for subqueries in FROM
77
+ for join in select.args.get("joins", []):
78
+ if isinstance(join.this, exp.Select):
79
+ raise ParseError("Subqueries in JOIN are not supported")
80
+
81
+ # Check for aggregations in SELECT
82
+ for expr in select.expressions:
83
+ if _has_aggregation(expr):
84
+ raise ParseError("Aggregations are not supported")
85
+
86
+
87
+ def _has_aggregation(expr):
88
+ """Check if expression contains aggregations."""
89
+ for node in expr.walk():
90
+ if isinstance(node, (exp.Count, exp.Sum, exp.Avg, exp.Max, exp.Min)):
91
+ return True
92
+ return False
93
+