streaming-sql-engine 0.1.9__tar.gz → 0.1.12__tar.gz

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.
Files changed (82) hide show
  1. streaming_sql_engine-0.1.12/PKG-INFO +1482 -0
  2. streaming_sql_engine-0.1.12/README.md +1434 -0
  3. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/__init__.py +1 -1
  4. streaming_sql_engine-0.1.12/documentation/COMPREHENSIVE_ARTICLE.md +1141 -0
  5. streaming_sql_engine-0.1.12/documentation/FIRST_MATCH_ONLY_WARNINGS.md +206 -0
  6. streaming_sql_engine-0.1.12/documentation/MEDIUM_ARTICLE.md +1434 -0
  7. streaming_sql_engine-0.1.12/documentation/WHY_ORIGINAL_IS_FASTER.md +263 -0
  8. streaming_sql_engine-0.1.12/documentation/XML_MONGO_USE_CASE.md +224 -0
  9. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/evaluator.py +57 -0
  10. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/pyproject.toml +1 -1
  11. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/setup.py +1 -1
  12. streaming_sql_engine-0.1.12/streaming_sql_engine.egg-info/PKG-INFO +1482 -0
  13. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/streaming_sql_engine.egg-info/SOURCES.txt +5 -0
  14. streaming_sql_engine-0.1.9/PKG-INFO +0 -581
  15. streaming_sql_engine-0.1.9/README.md +0 -533
  16. streaming_sql_engine-0.1.9/streaming_sql_engine.egg-info/PKG-INFO +0 -581
  17. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/DEPLOYMENT.md +0 -0
  18. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/MANIFEST.in +0 -0
  19. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/QUICK_DEPLOY.md +0 -0
  20. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/QUICK_FIX.md +0 -0
  21. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/APACHE_DRILL_COMPARISON.md +0 -0
  22. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/API_JOIN_OPERATIONS.md +0 -0
  23. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/ARCHITECTURAL_RECOMMENDATION.md +0 -0
  24. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/ARCHITECTURE_DECISION.md +0 -0
  25. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/ARCHITECTURE_SYNCED.md +0 -0
  26. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/BEST_USE_CASES.md +0 -0
  27. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/BETTER_FILTER_APPROACH.md +0 -0
  28. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/CHANGES_SUMMARY.md +0 -0
  29. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/COMPREHENSIVE_DOCUMENTATION.md +0 -0
  30. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/DEVELOPER_GUIDE.md +0 -0
  31. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/DUCKDB_COMPARISON.md +0 -0
  32. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/FINAL_IMPLEMENTATION_RECOMMENDATIONS.md +0 -0
  33. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/FINAL_RECOMMENDATION.md +0 -0
  34. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/HOW_PROTOCOL_DETECTION_WORKS.md +0 -0
  35. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/HOW_TO_ADD_TO_PROJECT.md +0 -0
  36. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/INSTALLATION.md +0 -0
  37. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/JSONL_EXECUTOR_ANALYSIS.md +0 -0
  38. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/JSONL_EXECUTOR_REMOVED.md +0 -0
  39. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/LIBRARY_DOCUMENTATION.md +0 -0
  40. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/MIGRATION_GUIDE.md +0 -0
  41. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/MULTI_SOURCE_EXAMPLE_README.md +0 -0
  42. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/MYSQL_USAGE.md +0 -0
  43. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/OPTIMIZATIONS_BREAKDOWN.md +0 -0
  44. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/OPTIMIZATIONS_NOT_DATABASE_ONLY.md +0 -0
  45. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/OPTIMIZATIONS_VS_POLARS.md +0 -0
  46. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/OPTIMIZER_AUTOMATED.md +0 -0
  47. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/PERFORMANCE.md +0 -0
  48. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/PERFORMANCE_COMPARISON.md +0 -0
  49. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/POLARS_AND_MMAP_GUIDE.md +0 -0
  50. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/PROTOCOL_AND_OPTIMIZATIONS_EXPLAINED.md +0 -0
  51. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/PROTOCOL_EXPLANATION.md +0 -0
  52. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/PUBLISHING.md +0 -0
  53. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/PYPI_CHECKLIST.md +0 -0
  54. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/QUICK_PUBLISH.md +0 -0
  55. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/QUICK_START.md +0 -0
  56. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/SIMPLE_PROTOCOL_GUIDE.md +0 -0
  57. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/SIMPLE_SOURCE_FUNCTIONS.md +0 -0
  58. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/SOURCE_COMBINATIONS_GUIDE.md +0 -0
  59. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/TECHNICAL_DOCUMENTATION.md +0 -0
  60. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/USER_GUIDE.md +0 -0
  61. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/WHAT_IS_WHERE_TO_PARAMS.md +0 -0
  62. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/WHEN_POLARS_IS_USED.md +0 -0
  63. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/WHY_API_CONVERTER_NEEDED.md +0 -0
  64. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/WHY_MANUAL_PARSING.md +0 -0
  65. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/documentation/WHY_PROTOCOL_IN_SOURCES.md +0 -0
  66. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/engine.py +0 -0
  67. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/executor.py +0 -0
  68. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/mmap_index.py +0 -0
  69. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/operators.py +0 -0
  70. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/operators_mmap.py +0 -0
  71. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/operators_polars.py +0 -0
  72. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/optimizer.py +0 -0
  73. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/parser.py +0 -0
  74. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/planner.py +0 -0
  75. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/polars_expression_translator.py +0 -0
  76. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/polars_operators.py +0 -0
  77. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/protocol_helpers.py +0 -0
  78. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/requirements.txt +0 -0
  79. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/setup.cfg +0 -0
  80. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/streaming_sql_engine.egg-info/dependency_links.txt +0 -0
  81. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/streaming_sql_engine.egg-info/requires.txt +0 -0
  82. {streaming_sql_engine-0.1.9 → streaming_sql_engine-0.1.12}/streaming_sql_engine.egg-info/top_level.txt +0 -0
@@ -0,0 +1,1482 @@
1
+ Metadata-Version: 2.4
2
+ Name: streaming-sql-engine
3
+ Version: 0.1.12
4
+ Summary: A lightweight SQL execution engine for streaming row-by-row queries with joins across multiple data sources
5
+ Home-page: https://github.com/Ierofantis/streaming-sql-engine/tree/master
6
+ Author: Theodore Pantazopoulo
7
+ Author-email: Theodore Pantazopoulo <your.email@example.com>
8
+ Project-URL: Homepage, https://github.com/Ierofantis/streaming-sql-engine/tree/master
9
+ Project-URL: Repository, https://github.com/Ierofantis/streaming-sql-engine/tree/master
10
+ Project-URL: Issues, https://github.com/Ierofantis/streaming-sql-engine/issues
11
+ Project-URL: Documentation, https://github.com/Ierofantis/streaming-sql-engine/tree/master#readme
12
+ Keywords: sql,streaming,join,database,query,engine,etl,data-integration
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
+ Provides-Extra: polars
28
+ Requires-Dist: polars>=0.19.0; extra == "polars"
29
+ Provides-Extra: db
30
+ Requires-Dist: psycopg2-binary>=2.9.0; extra == "db"
31
+ Requires-Dist: pymysql>=1.0.0; extra == "db"
32
+ Requires-Dist: DBUtils>=3.0.0; extra == "db"
33
+ Requires-Dist: pymongo>=4.0.0; extra == "db"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
36
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
37
+ Requires-Dist: black>=23.0.0; extra == "dev"
38
+ Requires-Dist: flake8>=6.0.0; extra == "dev"
39
+ Provides-Extra: all
40
+ Requires-Dist: polars>=0.19.0; extra == "all"
41
+ Requires-Dist: psycopg2-binary>=2.9.0; extra == "all"
42
+ Requires-Dist: pymysql>=1.0.0; extra == "all"
43
+ Requires-Dist: DBUtils>=3.0.0; extra == "all"
44
+ Requires-Dist: pymongo>=4.0.0; extra == "all"
45
+ Dynamic: author
46
+ Dynamic: home-page
47
+ Dynamic: requires-python
48
+
49
+ # Join Data from Anywhere: The Streaming SQL Engine That Bridges Databases, APIs, and Files
50
+
51
+ ## How I Built a Python Library That Lets You Join MySQL, PostgreSQL, MongoDB, REST APIs, and Files in a Single SQL Query
52
+
53
+ ---
54
+
55
+ _Have you ever needed to join data from a MySQL database with a PostgreSQL database, a MongoDB collection, and a REST API — all in one query? Traditional databases can't do this. That's why I built the Streaming SQL Engine._
56
+
57
+ ---
58
+
59
+ ## The Problem: Data Lives Everywhere
60
+
61
+ Modern applications don't store all their data in one place. You might have:
62
+
63
+ - User data in PostgreSQL
64
+ - Order data in MySQL
65
+ - Product catalog in MongoDB
66
+ - Pricing information from a REST API
67
+ - Inventory data in CSV files
68
+ - Product feeds in XML files
69
+
70
+ **The challenge:** How do you join all this data together?
71
+
72
+ Traditional solutions require:
73
+
74
+ - Exporting data from each system
75
+ - Importing into a central database
76
+ - Writing complex ETL pipelines
77
+ - Maintaining data synchronization
78
+
79
+ **There had to be a better way.**
80
+
81
+ ---
82
+
83
+ ## The Solution: Streaming SQL Engine
84
+
85
+ I built a lightweight Python library that lets you join data from **any source** using standard SQL syntax — without exporting, importing, or setting up infrastructure.
86
+
87
+ ```python
88
+ from streaming_sql_engine import Engine
89
+ import psycopg2
90
+ import pymysql
91
+ from pymongo import MongoClient
92
+ import requests
93
+ import csv
94
+
95
+ engine = Engine()
96
+
97
+ # Register PostgreSQL source (iterator function)
98
+ def postgres_users():
99
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
100
+ cursor = conn.cursor()
101
+ cursor.execute("SELECT id, name, email FROM users")
102
+ for row in cursor:
103
+ yield {"id": row[0], "name": row[1], "email": row[2]}
104
+ conn.close()
105
+ engine.register("postgres_users", postgres_users)
106
+
107
+ # Register MySQL source (iterator function)
108
+ def mysql_products():
109
+ conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
110
+ cursor = conn.cursor()
111
+ cursor.execute("SELECT id, name, price FROM products")
112
+ for row in cursor:
113
+ yield {"id": row[0], "name": row[1], "price": row[2]}
114
+ conn.close()
115
+ engine.register("mysql_products", mysql_products)
116
+
117
+ # Register MongoDB source (iterator function)
118
+ def mongo_inventory():
119
+ client = MongoClient("mongodb://localhost:27017")
120
+ for doc in client.mydb.inventory.find():
121
+ yield doc
122
+ engine.register("mongo_inventory", mongo_inventory)
123
+
124
+ # Register REST API source (iterator function)
125
+ def api_prices():
126
+ response = requests.get("https://api.example.com/prices")
127
+ for item in response.json():
128
+ yield item
129
+ engine.register("api_prices", api_prices)
130
+
131
+ # Register CSV source (iterator function)
132
+ def csv_suppliers():
133
+ with open("suppliers.csv") as f:
134
+ for row in csv.DictReader(f):
135
+ yield row
136
+ engine.register("csv_suppliers", csv_suppliers)
137
+
138
+ # Join them all in one SQL query!
139
+ query = """
140
+ SELECT
141
+ mysql_products.name,
142
+ postgres_users.email,
143
+ mongo_inventory.quantity,
144
+ api_prices.price,
145
+ csv_suppliers.supplier_name
146
+ FROM mysql_products
147
+ JOIN postgres_users ON mysql_products.user_id = postgres_users.id
148
+ JOIN mongo_inventory ON mysql_products.sku = mongo_inventory.sku
149
+ JOIN api_prices ON mysql_products.sku = api_prices.sku
150
+ JOIN csv_suppliers ON mysql_products.supplier_id = csv_suppliers.id
151
+ WHERE api_prices.price > 100
152
+ """
153
+
154
+ for row in engine.query(query):
155
+ process(row)
156
+ ```
157
+
158
+ **That's it.** No clusters, no infrastructure, no data export — just pure Python and SQL.
159
+
160
+ ---
161
+
162
+ ## Why I Built This: The Problem That Needed Solving
163
+
164
+ I was working on a data reconciliation project where I needed to join data from multiple sources:
165
+
166
+ - MySQL database (product catalog)
167
+ - PostgreSQL database (user data)
168
+ - MongoDB collection (inventory)
169
+ - REST API (pricing information)
170
+ - CSV files (supplier data)
171
+
172
+ **The challenge:** Traditional databases can't join across different systems. I had three options:
173
+
174
+ 1. **Export everything to one database** - Time-consuming, requires ETL pipelines, data becomes stale
175
+ 2. **Write custom Python code** - Complex, error-prone, hard to maintain
176
+ 3. **Use existing tools** - Spark/Flink require clusters, DuckDB requires data import, Presto needs infrastructure
177
+
178
+ **None of these worked for my use case.** I needed something that:
179
+
180
+ - Could join data from different systems without export
181
+ - Was simple to use (SQL syntax)
182
+ - Required zero infrastructure
183
+ - Worked with Python natively
184
+ - Processed data efficiently (streaming)
185
+
186
+ So I built the Streaming SQL Engine.
187
+
188
+ ---
189
+
190
+ ## How I Built It: Architecture and Design Decisions
191
+
192
+ ### Core Design Philosophy
193
+
194
+ The engine follows a **pipeline architecture** inspired by database query execution engines (like PostgreSQL and SQLite), but implemented in pure Python using iterators.
195
+
196
+ **Key insight:** Python's iterator protocol is perfect for streaming data. Each operator in the pipeline is an iterator that processes rows one at a time.
197
+
198
+ ### The Architecture: Four Layers
199
+
200
+ #### Layer 1: SQL Parsing
201
+
202
+ **Technology:** Uses `sqlglot` library for SQL parsing
203
+
204
+ **Why sqlglot:**
205
+
206
+ - Supports multiple SQL dialects (MySQL, PostgreSQL, SQLite)
207
+ - Produces a standard AST (Abstract Syntax Tree)
208
+ - Handles SQL parsing edge cases
209
+ - No need to write a parser from scratch
210
+
211
+ **How it works:**
212
+
213
+ ```python
214
+ def parse_sql(sql: str):
215
+ # Try multiple dialects
216
+ for dialect in ['mysql', 'postgres', 'sqlite']:
217
+ try:
218
+ ast = sqlglot.parse_one(sql, dialect=dialect)
219
+ return ast
220
+ except:
221
+ continue
222
+ raise ValueError("Could not parse SQL")
223
+ ```
224
+
225
+ **Logic:** The parser converts SQL string into an AST, which is a tree structure representing the query. This AST is then used by the planner to build an execution plan.
226
+
227
+ #### Layer 2: Logical Planning
228
+
229
+ **Purpose:** Convert AST into a logical execution plan
230
+
231
+ **What it extracts:**
232
+
233
+ - Root table (the table in FROM clause)
234
+ - Join information (which tables to join, on what keys)
235
+ - WHERE clause conditions
236
+ - SELECT projections (which columns to return)
237
+
238
+ **Key design decision:** Separate logical planning from execution. This allows:
239
+
240
+ - Query optimization before execution
241
+ - Reuse of planning logic
242
+ - Easier testing and debugging
243
+
244
+ **How it works:**
245
+
246
+ ```python
247
+ class LogicalPlan:
248
+ root_table: str
249
+ joins: List[JoinInfo]
250
+ where_expr: Optional[Expression]
251
+ projections: List[str]
252
+ required_columns: Dict[str, List[str]] # Column pruning
253
+ pushable_where_expr: Optional[Expression] # Filter pushdown
254
+ ```
255
+
256
+ **Logic:** The planner walks the AST tree, extracting information about tables, joins, filters, and projections. It identifies which columns are needed from each table (for column pruning) and which WHERE conditions can be pushed to sources (for filter pushdown).
257
+
258
+ #### Layer 3: Optimization
259
+
260
+ **Two main optimizations:**
261
+
262
+ **1. Column Pruning**
263
+
264
+ - Identifies which columns are actually needed
265
+ - Only requests those columns from sources
266
+ - Reduces I/O and memory usage
267
+
268
+ **Logic:**
269
+
270
+ ```python
271
+ # Analyze SELECT clause
272
+ required_columns = {}
273
+ for projection in plan.projections:
274
+ table_name = extract_table_name(projection)
275
+ column_name = extract_column_name(projection)
276
+ required_columns[table_name].add(column_name)
277
+
278
+ # Also check WHERE clause - columns used in filters are needed
279
+ for condition in plan.where_expr:
280
+ table_name = extract_table_name(condition)
281
+ column_name = extract_column_name(condition)
282
+ required_columns[table_name].add(column_name)
283
+ ```
284
+
285
+ **2. Filter Pushdown**
286
+
287
+ - Identifies WHERE conditions that reference only the root table
288
+ - Pushes these conditions to the source function
289
+ - Reduces data transfer from databases
290
+
291
+ **Logic:**
292
+
293
+ ```python
294
+ # Check if WHERE condition only references root table
295
+ def can_push_where(where_expr, root_table):
296
+ referenced_tables = extract_table_references(where_expr)
297
+ return len(referenced_tables) == 1 and root_table in referenced_tables
298
+
299
+ if can_push_where(plan.where_expr, plan.root_table):
300
+ pushable_where_expr = plan.where_expr
301
+ ```
302
+
303
+ **Protocol-based detection:** The engine automatically detects if a source function supports optimizations by checking if it accepts `dynamic_where` and `dynamic_columns` parameters:
304
+
305
+ ```python
306
+ import inspect
307
+
308
+ def source_supports_optimizations(source_fn):
309
+ sig = inspect.signature(source_fn)
310
+ params = list(sig.parameters.keys())
311
+ return 'dynamic_where' in params or 'dynamic_columns' in params
312
+ ```
313
+
314
+ **Why this approach:** No flags needed. If your source function accepts these parameters, optimizations apply automatically. This makes the engine flexible - any Python function can be a source, and optimizations work if the source supports them.
315
+
316
+ #### Layer 4: Execution Pipeline
317
+
318
+ **The iterator pipeline:** Each operator is a Python iterator that processes rows incrementally.
319
+
320
+ **Pipeline structure:**
321
+
322
+ ```
323
+ ScanIterator → FilterIterator → JoinIterators → ProjectIterator → Results
324
+ ```
325
+
326
+ **How each iterator works:**
327
+
328
+ **1. ScanIterator**
329
+
330
+ - Reads rows from source function
331
+ - Prefixes columns with table name (e.g., `id` becomes `users.id`)
332
+ - Applies column pruning (only includes requested columns)
333
+
334
+ **Logic:**
335
+
336
+ ```python
337
+ class ScanIterator:
338
+ def __init__(self, source_fn, table_name, required_columns):
339
+ self.source_fn = source_fn
340
+ self.table_name = table_name
341
+ self.required_columns = required_columns
342
+
343
+ def __next__(self):
344
+ row = next(self.source_iterator)
345
+ # Column pruning
346
+ if self.required_columns:
347
+ row = {k: v for k, v in row.items() if k in self.required_columns}
348
+ # Prefix columns with table name
349
+ return {f"{self.table_name}.{k}": v for k, v in row.items()}
350
+ ```
351
+
352
+ **2. FilterIterator**
353
+
354
+ - Applies WHERE clause conditions
355
+ - Evaluates expressions row-by-row
356
+ - Only yields rows that match conditions
357
+
358
+ **Logic:**
359
+
360
+ ```python
361
+ class FilterIterator:
362
+ def __init__(self, source_iterator, where_expr):
363
+ self.source_iterator = source_iterator
364
+ self.where_expr = where_expr
365
+
366
+ def __next__(self):
367
+ while True:
368
+ row = next(self.source_iterator)
369
+ if evaluate_expression(self.where_expr, row):
370
+ return row
371
+ # Skip rows that don't match
372
+ ```
373
+
374
+ **3. JoinIterators (LookupJoinIterator, MergeJoinIterator)**
375
+
376
+ - **LookupJoinIterator:** Builds hash index on right side, looks up each left row
377
+ - **MergeJoinIterator:** Both sides sorted, merges like merge sort algorithm
378
+
379
+ **LookupJoinIterator logic:**
380
+
381
+ ```python
382
+ class LookupJoinIterator:
383
+ def __init__(self, left_iterator, right_source_fn, left_key, right_key):
384
+ self.left_iterator = left_iterator
385
+ self.right_source_fn = right_source_fn
386
+ self.left_key = left_key
387
+ self.right_key = right_key
388
+ self.index = None # Hash index on right side
389
+
390
+ def _build_index(self):
391
+ """Build hash index on right side - O(n) time, O(n) space"""
392
+ self.index = {}
393
+ for right_row in self.right_source_fn():
394
+ key = right_row[self.right_key]
395
+ if key not in self.index:
396
+ self.index[key] = []
397
+ self.index[key].append(right_row)
398
+
399
+ def __next__(self):
400
+ if self.index is None:
401
+ self._build_index()
402
+
403
+ left_row = next(self.left_iterator)
404
+ left_key_value = left_row[self.left_key]
405
+
406
+ # Lookup in index - O(1) time
407
+ matching_right_rows = self.index.get(left_key_value, [])
408
+
409
+ for right_row in matching_right_rows:
410
+ # Merge left and right rows
411
+ merged_row = {**left_row, **right_row}
412
+ yield merged_row
413
+ ```
414
+
415
+ **Why hash index:** O(1) lookup time per left row. Trade-off: O(n) memory for right side, but this is necessary for efficient joins.
416
+
417
+ **MergeJoinIterator logic:**
418
+
419
+ ```python
420
+ class MergeJoinIterator:
421
+ def __init__(self, left_iterator, right_iterator, left_key, right_key):
422
+ self.left_iterator = left_iterator
423
+ self.right_iterator = right_iterator
424
+ self.left_key = left_key
425
+ self.right_key = right_key
426
+ self.right_buffer = [] # Buffer for right side
427
+
428
+ def __next__(self):
429
+ left_row = next(self.left_iterator)
430
+ left_key_value = left_row[self.left_key]
431
+
432
+ # Advance right iterator until we find matching key
433
+ while True:
434
+ if not self.right_buffer:
435
+ right_row = next(self.right_iterator)
436
+ self.right_buffer.append(right_row)
437
+
438
+ right_key_value = self.right_buffer[0][self.right_key]
439
+
440
+ if right_key_value == left_key_value:
441
+ # Match found - merge and yield
442
+ right_row = self.right_buffer.pop(0)
443
+ return {**left_row, **right_row}
444
+ elif right_key_value > left_key_value:
445
+ # Right side ahead - no match for this left row
446
+ return None
447
+ else:
448
+ # Right side behind - advance right
449
+ self.right_buffer.pop(0)
450
+ ```
451
+
452
+ **Why merge join:** O(n+m) time complexity, O(1) memory. Perfect for pre-sorted data.
453
+
454
+ **4. ProjectIterator**
455
+
456
+ - Applies SELECT clause
457
+ - Only includes requested columns
458
+ - Handles column aliases
459
+
460
+ **Logic:**
461
+
462
+ ```python
463
+ class ProjectIterator:
464
+ def __init__(self, source_iterator, projections):
465
+ self.source_iterator = source_iterator
466
+ self.projections = projections # List of (table.col, alias) tuples
467
+
468
+ def __next__(self):
469
+ row = next(self.source_iterator)
470
+ result = {}
471
+ for table_col, alias in self.projections:
472
+ result[alias or table_col] = row[table_col]
473
+ return result
474
+ ```
475
+
476
+ ### Why Iterator-Based Architecture?
477
+
478
+ **Key advantages:**
479
+
480
+ 1. **Memory efficiency:** Only one row in memory at a time (except for join indexes)
481
+ 2. **Lazy evaluation:** Processing starts only when you iterate over results
482
+ 3. **Composability:** Operators can be chained arbitrarily
483
+ 4. **Extensibility:** Easy to add new operators
484
+ 5. **Python-native:** Uses standard Python iterator protocol
485
+
486
+ **Trade-offs:**
487
+
488
+ - **Performance:** Python iterators are slower than compiled code, but flexibility is worth it
489
+ - **Memory:** Join indexes require memory, but this is necessary for efficient joins
490
+ - **Complexity:** Iterator chains can be complex, but they're composable and testable
491
+
492
+ ### Expression Evaluation
493
+
494
+ **How WHERE clauses are evaluated:**
495
+
496
+ The engine uses recursive AST traversal to evaluate expressions:
497
+
498
+ ```python
499
+ def evaluate_expression(expr, row):
500
+ """Recursively evaluate SQL expression against row data"""
501
+
502
+ if isinstance(expr, exp.Column):
503
+ # Column reference: lookup value in row
504
+ return row[expr.sql()]
505
+
506
+ elif isinstance(expr, exp.Literal):
507
+ # Literal value: return as-is
508
+ return expr.this
509
+
510
+ elif isinstance(expr, exp.EQ):
511
+ # Equality: evaluate left and right, compare
512
+ left = evaluate_expression(expr.this, row)
513
+ right = evaluate_expression(expr.expression, row)
514
+ return left == right
515
+
516
+ elif isinstance(expr, exp.GT):
517
+ # Greater than: evaluate and compare
518
+ left = evaluate_expression(expr.this, row)
519
+ right = evaluate_expression(expr.expression, row)
520
+ return left > right
521
+
522
+ # ... handle other operators (AND, OR, NOT, etc.)
523
+ ```
524
+
525
+ **Why recursive:** SQL expressions are trees. Recursive evaluation naturally handles nested expressions like `(a > 10 AND b < 20) OR c = 5`.
526
+
527
+ ### Join Algorithm Selection
528
+
529
+ **How the engine chooses join algorithms:**
530
+
531
+ 1. **Check if both sides are sorted** (`ordered_by` metadata)
532
+
533
+ - If yes → Use MergeJoinIterator
534
+ - If no → Use LookupJoinIterator
535
+
536
+ 2. **Check if right side is a file** (`filename` metadata)
537
+
538
+ - If yes → Use MmapLookupJoinIterator (memory-mapped)
539
+
540
+ 3. **Check if Polars is available** (`use_polars` flag)
541
+ - If yes → Use PolarsLookupJoinIterator (vectorized)
542
+
543
+ **Logic:**
544
+
545
+ ```python
546
+ def _build_join_iterator(left_iterator, right_source_fn, left_key, right_key,
547
+ right_metadata, use_polars):
548
+ # Check for merge join (both sides sorted)
549
+ if left_metadata.get('ordered_by') == left_key and \
550
+ right_metadata.get('ordered_by') == right_key:
551
+ return MergeJoinIterator(left_iterator, right_source_fn, left_key, right_key)
552
+
553
+ # Check for mmap join (file-based)
554
+ if right_metadata.get('filename') and MMAP_AVAILABLE:
555
+ return MmapLookupJoinIterator(left_iterator, right_source_fn,
556
+ right_metadata['filename'], left_key, right_key)
557
+
558
+ # Check for Polars join (vectorized)
559
+ if use_polars and POLARS_AVAILABLE:
560
+ return PolarsLookupJoinIterator(left_iterator, right_source_fn,
561
+ left_key, right_key)
562
+
563
+ # Default: standard lookup join
564
+ return LookupJoinIterator(left_iterator, right_source_fn, left_key, right_key)
565
+ ```
566
+
567
+ ### Protocol-Based Optimization
568
+
569
+ **The key innovation:** Automatic optimization detection via function signature inspection.
570
+
571
+ **How it works:**
572
+
573
+ 1. Engine inspects source function signature using `inspect.signature()`
574
+ 2. If function accepts `dynamic_where` or `dynamic_columns` parameters, it supports optimizations
575
+ 3. Engine passes optimization parameters automatically
576
+ 4. Source function applies optimizations (filter pushdown, column pruning)
577
+
578
+ **Why this approach:**
579
+
580
+ - **No flags needed:** Detection is automatic
581
+ - **Flexible:** Any Python function can be a source
582
+ - **Backward compatible:** Simple sources still work (no optimizations)
583
+ - **Extensible:** Easy to add new optimization parameters
584
+
585
+ **Example:**
586
+
587
+ ```python
588
+ # Simple source (no optimizations)
589
+ def simple_source():
590
+ return iter([{"id": 1, "name": "Alice"}])
591
+
592
+ # Optimized source (with protocol)
593
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
594
+ query = "SELECT "
595
+ if dynamic_columns:
596
+ query += ", ".join(dynamic_columns)
597
+ else:
598
+ query += "*"
599
+ query += " FROM table"
600
+ if dynamic_where:
601
+ query += f" WHERE {dynamic_where}"
602
+ return execute_query(query)
603
+
604
+ # Both work the same way:
605
+ engine.register("users", simple_source) # No optimizations
606
+ engine.register("products", optimized_source) # Optimizations apply automatically!
607
+ ```
608
+
609
+ ### Memory Management
610
+
611
+ **Key strategies:**
612
+
613
+ 1. **Streaming:** Process one row at a time, never load full tables
614
+ 2. **Join indexes:** Only right side of joins is materialized (necessary for lookups)
615
+ 3. **Memory-mapped files:** For large JSONL files, use OS virtual memory
616
+ 4. **Column pruning:** Only extract needed columns
617
+ 5. **Filter pushdown:** Filter at source, reduce data transfer
618
+
619
+ **Memory footprint:**
620
+
621
+ - **Left side of join:** O(1) - one row at a time
622
+ - **Right side of join:** O(n) - hash index in memory
623
+ - **Total:** O(n) where n = size of right side
624
+
625
+ **Why this works:** In most queries, the right side is smaller (e.g., joining large product table with small category table). The engine is designed to put smaller tables on the right side.
626
+
627
+ ### Performance Optimizations
628
+
629
+ **1. Polars Vectorization**
630
+
631
+ When Polars is available, the engine uses vectorized operations:
632
+
633
+ ```python
634
+ # Instead of row-by-row filtering:
635
+ for row in rows:
636
+ if row['price'] > 100:
637
+ yield row
638
+
639
+ # Use Polars batch filtering:
640
+ df = pl.DataFrame(rows)
641
+ filtered_df = df.filter(pl.col('price') > 100)
642
+ for row in filtered_df.iter_rows(named=True):
643
+ yield row
644
+ ```
645
+
646
+ **Why faster:** Polars uses SIMD instructions and columnar processing, 10-200x faster than row-by-row Python loops.
647
+
648
+ **2. Memory-Mapped Joins**
649
+
650
+ For large JSONL files, use OS virtual memory instead of loading into RAM:
651
+
652
+ ```python
653
+ # Instead of loading entire file:
654
+ with open('large_file.jsonl') as f:
655
+ data = [json.loads(line) for line in f] # 10GB in memory!
656
+
657
+ # Use memory-mapped file:
658
+ import mmap
659
+ with open('large_file.jsonl', 'rb') as f:
660
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
661
+ # OS handles memory, can process files larger than RAM
662
+ ```
663
+
664
+ **Why this works:** OS virtual memory allows accessing file data without loading it all into RAM. 90-99% memory reduction for large files.
665
+
666
+ **3. First Match Only Optimization**
667
+
668
+ For joins where only the first match matters (prevents Cartesian products):
669
+
670
+ ```python
671
+ class LookupJoinIterator:
672
+ def __init__(self, ..., first_match_only=False):
673
+ self.first_match_only = first_match_only
674
+
675
+ def _build_index(self):
676
+ self.index = {}
677
+ for right_row in self.right_source_fn():
678
+ key = right_row[self.right_key]
679
+ if self.first_match_only:
680
+ # Only keep first match per key
681
+ if key not in self.index:
682
+ self.index[key] = right_row
683
+ else:
684
+ # Keep all matches
685
+ if key not in self.index:
686
+ self.index[key] = []
687
+ self.index[key].append(right_row)
688
+ ```
689
+
690
+ **Why useful:** Prevents Cartesian products when right side has duplicate keys. Significantly reduces output size and processing time.
691
+
692
+ ### Design Decisions and Trade-offs
693
+
694
+ **1. Why Python iterators instead of compiled code?**
695
+
696
+ **Decision:** Use Python iterators for flexibility
697
+
698
+ **Trade-off:** Slower than compiled code, but:
699
+
700
+ - Works with any Python data source
701
+ - Easy to extend and customize
702
+ - No compilation step needed
703
+ - Python-native integration
704
+
705
+ **2. Why separate logical planning from execution?**
706
+
707
+ **Decision:** Two-phase approach (plan then execute)
708
+
709
+ **Trade-off:** Extra step, but:
710
+
711
+ - Enables query optimization
712
+ - Easier to test and debug
713
+ - Can reuse planning logic
714
+ - Clear separation of concerns
715
+
716
+ **3. Why protocol-based optimization instead of flags?**
717
+
718
+ **Decision:** Automatic detection via function signature
719
+
720
+ **Trade-off:** Slightly more complex detection, but:
721
+
722
+ - No flags to remember
723
+ - Automatic optimization
724
+ - Backward compatible
725
+ - More Pythonic
726
+
727
+ **4. Why materialize right side of joins?**
728
+
729
+ **Decision:** Build hash index on right side
730
+
731
+ **Trade-off:** Memory usage, but:
732
+
733
+ - O(1) lookup time per left row
734
+ - Necessary for efficient joins
735
+ - Can use memory-mapped files for large files
736
+ - Standard database approach
737
+
738
+ **5. Why limit SQL features (no GROUP BY, aggregations)?**
739
+
740
+ **Decision:** Focus on joins and filtering
741
+
742
+ **Trade-off:** Less SQL support, but:
743
+
744
+ - Simpler implementation
745
+ - Faster execution
746
+ - Focuses on core use case (cross-system joins)
747
+ - Can add later if needed
748
+
749
+ ### The Result
750
+
751
+ A lightweight Python library that:
752
+
753
+ - Joins data from any source using SQL
754
+ - Processes data row-by-row (streaming)
755
+ - Requires zero infrastructure
756
+ - Automatically optimizes when possible
757
+ - Works with any Python iterator
758
+
759
+ **The key insight:** Python's iterator protocol is perfect for streaming SQL execution. By combining SQL parsing, logical planning, and iterator-based execution, I created a tool that solves a real problem: joining data from different systems without complex infrastructure.
760
+
761
+ ---
762
+
763
+ ## Real-World Performance: 39 Million Records in 7 Minutes
764
+
765
+ I recently used this engine in production to compare prices between two XML files (17 million records each) and match them with a MongoDB collection (5 million records).
766
+
767
+ **The results:**
768
+
769
+ - **39 million total records processed**
770
+ - **7 minutes execution time**
771
+ - **400 MB memory usage**
772
+ - **92,857 records/second throughput**
773
+
774
+ This demonstrates the engine's efficiency: processing massive datasets with minimal memory footprint through true streaming architecture.
775
+
776
+ ---
777
+
778
+ ## How It Works: Streaming Architecture
779
+
780
+ The engine processes data **row-by-row**, never loading entire tables into memory:
781
+
782
+ ```
783
+ SQL Query
784
+ ↓
785
+ Parser → AST
786
+ ↓
787
+ Planner → Logical Plan
788
+ ↓
789
+ Executor → Iterator Pipeline
790
+ ↓
791
+ Results (Generator)
792
+ ```
793
+
794
+ **Iterator Pipeline:**
795
+
796
+ ```
797
+ ScanIterator → FilterIterator → JoinIterators → ProjectIterator → Results
798
+ ```
799
+
800
+ Each iterator processes rows incrementally, enabling true streaming execution. This means:
801
+
802
+ - Low memory footprint
803
+ - Can process data larger than RAM
804
+ - Results yielded immediately
805
+ - No buffering required
806
+
807
+ ---
808
+
809
+ ## Supported Data Sources
810
+
811
+ The engine works with **any Python iterator**, making it incredibly flexible:
812
+
813
+ ### Databases
814
+
815
+ All databases are accessed via Python iterator functions. The engine doesn't use connectors - it works with any Python function that returns an iterator:
816
+
817
+ - **PostgreSQL** - Create iterator function that queries PostgreSQL and yields rows
818
+ - **MySQL** - Create iterator function that queries MySQL and yields rows
819
+ - **MongoDB** - Create iterator function that queries MongoDB and yields documents
820
+
821
+ ### Files
822
+
823
+ - **CSV** - Standard CSV files
824
+ - **JSONL** - JSON Lines format with memory-mapped joins
825
+ - **JSON** - Standard JSON files
826
+ - **XML** - XML parsing with ElementTree
827
+
828
+ ### APIs
829
+
830
+ - **REST APIs** - Any HTTP endpoint
831
+ - **GraphQL** - Via custom functions
832
+ - **WebSockets** - Streaming data sources
833
+
834
+ ### Custom Sources
835
+
836
+ - **Any Python function** that returns an iterator
837
+ - **Generators** - Perfect for streaming data
838
+ - **Custom transformations** - Apply Python logic between joins
839
+
840
+ ---
841
+
842
+ ## SQL Features
843
+
844
+ The engine supports standard SQL syntax:
845
+
846
+ ### Supported Features
847
+
848
+ **SELECT** - Column selection, aliasing, table-qualified columns
849
+
850
+ ```sql
851
+ SELECT users.name, orders.total AS order_total
852
+ FROM users
853
+ JOIN orders ON users.id = orders.user_id
854
+ ```
855
+
856
+ **JOIN** - INNER JOIN and LEFT JOIN with equality conditions
857
+
858
+ ```sql
859
+ SELECT *
860
+ FROM table1 t1
861
+ JOIN table2 t2 ON t1.id = t2.id
862
+ LEFT JOIN table3 t3 ON t1.id = t3.id
863
+ ```
864
+
865
+ **WHERE** - Comparisons, boolean logic, NULL checks, IN clauses
866
+
867
+ ```sql
868
+ SELECT *
869
+ FROM products
870
+ WHERE price > 100
871
+ AND status IN ('active', 'pending')
872
+ AND description IS NOT NULL
873
+ ```
874
+
875
+ **Arithmetic** - Addition, subtraction, multiplication, division, modulo
876
+
877
+ ```sql
878
+ SELECT
879
+ price - discount AS final_price,
880
+ quantity * unit_price AS total
881
+ FROM orders
882
+ ```
883
+
884
+ ### Not Supported
885
+
886
+ - GROUP BY and aggregations (COUNT, SUM, AVG)
887
+ - ORDER BY
888
+ - HAVING
889
+ - Subqueries
890
+
891
+ _These limitations keep the engine focused on joins and filtering — its core strength._
892
+
893
+ ---
894
+
895
+ ## Performance Optimizations
896
+
897
+ The engine includes several automatic optimizations:
898
+
899
+ ### 1. Column Pruning
900
+
901
+ Only extracts columns needed for the query, reducing I/O and memory:
902
+
903
+ ```python
904
+ # Query only requests 'name' and 'price'
905
+ query = "SELECT name, price FROM products"
906
+
907
+ # Engine automatically requests only these columns from source
908
+ def source(dynamic_columns=None):
909
+ columns = ", ".join(dynamic_columns) # ['name', 'price']
910
+ query = f"SELECT {columns} FROM table"
911
+ ```
912
+
913
+ ### 2. Filter Pushdown
914
+
915
+ Pushes WHERE conditions to data sources when possible:
916
+
917
+ ```python
918
+ # Query has WHERE clause
919
+ query = "SELECT * FROM products WHERE price > 100"
920
+
921
+ # Engine automatically pushes filter to source
922
+ def source(dynamic_where=None):
923
+ query = f"SELECT * FROM table WHERE {dynamic_where}"
924
+ ```
925
+
926
+ ### 3. Polars Vectorization
927
+
928
+ 10-200x faster processing for large datasets using SIMD-accelerated operations:
929
+
930
+ ```python
931
+ engine = Engine(use_polars=True) # Enabled by default
932
+
933
+ # Automatically uses Polars for:
934
+ # - Vectorized filtering
935
+ # - Vectorized projections
936
+ # - Batch processing
937
+ ```
938
+
939
+ ### 4. Memory-Mapped Joins
940
+
941
+ 90-99% memory reduction for large JSONL files:
942
+
943
+ ```python
944
+ # Register with filename to enable mmap joins
945
+ engine.register("products", jsonl_source, filename="products.jsonl")
946
+
947
+ # Engine uses OS virtual memory instead of RAM
948
+ # Can process files larger than available RAM
949
+ ```
950
+
951
+ ### 5. Merge Joins
952
+
953
+ Efficient joins for pre-sorted data (O(n+m) time complexity):
954
+
955
+ ```python
956
+ # Register with ordered_by to enable merge join
957
+ engine.register("users", users_source, ordered_by="id")
958
+
959
+ # Engine uses merge join algorithm
960
+ # Both sides must be sorted by join key
961
+ ```
962
+
963
+ ---
964
+
965
+ ## Real-World Examples
966
+
967
+ ### Example 1: Microservices Data Integration
968
+
969
+ In a microservices architecture, data is distributed across services:
970
+
971
+ ```python
972
+ from streaming_sql_engine import Engine
973
+ import psycopg2
974
+ import pymysql
975
+ import requests
976
+
977
+ engine = Engine()
978
+
979
+ # Service 1: User service (PostgreSQL) - iterator function
980
+ def users_source():
981
+ conn = psycopg2.connect(host="user-db", port=5432, user="user", password="pass", database="users_db")
982
+ cursor = conn.cursor()
983
+ cursor.execute("SELECT id, name, email FROM users")
984
+ for row in cursor:
985
+ yield {"id": row[0], "name": row[1], "email": row[2]}
986
+ conn.close()
987
+ engine.register("users", users_source)
988
+
989
+ # Service 2: Order service (MySQL) - iterator function
990
+ def orders_source():
991
+ conn = pymysql.connect(host="order-db", port=3306, user="user", password="pass", database="orders_db")
992
+ cursor = conn.cursor()
993
+ cursor.execute("SELECT id, user_id, total FROM orders")
994
+ for row in cursor:
995
+ yield {"id": row[0], "user_id": row[1], "total": row[2]}
996
+ conn.close()
997
+ engine.register("orders", orders_source)
998
+
999
+ # Service 3: Payment service (REST API) - iterator function
1000
+ def payment_source():
1001
+ response = requests.get("https://payments.service/api/transactions")
1002
+ for item in response.json():
1003
+ yield item
1004
+ engine.register("payments", payment_source)
1005
+
1006
+ # Join across services
1007
+ query = """
1008
+ SELECT users.name, orders.total, payments.status
1009
+ FROM users
1010
+ JOIN orders ON users.id = orders.user_id
1011
+ JOIN payments ON orders.id = payments.order_id
1012
+ """
1013
+ ```
1014
+
1015
+ **Why this matters:** No need for a shared database or complex ETL pipelines. The engine accepts any Python function that returns an iterator, making it incredibly flexible.
1016
+
1017
+ ### Example 2: Real-Time Price Comparison
1018
+
1019
+ Compare prices from multiple XML feeds and match with MongoDB:
1020
+
1021
+ ```python
1022
+ def parse_xml(filepath):
1023
+ tree = ET.parse(filepath)
1024
+ for product in tree.findall('.//product'):
1025
+ yield {
1026
+ 'ean': product.find('ean').text,
1027
+ 'price': float(product.find('price').text),
1028
+ 'name': product.find('name').text
1029
+ }
1030
+
1031
+ engine.register("xml1", lambda: parse_xml("prices1.xml"))
1032
+ engine.register("xml2", lambda: parse_xml("prices2.xml"))
1033
+ engine.register("mongo", mongo_source)
1034
+
1035
+ query = """
1036
+ SELECT
1037
+ xml1.ean,
1038
+ xml1.price AS price1,
1039
+ xml2.price AS price2,
1040
+ mongo.sf_sku
1041
+ FROM xml1
1042
+ JOIN xml2 ON xml1.ean = xml2.ean
1043
+ JOIN mongo ON xml1.ean = mongo.ean
1044
+ WHERE xml1.price != xml2.price
1045
+ """
1046
+ ```
1047
+
1048
+ **Production results:** 17M + 17M XML records + 5M MongoDB records processed in 7 minutes using 400 MB RAM.
1049
+
1050
+ ### Example 3: Python Processing Between Joins
1051
+
1052
+ Apply Python logic (ML models, custom functions) between joins:
1053
+
1054
+ ```python
1055
+ def enriched_source():
1056
+ """Source that processes data with Python before joining"""
1057
+ import psycopg2
1058
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
1059
+ cursor = conn.cursor()
1060
+ cursor.execute("SELECT id, name, category_id FROM products")
1061
+ for row in cursor:
1062
+ product = {"id": row[0], "name": row[1], "category_id": row[2]}
1063
+ # Apply Python logic
1064
+ product['ml_score'] = ml_model.predict(product)
1065
+ product['custom_field'] = custom_function(product)
1066
+ yield product
1067
+ conn.close()
1068
+
1069
+ def categories_source():
1070
+ import psycopg2
1071
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
1072
+ cursor = conn.cursor()
1073
+ cursor.execute("SELECT id, name FROM categories")
1074
+ for row in cursor:
1075
+ yield {"id": row[0], "category_name": row[1]}
1076
+ conn.close()
1077
+
1078
+ engine.register("enriched_products", enriched_source)
1079
+ engine.register("categories", categories_source)
1080
+
1081
+ query = """
1082
+ SELECT p.name, p.ml_score, c.category_name
1083
+ FROM enriched_products p
1084
+ JOIN categories c ON p.category_id = c.id
1085
+ """
1086
+ ```
1087
+
1088
+ **Why this matters:** Seamless integration with Python ecosystem — use any library, apply any logic.
1089
+
1090
+ ---
1091
+
1092
+ ## Comparison with Alternatives
1093
+
1094
+ ### vs DuckDB
1095
+
1096
+ | Feature | Streaming SQL Engine | DuckDB |
1097
+ | ----------------------- | -------------------- | ------------------- |
1098
+ | Cross-system joins | ✅ Direct | ⚠️ Requires import |
1099
+ | API + Database join | ✅ Direct | ❌ Must export API |
1100
+ | Real-time streaming | ✅ True streaming | ⚠️ Buffering needed |
1101
+ | Python processing | ✅ Native | ⚠️ Export/import |
1102
+ | GROUP BY / Aggregations | ❌ Not supported | ✅ Full support |
1103
+ | Performance (same DB) | ⚠️ Moderate | ✅ Very fast |
1104
+
1105
+ **Use Streaming SQL Engine when:** You need to join data from different systems that can't be imported into DuckDB.
1106
+
1107
+ **Use DuckDB when:** All data can be imported and you need aggregations.
1108
+
1109
+ ### vs PySpark
1110
+
1111
+ | Feature | Streaming SQL Engine | PySpark |
1112
+ | ---------------------- | -------------------- | ------------------ |
1113
+ | Infrastructure | ✅ Zero | ❌ Cluster needed |
1114
+ | Setup time | ✅ Seconds | ❌ Hours |
1115
+ | Memory (small queries) | ✅ 100-500 MB | ❌ 4-8 GB minimum |
1116
+ | Cross-system joins | ✅ Direct | ⚠️ Requires import |
1117
+ | Distributed processing | ❌ Single machine | ✅ Multi-machine |
1118
+ | Big data (petabytes) | ❌ Not suitable | ✅ Excellent |
1119
+ | Python integration | ✅ Native Python | ⚠️ PySpark API |
1120
+ | Learning curve | ✅ Simple | ❌ Steeper |
1121
+
1122
+ **Use Streaming SQL Engine when:** You need cross-system joins on a single machine with simple deployment.
1123
+
1124
+ **Use PySpark when:** You need distributed processing across multiple machines for petabyte-scale data.
1125
+
1126
+ ### vs Apache Flink
1127
+
1128
+ | Feature | Streaming SQL Engine | Apache Flink |
1129
+ | ---------------------- | -------------------- | ---------------------- |
1130
+ | Infrastructure | ✅ Zero | ❌ Cluster needed |
1131
+ | Setup complexity | ✅ Very low | ❌ High |
1132
+ | Python-native | ✅ Pure Python | ⚠️ Python API wrapper |
1133
+ | Cross-system joins | ✅ Direct | ⚠️ Requires connectors |
1134
+ | Real-time streaming | ✅ True streaming | ✅ Excellent |
1135
+ | Distributed processing | ❌ Single machine | ✅ Multi-machine |
1136
+ | Fault tolerance | ❌ Not provided | ✅ Built-in |
1137
+ | Exactly-once semantics | ❌ Not provided | ✅ Supported |
1138
+ | Event-time processing | ❌ Not supported | ✅ Full support |
1139
+ | Low latency | ✅ Immediate | ⚠️ Network overhead |
1140
+
1141
+ **Use Streaming SQL Engine when:** You need simple cross-system joins, Python-native workflows, and zero infrastructure.
1142
+
1143
+ **Use Apache Flink when:** You need distributed stream processing, fault tolerance, exactly-once semantics, and complex event-time processing.
1144
+
1145
+ ### vs Pandas
1146
+
1147
+ | Feature | Streaming SQL Engine | Pandas |
1148
+ | ------------------------ | ---------------------- | ------------------------ |
1149
+ | Cross-system joins | ✅ Direct | ❌ Must load all data |
1150
+ | Memory efficiency | ✅ Streaming | ❌ Loads all in memory |
1151
+ | SQL syntax | ✅ Standard SQL | ❌ DataFrame API |
1152
+ | Large datasets | ✅ Can exceed RAM | ❌ Limited by RAM |
1153
+ | Real-time data | ✅ Streaming | ❌ Batch only |
1154
+ | File formats | ✅ Any Python iterator | ⚠️ Limited formats |
1155
+ | Performance (large data) | ✅ Streaming | ⚠️ Slower for large data |
1156
+
1157
+ **Use Streaming SQL Engine when:** You need to join data from different systems, process data larger than RAM, or use SQL syntax.
1158
+
1159
+ **Use Pandas when:** All data fits in memory and you prefer DataFrame API.
1160
+
1161
+ ### vs SQLAlchemy
1162
+
1163
+ | Feature | Streaming SQL Engine | SQLAlchemy |
1164
+ | --------------------- | -------------------- | ------------------------- |
1165
+ | Cross-database joins | ✅ Direct | ❌ One database at a time |
1166
+ | API joins | ✅ Direct | ❌ Not supported |
1167
+ | File joins | ✅ Direct | ❌ Not supported |
1168
+ | SQL syntax | ✅ Standard SQL | ✅ ORM or SQL |
1169
+ | Same-database queries | ⚠️ Slower | ✅ Optimized |
1170
+ | Database abstraction | ❌ Not provided | ✅ Full ORM |
1171
+
1172
+ **Use Streaming SQL Engine when:** You need to join data from different systems (databases, APIs, files).
1173
+
1174
+ **Use SQLAlchemy when:** All data is in the same database and you want ORM features.
1175
+
1176
+ ### vs Presto/Trino
1177
+
1178
+ | Feature | Streaming SQL Engine | Presto/Trino |
1179
+ | ------------------ | -------------------- | ----------------------------- |
1180
+ | Infrastructure | ✅ Zero | ❌ Cluster needed |
1181
+ | Setup complexity | ✅ Very low | ❌ High |
1182
+ | Cross-system joins | ✅ Direct | ✅ Supported |
1183
+ | Python integration | ✅ Native | ⚠️ JDBC/ODBC |
1184
+ | Real-time APIs | ✅ Direct | ⚠️ Requires connector |
1185
+ | Memory efficiency | ✅ Streaming | ⚠️ Query coordinator overhead |
1186
+ | SQL features | ⚠️ Limited | ✅ Full SQL |
1187
+ | Aggregations | ❌ Not supported | ✅ Full support |
1188
+
1189
+ **Use Streaming SQL Engine when:** You need Python-native cross-system joins with zero infrastructure.
1190
+
1191
+ **Use Presto/Trino when:** You need full SQL features, aggregations, and have infrastructure for a cluster.
1192
+
1193
+ ### vs Apache Drill
1194
+
1195
+ | Feature | Streaming SQL Engine | Apache Drill |
1196
+ | ------------------ | -------------------- | --------------------- |
1197
+ | Infrastructure | ✅ Zero | ❌ Cluster needed |
1198
+ | Language | ✅ Python | ❌ Java |
1199
+ | Deployment | ✅ pip install | ❌ Server setup |
1200
+ | Cross-system joins | ✅ Direct | ✅ Supported |
1201
+ | API joins | ✅ Direct | ⚠️ Requires connector |
1202
+ | Python integration | ✅ Native | ⚠️ JDBC/ODBC |
1203
+ | SQL features | ⚠️ Limited | ✅ Full SQL |
1204
+ | Scalability | ❌ Single machine | ✅ 1000+ nodes |
1205
+
1206
+ **Use Streaming SQL Engine when:** You need simple Python-native cross-system joins with zero setup.
1207
+
1208
+ **Use Apache Drill when:** You need enterprise-scale distributed querying across Hadoop/NoSQL systems.
1209
+
1210
+ ### vs ksqlDB
1211
+
1212
+ | Feature | Streaming SQL Engine | ksqlDB |
1213
+ | ------------------ | -------------------- | ----------------------- |
1214
+ | Infrastructure | ✅ Zero | ❌ Kafka cluster needed |
1215
+ | Data sources | ✅ Any Python source | ⚠️ Kafka topics only |
1216
+ | API joins | ✅ Direct | ❌ Not supported |
1217
+ | File joins | ✅ Direct | ⚠️ Requires Kafka |
1218
+ | Python integration | ✅ Native | ⚠️ REST API |
1219
+ | Real-time | ✅ Streaming | ✅ Excellent |
1220
+ | SQL features | ⚠️ Limited | ✅ Full SQL |
1221
+
1222
+ **Use Streaming SQL Engine when:** You need to join data from databases, APIs, and files without Kafka.
1223
+
1224
+ **Use ksqlDB when:** You're already using Kafka and need streaming SQL on Kafka topics.
1225
+
1226
+ ### vs Materialize
1227
+
1228
+ | Feature | Streaming SQL Engine | Materialize |
1229
+ | ------------------ | -------------------- | ------------------------ |
1230
+ | Infrastructure | ✅ Zero | ❌ Database server |
1231
+ | Deployment | ✅ Python library | ❌ Database installation |
1232
+ | Cross-system joins | ✅ Direct | ⚠️ Requires connectors |
1233
+ | Materialized views | ❌ Not supported | ✅ Core feature |
1234
+ | Python integration | ✅ Native | ⚠️ SQL/psql |
1235
+ | Real-time | ✅ Streaming | ✅ Excellent |
1236
+ | SQL features | ⚠️ Limited | ✅ Full SQL |
1237
+
1238
+ **Use Streaming SQL Engine when:** You need simple Python-native joins without database infrastructure.
1239
+
1240
+ **Use Materialize when:** You need materialized views over streaming data with full SQL support.
1241
+
1242
+ ### vs DataFusion (Apache Arrow)
1243
+
1244
+ | Feature | Streaming SQL Engine | DataFusion |
1245
+ | ------------------ | -------------------- | ------------------------ |
1246
+ | Language | ✅ Python | ⚠️ Rust (Python wrapper) |
1247
+ | Infrastructure | ✅ Zero | ✅ Zero |
1248
+ | Cross-system joins | ✅ Direct | ⚠️ Limited connectors |
1249
+ | API joins | ✅ Direct | ❌ Not supported |
1250
+ | Python integration | ✅ Native | ⚠️ Python wrapper |
1251
+ | Performance | ⚠️ Moderate | ✅ Very fast (Rust) |
1252
+ | SQL features | ⚠️ Limited | ✅ Full SQL |
1253
+
1254
+ **Use Streaming SQL Engine when:** You need to join APIs and files with Python-native flexibility.
1255
+
1256
+ **Use DataFusion when:** You need high-performance SQL queries on Arrow/Parquet data.
1257
+
1258
+ ### vs Polars SQL
1259
+
1260
+ | Feature | Streaming SQL Engine | Polars SQL |
1261
+ | ------------------ | -------------------- | ------------------------ |
1262
+ | Data sources | ✅ Any Python source | ⚠️ DataFrames/Parquet |
1263
+ | Cross-system joins | ✅ Direct | ⚠️ Must load into Polars |
1264
+ | API joins | ✅ Direct | ❌ Not supported |
1265
+ | Memory efficiency | ✅ Streaming | ⚠️ Loads into memory |
1266
+ | SQL syntax | ✅ Standard SQL | ✅ Standard SQL |
1267
+ | Python integration | ✅ Native | ✅ Native |
1268
+ | Performance | ⚠️ Moderate | ✅ Very fast |
1269
+
1270
+ **Use Streaming SQL Engine when:** You need to join data from different systems without loading into Polars.
1271
+
1272
+ **Use Polars SQL when:** All data can be loaded into Polars DataFrames and you need high performance.
1273
+
1274
+ ---
1275
+
1276
+ ## Are There Other Tools Like This?
1277
+
1278
+ **Short answer: Not exactly.**
1279
+
1280
+ While there are many tools that do **parts** of what Streaming SQL Engine does, none combine all these characteristics:
1281
+
1282
+ ### What Makes Streaming SQL Engine Unique
1283
+
1284
+ 1. **Zero Infrastructure + Cross-System Joins**
1285
+
1286
+ - Most tools require clusters (Spark, Flink, Drill)
1287
+ - Or require specific infrastructure (ksqlDB needs Kafka)
1288
+ - Streaming SQL Engine: Just Python
1289
+
1290
+ 2. **Any Python Iterator as Data Source**
1291
+
1292
+ - Most tools require specific connectors
1293
+ - Streaming SQL Engine: Any Python function works
1294
+
1295
+ 3. **Direct API Joins**
1296
+
1297
+ - Most tools can't join REST APIs directly
1298
+ - Streaming SQL Engine: Native support
1299
+
1300
+ 4. **Python-Native Architecture**
1301
+ - Most tools are Java/Rust with Python wrappers
1302
+ - Streaming SQL Engine: Pure Python, seamless integration
1303
+
1304
+ ### Similar Tools (But Different)
1305
+
1306
+ **Apache Drill** — Similar cross-system capability, but requires cluster and Java
1307
+
1308
+ **ksqlDB** — Streaming SQL, but Kafka-only and requires infrastructure
1309
+
1310
+ **Materialize** — Streaming database, but requires database server
1311
+
1312
+ **DataFusion** — Fast SQL engine, but limited to Arrow/Parquet data
1313
+
1314
+ **Polars SQL** — Fast SQL, but requires loading data into DataFrames first
1315
+
1316
+ **Presto/Trino** — Cross-system SQL, but requires cluster infrastructure
1317
+
1318
+ **None of these** combine:
1319
+
1320
+ - Zero infrastructure
1321
+ - Any Python iterator as source
1322
+ - Direct API joins
1323
+ - Pure Python implementation
1324
+ - Simple deployment
1325
+
1326
+ **That's what makes Streaming SQL Engine unique.**
1327
+
1328
+ ---
1329
+
1330
+ ## Key Wins
1331
+
1332
+ ### 1. Cross-System Joins
1333
+
1334
+ The **only tool** that can join MySQL + PostgreSQL + MongoDB + REST API + CSV files in a single SQL query without data export/import.
1335
+
1336
+ ### 2. Zero Infrastructure
1337
+
1338
+ No clusters, no setup, just Python. Install and use immediately:
1339
+
1340
+ ```bash
1341
+ pip install streaming-sql-engine
1342
+ ```
1343
+
1344
+ ### 3. Memory Efficient
1345
+
1346
+ Processes 39 million records with only 400 MB RAM. True streaming architecture means you can process data larger than available RAM.
1347
+
1348
+ ### 4. Python-Native
1349
+
1350
+ Seamless integration with Python ecosystem. Use any Python function as a data source, apply ML models, use any library.
1351
+
1352
+ ### 5. Real-Time Processing
1353
+
1354
+ Join live streaming data with static reference data. No buffering required — true streaming execution.
1355
+
1356
+ ### 6. Automatic Optimizations
1357
+
1358
+ Filter pushdown, column pruning, and vectorization applied automatically. No configuration needed — the engine detects protocol support.
1359
+
1360
+ ---
1361
+
1362
+ ## When to Use Streaming SQL Engine
1363
+
1364
+ **Perfect for:**
1365
+
1366
+ - Joining data from different systems (databases, APIs, files)
1367
+ - Microservices data aggregation
1368
+ - Real-time data integration
1369
+ - Memory-constrained environments
1370
+ - Python-native workflows
1371
+ - Ad-hoc cross-system queries
1372
+
1373
+ **Not for:**
1374
+
1375
+ - All data in same database (use direct SQL - 10-100x faster)
1376
+ - Need GROUP BY or aggregations (use database)
1377
+ - Maximum performance for same-database queries (use database)
1378
+ - Distributed processing (use Spark/Flink)
1379
+
1380
+ ---
1381
+
1382
+ ## Getting Started
1383
+
1384
+ Installation:
1385
+
1386
+ ```bash
1387
+ pip install streaming-sql-engine
1388
+ ```
1389
+
1390
+ Quick start:
1391
+
1392
+ ```python
1393
+ from streaming_sql_engine import Engine
1394
+
1395
+ engine = Engine()
1396
+
1397
+ # Register data sources (any Python function that returns an iterator)
1398
+ def users_source():
1399
+ return iter([
1400
+ {"id": 1, "name": "Alice", "dept_id": 10},
1401
+ {"id": 2, "name": "Bob", "dept_id": 20},
1402
+ ])
1403
+
1404
+ def departments_source():
1405
+ return iter([
1406
+ {"id": 10, "name": "Engineering"},
1407
+ {"id": 20, "name": "Sales"},
1408
+ ])
1409
+
1410
+ engine.register("users", users_source)
1411
+ engine.register("departments", departments_source)
1412
+
1413
+ # Execute SQL query
1414
+ query = """
1415
+ SELECT users.name, departments.name AS dept
1416
+ FROM users
1417
+ JOIN departments ON users.dept_id = departments.id
1418
+ """
1419
+
1420
+ for row in engine.query(query):
1421
+ print(row)
1422
+ # Output:
1423
+ # {'users.name': 'Alice', 'departments.name': 'Engineering'}
1424
+ # {'users.name': 'Bob', 'departments.name': 'Sales'}
1425
+ ```
1426
+
1427
+ **For database connections**, create iterator functions:
1428
+
1429
+ ```python
1430
+ from streaming_sql_engine import Engine
1431
+ import psycopg2
1432
+
1433
+ engine = Engine()
1434
+
1435
+ # Register database table (iterator function)
1436
+ def users_source():
1437
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
1438
+ cursor = conn.cursor()
1439
+ cursor.execute("SELECT id, name, email FROM users WHERE active = true")
1440
+ for row in cursor:
1441
+ yield {"id": row[0], "name": row[1], "email": row[2]}
1442
+ conn.close()
1443
+
1444
+ engine.register("users", users_source)
1445
+
1446
+ # Query
1447
+ for row in engine.query("SELECT * FROM users WHERE users.active = true"):
1448
+ print(row)
1449
+ ```
1450
+
1451
+ ---
1452
+
1453
+ ## Conclusion
1454
+
1455
+ The Streaming SQL Engine fills a unique niche: **cross-system data integration**. While it may not match the raw performance of specialized tools for their specific use cases, it excels at joining data from different systems — a problem that traditional databases cannot solve.
1456
+
1457
+ **Key strengths:**
1458
+
1459
+ - Cross-system joins (databases, APIs, files)
1460
+ - Zero infrastructure requirements
1461
+ - Memory-efficient streaming architecture
1462
+ - Python-native integration
1463
+ - Automatic optimizations
1464
+ - Simple deployment
1465
+
1466
+ **Best suited for:**
1467
+
1468
+ - Microservices data aggregation
1469
+ - Cross-system ETL pipelines
1470
+ - Real-time data integration
1471
+ - Memory-constrained environments
1472
+ - Python-native workflows
1473
+
1474
+ For cross-system data integration, the Streaming SQL Engine provides a unique solution that balances performance, simplicity, and flexibility.
1475
+
1476
+ ---
1477
+
1478
+ ## Resources
1479
+
1480
+ - **PyPI:** `pip install streaming-sql-engine`
1481
+
1482
+ ---