streaming-sql-engine 0.1.2__py3-none-any.whl → 0.1.4__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.
@@ -6,25 +6,26 @@ without loading full tables into memory.
6
6
  """
7
7
 
8
8
  from .engine import Engine
9
- from .db_connector import (
10
- PostgreSQLPool,
11
- MySQLPool,
12
- create_pool_from_env,
13
- create_mysql_pool_from_env,
14
- create_postgresql_pool_from_env,
15
- stream_query,
16
- create_table_source
17
- )
18
9
 
19
- __version__ = "0.1.2"
20
- __all__ = [
21
- "Engine",
22
- "PostgreSQLPool",
23
- "MySQLPool",
24
- "create_pool_from_env",
25
- "create_mysql_pool_from_env",
26
- "create_postgresql_pool_from_env",
27
- "stream_query",
28
- "create_table_source"
29
- ]
10
+ # Protocol helpers for easy source creation
11
+ try:
12
+ from .protocol_helpers import (
13
+ add_protocol_support,
14
+ wrap_simple_source,
15
+ create_protocol_source,
16
+ register_file_source,
17
+ register_api_source,
18
+ )
19
+ __all__ = [
20
+ "Engine",
21
+ "add_protocol_support",
22
+ "wrap_simple_source",
23
+ "create_protocol_source",
24
+ "register_file_source",
25
+ "register_api_source",
26
+ ]
27
+ except ImportError:
28
+ __all__ = ["Engine"]
29
+
30
+ __version__ = "0.1.4"
30
31
 
@@ -1,109 +1,123 @@
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
+
10
+
11
+ class Engine:
12
+ """
13
+ Main interface for the streaming SQL execution engine.
14
+
15
+ Usage:
16
+ engine = Engine(debug=True) # Enable debug mode
17
+ engine.register("users", lambda: iter([{"id": 1, "name": "Alice"}]))
18
+ results = engine.query("SELECT users.name FROM users WHERE users.id = 1")
19
+ for row in results:
20
+ print(row)
21
+ """
22
+
23
+ def __init__(self, debug=False, use_polars=True):
24
+ """
25
+ Initialize a new engine instance.
26
+
27
+ Args:
28
+ debug: If True, enables verbose logging of execution stages
29
+ use_polars: If True, uses Polars for optimizations when available (default: True)
30
+ """
31
+ self._sources = {}
32
+ self._source_metadata = {}
33
+ self.debug = debug
34
+ self.use_polars = use_polars
35
+
36
+ def register(
37
+ self,
38
+ table_name,
39
+ source_fn,
40
+ ordered_by=None,
41
+ filename=None
42
+ ):
43
+ """
44
+ Register a table source.
45
+
46
+ Args:
47
+ table_name: Name of the table as used in SQL queries
48
+ source_fn: Function that returns an iterator of row dictionaries.
49
+ If the function accepts `dynamic_where` and/or `dynamic_columns` parameters,
50
+ optimizations (filter pushdown and column pruning) will be applied automatically.
51
+ ordered_by: Optional column name if the source is sorted by this column
52
+ (enables merge joins)
53
+ filename: Optional filename if source is file-based (enables mmap-based joins
54
+ for 90-99% memory reduction)
55
+
56
+ Example:
57
+ # Simple source (no optimizations)
58
+ def simple_source():
59
+ return iter([{"id": 1, "name": "Alice"}])
60
+ engine.register("users", simple_source)
61
+
62
+ # Optimized source (with protocol)
63
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
64
+ # Build query with optimizations
65
+ query = build_query(dynamic_where, dynamic_columns)
66
+ for row in execute(query):
67
+ yield row
68
+ engine.register("products", optimized_source)
69
+ # Optimizations apply automatically!
70
+ """
71
+ if not callable(source_fn):
72
+ raise ValueError(f"source_fn must be callable, got {type(source_fn)}")
73
+
74
+ self._sources[table_name] = source_fn
75
+ self._source_metadata[table_name] = {
76
+ "ordered_by": ordered_by,
77
+ "filename": filename # Enable mmap-based joins
78
+ }
79
+
80
+ def query(self, sql):
81
+ """
82
+ Execute a SQL query and return a generator of result rows.
83
+
84
+ Args:
85
+ sql: SQL query string
86
+
87
+ Returns:
88
+ Generator yielding dictionaries representing result rows
89
+
90
+ Raises:
91
+ ValueError: If query contains unsupported constructs
92
+ KeyError: If referenced table is not registered
93
+ """
94
+ if self.debug:
95
+ print("=" * 60)
96
+ print("STREAMING SQL ENGINE - DEBUG MODE")
97
+ print("=" * 60)
98
+ print(f"\n[1/3] PARSING SQL QUERY...")
99
+ print(f"Query:\n{sql}\n")
100
+
101
+ # Parse SQL into AST
102
+ ast = parse_sql(sql)
103
+
104
+ if self.debug:
105
+ print(f"✓ SQL parsed successfully")
106
+ print(f"\n[2/3] BUILDING LOGICAL PLAN...")
107
+
108
+ # Build logical plan
109
+ logical_plan = build_logical_plan(ast, self._sources.keys())
110
+
111
+ if self.debug:
112
+ print(f"✓ Logical plan built:")
113
+ print(f" - Root table: {logical_plan.root_table} (alias: {logical_plan.root_alias})")
114
+ print(f" - Joins: {len(logical_plan.joins)}")
115
+ for i, join in enumerate[Any](logical_plan.joins, 1):
116
+ print(f" {i}. {join.join_type} JOIN {join.table} ON {join.left_key} = {join.right_key}")
117
+ print(f" - WHERE clause: {'Yes' if logical_plan.where_expr else 'No'}")
118
+ print(f" - Projections: {len(logical_plan.projections)}")
119
+ print(f"\n[3/3] EXECUTING QUERY...")
120
+ print(f"Building execution pipeline...\n")
121
+
122
+ # Execute plan
123
+ return execute_plan(logical_plan, self._sources, self._source_metadata, debug=self.debug, use_polars=self.use_polars)