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.
@@ -0,0 +1,470 @@
1
+ """
2
+ Query optimization: Column pruning and filter pushdown.
3
+
4
+ This module analyzes queries to:
5
+ 1. Determine which columns are actually needed from each table
6
+ 2. Identify WHERE clause conditions that can be pushed to data sources
7
+ """
8
+
9
+ from sqlglot import expressions as exp
10
+ from typing import Set, Dict, Optional, Tuple
11
+ from .planner import LogicalPlan, JoinInfo
12
+
13
+
14
+ def analyze_required_columns(plan: LogicalPlan) -> Dict[str, Set[str]]:
15
+ """
16
+ Analyze which columns are needed from each table.
17
+
18
+ Args:
19
+ plan: Logical execution plan
20
+
21
+ Returns:
22
+ Dictionary mapping table name to set of required column names
23
+ (without table prefix, e.g., "id" not "users.id")
24
+ """
25
+ required_columns = {}
26
+
27
+ # Track table aliases
28
+ table_aliases = {plan.root_table: plan.root_alias or plan.root_table}
29
+ for join in plan.joins:
30
+ table_aliases[join.table] = join.alias or join.table
31
+
32
+ # 1. Columns needed for SELECT projections
33
+ for projection in plan.projections:
34
+ _extract_columns_from_expr(projection, required_columns, table_aliases)
35
+
36
+ # 2. Columns needed for WHERE clause
37
+ if plan.where_expr:
38
+ _extract_columns_from_expr(plan.where_expr, required_columns, table_aliases)
39
+
40
+ # 3. Columns needed for JOIN keys
41
+ for join in plan.joins:
42
+ # Left key (from already processed tables)
43
+ left_table = _extract_table_from_key(join.left_key)
44
+ if left_table:
45
+ left_col = _extract_column_from_key(join.left_key)
46
+ table_name = _find_table_by_alias(left_table, table_aliases)
47
+ if table_name:
48
+ if table_name not in required_columns:
49
+ required_columns[table_name] = set()
50
+ required_columns[table_name].add(left_col)
51
+
52
+ # Right key (from joined table)
53
+ right_col = _extract_column_from_key(join.right_key)
54
+ if join.table not in required_columns:
55
+ required_columns[join.table] = set()
56
+ required_columns[join.table].add(right_col)
57
+
58
+ return required_columns
59
+
60
+
61
+ def _extract_columns_from_expr(expr, required_columns: Dict[str, Set[str]],
62
+ table_aliases: Dict[str, str]):
63
+ """Recursively extract column references from an expression."""
64
+ if isinstance(expr, exp.Column):
65
+ table_alias = expr.table
66
+ column_name = expr.name
67
+
68
+ if table_alias:
69
+ # Find which table this alias refers to
70
+ table_name = _find_table_by_alias(table_alias, table_aliases)
71
+ if table_name:
72
+ if table_name not in required_columns:
73
+ required_columns[table_name] = set()
74
+ required_columns[table_name].add(column_name)
75
+ else:
76
+ # Column without table - add to all tables (ambiguous, but safe)
77
+ for table_name in table_aliases.keys():
78
+ if table_name not in required_columns:
79
+ required_columns[table_name] = set()
80
+ required_columns[table_name].add(column_name)
81
+
82
+ elif isinstance(expr, exp.Alias):
83
+ # Recurse into aliased expression
84
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
85
+
86
+ elif isinstance(expr, exp.Paren):
87
+ # Recurse into parenthesized expression
88
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
89
+
90
+ elif isinstance(expr, (exp.EQ, exp.NEQ, exp.LT, exp.GT, exp.LTE, exp.GTE)):
91
+ # Binary comparison - check both sides
92
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
93
+ _extract_columns_from_expr(expr.expression, required_columns, table_aliases)
94
+
95
+ elif isinstance(expr, (exp.And, exp.Or)):
96
+ # Boolean operators - check both sides
97
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
98
+ _extract_columns_from_expr(expr.expression, required_columns, table_aliases)
99
+
100
+ elif isinstance(expr, exp.Not):
101
+ # NOT operator - recurse
102
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
103
+
104
+ elif isinstance(expr, exp.Is):
105
+ # IS NULL / IS NOT NULL
106
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
107
+
108
+ elif isinstance(expr, exp.In):
109
+ # IN clause
110
+ _extract_columns_from_expr(expr.this, required_columns, table_aliases)
111
+ if isinstance(expr.expression, exp.Tuple):
112
+ for e in expr.expression.expressions:
113
+ _extract_columns_from_expr(e, required_columns, table_aliases)
114
+
115
+ # Literals and other expressions don't reference columns
116
+
117
+
118
+ def _find_table_by_alias(alias: str, table_aliases: Dict[str, str]) -> Optional[str]:
119
+ """Find table name by its alias."""
120
+ for table_name, table_alias in table_aliases.items():
121
+ if table_alias == alias or table_name == alias:
122
+ return table_name
123
+ return None
124
+
125
+
126
+ def _extract_table_from_key(key: str) -> Optional[str]:
127
+ """Extract table alias from a key like 'alias.column'."""
128
+ if "." in key:
129
+ return key.split(".", 1)[0]
130
+ return None
131
+
132
+
133
+ def _extract_column_from_key(key: str) -> str:
134
+ """Extract column name from a key like 'alias.column'."""
135
+ if "." in key:
136
+ return key.split(".", 1)[1]
137
+ return key
138
+
139
+
140
+ def analyze_filter_pushdown(plan: LogicalPlan) -> Tuple[Optional[exp.Expression], Optional[exp.Expression]]:
141
+ """
142
+ Analyze WHERE clause to determine what can be pushed to root table.
143
+
144
+ Only conditions that reference ONLY the root table can be pushed down.
145
+ Conditions referencing joined tables must be evaluated after joins.
146
+
147
+ Args:
148
+ plan: Logical execution plan
149
+
150
+ Returns:
151
+ Tuple of (pushable_where_expr, remaining_where_expr)
152
+ - pushable_where_expr: WHERE conditions that only reference root table (can be pushed)
153
+ - remaining_where_expr: WHERE conditions that reference other tables (must stay)
154
+ """
155
+ if not plan.where_expr:
156
+ return None, None
157
+
158
+ root_alias = plan.root_alias or plan.root_table
159
+
160
+ # Get all table aliases (for joined tables)
161
+ joined_aliases = set()
162
+ for join in plan.joins:
163
+ joined_aliases.add(join.alias or join.table)
164
+
165
+ # Analyze expression to split pushable vs non-pushable
166
+ pushable_parts = []
167
+ remaining_parts = []
168
+
169
+ _split_where_expression(
170
+ plan.where_expr,
171
+ root_alias,
172
+ joined_aliases,
173
+ pushable_parts,
174
+ remaining_parts
175
+ )
176
+
177
+ # Reconstruct expressions
178
+ pushable_expr = _combine_expressions(pushable_parts, exp.And) if pushable_parts else None
179
+ remaining_expr = _combine_expressions(remaining_parts, exp.And) if remaining_parts else None
180
+
181
+ return pushable_expr, remaining_expr
182
+
183
+
184
+ def _split_where_expression(expr, root_alias: str, joined_aliases: Set[str],
185
+ pushable_parts: list, remaining_parts: list):
186
+ """
187
+ Recursively split WHERE expression into pushable and non-pushable parts.
188
+ """
189
+ if isinstance(expr, exp.And):
190
+ # AND: both sides must be pushable for whole expression to be pushable
191
+ _split_where_expression(expr.this, root_alias, joined_aliases, pushable_parts, remaining_parts)
192
+ _split_where_expression(expr.expression, root_alias, joined_aliases, pushable_parts, remaining_parts)
193
+
194
+ elif isinstance(expr, exp.Or):
195
+ # OR: if either side references joined tables, whole expression can't be pushed
196
+ # For simplicity, we don't push OR expressions (could be optimized further)
197
+ remaining_parts.append(expr)
198
+
199
+ elif isinstance(expr, exp.Not):
200
+ # NOT: check if inner expression is pushable
201
+ inner_pushable = _is_expression_pushable(expr.this, root_alias, joined_aliases)
202
+ if inner_pushable:
203
+ pushable_parts.append(expr)
204
+ else:
205
+ remaining_parts.append(expr)
206
+
207
+ else:
208
+ # Leaf expression (EQ, NEQ, LT, GT, etc.)
209
+ if _is_expression_pushable(expr, root_alias, joined_aliases):
210
+ pushable_parts.append(expr)
211
+ else:
212
+ remaining_parts.append(expr)
213
+
214
+
215
+ def _is_expression_pushable(expr, root_alias: str, joined_aliases: Set[str]) -> bool:
216
+ """
217
+ Check if an expression only references the root table (can be pushed).
218
+ """
219
+ referenced_aliases = set()
220
+ _extract_table_aliases_from_expr(expr, referenced_aliases)
221
+
222
+ # Can push if only references root table (or no table references)
223
+ return len(referenced_aliases - {root_alias}) == 0
224
+
225
+
226
+ def _extract_table_aliases_from_expr(expr, aliases: Set[str]):
227
+ """Extract all table aliases referenced in an expression."""
228
+ if isinstance(expr, exp.Column):
229
+ if expr.table:
230
+ aliases.add(expr.table)
231
+
232
+ elif isinstance(expr, exp.Alias):
233
+ _extract_table_aliases_from_expr(expr.this, aliases)
234
+
235
+ elif isinstance(expr, exp.Paren):
236
+ _extract_table_aliases_from_expr(expr.this, aliases)
237
+
238
+ elif isinstance(expr, (exp.EQ, exp.NEQ, exp.LT, exp.GT, exp.LTE, exp.GTE)):
239
+ _extract_table_aliases_from_expr(expr.this, aliases)
240
+ _extract_table_aliases_from_expr(expr.expression, aliases)
241
+
242
+ elif isinstance(expr, (exp.And, exp.Or)):
243
+ _extract_table_aliases_from_expr(expr.this, aliases)
244
+ _extract_table_aliases_from_expr(expr.expression, aliases)
245
+
246
+ elif isinstance(expr, exp.Not):
247
+ _extract_table_aliases_from_expr(expr.this, aliases)
248
+
249
+ elif isinstance(expr, exp.Is):
250
+ _extract_table_aliases_from_expr(expr.this, aliases)
251
+
252
+ elif isinstance(expr, exp.In):
253
+ _extract_table_aliases_from_expr(expr.this, aliases)
254
+ if isinstance(expr.expression, exp.Tuple):
255
+ for e in expr.expression.expressions:
256
+ _extract_table_aliases_from_expr(e, aliases)
257
+
258
+
259
+ def _combine_expressions(expressions: list, operator_class) -> Optional[exp.Expression]:
260
+ """Combine list of expressions with AND/OR operator."""
261
+ if not expressions:
262
+ return None
263
+ if len(expressions) == 1:
264
+ return expressions[0]
265
+
266
+ # Combine from left to right
267
+ result = expressions[0]
268
+ for expr in expressions[1:]:
269
+ result = operator_class(this=result, expression=expr)
270
+ return result
271
+
272
+
273
+ def expression_to_sql_string(expr: exp.Expression) -> str:
274
+ """
275
+ Convert a SQL expression to SQL string (for WHERE clause pushdown).
276
+
277
+ This is a simplified version - in production, you'd want more robust SQL generation.
278
+ """
279
+ if isinstance(expr, exp.Column):
280
+ return f"{expr.table}.{expr.name}" if expr.table else expr.name
281
+
282
+ elif isinstance(expr, exp.Literal):
283
+ if isinstance(expr.this, str):
284
+ return f"'{expr.this.replace(chr(39), chr(39)+chr(39))}'" # Escape single quotes
285
+ return str(expr.this)
286
+
287
+ elif isinstance(expr, exp.EQ):
288
+ left = expression_to_sql_string(expr.this)
289
+ right = expression_to_sql_string(expr.expression)
290
+ return f"{left} = {right}"
291
+
292
+ elif isinstance(expr, exp.NEQ):
293
+ left = expression_to_sql_string(expr.this)
294
+ right = expression_to_sql_string(expr.expression)
295
+ return f"{left} != {right}"
296
+
297
+ elif isinstance(expr, exp.LT):
298
+ left = expression_to_sql_string(expr.this)
299
+ right = expression_to_sql_string(expr.expression)
300
+ return f"{left} < {right}"
301
+
302
+ elif isinstance(expr, exp.GT):
303
+ left = expression_to_sql_string(expr.this)
304
+ right = expression_to_sql_string(expr.expression)
305
+ return f"{left} > {right}"
306
+
307
+ elif isinstance(expr, exp.LTE):
308
+ left = expression_to_sql_string(expr.this)
309
+ right = expression_to_sql_string(expr.expression)
310
+ return f"{left} <= {right}"
311
+
312
+ elif isinstance(expr, exp.GTE):
313
+ left = expression_to_sql_string(expr.this)
314
+ right = expression_to_sql_string(expr.expression)
315
+ return f"{left} >= {right}"
316
+
317
+ elif isinstance(expr, exp.And):
318
+ left = expression_to_sql_string(expr.this)
319
+ right = expression_to_sql_string(expr.expression)
320
+ return f"({left} AND {right})"
321
+
322
+ elif isinstance(expr, exp.Or):
323
+ left = expression_to_sql_string(expr.this)
324
+ right = expression_to_sql_string(expr.expression)
325
+ return f"({left} OR {right})"
326
+
327
+ elif isinstance(expr, exp.Not):
328
+ inner = expression_to_sql_string(expr.this)
329
+ return f"NOT ({inner})"
330
+
331
+ elif isinstance(expr, exp.Is):
332
+ left = expression_to_sql_string(expr.this)
333
+ if expr.expression is None or (isinstance(expr.expression, exp.Null)):
334
+ return f"{left} IS NULL"
335
+ elif isinstance(expr.expression, exp.Not) and isinstance(expr.expression.this, exp.Null):
336
+ return f"{left} IS NOT NULL"
337
+
338
+ elif isinstance(expr, exp.In):
339
+ left = expression_to_sql_string(expr.this)
340
+ if isinstance(expr.expression, exp.Tuple):
341
+ values = [expression_to_sql_string(e) for e in expr.expression.expressions]
342
+ return f"{left} IN ({', '.join(values)})"
343
+
344
+ # Fallback: use sqlglot's SQL generation
345
+ try:
346
+ return expr.sql()
347
+ except:
348
+ return str(expr)
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
@@ -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
+