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,156 @@
1
+ """
2
+ Logical plan construction from parsed SQL AST.
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+ from sqlglot import expressions as exp
7
+ from .parser import ParseError
8
+
9
+
10
+ @dataclass
11
+ class JoinInfo:
12
+ """Information about a single join."""
13
+ table: str
14
+ alias: object
15
+ join_type: str # "INNER" or "LEFT"
16
+ left_key: str # e.g., "sp.fk_abs"
17
+ right_key: str # e.g., "spa.id"
18
+
19
+
20
+ @dataclass
21
+ class LogicalPlan:
22
+ """Logical execution plan for a query."""
23
+ root_table: str
24
+ root_alias: object
25
+ joins: list
26
+ where_expr: object
27
+ projections: list # SELECT expressions with aliases
28
+
29
+
30
+ def build_logical_plan(ast, registered_tables):
31
+ """
32
+ Convert SQL AST into a logical plan.
33
+
34
+ Args:
35
+ ast: Parsed SELECT expression
36
+ registered_tables: Set of registered table names
37
+
38
+ Returns:
39
+ LogicalPlan object
40
+
41
+ Raises:
42
+ ParseError: If plan construction fails
43
+ """
44
+ # Extract FROM clause
45
+ # Note: sqlglot uses 'from_' (with underscore) to avoid Python keyword conflict
46
+ from_expr = ast.args.get("from_") or ast.args.get("from")
47
+ if not from_expr:
48
+ raise ParseError("Query must have a FROM clause")
49
+
50
+ root_table, root_alias = _extract_table_and_alias(from_expr.this)
51
+
52
+ if root_table not in registered_tables:
53
+ raise ParseError(f"Table '{root_table}' is not registered")
54
+
55
+ # Extract JOINs
56
+ joins = []
57
+ for join_expr in ast.args.get("joins", []):
58
+ join_info = _extract_join(join_expr, registered_tables)
59
+ joins.append(join_info)
60
+
61
+ # Extract WHERE clause
62
+ where_expr = ast.args.get("where")
63
+ # Unwrap Where node if present (sqlglot wraps WHERE expressions in a Where node)
64
+ if where_expr is not None:
65
+ if isinstance(where_expr, exp.Where):
66
+ where_expr = where_expr.this
67
+ # where_expr is now the actual expression (And, Or, EQ, etc.)
68
+
69
+ # Extract SELECT projections
70
+ projections = list(ast.expressions)
71
+
72
+ return LogicalPlan(
73
+ root_table=root_table,
74
+ root_alias=root_alias,
75
+ joins=joins,
76
+ where_expr=where_expr,
77
+ projections=projections
78
+ )
79
+
80
+
81
+ def _extract_table_and_alias(expr):
82
+ """Extract table name and alias from a table expression."""
83
+ if isinstance(expr, exp.Table):
84
+ table_name = expr.name
85
+ alias = expr.alias
86
+ return table_name, alias
87
+ elif isinstance(expr, exp.Alias):
88
+ # Handle table with alias
89
+ if isinstance(expr.this, exp.Table):
90
+ return expr.this.name, expr.alias
91
+ else:
92
+ raise ParseError(f"Unsupported table expression: {type(expr.this)}")
93
+ else:
94
+ raise ParseError(f"Unsupported FROM expression: {type(expr)}")
95
+
96
+
97
+ def _extract_join(join_expr, registered_tables):
98
+ """Extract join information from a JOIN expression."""
99
+ # Determine join type
100
+ join_type = "INNER"
101
+ if join_expr.kind == "LEFT":
102
+ join_type = "LEFT"
103
+ elif join_expr.kind and join_expr.kind.upper() not in ("INNER", "LEFT"):
104
+ raise ParseError(f"Unsupported join type: {join_expr.kind}")
105
+
106
+ # Extract table and alias
107
+ table, alias = _extract_table_and_alias(join_expr.this)
108
+
109
+ if table not in registered_tables:
110
+ raise ParseError(f"Table '{table}' in JOIN is not registered")
111
+
112
+ # Extract join condition
113
+ on_expr = join_expr.args.get("on")
114
+ if not on_expr:
115
+ raise ParseError("JOIN must have an ON condition")
116
+
117
+ left_key, right_key = _extract_join_keys(on_expr)
118
+
119
+ return JoinInfo(
120
+ table=table,
121
+ alias=alias,
122
+ join_type=join_type,
123
+ left_key=left_key,
124
+ right_key=right_key
125
+ )
126
+
127
+
128
+ def _extract_join_keys(on_expr):
129
+ """
130
+ Extract join keys from ON condition.
131
+ Currently only supports equality joins: alias1.col1 = alias2.col2
132
+ """
133
+ if not isinstance(on_expr, exp.EQ):
134
+ raise ParseError("Only equality joins are supported in ON clause")
135
+
136
+ left = on_expr.this
137
+ right = on_expr.expression
138
+
139
+ left_key = _column_to_string(left)
140
+ right_key = _column_to_string(right)
141
+
142
+ return left_key, right_key
143
+
144
+
145
+ def _column_to_string(expr):
146
+ """Convert a column expression to string format 'alias.column'."""
147
+ if isinstance(expr, exp.Column):
148
+ table = expr.table
149
+ column = expr.name
150
+ if table:
151
+ return f"{table}.{column}"
152
+ else:
153
+ raise ParseError(f"Column reference must include table alias: {expr}")
154
+ else:
155
+ raise ParseError(f"Join key must be a column reference, got {type(expr)}")
156
+
@@ -0,0 +1,289 @@
1
+ Metadata-Version: 2.4
2
+ Name: streaming-sql-engine
3
+ Version: 0.1.0
4
+ Summary: A lightweight SQL execution engine for streaming row-by-row queries with joins
5
+ Home-page: https://github.com/Ierofantis/streaming-sql-engine
6
+ Author: Ierofantis
7
+ Author-email: Ierofantis <teopanta1986@gmail.com>
8
+ Project-URL: Homepage, https://github.com/Ierofantis/streaming-sql-engine
9
+ Project-URL: Repository, https://github.com/Ierofantis/streaming-sql-engine
10
+ Project-URL: Issues, https://github.com/Ierofantis/streaming-sql-engine/issues
11
+ Project-URL: Documentation, https://github.com/Ierofantis/streaming-sql-engine
12
+ Keywords: sql,streaming,join,database,query,engine
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: Database
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ Requires-Dist: sqlglot>=23.0.0
27
+ Requires-Dist: psycopg2-binary>=2.9.0
28
+ Requires-Dist: python-dotenv>=1.0.0
29
+ Requires-Dist: pymysql>=1.0.0
30
+ Requires-Dist: DBUtils>=3.0.0
31
+ Requires-Dist: requests>=2.28.0
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
34
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
35
+ Requires-Dist: black>=23.0.0; extra == "dev"
36
+ Requires-Dist: flake8>=6.0.0; extra == "dev"
37
+ Dynamic: author
38
+ Dynamic: home-page
39
+ Dynamic: requires-python
40
+
41
+ # Streaming SQL Join Engine
42
+
43
+ A lightweight Python library for executing SQL queries with joins in a streaming, row-by-row fashion without loading full tables into memory.
44
+
45
+ ## Features
46
+
47
+ - **Streaming execution**: Processes queries row-by-row using Python generators
48
+ - **INNER and LEFT JOIN support**: Efficient join algorithms (lookup-based and merge joins)
49
+ - **WHERE clause filtering**: Supports comparisons, boolean logic, and NULL checks
50
+ - **Column projection**: SELECT with column selection and aliasing
51
+ - **Memory efficient**: Only materializes lookup-side tables for joins, not full result sets
52
+
53
+ ## Installation
54
+
55
+ > **Quick Start:** For detailed installation instructions, see [INSTALLATION.md](INSTALLATION.md)
56
+
57
+ ### Option 1: Install from Local Directory (Development)
58
+
59
+ If you have the library source code locally:
60
+
61
+ ```bash
62
+ # Navigate to the library directory
63
+ cd sql_engine
64
+
65
+ # Install in editable mode (recommended for development)
66
+ pip install -e .
67
+
68
+ # Or install normally
69
+ pip install .
70
+ ```
71
+
72
+ ### Option 2: Install Dependencies Only
73
+
74
+ If you want to use the library without installing it as a package:
75
+
76
+ ```bash
77
+ pip install -r requirements.txt
78
+ ```
79
+
80
+ Then add the library directory to your Python path or import directly:
81
+
82
+ ```python
83
+ import sys
84
+ sys.path.insert(0, '/path/to/sql_engine')
85
+ from streaming_sql_engine import Engine
86
+ ```
87
+
88
+ ### Option 3: Install from Git Repository
89
+
90
+ If the library is hosted on GitHub or another Git repository:
91
+
92
+ ```bash
93
+ pip install git+https://github.com/Ierofantis/streaming-sql-engine.git
94
+ ```
95
+
96
+ ### Option 4: Install as a Package in Your Project
97
+
98
+ Add to your project's `requirements.txt`:
99
+
100
+ ```
101
+ streaming-sql-engine @ file:///path/to/sql_engine
102
+ ```
103
+
104
+ Or if using `pyproject.toml`:
105
+
106
+ ```toml
107
+ [project.dependencies]
108
+ streaming-sql-engine = {path = "../sql_engine", develop = true}
109
+ ```
110
+
111
+ ## PostgreSQL Integration
112
+
113
+ The library includes utilities for connecting to PostgreSQL databases:
114
+
115
+ ```python
116
+ from streaming_sql_engine import Engine, create_pool_from_env, create_table_source
117
+ from dotenv import load_dotenv
118
+ import os
119
+
120
+ load_dotenv()
121
+
122
+ # Create connection pool from environment variables
123
+ pool = create_pool_from_env()
124
+
125
+ # Create engine
126
+ engine = Engine()
127
+
128
+ # Register tables from PostgreSQL
129
+ engine.register(
130
+ "users",
131
+ create_table_source(pool, "users", where_clause="active = true", order_by="id"),
132
+ ordered_by="id" # Enable merge joins if sorted
133
+ )
134
+
135
+ # Execute queries
136
+ for row in engine.query("SELECT users.name FROM users WHERE users.id > 1"):
137
+ print(row)
138
+ ```
139
+
140
+ Required environment variables (in `.env` file):
141
+
142
+ - `db_host`
143
+ - `db_port`
144
+ - `db_user`
145
+ - `db_password`
146
+ - `db_name`
147
+
148
+ ## Quick Start
149
+
150
+ ```python
151
+ from streaming_sql_engine import Engine
152
+
153
+ # Create engine instance
154
+ engine = Engine()
155
+
156
+ # Register table sources (functions that return iterators of dictionaries)
157
+ def users_source():
158
+ return iter([
159
+ {"id": 1, "name": "Alice", "dept_id": 10},
160
+ {"id": 2, "name": "Bob", "dept_id": 20},
161
+ {"id": 3, "name": "Charlie", "dept_id": 10},
162
+ ])
163
+
164
+ def departments_source():
165
+ return iter([
166
+ {"id": 10, "name": "Engineering"},
167
+ {"id": 20, "name": "Sales"},
168
+ ])
169
+
170
+ engine.register("users", users_source)
171
+ engine.register("departments", departments_source)
172
+
173
+ # Execute a query
174
+ query = """
175
+ SELECT users.name, departments.name AS dept_name
176
+ FROM users
177
+ JOIN departments ON users.dept_id = departments.id
178
+ WHERE users.id > 1
179
+ """
180
+
181
+ for row in engine.query(query):
182
+ print(row)
183
+ # Output:
184
+ # {'name': 'Bob', 'dept_name': 'Sales'}
185
+ # {'name': 'Charlie', 'dept_name': 'Engineering'}
186
+ ```
187
+
188
+ ## Supported SQL Features
189
+
190
+ ### SELECT
191
+
192
+ - Column selection: `SELECT col1, col2`
193
+ - Aliasing: `SELECT col1 AS alias1`
194
+ - Table-qualified columns: `SELECT users.name`
195
+
196
+ ### FROM
197
+
198
+ - Single table: `FROM table_name`
199
+ - Table aliases: `FROM users AS u`
200
+
201
+ ### JOIN
202
+
203
+ - INNER JOIN: `JOIN table ON left.key = right.key`
204
+ - LEFT JOIN: `LEFT JOIN table ON left.key = right.key`
205
+ - Multiple joins in sequence
206
+ - Only equality joins are supported
207
+
208
+ ### WHERE
209
+
210
+ - Comparisons: `=`, `!=`, `<`, `>`, `<=`, `>=`
211
+ - Boolean operators: `AND`, `OR`, `NOT`
212
+ - NULL checks: `IS NULL`, `IS NOT NULL`
213
+ - IN clauses: `column IN (value1, value2, ...)`
214
+ - Column references: `alias.column`
215
+ - Constants: strings, numbers
216
+
217
+ ## Not Supported
218
+
219
+ - GROUP BY and aggregations
220
+ - ORDER BY
221
+ - HAVING
222
+ - UNION
223
+ - Subqueries
224
+ - Non-equality joins
225
+ - Arithmetic expressions
226
+ - Functions (except basic literals)
227
+
228
+ ## Advanced: Merge Joins
229
+
230
+ For better performance when both tables are sorted by the join key, you can register sources with `ordered_by`:
231
+
232
+ ```python
233
+ # Register a source that's sorted by id
234
+ engine.register(
235
+ "users",
236
+ users_source,
237
+ ordered_by="id" # Enables merge join optimization
238
+ )
239
+ ```
240
+
241
+ ## Architecture
242
+
243
+ The engine follows a pipeline architecture:
244
+
245
+ 1. **Parser**: Uses `sqlglot` to parse SQL into an AST
246
+ 2. **Planner**: Converts AST into a logical execution plan
247
+ 3. **Executor**: Builds a chain of iterator operators:
248
+ - `ScanIterator`: Reads from source
249
+ - `FilterIterator`: Applies WHERE clause
250
+ - `LookupJoinIterator`: Joins using hash lookup (indexes smaller table)
251
+ - `MergeJoinIterator`: Joins using merge algorithm (when both sides sorted)
252
+ - `ProjectIterator`: Applies SELECT projection
253
+
254
+ ## Error Handling
255
+
256
+ The engine raises clear exceptions for:
257
+
258
+ - Unsupported SQL constructs
259
+ - Missing table registrations
260
+ - Ambiguous column references
261
+ - Invalid join conditions
262
+
263
+ ## Performance Considerations
264
+
265
+ - **Lookup joins**: Memory usage proportional to size of lookup-side table
266
+ - **Merge joins**: Memory usage proportional to size of equal-key runs (usually very small)
267
+ - **Streaming**: Results are yielded as soon as they're produced
268
+ - **No buffering**: Intermediate results are not fully materialized
269
+
270
+ ## Documentation
271
+
272
+ - **[TECHNICAL_DOCUMENTATION.md](TECHNICAL_DOCUMENTATION.md)**: Complete technical documentation explaining architecture, algorithms, and design decisions
273
+ - **[DEVELOPER_GUIDE.md](DEVELOPER_GUIDE.md)**: Guide for developers who want to understand, modify, or extend the codebase
274
+ - **[PERFORMANCE.md](PERFORMANCE.md)**: Performance comparison with database joins and optimization tips
275
+ - **[MYSQL_USAGE.md](MYSQL_USAGE.md)**: MySQL-specific usage guide
276
+ - **[QUICK_START.md](QUICK_START.md)**: Quick start guide for new users
277
+ - **[INSTALLATION.md](INSTALLATION.md)**: Detailed installation instructions
278
+
279
+ ## Installation from PyPI
280
+
281
+ Once published, you can install the package directly from PyPI:
282
+
283
+ ```bash
284
+ pip install streaming-sql-engine
285
+ ```
286
+
287
+ ## License
288
+
289
+ MIT License - see [LICENSE](LICENSE) file for details.
@@ -0,0 +1,13 @@
1
+ streaming_sql_engine/__init__.py,sha256=co3TexgJAgN7OHJTJ82V6TJ1FGPc2SDbz19ylsre1-I,653
2
+ streaming_sql_engine/db_connector.py,sha256=JHJuAY13hv8F_jJplYPs-TGXwtIGN5SBj11NiHPcSwI,10518
3
+ streaming_sql_engine/engine.py,sha256=avqnRudHfCX49_9eAMq0U_HDdRCXmxmZ03_4Hn1uwr0,3927
4
+ streaming_sql_engine/evaluator.py,sha256=255gmA58yES5E_2_WJTNKuWATqXZDPC042iEMkbo_oY,7550
5
+ streaming_sql_engine/executor.py,sha256=CrOJeC1PdsutmosX-0BLemGIYqZPPmDXruJld72pkPE,3700
6
+ streaming_sql_engine/jsonl_executor.py,sha256=7zXHRPYocOqwXuk2zTyoLTUFGUrI8YBgcS_gye8Afv8,14820
7
+ streaming_sql_engine/operators.py,sha256=yZqNK9IBouPIeVdvzw5YuEwFM5I8GO4e7gI568e_zIc,17720
8
+ streaming_sql_engine/parser.py,sha256=Dzd-0NWrqHkjgdZkgdvQyPUaqSkkKQ68hLqAnkiCPwU,2944
9
+ streaming_sql_engine/planner.py,sha256=Y9vmn6kQKPPlGcrD0EzGJXyPFz4lZWo0mAdu_SMeRIM,4583
10
+ streaming_sql_engine-0.1.0.dist-info/METADATA,sha256=Vl2iWpFEF2NkD4X6Zcxz8cyn5qg8WW1iZYznljW50-s,8543
11
+ streaming_sql_engine-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
+ streaming_sql_engine-0.1.0.dist-info/top_level.txt,sha256=PRib0mE9E-m1Ih3dM63YmED6WZzXwgatTGcOZzc1Nio,21
13
+ streaming_sql_engine-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ streaming_sql_engine