streaming-sql-engine 0.1.2__py3-none-any.whl → 0.1.3__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.
@@ -16,7 +16,7 @@ from .db_connector import (
16
16
  create_table_source
17
17
  )
18
18
 
19
- __version__ = "0.1.2"
19
+ __version__ = "0.1.0"
20
20
  __all__ = [
21
21
  "Engine",
22
22
  "PostgreSQLPool",
@@ -320,7 +320,10 @@ def create_table_source(
320
320
  pool,
321
321
  table_name,
322
322
  where_clause=None,
323
- order_by=None
323
+ order_by=None,
324
+ columns=None,
325
+ _dynamic_where=None,
326
+ _dynamic_columns=None
324
327
  ):
325
328
  """
326
329
  Create a source function for a database table.
@@ -331,6 +334,10 @@ def create_table_source(
331
334
  table_name: Name of the table
332
335
  where_clause: Optional WHERE clause (without WHERE keyword)
333
336
  order_by: Optional ORDER BY clause (without ORDER BY keyword)
337
+ columns: Optional list/set of column names to select (None = all columns)
338
+ This enables column pruning for better performance
339
+ _dynamic_where: Internal - allows WHERE to be set dynamically at query time
340
+ _dynamic_columns: Internal - allows columns to be set dynamically at query time
334
341
 
335
342
  Returns:
336
343
  A function that returns an iterator of row dictionaries
@@ -338,12 +345,29 @@ def create_table_source(
338
345
  Example:
339
346
  pool = create_pool_from_env()
340
347
  source_fn = create_table_source(pool, "users", "active = 1", "id")
341
- engine.register("users", source_fn, ordered_by="id")
348
+ engine.register("users", source_fn, ordered_by="id", is_database_source=True)
349
+
350
+ # With column pruning:
351
+ source_fn = create_table_source(pool, "users", columns=["id", "name", "email"])
352
+ engine.register("users", source_fn, is_database_source=True)
342
353
  """
343
- def source_fn():
344
- query = f"SELECT * FROM {table_name}"
345
- if where_clause:
346
- query += f" WHERE {where_clause}"
354
+ def source_fn(dynamic_where=None, dynamic_columns=None):
355
+ # Use dynamic parameters if provided (for query-time optimization)
356
+ # Otherwise use static parameters
357
+ final_where = dynamic_where if dynamic_where is not None else where_clause
358
+ final_columns = dynamic_columns if dynamic_columns is not None else columns
359
+
360
+ # Build column list
361
+ if final_columns:
362
+ # Column pruning: only select needed columns
363
+ column_list = ", ".join(final_columns)
364
+ query = f"SELECT {column_list} FROM {table_name}"
365
+ else:
366
+ query = f"SELECT * FROM {table_name}"
367
+
368
+ # Push WHERE clause to database (filter pushdown)
369
+ if final_where:
370
+ query += f" WHERE {final_where}"
347
371
  if order_by:
348
372
  query += f" ORDER BY {order_by}"
349
373
 
@@ -1,109 +1,119 @@
1
- """
2
- Main Engine class - public API for the streaming SQL engine.
3
- """
4
-
5
- from typing import Any
6
- from .parser import parse_sql
7
- from .planner import build_logical_plan
8
- from .executor import execute_plan
9
- from .jsonl_executor import execute_plan_jsonl
10
-
11
-
12
- class Engine:
13
- """
14
- Main interface for the streaming SQL execution engine.
15
-
16
- Usage:
17
- engine = Engine(debug=True) # Enable debug mode
18
- engine.register("users", lambda: iter([{"id": 1, "name": "Alice"}]))
19
- results = engine.query("SELECT users.name FROM users WHERE users.id = 1")
20
- for row in results:
21
- print(row)
22
- """
23
-
24
- def __init__(self, debug=False, use_jsonl_mode=False):
25
- """
26
- Initialize a new engine instance.
27
-
28
- Args:
29
- 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
- """
33
- self._sources = {}
34
- self._source_metadata = {}
35
- self.debug = debug
36
- self.use_jsonl_mode = use_jsonl_mode
37
-
38
- def register(
39
- self,
40
- table_name,
41
- source_fn,
42
- ordered_by=None
43
- ):
44
- """
45
- Register a table source.
46
-
47
- Args:
48
- table_name: Name of the table as used in SQL queries
49
- source_fn: Function that returns an iterator of row dictionaries
50
- ordered_by: Optional column name if the source is sorted by this column
51
- (enables merge joins)
52
- """
53
- if not callable(source_fn):
54
- raise ValueError(f"source_fn must be callable, got {type(source_fn)}")
55
-
56
- self._sources[table_name] = source_fn
57
- self._source_metadata[table_name] = {
58
- "ordered_by": ordered_by
59
- }
60
-
61
- def query(self, sql):
62
- """
63
- Execute a SQL query and return a generator of result rows.
64
-
65
- Args:
66
- sql: SQL query string
67
-
68
- Returns:
69
- Generator yielding dictionaries representing result rows
70
-
71
- Raises:
72
- ValueError: If query contains unsupported constructs
73
- KeyError: If referenced table is not registered
74
- """
75
- if self.debug:
76
- print("=" * 60)
77
- print("STREAMING SQL ENGINE - DEBUG MODE")
78
- print("=" * 60)
79
- print(f"\n[1/3] PARSING SQL QUERY...")
80
- print(f"Query:\n{sql}\n")
81
-
82
- # Parse SQL into AST
83
- ast = parse_sql(sql)
84
-
85
- if self.debug:
86
- print(f"✓ SQL parsed successfully")
87
- print(f"\n[2/3] BUILDING LOGICAL PLAN...")
88
-
89
- # Build logical plan
90
- logical_plan = build_logical_plan(ast, self._sources.keys())
91
-
92
- if self.debug:
93
- print(f"✓ Logical plan built:")
94
- print(f" - Root table: {logical_plan.root_table} (alias: {logical_plan.root_alias})")
95
- print(f" - Joins: {len(logical_plan.joins)}")
96
- for i, join in enumerate[Any](logical_plan.joins, 1):
97
- print(f" {i}. {join.join_type} JOIN {join.table} ON {join.left_key} = {join.right_key}")
98
- print(f" - WHERE clause: {'Yes' if logical_plan.where_expr else 'No'}")
99
- print(f" - Projections: {len(logical_plan.projections)}")
100
- print(f"\n[3/3] EXECUTING QUERY...")
101
- print(f"Building execution pipeline...\n")
102
-
103
- # Execute plan
104
- if self.use_jsonl_mode:
105
- if self.debug:
106
- print(f"\nUsing JSONL-based execution mode (simpler, lower CPU)\n")
107
- return execute_plan_jsonl(logical_plan, self._sources, self._source_metadata, debug=self.debug)
108
- else:
109
- return execute_plan(logical_plan, self._sources, self._source_metadata, debug=self.debug)
1
+ """
2
+ Main Engine class - public API for the streaming SQL engine.
3
+ """
4
+
5
+ from typing import Any
6
+ from .parser import parse_sql
7
+ from .planner import build_logical_plan
8
+ from .executor import execute_plan
9
+ from .jsonl_executor import execute_plan_jsonl
10
+
11
+
12
+ class Engine:
13
+ """
14
+ Main interface for the streaming SQL execution engine.
15
+
16
+ Usage:
17
+ engine = Engine(debug=True) # Enable debug mode
18
+ engine.register("users", lambda: iter([{"id": 1, "name": "Alice"}]))
19
+ results = engine.query("SELECT users.name FROM users WHERE users.id = 1")
20
+ for row in results:
21
+ print(row)
22
+ """
23
+
24
+ def __init__(self, debug=False, use_jsonl_mode=False, use_polars=True):
25
+ """
26
+ Initialize a new engine instance.
27
+
28
+ Args:
29
+ 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
+ use_polars: If True, uses Polars for optimizations when available (default: True)
33
+ """
34
+ self._sources = {}
35
+ self._source_metadata = {}
36
+ self.debug = debug
37
+ self.use_jsonl_mode = use_jsonl_mode
38
+ self.use_polars = use_polars
39
+
40
+ def register(
41
+ self,
42
+ table_name,
43
+ source_fn,
44
+ ordered_by=None,
45
+ is_database_source=False,
46
+ filename=None
47
+ ):
48
+ """
49
+ Register a table source.
50
+
51
+ Args:
52
+ table_name: Name of the table as used in SQL queries
53
+ source_fn: Function that returns an iterator of row dictionaries
54
+ ordered_by: Optional column name if the source is sorted by this column
55
+ (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
+ filename: Optional filename if source is file-based (enables mmap-based joins
59
+ for 90-99% memory reduction)
60
+ """
61
+ if not callable(source_fn):
62
+ raise ValueError(f"source_fn must be callable, got {type(source_fn)}")
63
+
64
+ self._sources[table_name] = source_fn
65
+ self._source_metadata[table_name] = {
66
+ "ordered_by": ordered_by,
67
+ "is_database_source": is_database_source,
68
+ "filename": filename # Enable mmap-based joins
69
+ }
70
+
71
+ def query(self, sql):
72
+ """
73
+ Execute a SQL query and return a generator of result rows.
74
+
75
+ Args:
76
+ sql: SQL query string
77
+
78
+ Returns:
79
+ Generator yielding dictionaries representing result rows
80
+
81
+ Raises:
82
+ ValueError: If query contains unsupported constructs
83
+ KeyError: If referenced table is not registered
84
+ """
85
+ if self.debug:
86
+ print("=" * 60)
87
+ print("STREAMING SQL ENGINE - DEBUG MODE")
88
+ print("=" * 60)
89
+ print(f"\n[1/3] PARSING SQL QUERY...")
90
+ print(f"Query:\n{sql}\n")
91
+
92
+ # Parse SQL into AST
93
+ ast = parse_sql(sql)
94
+
95
+ if self.debug:
96
+ print(f"✓ SQL parsed successfully")
97
+ print(f"\n[2/3] BUILDING LOGICAL PLAN...")
98
+
99
+ # Build logical plan
100
+ logical_plan = build_logical_plan(ast, self._sources.keys())
101
+
102
+ if self.debug:
103
+ print(f"✓ Logical plan built:")
104
+ print(f" - Root table: {logical_plan.root_table} (alias: {logical_plan.root_alias})")
105
+ print(f" - Joins: {len(logical_plan.joins)}")
106
+ for i, join in enumerate[Any](logical_plan.joins, 1):
107
+ print(f" {i}. {join.join_type} JOIN {join.table} ON {join.left_key} = {join.right_key}")
108
+ print(f" - WHERE clause: {'Yes' if logical_plan.where_expr else 'No'}")
109
+ print(f" - Projections: {len(logical_plan.projections)}")
110
+ print(f"\n[3/3] EXECUTING QUERY...")
111
+ print(f"Building execution pipeline...\n")
112
+
113
+ # Execute plan
114
+ if self.use_jsonl_mode:
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)