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,533 @@
1
+ # Streaming SQL Engine
2
+
3
+ A lightweight Python library that executes SQL queries **row-by-row** across **any data source** - databases, APIs, files, or custom Python functions. Join data from different systems using standard SQL syntax, without loading everything into memory.
4
+
5
+ ## 🎯 What It Does
6
+
7
+ **Execute SQL queries that join data from multiple sources:**
8
+
9
+ - ✅ **Databases** (PostgreSQL, MySQL, MongoDB)
10
+ - ✅ **REST APIs** (any HTTP endpoint)
11
+ - ✅ **Files** (JSONL, CSV, JSON)
12
+ - ✅ **Custom Python functions** (any iterator)
13
+
14
+ **All in one SQL query, streaming results row-by-row.**
15
+
16
+ ---
17
+
18
+ ## 🚀 Why It's Useful
19
+
20
+ ### Problem: You Can't Join Across Different Systems
21
+
22
+ **Traditional databases can't do this:**
23
+
24
+ ```python
25
+ # ❌ Can't join MySQL + PostgreSQL + REST API in one query
26
+ # ❌ Can't join database + CSV file
27
+ # ❌ Can't join API + JSON file
28
+ ```
29
+
30
+ **This library solves it:**
31
+
32
+ ```python
33
+ # ✅ Join MySQL + PostgreSQL + REST API + CSV file
34
+ # ✅ All in one SQL query
35
+ # ✅ Streams results row-by-row (low memory)
36
+ ```
37
+
38
+ ### Key Benefits
39
+
40
+ 1. **Cross-System Joins** - Join data from completely different sources
41
+ 2. **Memory Efficient** - Processes row-by-row, never loads full tables
42
+ 3. **Zero Infrastructure** - No clusters, no setup, just Python
43
+ 4. **Automatic Optimizations** - Filter pushdown, column pruning, vectorized operations
44
+ 5. **Simple API** - Standard SQL syntax, easy to use
45
+
46
+ ---
47
+
48
+ ## 📦 Installation
49
+
50
+ ```bash
51
+ pip install streaming-sql-engine
52
+ ```
53
+
54
+ **Or install from source:**
55
+
56
+ ```bash
57
+ git clone <repository>
58
+ cd streaming_sql_engine
59
+ pip install -e .
60
+ ```
61
+
62
+ ---
63
+
64
+ ## 💡 Quick Start
65
+
66
+ ### Example 1: Simple Join
67
+
68
+ ```python
69
+ from streaming_sql_engine import Engine
70
+
71
+ # Create engine
72
+ engine = Engine()
73
+
74
+ # Register data sources (any Python iterators)
75
+ def users_source():
76
+ return iter([
77
+ {"id": 1, "name": "Alice", "dept_id": 10},
78
+ {"id": 2, "name": "Bob", "dept_id": 20},
79
+ ])
80
+
81
+ def departments_source():
82
+ return iter([
83
+ {"id": 10, "name": "Engineering"},
84
+ {"id": 20, "name": "Sales"},
85
+ ])
86
+
87
+ engine.register("users", users_source)
88
+ engine.register("departments", departments_source)
89
+
90
+ # Execute SQL query
91
+ query = """
92
+ SELECT users.name, departments.name AS dept
93
+ FROM users
94
+ JOIN departments ON users.dept_id = departments.id
95
+ """
96
+
97
+ for row in engine.query(query):
98
+ print(row)
99
+ # Output:
100
+ # {'users.name': 'Alice', 'departments.name': 'Engineering'}
101
+ # {'users.name': 'Bob', 'departments.name': 'Sales'}
102
+ ```
103
+
104
+ ### Example 2: Join Database + API + File
105
+
106
+ ```python
107
+ from streaming_sql_engine import Engine
108
+ from examples.database_helpers import create_table_source, create_pool_from_env
109
+ import requests
110
+ import json
111
+
112
+ engine = Engine()
113
+
114
+ # 1. Database source (PostgreSQL)
115
+ pool = create_pool_from_env()
116
+ engine.register(
117
+ "products",
118
+ create_table_source(pool, "products")
119
+ )
120
+
121
+ # 2. REST API source
122
+ def api_customers():
123
+ response = requests.get("https://api.example.com/customers")
124
+ for item in response.json():
125
+ yield item
126
+
127
+ engine.register("customers", api_customers)
128
+
129
+ # 3. JSONL file source
130
+ def file_orders():
131
+ with open("orders.jsonl") as f:
132
+ for line in f:
133
+ yield json.loads(line)
134
+
135
+ engine.register("orders", file_orders, filename="orders.jsonl")
136
+
137
+ # Join all three sources!
138
+ query = """
139
+ SELECT
140
+ products.name,
141
+ customers.email,
142
+ orders.quantity
143
+ FROM products
144
+ JOIN customers ON products.customer_id = customers.id
145
+ JOIN orders ON products.id = orders.product_id
146
+ WHERE products.price > 100
147
+ """
148
+
149
+ for row in engine.query(query):
150
+ print(row)
151
+ ```
152
+
153
+ ### Example 3: Simple Protocol Support (Automated!)
154
+
155
+ **Use helper functions - no manual implementation needed:**
156
+
157
+ ```python
158
+ from streaming_sql_engine import Engine
159
+ from streaming_sql_engine.protocol_helpers import (
160
+ register_file_source,
161
+ register_api_source,
162
+ )
163
+
164
+ engine = Engine()
165
+
166
+ # Register file sources with automatic protocol support
167
+ register_file_source(engine, "products", "data/products.jsonl")
168
+ register_file_source(engine, "categories", "data/categories.csv")
169
+
170
+ # Register API source with automatic protocol support
171
+ register_api_source(engine, "customers", "http://localhost:8000", "customers")
172
+
173
+ # Query with automatic optimizations (filter pushdown, column pruning)
174
+ for row in engine.query("""
175
+ SELECT products.name, categories.name AS category
176
+ FROM products
177
+ JOIN categories ON products.category_id = categories.id
178
+ WHERE products.price > 100
179
+ """):
180
+ print(row)
181
+ ```
182
+
183
+ **That's it!** No manual SQL parsing, no manual filtering - everything is automatic! 🎉
184
+
185
+ See [Simple Protocol Guide](documentation/SIMPLE_PROTOCOL_GUIDE.md) for more details.
186
+
187
+ ---
188
+
189
+ ## 🎯 Use Cases
190
+
191
+ ### ✅ Perfect For
192
+
193
+ 1. **Cross-System Data Integration**
194
+
195
+ - Join MySQL + PostgreSQL + MongoDB
196
+ - Join database + REST API
197
+ - Join API + CSV file
198
+
199
+ 2. **Real-Time Data Processing**
200
+
201
+ - Stream data from multiple sources
202
+ - Process row-by-row without buffering
203
+ - Low memory footprint
204
+
205
+ 3. **Data Pipeline ETL**
206
+
207
+ - Transform data from multiple sources
208
+ - Join before loading to destination
209
+ - Python-native processing
210
+
211
+ 4. **Microservices Data Aggregation**
212
+ - Join data from multiple services
213
+ - No shared database needed
214
+ - Simple Python integration
215
+
216
+ ### ❌ Not For
217
+
218
+ - **Single Database Queries** - Use direct SQL (10-100x faster)
219
+ - **Complex SQL** - GROUP BY, aggregations, subqueries not supported
220
+ - **Maximum Performance** - For same-database joins, use database directly
221
+
222
+ ---
223
+
224
+ ## 🔧 Features
225
+
226
+ ### Supported SQL
227
+
228
+ - ✅ **SELECT** - Column selection, aliasing
229
+ - ✅ **FROM** - Single table, aliases
230
+ - ✅ **JOIN** - INNER JOIN, LEFT JOIN
231
+ - ✅ **WHERE** - Comparisons, boolean logic, NULL checks, IN clauses
232
+ - ✅ **Table-qualified columns** - `table.column`
233
+
234
+ ### Not Supported
235
+
236
+ - ❌ GROUP BY, aggregations
237
+ - ❌ ORDER BY
238
+ - ❌ HAVING
239
+ - ❌ UNION
240
+ - ❌ Subqueries
241
+ - ❌ Non-equality joins
242
+
243
+ ---
244
+
245
+ ## ⚡ Performance Optimizations
246
+
247
+ ### 1. Protocol-Based Optimizations (Automatic)
248
+
249
+ **Filter Pushdown** - Push WHERE clauses to data sources:
250
+
251
+ ```python
252
+ # Engine automatically passes WHERE clause to source
253
+ def source(dynamic_where=None, dynamic_columns=None):
254
+ query = f"SELECT * FROM table WHERE {dynamic_where}"
255
+ # Source filters before returning data
256
+ ```
257
+
258
+ **Column Pruning** - Only request needed columns:
259
+
260
+ ```python
261
+ # Engine automatically requests only needed columns
262
+ def source(dynamic_where=None, dynamic_columns=None):
263
+ columns = ", ".join(dynamic_columns) # Only requested columns
264
+ query = f"SELECT {columns} FROM table"
265
+ ```
266
+
267
+ **How it works:** Engine detects if your source function accepts `dynamic_where`/`dynamic_columns` parameters automatically. No flags needed!
268
+
269
+ **💡 Tip:** Use helper functions to automate protocol support - see [Simple Protocol Guide](documentation/SIMPLE_PROTOCOL_GUIDE.md)!
270
+
271
+ ### 2. Polars Vectorization (Automatic)
272
+
273
+ **10-200x faster** for large datasets:
274
+
275
+ - Vectorized filtering (SIMD-accelerated)
276
+ - Vectorized projections
277
+ - Batch processing
278
+
279
+ Enabled by default. Disable with:
280
+
281
+ ```python
282
+ engine = Engine(use_polars=False)
283
+ ```
284
+
285
+ ### 3. Memory-Mapped Joins (For Files)
286
+
287
+ **90-99% memory reduction** for large JSONL files:
288
+
289
+ ```python
290
+ engine.register(
291
+ "products",
292
+ lambda: read_jsonl("products.jsonl"),
293
+ filename="products.jsonl" # Enables mmap joins
294
+ )
295
+ ```
296
+
297
+ ### 4. Merge Joins (For Sorted Data)
298
+
299
+ **Efficient joins** when both sides are sorted:
300
+
301
+ ```python
302
+ engine.register(
303
+ "users",
304
+ users_source,
305
+ ordered_by="id" # Enables merge join
306
+ )
307
+ ```
308
+
309
+ ---
310
+
311
+ ## 📚 Examples
312
+
313
+ ### Database + Database
314
+
315
+ ```python
316
+ from examples.database_helpers import create_table_source, create_pool_from_env
317
+
318
+ # PostgreSQL
319
+ pg_pool = create_postgresql_pool_from_env()
320
+ engine.register("pg_users", create_table_source(pg_pool, "users"))
321
+
322
+ # MySQL
323
+ mysql_pool = create_mysql_pool_from_env()
324
+ engine.register("mysql_orders", create_table_source(mysql_pool, "orders"))
325
+
326
+ # Join across databases!
327
+ query = """
328
+ SELECT pg_users.name, mysql_orders.total
329
+ FROM pg_users
330
+ JOIN mysql_orders ON pg_users.id = mysql_orders.user_id
331
+ """
332
+ ```
333
+
334
+ ### Database + REST API
335
+
336
+ ```python
337
+ import requests
338
+
339
+ def api_products():
340
+ response = requests.get("https://api.example.com/products")
341
+ return iter(response.json())
342
+
343
+ engine.register("api_products", api_products)
344
+ engine.register("db_orders", create_table_source(pool, "orders"))
345
+
346
+ query = """
347
+ SELECT api_products.name, db_orders.quantity
348
+ FROM api_products
349
+ JOIN db_orders ON api_products.id = db_orders.product_id
350
+ """
351
+ ```
352
+
353
+ ### File + File
354
+
355
+ ```python
356
+ def read_jsonl(filename):
357
+ with open(filename) as f:
358
+ for line in f:
359
+ yield json.loads(line)
360
+
361
+ engine.register("products", lambda: read_jsonl("products.jsonl"), filename="products.jsonl")
362
+ engine.register("images", lambda: read_jsonl("images.jsonl"), filename="images.jsonl")
363
+
364
+ query = """
365
+ SELECT products.name, images.url
366
+ FROM products
367
+ JOIN images ON products.id = images.product_id
368
+ """
369
+ ```
370
+
371
+ ---
372
+
373
+ ## 🏗️ Architecture
374
+
375
+ ### How It Works
376
+
377
+ ```
378
+ SQL Query
379
+ ↓
380
+ Parser (sqlglot) → AST
381
+ ↓
382
+ Planner → Logical Plan
383
+ ↓
384
+ Optimizer → Optimized Plan (column pruning, filter pushdown)
385
+ ↓
386
+ Executor → Iterator Pipeline
387
+ ↓
388
+ Results (Generator) → Row-by-row streaming
389
+ ```
390
+
391
+ ### Iterator Pipeline
392
+
393
+ ```
394
+ ScanIterator → FilterIterator → JoinIterators → ProjectIterator
395
+ ```
396
+
397
+ Each iterator processes rows incrementally, never loading full tables.
398
+
399
+ ---
400
+
401
+ ## 🔍 Debug Mode
402
+
403
+ Enable debug output to see execution details:
404
+
405
+ ```python
406
+ engine = Engine(debug=True)
407
+
408
+ for row in engine.query("SELECT * FROM users"):
409
+ print(row)
410
+ ```
411
+
412
+ **Output:**
413
+
414
+ ```
415
+ ============================================================
416
+ STREAMING SQL ENGINE - DEBUG MODE
417
+ ============================================================
418
+
419
+ [1/3] PARSING SQL QUERY...
420
+ ✓ SQL parsed successfully
421
+
422
+ [2/3] BUILDING LOGICAL PLAN...
423
+ ✓ Logical plan built:
424
+ - Root table: users
425
+ - Joins: 1
426
+ - WHERE clause: Yes
427
+ - Projections: 2
428
+
429
+ [3/3] EXECUTING QUERY...
430
+ [OPTIMIZATION] Source supports protocol - applying column pruning
431
+ [SCAN] Scanning table: users
432
+ [JOIN] INNER JOIN orders
433
+ [PROJECT] Applying SELECT projection
434
+ ```
435
+
436
+ ---
437
+
438
+ ## 📖 Documentation
439
+
440
+ - **[Quick Start Guide](documentation/QUICK_START.md)** - Get started in 5 minutes
441
+ - **[User Guide](documentation/USER_GUIDE.md)** - Complete usage guide
442
+ - **[Best Use Cases](documentation/BEST_USE_CASES.md)** - When to use this library
443
+ - **[Performance Guide](documentation/PERFORMANCE.md)** - Performance tips and benchmarks
444
+ - **[Migration Guide](documentation/MIGRATION_GUIDE.md)** - Upgrading from older versions
445
+ - **[Developer Guide](documentation/DEVELOPER_GUIDE.md)** - Contributing and extending
446
+
447
+ ---
448
+
449
+ ## 🎓 Key Concepts
450
+
451
+ ### Protocol-Based Optimization
452
+
453
+ **No flags needed!** The engine automatically detects if your source supports optimizations:
454
+
455
+ ```python
456
+ # Simple source (no optimizations)
457
+ def simple_source():
458
+ return iter([...])
459
+
460
+ # Optimized source (with protocol)
461
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
462
+ # Engine automatically passes optimization parameters
463
+ ...
464
+ ```
465
+
466
+ ### Streaming Execution
467
+
468
+ **Row-by-row processing:**
469
+
470
+ - Results are yielded immediately as they're produced
471
+ - Never loads full tables into memory
472
+ - Perfect for large datasets
473
+
474
+ ### Cross-Source Joins
475
+
476
+ **Join any data sources:**
477
+
478
+ - Databases (PostgreSQL, MySQL, MongoDB)
479
+ - APIs (REST, GraphQL, any HTTP endpoint)
480
+ - Files (JSONL, CSV, JSON)
481
+ - Custom Python functions
482
+
483
+ ---
484
+
485
+ ## 🤝 Contributing
486
+
487
+ Contributions welcome! See [Developer Guide](documentation/DEVELOPER_GUIDE.md) for details.
488
+
489
+ ---
490
+
491
+ ## 📄 License
492
+
493
+ MIT
494
+
495
+ ---
496
+
497
+ ## 🙋 FAQ
498
+
499
+ **Q: Can I join data from different databases?**
500
+ A: Yes! That's the main use case. Join MySQL + PostgreSQL + MongoDB in one query.
501
+
502
+ **Q: Is it faster than database queries?**
503
+ A: No. For same-database queries, use direct SQL (10-100x faster). This library is for cross-system joins.
504
+
505
+ **Q: Does it support GROUP BY?**
506
+ A: No. Use a database for aggregations. This library focuses on joins and filtering.
507
+
508
+ **Q: How does it handle large datasets?**
509
+ A: Streams row-by-row, uses memory-mapped files for large JSONL files, and Polars for vectorized operations.
510
+
511
+ **Q: Can I use it with APIs?**
512
+ A: Yes! Any Python function that returns an iterator works. Perfect for REST APIs.
513
+
514
+ ---
515
+
516
+ ## ⭐ Why Use This?
517
+
518
+ **Use this library when:**
519
+
520
+ - ✅ You need to join data from different systems
521
+ - ✅ You want to process data row-by-row (low memory)
522
+ - ✅ You need Python-native data processing
523
+ - ✅ You want simple SQL syntax for complex data integration
524
+
525
+ **Don't use this library when:**
526
+
527
+ - ❌ All data is in the same database (use direct SQL)
528
+ - ❌ You need GROUP BY or aggregations (use database)
529
+ - ❌ You need maximum performance for same-database queries (use database)
530
+
531
+ ---
532
+
533
+ **Ready to get started?** Check out the [Quick Start Guide](documentation/QUICK_START.md)!
@@ -0,0 +1,31 @@
1
+ """
2
+ Streaming SQL Join Engine
3
+
4
+ A lightweight SQL execution engine that processes queries row-by-row
5
+ without loading full tables into memory.
6
+ """
7
+
8
+ from .engine import Engine
9
+
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.6"
31
+
@@ -0,0 +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
+
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)