streaming-sql-engine 0.1.31__py3-none-any.whl → 0.2.1__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.
Files changed (30) hide show
  1. streaming_sql_engine/README.md +1691 -1593
  2. streaming_sql_engine/__init__.py +1 -1
  3. streaming_sql_engine/app/__init__.py +8 -0
  4. streaming_sql_engine/app/__main__.py +46 -0
  5. streaming_sql_engine/app/demo.py +106 -0
  6. streaming_sql_engine/app/jobs.py +165 -0
  7. streaming_sql_engine/app/server.py +288 -0
  8. streaming_sql_engine/app/sources.py +320 -0
  9. streaming_sql_engine/app/static/app.css +467 -0
  10. streaming_sql_engine/app/static/app.js +1283 -0
  11. streaming_sql_engine/app/static/index.html +202 -0
  12. streaming_sql_engine/app/worker.py +819 -0
  13. streaming_sql_engine/core/evaluator.py +21 -5
  14. streaming_sql_engine/core/executor.py +12 -3
  15. streaming_sql_engine/core/optimizer.py +470 -470
  16. streaming_sql_engine/core/planner.py +174 -174
  17. streaming_sql_engine/engine.py +10 -5
  18. streaming_sql_engine/operators/base.py +520 -586
  19. streaming_sql_engine/operators/mmap.py +262 -332
  20. streaming_sql_engine/operators/polars.py +732 -732
  21. streaming_sql_engine/run_app.py +17 -0
  22. streaming_sql_engine/storage/__init__.py +4 -2
  23. streaming_sql_engine/storage/file_index.py +405 -0
  24. streaming_sql_engine/storage/mmap_index.py +391 -391
  25. {streaming_sql_engine-0.1.31.dist-info → streaming_sql_engine-0.2.1.dist-info}/METADATA +105 -2
  26. streaming_sql_engine-0.2.1.dist-info/RECORD +36 -0
  27. {streaming_sql_engine-0.1.31.dist-info → streaming_sql_engine-0.2.1.dist-info}/WHEEL +1 -1
  28. streaming_sql_engine-0.2.1.dist-info/entry_points.txt +2 -0
  29. streaming_sql_engine-0.1.31.dist-info/RECORD +0 -23
  30. {streaming_sql_engine-0.1.31.dist-info → streaming_sql_engine-0.2.1.dist-info}/top_level.txt +0 -0
@@ -1,1593 +1,1691 @@
1
- # Streaming SQL Engine: Join Data from Anywhere
2
-
3
- Join data from MySQL, PostgreSQL, MongoDB, REST APIs, CSV files, and more — all in one SQL query, without infrastructure or data import.
4
-
5
- ---
6
-
7
- ## Installation
8
-
9
- ```bash
10
- pip install streaming-sql-engine
11
- ```
12
-
13
- That's it! No clusters, no servers, no configuration files.
14
-
15
- ---
16
-
17
- ## Quick Start
18
-
19
- Join data from different sources in 3 steps:
20
-
21
- ```python
22
- from streaming_sql_engine import Engine
23
-
24
- # 1. Create engine
25
- engine = Engine()
26
-
27
- # 2. Register data sources (any Python iterator function)
28
- def postgres_users():
29
- import psycopg2
30
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
31
- cursor = conn.cursor()
32
- cursor.execute("SELECT id, name, email FROM users")
33
- for row in cursor:
34
- yield {"id": row[0], "name": row[1], "email": row[2]}
35
- conn.close()
36
-
37
- def mysql_orders():
38
- import pymysql
39
- conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
40
- cursor = conn.cursor()
41
- cursor.execute("SELECT id, user_id, total FROM orders")
42
- for row in cursor:
43
- yield {"id": row[0], "user_id": row[1], "total": row[2]}
44
- conn.close()
45
-
46
- engine.register("users", postgres_users)
47
- engine.register("orders", mysql_orders)
48
-
49
- # 3. Write SQL and execute
50
- query = """
51
- SELECT users.name, users.email, orders.total
52
- FROM users
53
- JOIN orders ON users.id = orders.user_id
54
- WHERE orders.total > 100
55
- """
56
-
57
- for row in engine.query(query):
58
- print(row)
59
- ```
60
-
61
- **Output:**
62
-
63
- ```python
64
- {'name': 'Alice', 'email': 'alice@example.com', 'total': 150.50}
65
- {'name': 'Bob', 'email': 'bob@example.com', 'total': 200.00}
66
- ```
67
-
68
- ---
69
-
70
- ## The Problem: Data Lives Everywhere
71
-
72
- Modern applications don't store all their data in one place. You might have:
73
-
74
- - User data in PostgreSQL
75
- - Order data in MySQL
76
- - Product catalog in MongoDB
77
- - Pricing information from a REST API
78
- - Inventory data in CSV files
79
- - Product feeds in XML files
80
-
81
- **The challenge:** How do you join all this data together?
82
-
83
- Traditional solutions require:
84
-
85
- - Exporting data from each system
86
- - Importing into a central database
87
- - Writing complex ETL pipelines
88
- - Maintaining data synchronization
89
-
90
- **There had to be a better way.**
91
-
92
- ---
93
-
94
- ## The Solution: Streaming SQL Engine
95
-
96
- 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.
97
-
98
- ```python
99
- from streaming_sql_engine import Engine
100
- import psycopg2
101
- import pymysql
102
- from pymongo import MongoClient
103
- import requests
104
- import csv
105
-
106
- engine = Engine()
107
-
108
- # Register PostgreSQL source (iterator function)
109
- def postgres_users():
110
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
111
- cursor = conn.cursor()
112
- cursor.execute("SELECT id, name, email FROM users")
113
- for row in cursor:
114
- yield {"id": row[0], "name": row[1], "email": row[2]}
115
- conn.close()
116
- engine.register("postgres_users", postgres_users)
117
-
118
- # Register MySQL source (iterator function)
119
- def mysql_products():
120
- conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
121
- cursor = conn.cursor()
122
- cursor.execute("SELECT id, name, price FROM products")
123
- for row in cursor:
124
- yield {"id": row[0], "name": row[1], "price": row[2]}
125
- conn.close()
126
- engine.register("mysql_products", mysql_products)
127
-
128
- # Register MongoDB source (iterator function)
129
- def mongo_inventory():
130
- client = MongoClient("mongodb://localhost:27017")
131
- for doc in client.mydb.inventory.find():
132
- yield doc
133
- engine.register("mongo_inventory", mongo_inventory)
134
-
135
- # Register REST API source (iterator function)
136
- def api_prices():
137
- response = requests.get("https://api.example.com/prices")
138
- for item in response.json():
139
- yield item
140
- engine.register("api_prices", api_prices)
141
-
142
- # Register CSV source (iterator function)
143
- def csv_suppliers():
144
- with open("suppliers.csv") as f:
145
- for row in csv.DictReader(f):
146
- yield row
147
- engine.register("csv_suppliers", csv_suppliers)
148
-
149
- # Join them all in one SQL query!
150
- query = """
151
- SELECT
152
- mysql_products.name,
153
- postgres_users.email,
154
- mongo_inventory.quantity,
155
- api_prices.price,
156
- csv_suppliers.supplier_name
157
- FROM mysql_products
158
- JOIN postgres_users ON mysql_products.user_id = postgres_users.id
159
- JOIN mongo_inventory ON mysql_products.sku = mongo_inventory.sku
160
- JOIN api_prices ON mysql_products.sku = api_prices.sku
161
- JOIN csv_suppliers ON mysql_products.supplier_id = csv_suppliers.id
162
- WHERE api_prices.price > 100
163
- """
164
-
165
- for row in engine.query(query):
166
- process(row)
167
- ```
168
-
169
- **That's it.** No clusters, no infrastructure, no data export — just pure Python and SQL.
170
-
171
- ---
172
-
173
- ## Data Source Examples
174
-
175
- The engine works with **any Python iterator function**. Here are practical examples:
176
-
177
- ### PostgreSQL
178
-
179
- ```python
180
- def postgres_users():
181
- import psycopg2
182
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
183
- cursor = conn.cursor()
184
- cursor.execute("SELECT id, name, email FROM users")
185
- for row in cursor:
186
- yield {"id": row[0], "name": row[1], "email": row[2]}
187
- conn.close()
188
-
189
- engine.register("users", postgres_users)
190
- ```
191
-
192
- ### MySQL
193
-
194
- ```python
195
- def mysql_products():
196
- import pymysql
197
- conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
198
- cursor = conn.cursor()
199
- cursor.execute("SELECT id, name, price FROM products")
200
- for row in cursor:
201
- yield {"id": row[0], "name": row[1], "price": row[2]}
202
- conn.close()
203
-
204
- engine.register("products", mysql_products)
205
- ```
206
-
207
- ### MongoDB
208
-
209
- ```python
210
- def mongo_inventory():
211
- from pymongo import MongoClient
212
- client = MongoClient("mongodb://localhost:27017")
213
- for doc in client.mydb.inventory.find():
214
- yield doc # MongoDB documents are already dictionaries
215
- client.close()
216
-
217
- engine.register("inventory", mongo_inventory)
218
- ```
219
-
220
- ### CSV Files
221
-
222
- ```python
223
- def csv_suppliers():
224
- import csv
225
- with open("suppliers.csv") as f:
226
- reader = csv.DictReader(f)
227
- for row in reader:
228
- yield row # DictReader yields dictionaries
229
-
230
- engine.register("suppliers", csv_suppliers)
231
- ```
232
-
233
- ### JSONL Files
234
-
235
- ```python
236
- def jsonl_products():
237
- import json
238
- with open("products.jsonl") as f:
239
- for line in f:
240
- yield json.loads(line)
241
-
242
- # For large files, use MMAP join
243
- engine.register("products", jsonl_products, filename="products.jsonl")
244
- ```
245
-
246
- ### REST APIs
247
-
248
- ```python
249
- def api_prices():
250
- import requests
251
- response = requests.get("https://api.example.com/prices")
252
- for item in response.json():
253
- yield item
254
-
255
- # For paginated APIs
256
- def api_prices_paginated():
257
- import requests
258
- page = 1
259
- while True:
260
- response = requests.get(f"https://api.example.com/prices?page={page}")
261
- data = response.json()
262
- if not data:
263
- break
264
- for item in data:
265
- yield item
266
- page += 1
267
-
268
- engine.register("prices", api_prices_paginated)
269
- ```
270
-
271
- ### XML Files
272
-
273
- ```python
274
- def xml_products():
275
- import xml.etree.ElementTree as ET
276
- tree = ET.parse("products.xml")
277
- for product in tree.findall('.//product'):
278
- yield {
279
- 'id': product.find('id').text,
280
- 'name': product.find('name').text,
281
- 'price': float(product.find('price').text)
282
- }
283
-
284
- engine.register("products", xml_products)
285
- ```
286
-
287
- ### Custom Python Logic
288
-
289
- ```python
290
- def enriched_products():
291
- """Apply Python processing before joining"""
292
- import psycopg2
293
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
294
- cursor = conn.cursor()
295
- cursor.execute("SELECT id, name, category_id FROM products")
296
- for row in cursor:
297
- product = {"id": row[0], "name": row[1], "category_id": row[2]}
298
- # Apply custom Python logic
299
- product['ml_score'] = ml_model.predict(product)
300
- product['custom_field'] = custom_function(product)
301
- yield product
302
- conn.close()
303
-
304
- engine.register("products", enriched_products)
305
- ```
306
-
307
- ---
308
-
309
- ## SQL Features
310
-
311
- The engine supports standard SQL syntax, providing a declarative interface that eliminates the need for manual Python code. Instead of writing 50-100 lines of hash index construction, nested loops, and dictionary lookups, you can express complex cross-system joins in a single SQL query.
312
-
313
- ### Supported Features
314
-
315
- **SELECT** - Column selection, aliasing, table-qualified columns
316
-
317
- ```sql
318
- SELECT users.name, orders.total AS order_total
319
- FROM users
320
- JOIN orders ON users.id = orders.user_id
321
- ```
322
-
323
- **JOIN** - INNER JOIN and LEFT JOIN with equality conditions
324
-
325
- ```sql
326
- SELECT *
327
- FROM table1 t1
328
- JOIN table2 t2 ON t1.id = t2.id
329
- LEFT JOIN table3 t3 ON t1.id = t3.id
330
- ```
331
-
332
- **WHERE** - Comparisons, boolean logic, NULL checks, IN clauses
333
-
334
- ```sql
335
- SELECT *
336
- FROM products
337
- WHERE price > 100
338
- AND status IN ('active', 'pending')
339
- AND description IS NOT NULL
340
- ```
341
-
342
- **Arithmetic** - Addition, subtraction, multiplication, division, modulo
343
-
344
- ```sql
345
- SELECT
346
- price - discount AS final_price,
347
- quantity * unit_price AS total
348
- FROM orders
349
- ```
350
-
351
- ### Not Supported
352
-
353
- - GROUP BY and aggregations (COUNT, SUM, AVG)
354
- - ORDER BY
355
- - HAVING
356
- - Subqueries
357
-
358
- _These limitations keep the engine focused on joins and filtering — its core strength._
359
-
360
- ---
361
-
362
- ## Join Types and Algorithms
363
-
364
- The engine automatically selects the best join algorithm based on your data. You can also configure it explicitly.
365
-
366
- ### 1. Lookup Join (Default)
367
-
368
- General-purpose hash-based join for unsorted data:
369
-
370
- ```python
371
- engine = Engine() # Default: use_polars=False
372
-
373
- def products_source():
374
- # Your iterator function
375
- yield {"id": 1, "name": "Product A"}
376
- yield {"id": 2, "name": "Product B"}
377
-
378
- def categories_source():
379
- yield {"id": 1, "category": "Electronics"}
380
- yield {"id": 2, "category": "Books"}
381
-
382
- engine.register("products", products_source)
383
- engine.register("categories", categories_source)
384
-
385
- query = """
386
- SELECT products.name, categories.category
387
- FROM products
388
- JOIN categories ON products.id = categories.id
389
- """
390
- ```
391
-
392
- **When to use:** Default choice, works with any data, most compatible.
393
-
394
- ### 2. Merge Join (For Sorted Data)
395
-
396
- Most memory-efficient for pre-sorted data (O(1) memory):
397
-
398
- ```python
399
- engine = Engine(use_polars=False)
400
-
401
- # Register with ordered_by to enable merge join
402
- def sorted_products():
403
- # Data must be sorted by join key
404
- yield {"id": 1, "name": "Product A"} # sorted by id
405
- yield {"id": 2, "name": "Product B"}
406
- yield {"id": 3, "name": "Product C"}
407
-
408
- def sorted_categories():
409
- yield {"id": 1, "category": "Electronics"} # sorted by id
410
- yield {"id": 2, "category": "Books"}
411
- yield {"id": 3, "category": "Clothing"}
412
-
413
- engine.register("products", sorted_products, ordered_by="id")
414
- engine.register("categories", sorted_categories, ordered_by="id")
415
-
416
- query = """
417
- SELECT products.name, categories.category
418
- FROM products
419
- JOIN categories ON products.id = categories.id
420
- """
421
- ```
422
-
423
- **When to use:** Data is pre-sorted by join key, memory is constrained.
424
-
425
- ### 3. Polars Join (For Large Datasets)
426
-
427
- Vectorized, SIMD-accelerated joins for large datasets:
428
-
429
- ```python
430
- engine = Engine(use_polars=True) # Enable Polars
431
-
432
- def large_products_source():
433
- # Large dataset (> 10K rows)
434
- for i in range(100000):
435
- yield {"id": i, "name": f"Product {i}"}
436
-
437
- def large_categories_source():
438
- for i in range(1000):
439
- yield {"id": i, "category": f"Category {i}"}
440
-
441
- engine.register("products", large_products_source)
442
- engine.register("categories", large_categories_source)
443
-
444
- query = """
445
- SELECT products.name, categories.category
446
- FROM products
447
- JOIN categories ON products.id = categories.id
448
- """
449
- ```
450
-
451
- **When to use:** Large datasets (> 100K rows), consistent data types, speed priority.
452
-
453
- **Install Polars:** `pip install polars`
454
-
455
- ### 4. MMAP Join (For Large Files)
456
-
457
- Memory-mapped joins for files larger than RAM:
458
-
459
- ```python
460
- engine = Engine(use_polars=False) # MMAP requires use_polars=False
461
-
462
- def jsonl_source():
463
- import json
464
- with open("large_file.jsonl") as f:
465
- for line in f:
466
- yield json.loads(line)
467
-
468
- # Register with filename to enable MMAP
469
- engine.register("products", jsonl_source, filename="large_file.jsonl")
470
-
471
- query = """
472
- SELECT products.name, categories.category
473
- FROM products
474
- JOIN categories ON products.id = categories.id
475
- """
476
- ```
477
-
478
- **When to use:** Large JSONL files (> 1GB), memory-constrained environments.
479
-
480
- ---
481
-
482
- ## Optimizations
483
-
484
- The engine includes automatic optimizations that can significantly improve performance.
485
-
486
- ### 1. Column Pruning
487
-
488
- Only extracts columns needed for the query:
489
-
490
- ```python
491
- # Query only requests 'name' and 'price'
492
- query = "SELECT name, price FROM products"
493
-
494
- # Source function receives requested columns
495
- def products_source(dynamic_columns=None):
496
- if dynamic_columns:
497
- columns = ", ".join(dynamic_columns) # ['name', 'price']
498
- query = f"SELECT {columns} FROM products_table"
499
- else:
500
- query = "SELECT * FROM products_table"
501
- # Execute query and yield rows
502
- for row in execute_query(query):
503
- yield row
504
-
505
- engine.register("products", products_source)
506
- ```
507
-
508
- **Benefit:** Reduces I/O and memory by only fetching needed columns.
509
-
510
- ### 2. Filter Pushdown
511
-
512
- Pushes WHERE conditions to data sources:
513
-
514
- ```python
515
- # Query has WHERE clause
516
- query = "SELECT * FROM products WHERE price > 100"
517
-
518
- # Source function receives filter condition
519
- def products_source(dynamic_where=None):
520
- query = "SELECT * FROM products_table"
521
- if dynamic_where:
522
- query += f" WHERE {dynamic_where}" # "price > 100"
523
- # Execute filtered query at source
524
- for row in execute_query(query):
525
- yield row
526
-
527
- engine.register("products", products_source)
528
- ```
529
-
530
- **Benefit:** Filters data at source, reducing data transfer and processing.
531
-
532
- ### 3. Protocol Detection
533
-
534
- Automatic optimization detection via function signature:
535
-
536
- ```python
537
- # Simple source (no optimizations)
538
- def simple_source():
539
- return iter([{"id": 1, "name": "Alice"}])
540
-
541
- # Optimized source (supports both optimizations)
542
- def optimized_source(dynamic_where=None, dynamic_columns=None):
543
- query = "SELECT "
544
- if dynamic_columns:
545
- query += ", ".join(dynamic_columns)
546
- else:
547
- query += "*"
548
- query += " FROM table"
549
- if dynamic_where:
550
- query += f" WHERE {dynamic_where}"
551
- return execute_query(query)
552
-
553
- # Both work the same way - optimizations apply automatically!
554
- engine.register("users", simple_source) # No optimizations
555
- engine.register("products", optimized_source) # Optimizations apply automatically
556
- ```
557
-
558
- **Benefit:** Zero configuration - engine detects capabilities automatically.
559
-
560
- ---
561
-
562
- ## Real-World Examples
563
-
564
- ### Example 1: Microservices Data Integration
565
-
566
- In a microservices architecture, data is distributed across services:
567
-
568
- ```python
569
- from streaming_sql_engine import Engine
570
- import psycopg2
571
- import pymysql
572
- import requests
573
-
574
- engine = Engine()
575
-
576
- # Service 1: User service (PostgreSQL) - iterator function
577
- def users_source():
578
- conn = psycopg2.connect(host="user-db", port=5432, user="user", password="pass", database="users_db")
579
- cursor = conn.cursor()
580
- cursor.execute("SELECT id, name, email FROM users")
581
- for row in cursor:
582
- yield {"id": row[0], "name": row[1], "email": row[2]}
583
- conn.close()
584
- engine.register("users", users_source)
585
-
586
- # Service 2: Order service (MySQL) - iterator function
587
- def orders_source():
588
- conn = pymysql.connect(host="order-db", port=3306, user="user", password="pass", database="orders_db")
589
- cursor = conn.cursor()
590
- cursor.execute("SELECT id, user_id, total FROM orders")
591
- for row in cursor:
592
- yield {"id": row[0], "user_id": row[1], "total": row[2]}
593
- conn.close()
594
- engine.register("orders", orders_source)
595
-
596
- # Service 3: Payment service (REST API) - iterator function
597
- def payment_source():
598
- response = requests.get("https://payments.service/api/transactions")
599
- for item in response.json():
600
- yield item
601
- engine.register("payments", payment_source)
602
-
603
- # Join across services
604
- query = """
605
- SELECT users.name, orders.total, payments.status
606
- FROM users
607
- JOIN orders ON users.id = orders.user_id
608
- JOIN payments ON orders.id = payments.order_id
609
- """
610
- ```
611
-
612
- **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.
613
-
614
- ### Example 2: Real-Time Price Comparison
615
-
616
- Compare prices from multiple XML feeds and match with MongoDB:
617
-
618
- ```python
619
- def parse_xml(filepath):
620
- tree = ET.parse(filepath)
621
- for product in tree.findall('.//product'):
622
- yield {
623
- 'ean': product.find('ean').text,
624
- 'price': float(product.find('price').text),
625
- 'name': product.find('name').text
626
- }
627
-
628
- engine.register("xml1", lambda: parse_xml("prices1.xml"))
629
- engine.register("xml2", lambda: parse_xml("prices2.xml"))
630
- engine.register("mongo", mongo_source)
631
-
632
- query = """
633
- SELECT
634
- xml1.ean,
635
- xml1.price AS price1,
636
- xml2.price AS price2,
637
- mongo.sf_sku
638
- FROM xml1
639
- JOIN xml2 ON xml1.ean = xml2.ean
640
- JOIN mongo ON xml1.ean = mongo.ean
641
- WHERE xml1.price != xml2.price
642
- """
643
- ```
644
-
645
- **Production results:** 17M + 17M XML records + 5M MongoDB records processed in 7 minutes using 400 MB RAM.
646
-
647
- ### Example 3: Python Processing Between Joins
648
-
649
- Apply Python logic (ML models, custom functions) between joins:
650
-
651
- ```python
652
- def enriched_source():
653
- """Source that processes data with Python before joining"""
654
- import psycopg2
655
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
656
- cursor = conn.cursor()
657
- cursor.execute("SELECT id, name, category_id FROM products")
658
- for row in cursor:
659
- product = {"id": row[0], "name": row[1], "category_id": row[2]}
660
- # Apply Python logic
661
- product['ml_score'] = ml_model.predict(product)
662
- product['custom_field'] = custom_function(product)
663
- yield product
664
- conn.close()
665
-
666
- def categories_source():
667
- import psycopg2
668
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
669
- cursor = conn.cursor()
670
- cursor.execute("SELECT id, name FROM categories")
671
- for row in cursor:
672
- yield {"id": row[0], "category_name": row[1]}
673
- conn.close()
674
-
675
- engine.register("enriched_products", enriched_source)
676
- engine.register("categories", categories_source)
677
-
678
- query = """
679
- SELECT p.name, p.ml_score, c.category_name
680
- FROM enriched_products p
681
- JOIN categories c ON p.category_id = c.id
682
- """
683
- ```
684
-
685
- **Why this matters:** Seamless integration with Python ecosystem — use any library, apply any logic.
686
-
687
- ---
688
-
689
- ### What Makes Streaming SQL Engine Unique
690
-
691
- 1. **Zero Infrastructure + Cross-System Joins**
692
-
693
- - Most tools require clusters (Spark, Flink, Drill)
694
- - Or require specific infrastructure (ksqlDB needs Kafka)
695
- - Streaming SQL Engine: Just Python
696
-
697
- 2. **Any Python Iterator as Data Source**
698
-
699
- - Most tools require specific connectors
700
- - Streaming SQL Engine: Any Python function works
701
-
702
- 3. **Direct API Joins**
703
-
704
- - Most tools can't join REST APIs directly
705
- - Streaming SQL Engine: Native support
706
-
707
- 4. **Python-Native Architecture**
708
- - Most tools are Java/Rust with Python wrappers
709
- - Streaming SQL Engine: Pure Python, seamless integration
710
-
711
- ### Similar Tools (But Different)
712
-
713
- **Apache Drill** — Similar cross-system capability, but requires cluster and Java
714
-
715
- **ksqlDB** — Streaming SQL, but Kafka-only and requires infrastructure
716
-
717
- **Materialize** — Streaming database, but requires database server
718
-
719
- **DataFusion** — Fast SQL engine, but limited to Arrow/Parquet data
720
-
721
- **Polars SQL** — Fast SQL, but requires loading data into DataFrames first
722
-
723
- **Presto/Trino** — Cross-system SQL, but requires cluster infrastructure
724
-
725
- **None of these** combine:
726
-
727
- - Zero infrastructure
728
- - Any Python iterator as source
729
- - Direct API joins
730
- - Pure Python implementation
731
- - Simple deployment
732
-
733
- **That's what makes Streaming SQL Engine unique.**
734
-
735
- ---
736
-
737
- ## Key Wins
738
-
739
- ### 1. Cross-System Joins
740
-
741
- The **only tool** that can join MySQL + PostgreSQL + MongoDB + REST API + CSV files in a single SQL query without data export/import.
742
-
743
- ### 2. Zero Infrastructure
744
-
745
- No clusters, no setup, just Python. Install and use immediately:
746
-
747
- ```bash
748
- pip install streaming-sql-engine
749
- ```
750
-
751
- ### 3. Memory Efficient
752
-
753
- Processes 39 million records with only 400 MB RAM. True streaming architecture means you can process data larger than available RAM.
754
-
755
- ### 4. Python-Native
756
-
757
- Seamless integration with Python ecosystem. Use any Python function as a data source, apply ML models, use any library.
758
-
759
- ### 5. Real-Time Processing
760
-
761
- Join live streaming data with static reference data. No buffering required — true streaming execution.
762
-
763
- ### 6. Automatic Optimizations
764
-
765
- Filter pushdown, column pruning, and vectorization applied automatically. No configuration needed — the engine detects protocol support.
766
-
767
- ---
768
-
769
- ## When to Use Streaming SQL Engine
770
-
771
- **Perfect for:**
772
-
773
- - Joining data from different systems (databases, APIs, files)
774
- - Microservices data aggregation
775
- - Real-time data integration
776
- - Memory-constrained environments
777
- - Python-native workflows
778
- - Ad-hoc cross-system queries
779
-
780
- **Not for:**
781
-
782
- - All data in same database (use direct SQL - 10-100x faster)
783
- - Need GROUP BY or aggregations (use database)
784
- - Maximum performance for same-database queries (use database)
785
- - Distributed processing (use Spark/Flink)
786
-
787
- ---
788
-
789
- ## 🎯 Start Here: The Most Secure Way
790
-
791
- ### Step 1: Install and Basic Setup
792
-
793
- ```bash
794
- pip install streaming-sql-engine
795
- ```
796
-
797
- ### Step 2: Use the Default Configuration (Most Stable)
798
-
799
- **This is the safest way to start** — it handles all edge cases, works with any data types, and requires no special configuration:
800
-
801
- ```python
802
- from streaming_sql_engine import Engine
803
-
804
- # Default configuration: Most stable and reliable
805
- engine = Engine() # use_polars=False (default)
806
-
807
- # Register your data sources
808
- def postgres_users():
809
- # Your PostgreSQL connection code
810
- for row in cursor:
811
- yield {"id": row[0], "name": row[1]}
812
-
813
- def mysql_orders():
814
- # Your MySQL connection code
815
- for row in cursor:
816
- yield {"id": row[0], "user_id": row[1], "total": row[2]}
817
-
818
- engine.register("users", postgres_users)
819
- engine.register("orders", mysql_orders)
820
-
821
- # Write SQL queries
822
- query = """
823
- SELECT users.name, orders.total
824
- FROM users
825
- JOIN orders ON users.id = orders.user_id
826
- WHERE orders.total > 100
827
- """
828
-
829
- # Execute and iterate results
830
- for row in engine.query(query):
831
- print(row)
832
- ```
833
-
834
- **Why This Configuration is Best to Start:**
835
-
836
- - **Most Stable**: Handles mixed data types gracefully
837
- - **No Schema Errors**: No type inference issues
838
- - **Works Everywhere**: No external dependencies required
839
- - **Reliable**: Battle-tested Python code
840
- - **Fast for Small-Medium Data**: 0.72s for 10K rows
841
-
842
- **Use this when:**
843
-
844
- - You're just getting started
845
- - Your datasets are < 100K rows
846
- - You have mixed data types
847
- - You need maximum reliability
848
- - Polars is not available
849
-
850
- ---
851
-
852
- ## Experimenting with Options
853
-
854
- Once you're comfortable with the basics, you can experiment with different options to optimize for your specific use case.
855
-
856
- ### Option 1: Enable Debug Mode
857
-
858
- See what's happening under the hood:
859
-
860
- ```python
861
- engine = Engine(debug=True) # Shows execution details
862
- ```
863
-
864
- **Output:**
865
-
866
- ```
867
- ============================================================
868
- STREAMING SQL ENGINE - DEBUG MODE
869
- ============================================================
870
-
871
- [1/3] PARSING SQL QUERY...
872
- SQL parsed successfully
873
-
874
- [2/3] BUILDING LOGICAL PLAN...
875
- Logical plan built
876
-
877
- [3/3] EXECUTING QUERY...
878
- Using LOOKUP JOIN (building index...)
879
- ```
880
-
881
- ---
882
-
883
- ### Option 2: Enable Polars (For Large Datasets)
884
-
885
- **When to use**: Large datasets (> 100K rows), consistent data types
886
-
887
- ```python
888
- engine = Engine(use_polars=True) # Enable Polars for speed
889
- ```
890
-
891
- **Benefits:**
892
-
893
- - Faster for large datasets (vectorized operations)
894
- - SIMD acceleration
895
- - Better for consistent schemas
896
-
897
- **Trade-offs:**
898
-
899
- - Requires data normalization (consistent types)
900
- - Can fail on mixed types
901
- - Requires Polars dependency
902
-
903
- **Example:**
904
-
905
- ```python
906
- engine = Engine(use_polars=True)
907
-
908
- # Make sure your data has consistent types
909
- def normalized_source():
910
- for row in raw_source():
911
- yield {
912
- "id": int(row.get("id", 0)),
913
- "price": float(row.get("price", 0.0)),
914
- "name": str(row.get("name", "")),
915
- }
916
-
917
- engine.register("products", normalized_source)
918
- ```
919
-
920
- ---
921
-
922
- ### Option 3: Enable MMAP (For Large Files)
923
-
924
- **When to use**: Large files (> 100MB), memory-constrained systems
925
-
926
- ```python
927
- engine = Engine()
928
- engine.register("products", source, filename="products.jsonl") # MMAP enabled
929
- ```
930
-
931
- **Benefits:**
932
-
933
- - 90-99% memory reduction
934
- - Works with files larger than RAM
935
- - OS-managed memory mapping
936
-
937
- **Trade-offs:**
938
-
939
- - Requires file-based sources
940
- - Slower for small files (overhead)
941
-
942
- **Example:**
943
-
944
- ```python
945
- engine = Engine()
946
-
947
- def jsonl_source():
948
- with open("products.jsonl", "r") as f:
949
- for line in f:
950
- if line.strip():
951
- yield json.loads(line)
952
-
953
- engine.register("products", jsonl_source, filename="products.jsonl")
954
- ```
955
-
956
- ---
957
-
958
- ### Option 4: Enable Merge Join (For Sorted Data)
959
-
960
- **When to use**: Pre-sorted data, memory-constrained environments
961
-
962
- ```python
963
- engine = Engine()
964
- engine.register("products", source, ordered_by="id") # Merge join enabled
965
- ```
966
-
967
- **Benefits:**
968
-
969
- - Lowest memory usage (no index needed)
970
- - Fast for sorted data
971
- - Streaming algorithm
972
-
973
- **Trade-offs:**
974
-
975
- - Requires pre-sorted data
976
- - Both tables must be sorted
977
-
978
- **Example:**
979
-
980
- ```python
981
- engine = Engine()
982
-
983
- # Data must be sorted by join key
984
- def sorted_users():
985
- # Users sorted by id
986
- return iter([
987
- {"id": 1, "name": "Alice"},
988
- {"id": 2, "name": "Bob"},
989
- {"id": 3, "name": "Charlie"},
990
- ])
991
-
992
- def sorted_orders():
993
- # Orders sorted by user_id
994
- return iter([
995
- {"id": 1, "user_id": 1, "total": 100},
996
- {"id": 2, "user_id": 2, "total": 200},
997
- ])
998
-
999
- engine.register("users", sorted_users, ordered_by="id")
1000
- engine.register("orders", sorted_orders, ordered_by="user_id")
1001
- ```
1002
-
1003
- ---
1004
-
1005
- ## Advanced: Mixing Options
1006
-
1007
- ### Mix 1: MMAP with Polars Index Building (Best for Large Files)
1008
-
1009
- **Important Note:** When `use_polars=False` (default), the engine uses **MMAP Join** or **Merge Join** when available. When `use_polars=True` is explicitly set, the engine uses **Polars Join** (not MMAP Join).
1010
-
1011
- However, **MMAP can use Polars internally** for faster index building even when `use_polars=False`:
1012
-
1013
- ```python
1014
- engine = Engine(use_polars=False) # MMAP Join will be used
1015
- engine.register("products", source, filename="products.jsonl") # MMAP for memory
1016
- # MMAP will use Polars internally for index building if available
1017
- ```
1018
-
1019
- **What You Get:**
1020
-
1021
- - Low memory (MMAP 90-99% reduction)
1022
- - Fast index building (if Polars is installed, used internally)
1023
- - Best balance for large files with memory constraints
1024
-
1025
- **Performance:**
1026
-
1027
- - Time: 8-15s for 500MB files (with Polars for index building)
1028
- - Memory: 0.01 MB (vs 500MB+ without MMAP)
1029
-
1030
- **When to Use:**
1031
-
1032
- - Large files (> 100MB)
1033
- - Memory-constrained systems
1034
- - When you want MMAP Join (not Polars Join)
1035
-
1036
- **Note:** If you set `use_polars=True`, the engine will use **Polars Join** instead of MMAP Join, prioritizing speed over memory efficiency.
1037
-
1038
- ---
1039
-
1040
- ### Mix 2: Polars + Column Pruning (For Wide Tables)
1041
-
1042
- **Optimize for tables with many columns:**
1043
-
1044
- ```python
1045
- engine = Engine(use_polars=True)
1046
-
1047
- def optimized_source(dynamic_columns=None):
1048
- # Only read requested columns
1049
- if dynamic_columns:
1050
- columns = dynamic_columns
1051
- else:
1052
- columns = ["id", "name", "price", "description", "category", ...] # All columns
1053
-
1054
- for row in read_data(columns):
1055
- yield row
1056
-
1057
- engine.register("products", optimized_source)
1058
- ```
1059
-
1060
- **What You Get:**
1061
-
1062
- - Reduced I/O (only reads needed columns)
1063
- - Faster queries (less data to process)
1064
- - Lower memory usage
1065
-
1066
- ---
1067
-
1068
- ### Mix 3: Polars + Filter Pushdown (For Selective Queries)
1069
-
1070
- **Optimize when queries filter most rows:**
1071
-
1072
- ```python
1073
- engine = Engine(use_polars=True)
1074
-
1075
- def optimized_source(dynamic_where=None, dynamic_columns=None):
1076
- # Apply WHERE clause at source level
1077
- query = "SELECT * FROM products"
1078
- if dynamic_where:
1079
- query += f" WHERE {dynamic_where}"
1080
-
1081
- for row in execute_query(query):
1082
- yield row
1083
-
1084
- engine.register("products", optimized_source)
1085
- ```
1086
-
1087
- **What You Get:**
1088
-
1089
- - Early filtering (reduces data volume)
1090
- - Faster execution (less data to process)
1091
- - Lower memory usage
1092
-
1093
- ---
1094
-
1095
- ### Mix 4: All Optimizations Combined
1096
-
1097
- **The Ultimate Configuration** for maximum performance:
1098
-
1099
- ```python
1100
- engine = Engine(use_polars=True)
1101
-
1102
- def ultimate_source(dynamic_where=None, dynamic_columns=None):
1103
- """
1104
- Source with all optimizations:
1105
- - Filter pushdown (dynamic_where)
1106
- - Column pruning (dynamic_columns)
1107
- - Data normalization (for Polars)
1108
- """
1109
- # Build optimized query
1110
- query = build_query(dynamic_where, dynamic_columns)
1111
-
1112
- for row in execute_query(query):
1113
- # Normalize types for Polars stability
1114
- yield normalize_types(row)
1115
-
1116
- engine.register("products", ultimate_source, filename="products.jsonl")
1117
- ```
1118
-
1119
- **What You Get:**
1120
-
1121
- - Polars Join (speed) - when `use_polars=True`
1122
- - Column Pruning (I/O)
1123
- - Filter Pushdown (early filtering)
1124
-
1125
- **Best for:** Very large datasets (> 1M rows) when speed is priority
1126
-
1127
- **Note:** This uses Polars Join, not MMAP Join. For memory-constrained scenarios, use `use_polars=False` with `filename` parameter instead.
1128
-
1129
- ---
1130
-
1131
- ## Performance Guide
1132
-
1133
- ### By Dataset Size
1134
-
1135
- | Size | Configuration | Why |
1136
- | ----------------- | ------------------------------- | ----------------------------------------- |
1137
- | **< 10K rows** | `use_polars=False` (default) | Fastest, most stable |
1138
- | **10K-100K rows** | `use_polars=False` (default) | Still fastest, handles mixed types |
1139
- | **100K-1M rows** | `use_polars=True` OR `filename` | Polars Join (speed) OR MMAP Join (memory) |
1140
- | **> 1M rows** | All optimizations | Maximum performance |
1141
-
1142
- ### By Priority
1143
-
1144
- **Priority: Stability** - Use default (`use_polars=False`)
1145
-
1146
- ```python
1147
- engine = Engine() # Most stable
1148
- ```
1149
-
1150
- **Priority: Speed** - Use Polars
1151
-
1152
- ```python
1153
- engine = Engine(use_polars=True) # Fastest for large datasets
1154
- ```
1155
-
1156
- **Priority: Memory** - Use MMAP
1157
-
1158
- ```python
1159
- engine = Engine()
1160
- engine.register("table", source, filename="data.jsonl") # Lowest memory
1161
- ```
1162
-
1163
- **Priority: Both** - Choose based on priority:
1164
-
1165
- **If speed is more important:**
1166
-
1167
- ```python
1168
- engine = Engine(use_polars=True) # Uses Polars Join (fastest)
1169
- engine.register("table", source) # No filename - Polars Join
1170
- ```
1171
-
1172
- **If memory is more important:**
1173
-
1174
- ```python
1175
- engine = Engine(use_polars=False) # Uses MMAP Join (lowest memory)
1176
- engine.register("table", source, filename="data.jsonl") # MMAP Join
1177
- ```
1178
-
1179
- **Note:** Polars Join and MMAP Join are mutually exclusive - the engine chooses one based on `use_polars` flag. MMAP Join can use Polars internally for index building, but the join algorithm itself is MMAP.
1180
-
1181
- ---
1182
-
1183
- ## Learning Path
1184
-
1185
- ### Level 1: Beginner (Start Here)
1186
-
1187
- ```python
1188
- # Most stable configuration
1189
- engine = Engine() # Default: use_polars=False
1190
- engine.register("table1", source1)
1191
- engine.register("table2", source2)
1192
- ```
1193
-
1194
- **Learn:**
1195
-
1196
- - Basic source registration
1197
- - Simple SQL queries
1198
- - How joins work
1199
-
1200
- ---
1201
-
1202
- ### Level 2: Intermediate
1203
-
1204
- ```python
1205
- # Add debug mode to see what's happening
1206
- engine = Engine(debug=True)
1207
-
1208
- # Experiment with Polars for large datasets
1209
- engine = Engine(use_polars=True)
1210
- ```
1211
-
1212
- **Learn:**
1213
-
1214
- - Debug output
1215
- - When to use Polars
1216
- - Data normalization
1217
-
1218
- ---
1219
-
1220
- ### Level 3: Advanced
1221
-
1222
- ```python
1223
- # Use MMAP for large files (requires use_polars=False)
1224
- engine = Engine(use_polars=False) # MMAP Join requires use_polars=False
1225
- engine.register("table", source, filename="data.jsonl")
1226
-
1227
- # Use Merge Join for sorted data
1228
- engine.register("table", source, ordered_by="key")
1229
- ```
1230
-
1231
- **Learn:**
1232
-
1233
- - MMAP for memory efficiency
1234
- - Merge Join for sorted data
1235
- - Protocol optimizations
1236
-
1237
- ---
1238
-
1239
- ### Level 4: Expert
1240
-
1241
- ```python
1242
- # All optimizations combined
1243
- engine = Engine(use_polars=True)
1244
-
1245
- def optimized_source(dynamic_where=None, dynamic_columns=None):
1246
- # Filter pushdown + Column pruning
1247
- pass
1248
-
1249
- engine.register("table", optimized_source, filename="data.jsonl")
1250
- ```
1251
-
1252
- **Learn:**
1253
-
1254
- - Protocol-based optimizations
1255
- - Combining all options
1256
- - Maximum performance tuning
1257
-
1258
- ---
1259
-
1260
- ## Common Pitfalls
1261
-
1262
- ### Pitfall 1: Using Polars Without Normalization
1263
-
1264
- **Problem:**
1265
-
1266
- ```python
1267
- engine = Engine(use_polars=True)
1268
- # Mixed types cause schema inference errors
1269
- ```
1270
-
1271
- **Solution:**
1272
-
1273
- ```python
1274
- def normalized_source():
1275
- for row in raw_source():
1276
- yield {
1277
- "id": int(row.get("id", 0)),
1278
- "price": float(row.get("price", 0.0)),
1279
- }
1280
- ```
1281
-
1282
- ---
1283
-
1284
- ### Pitfall 2: Using MMAP Without Polars (Very Slow)
1285
-
1286
- **Problem:**
1287
-
1288
- ```python
1289
- engine = Engine(use_polars=False)
1290
- engine.register("table", source, filename="data.jsonl") # Very slow!
1291
- ```
1292
-
1293
- **Solution:**
1294
-
1295
- ```python
1296
- engine = Engine(use_polars=True) # Polars speeds up MMAP index building
1297
- engine.register("table", source, filename="data.jsonl")
1298
- ```
1299
-
1300
- ---
1301
-
1302
- ### Pitfall 3: Using MMAP for Small Files
1303
-
1304
- **Problem:**
1305
-
1306
- ```python
1307
- # MMAP overhead > benefit for small files
1308
- engine.register("table", source, filename="small.jsonl") # Slower!
1309
- ```
1310
-
1311
- **Solution:**
1312
-
1313
- ```python
1314
- # No filename for small files
1315
- engine.register("table", source) # Faster for < 100MB
1316
- ```
1317
-
1318
- ---
1319
-
1320
- ## Quick Decision Guide
1321
-
1322
- - **Just starting?** Use default (`Engine()`)
1323
- - **Have large datasets?** Use `use_polars=True`
1324
- - **Memory constrained?** Use `filename` parameter (MMAP)
1325
- - **Data is sorted?** Use `ordered_by` parameter (Merge Join)
1326
- - **Want maximum performance?** Use `use_polars=True` + protocols (Polars Join) OR `use_polars=False` + `filename` (MMAP Join) + protocols
1327
-
1328
- ---
1329
-
1330
- ## Real-World Example: Complete Workflow
1331
-
1332
- ### Step 1: Start Simple (Most Secure)
1333
-
1334
- ```python
1335
- from streaming_sql_engine import Engine
1336
-
1337
- # Start with default (most stable)
1338
- engine = Engine()
1339
-
1340
- def postgres_users():
1341
- # Your PostgreSQL code
1342
- pass
1343
-
1344
- def mysql_orders():
1345
- # Your MySQL code
1346
- pass
1347
-
1348
- engine.register("users", postgres_users)
1349
- engine.register("orders", mysql_orders)
1350
-
1351
- results = engine.query("SELECT * FROM users JOIN orders ON users.id = orders.user_id")
1352
- ```
1353
-
1354
- ### Step 2: Add Debug Mode (Understand What's Happening)
1355
-
1356
- ```python
1357
- engine = Engine(debug=True) # See execution details
1358
- ```
1359
-
1360
- ### Step 3: Optimize for Your Use Case
1361
-
1362
- **If you have large datasets:**
1363
-
1364
- ```python
1365
- engine = Engine(use_polars=True) # Enable Polars
1366
- ```
1367
-
1368
- **If you have large files:**
1369
-
1370
- ```python
1371
- engine = Engine(use_polars=False) # MMAP Join requires use_polars=False
1372
- engine.register("table", source, filename="data.jsonl") # Enable MMAP
1373
- ```
1374
-
1375
- **If you have sorted data:**
1376
-
1377
- ```python
1378
- engine.register("table", source, ordered_by="key") # Enable Merge Join
1379
- ```
1380
-
1381
- ### Step 4: Combine Optimizations
1382
-
1383
- **For Speed Priority (Polars Join):**
1384
-
1385
- ```python
1386
- engine = Engine(use_polars=True) # Uses Polars Join
1387
-
1388
- def optimized_source(dynamic_where=None, dynamic_columns=None):
1389
- # Supports all optimizations
1390
- pass
1391
-
1392
- engine.register("table", optimized_source) # No filename - Polars Join
1393
- ```
1394
-
1395
- **For Memory Priority (MMAP Join):**
1396
-
1397
- ```python
1398
- engine = Engine(use_polars=False) # Uses MMAP Join
1399
-
1400
- def optimized_source(dynamic_where=None, dynamic_columns=None):
1401
- # Supports all optimizations
1402
- pass
1403
-
1404
- engine.register("table", optimized_source, filename="data.jsonl") # MMAP Join
1405
- ```
1406
-
1407
- ---
1408
-
1409
- ## Summary
1410
-
1411
- ### Start Here (Most Secure)
1412
-
1413
- ```python
1414
- engine = Engine() # Default: use_polars=False
1415
- engine.register("table1", source1)
1416
- engine.register("table2", source2)
1417
- ```
1418
-
1419
- **Why:** Most stable, handles all edge cases, works with any data types
1420
-
1421
- ---
1422
-
1423
- ### Then Experiment
1424
-
1425
- 1. **Add debug mode**: `Engine(debug=True)` - See what's happening
1426
- 2. **Try Polars**: `Engine(use_polars=True)` - For large datasets
1427
- 3. **Try MMAP**: `filename="data.jsonl"` - For large files
1428
- 4. **Try Merge Join**: `ordered_by="key"` - For sorted data
1429
-
1430
- ---
1431
-
1432
- ### Advanced: Mix Options
1433
-
1434
- **Best Mix for Large Files:**
1435
-
1436
- **Option 1: Speed Priority (Polars Join)**
1437
-
1438
- ```python
1439
- engine = Engine(use_polars=True) # Uses Polars Join (fastest)
1440
- engine.register("table", source) # No filename needed
1441
- ```
1442
-
1443
- **Option 2: Memory Priority (MMAP Join)**
1444
-
1445
- ```python
1446
- engine = Engine(use_polars=False) # Uses MMAP Join (lowest memory)
1447
- engine.register("table", source, filename="data.jsonl") # MMAP enabled
1448
- ```
1449
-
1450
- **Best Mix for Maximum Performance:**
1451
-
1452
- **Option 1: Speed Priority (Polars Join + Protocols)**
1453
-
1454
- ```python
1455
- engine = Engine(use_polars=True) # Uses Polars Join
1456
-
1457
- def source(dynamic_where=None, dynamic_columns=None):
1458
- # All optimizations (filter pushdown + column pruning)
1459
- pass
1460
-
1461
- engine.register("table", source) # No filename - Polars Join
1462
- ```
1463
-
1464
- **Option 2: Memory Priority (MMAP Join + Protocols)**
1465
-
1466
- ```python
1467
- engine = Engine(use_polars=False) # Uses MMAP Join
1468
-
1469
- def source(dynamic_where=None, dynamic_columns=None):
1470
- # All optimizations (filter pushdown + column pruning)
1471
- pass
1472
-
1473
- engine.register("table", source, filename="data.jsonl") # MMAP Join
1474
- ```
1475
-
1476
- ---
1477
-
1478
- ## Key Takeaways
1479
-
1480
- 1. **Start Simple**: Use default configuration (`Engine()`) - it's the most stable
1481
- 2. **Experiment Gradually**: Add options one at a time to understand their impact
1482
- 3. **Mix Wisely**: Choose Polars Join (speed) OR MMAP Join (memory) based on priority
1483
- 4. **Know When to Use Each**: Small files: default, Large files: Polars Join (speed) OR MMAP Join (memory)
1484
-
1485
- ---
1486
-
1487
- **Remember**: Start with the default configuration, then experiment with options as you understand your data and performance needs better.
1488
-
1489
- ## Getting Started
1490
-
1491
- Installation:
1492
-
1493
- ```bash
1494
- pip install streaming-sql-engine
1495
- ```
1496
-
1497
- Quick start:
1498
-
1499
- ```python
1500
- from streaming_sql_engine import Engine
1501
-
1502
- engine = Engine()
1503
-
1504
- # Register data sources (any Python function that returns an iterator)
1505
- def users_source():
1506
- return iter([
1507
- {"id": 1, "name": "Alice", "dept_id": 10},
1508
- {"id": 2, "name": "Bob", "dept_id": 20},
1509
- ])
1510
-
1511
- def departments_source():
1512
- return iter([
1513
- {"id": 10, "name": "Engineering"},
1514
- {"id": 20, "name": "Sales"},
1515
- ])
1516
-
1517
- engine.register("users", users_source)
1518
- engine.register("departments", departments_source)
1519
-
1520
- # Execute SQL query
1521
- query = """
1522
- SELECT users.name, departments.name AS dept
1523
- FROM users
1524
- JOIN departments ON users.dept_id = departments.id
1525
- """
1526
-
1527
- for row in engine.query(query):
1528
- print(row)
1529
- # Output:
1530
- # {'users.name': 'Alice', 'departments.name': 'Engineering'}
1531
- # {'users.name': 'Bob', 'departments.name': 'Sales'}
1532
- ```
1533
-
1534
- **For database connections**, create iterator functions:
1535
-
1536
- ```python
1537
- from streaming_sql_engine import Engine
1538
- import psycopg2
1539
-
1540
- engine = Engine()
1541
-
1542
- # Register database table (iterator function)
1543
- def users_source():
1544
- conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
1545
- cursor = conn.cursor()
1546
- cursor.execute("SELECT id, name, email FROM users WHERE active = true")
1547
- for row in cursor:
1548
- yield {"id": row[0], "name": row[1], "email": row[2]}
1549
- conn.close()
1550
-
1551
- engine.register("users", users_source)
1552
-
1553
- # Query
1554
- for row in engine.query("SELECT * FROM users WHERE users.active = true"):
1555
- print(row)
1556
- ```
1557
-
1558
- ---
1559
-
1560
- ## Conclusion
1561
-
1562
- 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.
1563
-
1564
- **Key strengths:**
1565
-
1566
- - Cross-system joins (databases, APIs, files)
1567
- - Zero infrastructure requirements
1568
- - Memory-efficient streaming architecture
1569
- - Python-native integration
1570
- - Automatic optimizations
1571
- - Simple deployment
1572
-
1573
- **Best suited for:**
1574
-
1575
- - Microservices data aggregation
1576
- - Cross-system ETL pipelines
1577
- - Real-time data integration
1578
- - Memory-constrained environments
1579
- - Python-native workflows
1580
-
1581
- For cross-system data integration, the Streaming SQL Engine provides a unique solution that balances performance, simplicity, and flexibility.
1582
-
1583
- ---
1584
-
1585
- ## Resources
1586
-
1587
- - **PyPI:** `pip install streaming-sql-engine`
1588
- - **Bug Reports:** `"https://github.com/Ierofantis/streaming_sql_engine/issues"`,
1589
- - **Source":** `"https://github.com/Ierofantis/streaming_sql_engine/"`,
1590
- - **Documentation":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/README.md"`,
1591
- - **Scientific Paper":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/Streaming_SQL_Engine_Paper.pdf"`
1592
-
1593
- ---
1
+ # Streaming SQL Engine: Join Data from Anywhere
2
+
3
+ Join data from MySQL, PostgreSQL, MongoDB, REST APIs, CSV files, and more — all in one SQL query, without infrastructure or data import.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install streaming-sql-engine
11
+ ```
12
+
13
+ That's it! No clusters, no servers, no configuration files.
14
+
15
+ ---
16
+
17
+ ## Quick Start
18
+
19
+ Join data from different sources in 3 steps:
20
+
21
+ ```python
22
+ from streaming_sql_engine import Engine
23
+
24
+ # 1. Create engine
25
+ engine = Engine()
26
+
27
+ # 2. Register data sources (any Python iterator function)
28
+ def postgres_users():
29
+ import psycopg2
30
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
31
+ cursor = conn.cursor()
32
+ cursor.execute("SELECT id, name, email FROM users")
33
+ for row in cursor:
34
+ yield {"id": row[0], "name": row[1], "email": row[2]}
35
+ conn.close()
36
+
37
+ def mysql_orders():
38
+ import pymysql
39
+ conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
40
+ cursor = conn.cursor()
41
+ cursor.execute("SELECT id, user_id, total FROM orders")
42
+ for row in cursor:
43
+ yield {"id": row[0], "user_id": row[1], "total": row[2]}
44
+ conn.close()
45
+
46
+ engine.register("users", postgres_users)
47
+ engine.register("orders", mysql_orders)
48
+
49
+ # 3. Write SQL and execute
50
+ query = """
51
+ SELECT users.name, users.email, orders.total
52
+ FROM users
53
+ JOIN orders ON users.id = orders.user_id
54
+ WHERE orders.total > 100
55
+ """
56
+
57
+ for row in engine.query(query):
58
+ print(row)
59
+ ```
60
+
61
+ **Output:**
62
+
63
+ ```python
64
+ {'name': 'Alice', 'email': 'alice@example.com', 'total': 150.50}
65
+ {'name': 'Bob', 'email': 'bob@example.com', 'total': 200.00}
66
+ ```
67
+
68
+ ---
69
+
70
+ ## File Compare app
71
+
72
+ A local web app on top of the engine: compare two or more large CSV, TSV, JSONL or Excel files by a key and watch the join run live. Nothing is uploaded; it runs on your machine and opens in your browser.
73
+
74
+ ```bash
75
+ pip install "streaming-sql-engine[app]"
76
+ sse-compare # or: python -m streaming_sql_engine.app
77
+ ```
78
+
79
+ From a source checkout: `python run_app.py`.
80
+
81
+ ![File Compare after a run: totals, join flow, throughput and memory charts, result rows, and the session's runs with Python, Rust and DuckDB side by side](https://raw.githubusercontent.com/Ierofantis/streaming_sql_engine/master/docs/app-runs.png)
82
+
83
+ While a comparison runs, the counters, charts and result rows update live:
84
+
85
+ ![File Compare during a run](https://raw.githubusercontent.com/Ierofantis/streaming_sql_engine/master/docs/app-running.png)
86
+
87
+ 1. Pick file A and file B (or generate synthetic demo files). "Add another file" adds file C, D and so on, up to twelve.
88
+ 2. Confirm the key columns; the app suggests them from column names and sample values.
89
+ 3. Choose what to show: rows in all files, rows only in one of them, or matched rows whose values differ.
90
+ 4. Press Run. Rows, throughput and memory update live, the generated SQL is shown, and the result downloads as CSV.
91
+
92
+ ### More than two files
93
+
94
+ Every other file is matched against file A on its own key column.
95
+
96
+ - **Rows in all files:** the key is present in every file. The result has the columns of all of them.
97
+ - **Rows only in C** (or any other file): rows of that file whose key is in none of the others.
98
+ - **Matched rows whose values differ:** rows present in every file where a column of A differs from the column you paired it with in another file. Each pair names its file.
99
+
100
+ The comparison runs as one join per extra file: A with B, the result with C, and so on. The page shows which step is running. Every join strategy works this way except the DuckDB comparison, which is set up for two files.
101
+
102
+ ![Four files compared: values that differ across a catalog, a supplier feed, a warehouse file and a marketplace file](https://raw.githubusercontent.com/Ierofantis/streaming_sql_engine/master/docs/app-four-files.png)
103
+
104
+ ### Join strategies
105
+
106
+ The "File index in Rust" strategy (files in any order) and the "Merge in Rust" strategies (files already sorted by the key) use an optional native extension that runs on all cores. It reads CSV and TSV. Build it once from a checkout (needs the Rust toolchain):
107
+
108
+ ```bash
109
+ pip install maturin
110
+ cd native && maturin develop --release
111
+ ```
112
+
113
+ How the Rust code works, step by step: [docs/rust-kernels.md](docs/rust-kernels.md).
114
+
115
+ Each run happens in its own process, so the memory figure is the cost of that run alone. Run the same comparison with the "In-memory hash" strategy to see the difference against the default file index join.
116
+
117
+ "DuckDB (for comparison)" runs the same comparison in DuckDB if it is installed (`pip install duckdb`), so you can put its time and memory next to the engine's own in the runs table.
118
+
119
+ ---
120
+
121
+ ## Benchmark: Python, Rust and DuckDB
122
+
123
+ The job: read two CSV files of 5 million rows, join them on a key, write the result (4.8 million rows) as CSV.
124
+
125
+ ![Median time and peak memory for the Python joins, the Rust joins and DuckDB](https://raw.githubusercontent.com/Ierofantis/streaming_sql_engine/master/docs/benchmark.svg)
126
+
127
+ Both files sorted by the key, 503 MB of input:
128
+
129
+ | Engine | Time | Peak memory |
130
+ |---|---|---|
131
+ | Python, file index join | 129 s | 194 MB |
132
+ | Python, in-memory hash join | 134 s | 4,089 MB |
133
+ | Python, merge join | 122 s | 68 MB |
134
+ | **Rust, file index join** | **1.6 s** | **95 MB** |
135
+ | **Rust, merge join** | **1.5 s** | **52 MB** |
136
+ | DuckDB 2.0.1 | 4.4 s | 1,208 MB |
137
+
138
+ Rust file index join against DuckDB on other data shapes (median of 5 runs):
139
+
140
+ | Data shape | Rust time | DuckDB time | Rust memory | DuckDB memory |
141
+ |---|---|---|---|---|
142
+ | File B shuffled | 2.4 s | 5.7 s | 99 MB | 1,254 MB |
143
+ | Both files shuffled | 2.1 s | 5.1 s | 97 MB | 1,280 MB |
144
+ | Both files sorted | 1.7 s | 4.2 s | 98 MB | 1,275 MB |
145
+ | Wide rows (2.4 GB input) | 9.6 s | 8.1 s | 106 MB | 2,301 MB |
146
+ | Repeated keys in B | 2.0 s | 4.7 s | 164 MB | 1,305 MB |
147
+ | Only 10% of rows match | 1.0 s | 2.7 s | 82 MB | 1,265 MB |
148
+
149
+ How to read this:
150
+
151
+ - **Machine:** a laptop with 4 physical / 8 logical cores and 32 GB RAM, Windows 11, Python 3.14. Rust and DuckDB use all 8 threads; the Python joins use one.
152
+ - **Method:** every run is a fresh process, the input files are already in the operating system's file cache, runs are interleaved, and the engines must produce the same result (row count, plus a checksum of the output for Rust and DuckDB). The Python joins were run once each; everything else is a median of 3 or 5 runs.
153
+ - **DuckDB reads the columns as text** here, as this engine does. With its own type detection it was up to 16% faster and used 6–26% less memory.
154
+ - **This is one job, not a general comparison.** DuckDB is a full analytical database; the Rust kernels do a two-file equality join on one key and copy bytes from input to output. On wide rows DuckDB is faster.
155
+ - **Not measured:** files larger than RAM, and machines with more cores.
156
+
157
+ Reproduce it (needs `duckdb`, `psutil` and the Rust extension):
158
+
159
+ ```bash
160
+ python benchmarks/bench_vs_duckdb.py --rows 5000000 # Rust and DuckDB, six data shapes
161
+ python benchmarks/bench_vs_duckdb.py --rows 5000000 --python --shapes shuffled,sorted
162
+ ```
163
+
164
+ Full reports: [Rust and DuckDB](benchmarks/results/rust-vs-duckdb-5m.md), [with the Python joins](benchmarks/results/python-rust-duckdb-5m.md).
165
+
166
+ ---
167
+
168
+ ## The Problem: Data Lives Everywhere
169
+
170
+ Modern applications don't store all their data in one place. You might have:
171
+
172
+ - User data in PostgreSQL
173
+ - Order data in MySQL
174
+ - Product catalog in MongoDB
175
+ - Pricing information from a REST API
176
+ - Inventory data in CSV files
177
+ - Product feeds in XML files
178
+
179
+ **The challenge:** How do you join all this data together?
180
+
181
+ Traditional solutions require:
182
+
183
+ - Exporting data from each system
184
+ - Importing into a central database
185
+ - Writing complex ETL pipelines
186
+ - Maintaining data synchronization
187
+
188
+ **There had to be a better way.**
189
+
190
+ ---
191
+
192
+ ## The Solution: Streaming SQL Engine
193
+
194
+ 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.
195
+
196
+ ```python
197
+ from streaming_sql_engine import Engine
198
+ import psycopg2
199
+ import pymysql
200
+ from pymongo import MongoClient
201
+ import requests
202
+ import csv
203
+
204
+ engine = Engine()
205
+
206
+ # Register PostgreSQL source (iterator function)
207
+ def postgres_users():
208
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
209
+ cursor = conn.cursor()
210
+ cursor.execute("SELECT id, name, email FROM users")
211
+ for row in cursor:
212
+ yield {"id": row[0], "name": row[1], "email": row[2]}
213
+ conn.close()
214
+ engine.register("postgres_users", postgres_users)
215
+
216
+ # Register MySQL source (iterator function)
217
+ def mysql_products():
218
+ conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
219
+ cursor = conn.cursor()
220
+ cursor.execute("SELECT id, name, price FROM products")
221
+ for row in cursor:
222
+ yield {"id": row[0], "name": row[1], "price": row[2]}
223
+ conn.close()
224
+ engine.register("mysql_products", mysql_products)
225
+
226
+ # Register MongoDB source (iterator function)
227
+ def mongo_inventory():
228
+ client = MongoClient("mongodb://localhost:27017")
229
+ for doc in client.mydb.inventory.find():
230
+ yield doc
231
+ engine.register("mongo_inventory", mongo_inventory)
232
+
233
+ # Register REST API source (iterator function)
234
+ def api_prices():
235
+ response = requests.get("https://api.example.com/prices")
236
+ for item in response.json():
237
+ yield item
238
+ engine.register("api_prices", api_prices)
239
+
240
+ # Register CSV source (iterator function)
241
+ def csv_suppliers():
242
+ with open("suppliers.csv") as f:
243
+ for row in csv.DictReader(f):
244
+ yield row
245
+ engine.register("csv_suppliers", csv_suppliers)
246
+
247
+ # Join them all in one SQL query!
248
+ query = """
249
+ SELECT
250
+ mysql_products.name,
251
+ postgres_users.email,
252
+ mongo_inventory.quantity,
253
+ api_prices.price,
254
+ csv_suppliers.supplier_name
255
+ FROM mysql_products
256
+ JOIN postgres_users ON mysql_products.user_id = postgres_users.id
257
+ JOIN mongo_inventory ON mysql_products.sku = mongo_inventory.sku
258
+ JOIN api_prices ON mysql_products.sku = api_prices.sku
259
+ JOIN csv_suppliers ON mysql_products.supplier_id = csv_suppliers.id
260
+ WHERE api_prices.price > 100
261
+ """
262
+
263
+ for row in engine.query(query):
264
+ process(row)
265
+ ```
266
+
267
+ **That's it.** No clusters, no infrastructure, no data export — just pure Python and SQL.
268
+
269
+ ---
270
+
271
+ ## Data Source Examples
272
+
273
+ The engine works with **any Python iterator function**. Here are practical examples:
274
+
275
+ ### PostgreSQL
276
+
277
+ ```python
278
+ def postgres_users():
279
+ import psycopg2
280
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
281
+ cursor = conn.cursor()
282
+ cursor.execute("SELECT id, name, email FROM users")
283
+ for row in cursor:
284
+ yield {"id": row[0], "name": row[1], "email": row[2]}
285
+ conn.close()
286
+
287
+ engine.register("users", postgres_users)
288
+ ```
289
+
290
+ ### MySQL
291
+
292
+ ```python
293
+ def mysql_products():
294
+ import pymysql
295
+ conn = pymysql.connect(host="localhost", database="mydb", user="user", password="pass")
296
+ cursor = conn.cursor()
297
+ cursor.execute("SELECT id, name, price FROM products")
298
+ for row in cursor:
299
+ yield {"id": row[0], "name": row[1], "price": row[2]}
300
+ conn.close()
301
+
302
+ engine.register("products", mysql_products)
303
+ ```
304
+
305
+ ### MongoDB
306
+
307
+ ```python
308
+ def mongo_inventory():
309
+ from pymongo import MongoClient
310
+ client = MongoClient("mongodb://localhost:27017")
311
+ for doc in client.mydb.inventory.find():
312
+ yield doc # MongoDB documents are already dictionaries
313
+ client.close()
314
+
315
+ engine.register("inventory", mongo_inventory)
316
+ ```
317
+
318
+ ### CSV Files
319
+
320
+ ```python
321
+ def csv_suppliers():
322
+ import csv
323
+ with open("suppliers.csv") as f:
324
+ reader = csv.DictReader(f)
325
+ for row in reader:
326
+ yield row # DictReader yields dictionaries
327
+
328
+ engine.register("suppliers", csv_suppliers)
329
+ ```
330
+
331
+ ### JSONL Files
332
+
333
+ ```python
334
+ def jsonl_products():
335
+ import json
336
+ with open("products.jsonl") as f:
337
+ for line in f:
338
+ yield json.loads(line)
339
+
340
+ # For large files, use MMAP join
341
+ engine.register("products", jsonl_products, filename="products.jsonl")
342
+ ```
343
+
344
+ ### REST APIs
345
+
346
+ ```python
347
+ def api_prices():
348
+ import requests
349
+ response = requests.get("https://api.example.com/prices")
350
+ for item in response.json():
351
+ yield item
352
+
353
+ # For paginated APIs
354
+ def api_prices_paginated():
355
+ import requests
356
+ page = 1
357
+ while True:
358
+ response = requests.get(f"https://api.example.com/prices?page={page}")
359
+ data = response.json()
360
+ if not data:
361
+ break
362
+ for item in data:
363
+ yield item
364
+ page += 1
365
+
366
+ engine.register("prices", api_prices_paginated)
367
+ ```
368
+
369
+ ### XML Files
370
+
371
+ ```python
372
+ def xml_products():
373
+ import xml.etree.ElementTree as ET
374
+ tree = ET.parse("products.xml")
375
+ for product in tree.findall('.//product'):
376
+ yield {
377
+ 'id': product.find('id').text,
378
+ 'name': product.find('name').text,
379
+ 'price': float(product.find('price').text)
380
+ }
381
+
382
+ engine.register("products", xml_products)
383
+ ```
384
+
385
+ ### Custom Python Logic
386
+
387
+ ```python
388
+ def enriched_products():
389
+ """Apply Python processing before joining"""
390
+ import psycopg2
391
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
392
+ cursor = conn.cursor()
393
+ cursor.execute("SELECT id, name, category_id FROM products")
394
+ for row in cursor:
395
+ product = {"id": row[0], "name": row[1], "category_id": row[2]}
396
+ # Apply custom Python logic
397
+ product['ml_score'] = ml_model.predict(product)
398
+ product['custom_field'] = custom_function(product)
399
+ yield product
400
+ conn.close()
401
+
402
+ engine.register("products", enriched_products)
403
+ ```
404
+
405
+ ---
406
+
407
+ ## SQL Features
408
+
409
+ The engine supports standard SQL syntax, providing a declarative interface that eliminates the need for manual Python code. Instead of writing 50-100 lines of hash index construction, nested loops, and dictionary lookups, you can express complex cross-system joins in a single SQL query.
410
+
411
+ ### Supported Features
412
+
413
+ **SELECT** - Column selection, aliasing, table-qualified columns
414
+
415
+ ```sql
416
+ SELECT users.name, orders.total AS order_total
417
+ FROM users
418
+ JOIN orders ON users.id = orders.user_id
419
+ ```
420
+
421
+ **JOIN** - INNER JOIN and LEFT JOIN with equality conditions
422
+
423
+ ```sql
424
+ SELECT *
425
+ FROM table1 t1
426
+ JOIN table2 t2 ON t1.id = t2.id
427
+ LEFT JOIN table3 t3 ON t1.id = t3.id
428
+ ```
429
+
430
+ **WHERE** - Comparisons, boolean logic, NULL checks, IN clauses
431
+
432
+ ```sql
433
+ SELECT *
434
+ FROM products
435
+ WHERE price > 100
436
+ AND status IN ('active', 'pending')
437
+ AND description IS NOT NULL
438
+ ```
439
+
440
+ **Arithmetic** - Addition, subtraction, multiplication, division, modulo
441
+
442
+ ```sql
443
+ SELECT
444
+ price - discount AS final_price,
445
+ quantity * unit_price AS total
446
+ FROM orders
447
+ ```
448
+
449
+ ### Not Supported
450
+
451
+ - GROUP BY and aggregations (COUNT, SUM, AVG)
452
+ - ORDER BY
453
+ - HAVING
454
+ - Subqueries
455
+
456
+ _These limitations keep the engine focused on joins and filtering — its core strength._
457
+
458
+ ---
459
+
460
+ ## Join Types and Algorithms
461
+
462
+ The engine automatically selects the best join algorithm based on your data. You can also configure it explicitly.
463
+
464
+ ### 1. Lookup Join (Default)
465
+
466
+ General-purpose hash-based join for unsorted data:
467
+
468
+ ```python
469
+ engine = Engine() # Default: use_polars=False
470
+
471
+ def products_source():
472
+ # Your iterator function
473
+ yield {"id": 1, "name": "Product A"}
474
+ yield {"id": 2, "name": "Product B"}
475
+
476
+ def categories_source():
477
+ yield {"id": 1, "category": "Electronics"}
478
+ yield {"id": 2, "category": "Books"}
479
+
480
+ engine.register("products", products_source)
481
+ engine.register("categories", categories_source)
482
+
483
+ query = """
484
+ SELECT products.name, categories.category
485
+ FROM products
486
+ JOIN categories ON products.id = categories.id
487
+ """
488
+ ```
489
+
490
+ **When to use:** Default choice, works with any data, most compatible.
491
+
492
+ ### 2. Merge Join (For Sorted Data)
493
+
494
+ Most memory-efficient for pre-sorted data (O(1) memory):
495
+
496
+ ```python
497
+ engine = Engine(use_polars=False)
498
+
499
+ # Register with ordered_by to enable merge join
500
+ def sorted_products():
501
+ # Data must be sorted by join key
502
+ yield {"id": 1, "name": "Product A"} # sorted by id
503
+ yield {"id": 2, "name": "Product B"}
504
+ yield {"id": 3, "name": "Product C"}
505
+
506
+ def sorted_categories():
507
+ yield {"id": 1, "category": "Electronics"} # sorted by id
508
+ yield {"id": 2, "category": "Books"}
509
+ yield {"id": 3, "category": "Clothing"}
510
+
511
+ engine.register("products", sorted_products, ordered_by="id")
512
+ engine.register("categories", sorted_categories, ordered_by="id")
513
+
514
+ query = """
515
+ SELECT products.name, categories.category
516
+ FROM products
517
+ JOIN categories ON products.id = categories.id
518
+ """
519
+ ```
520
+
521
+ **When to use:** Data is pre-sorted by join key, memory is constrained.
522
+
523
+ ### 3. Polars Join (For Large Datasets)
524
+
525
+ Vectorized, SIMD-accelerated joins for large datasets:
526
+
527
+ ```python
528
+ engine = Engine(use_polars=True) # Enable Polars
529
+
530
+ def large_products_source():
531
+ # Large dataset (> 10K rows)
532
+ for i in range(100000):
533
+ yield {"id": i, "name": f"Product {i}"}
534
+
535
+ def large_categories_source():
536
+ for i in range(1000):
537
+ yield {"id": i, "category": f"Category {i}"}
538
+
539
+ engine.register("products", large_products_source)
540
+ engine.register("categories", large_categories_source)
541
+
542
+ query = """
543
+ SELECT products.name, categories.category
544
+ FROM products
545
+ JOIN categories ON products.id = categories.id
546
+ """
547
+ ```
548
+
549
+ **When to use:** Large datasets (> 100K rows), consistent data types, speed priority.
550
+
551
+ **Install Polars:** `pip install polars`
552
+
553
+ ### 4. MMAP Join (For Large Files)
554
+
555
+ Memory-mapped joins for files larger than RAM. The `filename` can be a JSONL, CSV or TSV file; join keys are compared as text.
556
+
557
+ ```python
558
+ engine = Engine(use_polars=False) # MMAP requires use_polars=False
559
+
560
+ def jsonl_source():
561
+ import json
562
+ with open("large_file.jsonl") as f:
563
+ for line in f:
564
+ yield json.loads(line)
565
+
566
+ # Register with filename to enable MMAP
567
+ engine.register("products", jsonl_source, filename="large_file.jsonl")
568
+
569
+ query = """
570
+ SELECT products.name, categories.category
571
+ FROM products
572
+ JOIN categories ON products.id = categories.id
573
+ """
574
+ ```
575
+
576
+ **When to use:** Large JSONL files (> 1GB), memory-constrained environments.
577
+
578
+ ---
579
+
580
+ ## Optimizations
581
+
582
+ The engine includes automatic optimizations that can significantly improve performance.
583
+
584
+ ### 1. Column Pruning
585
+
586
+ Only extracts columns needed for the query:
587
+
588
+ ```python
589
+ # Query only requests 'name' and 'price'
590
+ query = "SELECT name, price FROM products"
591
+
592
+ # Source function receives requested columns
593
+ def products_source(dynamic_columns=None):
594
+ if dynamic_columns:
595
+ columns = ", ".join(dynamic_columns) # ['name', 'price']
596
+ query = f"SELECT {columns} FROM products_table"
597
+ else:
598
+ query = "SELECT * FROM products_table"
599
+ # Execute query and yield rows
600
+ for row in execute_query(query):
601
+ yield row
602
+
603
+ engine.register("products", products_source)
604
+ ```
605
+
606
+ **Benefit:** Reduces I/O and memory by only fetching needed columns.
607
+
608
+ ### 2. Filter Pushdown
609
+
610
+ Pushes WHERE conditions to data sources:
611
+
612
+ ```python
613
+ # Query has WHERE clause
614
+ query = "SELECT * FROM products WHERE price > 100"
615
+
616
+ # Source function receives filter condition
617
+ def products_source(dynamic_where=None):
618
+ query = "SELECT * FROM products_table"
619
+ if dynamic_where:
620
+ query += f" WHERE {dynamic_where}" # "price > 100"
621
+ # Execute filtered query at source
622
+ for row in execute_query(query):
623
+ yield row
624
+
625
+ engine.register("products", products_source)
626
+ ```
627
+
628
+ **Benefit:** Filters data at source, reducing data transfer and processing.
629
+
630
+ ### 3. Protocol Detection
631
+
632
+ Automatic optimization detection via function signature:
633
+
634
+ ```python
635
+ # Simple source (no optimizations)
636
+ def simple_source():
637
+ return iter([{"id": 1, "name": "Alice"}])
638
+
639
+ # Optimized source (supports both optimizations)
640
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
641
+ query = "SELECT "
642
+ if dynamic_columns:
643
+ query += ", ".join(dynamic_columns)
644
+ else:
645
+ query += "*"
646
+ query += " FROM table"
647
+ if dynamic_where:
648
+ query += f" WHERE {dynamic_where}"
649
+ return execute_query(query)
650
+
651
+ # Both work the same way - optimizations apply automatically!
652
+ engine.register("users", simple_source) # No optimizations
653
+ engine.register("products", optimized_source) # Optimizations apply automatically
654
+ ```
655
+
656
+ **Benefit:** Zero configuration - engine detects capabilities automatically.
657
+
658
+ ---
659
+
660
+ ## Real-World Examples
661
+
662
+ ### Example 1: Microservices Data Integration
663
+
664
+ In a microservices architecture, data is distributed across services:
665
+
666
+ ```python
667
+ from streaming_sql_engine import Engine
668
+ import psycopg2
669
+ import pymysql
670
+ import requests
671
+
672
+ engine = Engine()
673
+
674
+ # Service 1: User service (PostgreSQL) - iterator function
675
+ def users_source():
676
+ conn = psycopg2.connect(host="user-db", port=5432, user="user", password="pass", database="users_db")
677
+ cursor = conn.cursor()
678
+ cursor.execute("SELECT id, name, email FROM users")
679
+ for row in cursor:
680
+ yield {"id": row[0], "name": row[1], "email": row[2]}
681
+ conn.close()
682
+ engine.register("users", users_source)
683
+
684
+ # Service 2: Order service (MySQL) - iterator function
685
+ def orders_source():
686
+ conn = pymysql.connect(host="order-db", port=3306, user="user", password="pass", database="orders_db")
687
+ cursor = conn.cursor()
688
+ cursor.execute("SELECT id, user_id, total FROM orders")
689
+ for row in cursor:
690
+ yield {"id": row[0], "user_id": row[1], "total": row[2]}
691
+ conn.close()
692
+ engine.register("orders", orders_source)
693
+
694
+ # Service 3: Payment service (REST API) - iterator function
695
+ def payment_source():
696
+ response = requests.get("https://payments.service/api/transactions")
697
+ for item in response.json():
698
+ yield item
699
+ engine.register("payments", payment_source)
700
+
701
+ # Join across services
702
+ query = """
703
+ SELECT users.name, orders.total, payments.status
704
+ FROM users
705
+ JOIN orders ON users.id = orders.user_id
706
+ JOIN payments ON orders.id = payments.order_id
707
+ """
708
+ ```
709
+
710
+ **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.
711
+
712
+ ### Example 2: Real-Time Price Comparison
713
+
714
+ Compare prices from multiple XML feeds and match with MongoDB:
715
+
716
+ ```python
717
+ def parse_xml(filepath):
718
+ tree = ET.parse(filepath)
719
+ for product in tree.findall('.//product'):
720
+ yield {
721
+ 'ean': product.find('ean').text,
722
+ 'price': float(product.find('price').text),
723
+ 'name': product.find('name').text
724
+ }
725
+
726
+ engine.register("xml1", lambda: parse_xml("prices1.xml"))
727
+ engine.register("xml2", lambda: parse_xml("prices2.xml"))
728
+ engine.register("mongo", mongo_source)
729
+
730
+ query = """
731
+ SELECT
732
+ xml1.ean,
733
+ xml1.price AS price1,
734
+ xml2.price AS price2,
735
+ mongo.sf_sku
736
+ FROM xml1
737
+ JOIN xml2 ON xml1.ean = xml2.ean
738
+ JOIN mongo ON xml1.ean = mongo.ean
739
+ WHERE xml1.price != xml2.price
740
+ """
741
+ ```
742
+
743
+ **Production results:** 17M + 17M XML records + 5M MongoDB records processed in 7 minutes using 400 MB RAM.
744
+
745
+ ### Example 3: Python Processing Between Joins
746
+
747
+ Apply Python logic (ML models, custom functions) between joins:
748
+
749
+ ```python
750
+ def enriched_source():
751
+ """Source that processes data with Python before joining"""
752
+ import psycopg2
753
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
754
+ cursor = conn.cursor()
755
+ cursor.execute("SELECT id, name, category_id FROM products")
756
+ for row in cursor:
757
+ product = {"id": row[0], "name": row[1], "category_id": row[2]}
758
+ # Apply Python logic
759
+ product['ml_score'] = ml_model.predict(product)
760
+ product['custom_field'] = custom_function(product)
761
+ yield product
762
+ conn.close()
763
+
764
+ def categories_source():
765
+ import psycopg2
766
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
767
+ cursor = conn.cursor()
768
+ cursor.execute("SELECT id, name FROM categories")
769
+ for row in cursor:
770
+ yield {"id": row[0], "category_name": row[1]}
771
+ conn.close()
772
+
773
+ engine.register("enriched_products", enriched_source)
774
+ engine.register("categories", categories_source)
775
+
776
+ query = """
777
+ SELECT p.name, p.ml_score, c.category_name
778
+ FROM enriched_products p
779
+ JOIN categories c ON p.category_id = c.id
780
+ """
781
+ ```
782
+
783
+ **Why this matters:** Seamless integration with Python ecosystem — use any library, apply any logic.
784
+
785
+ ---
786
+
787
+ ### What Makes Streaming SQL Engine Unique
788
+
789
+ 1. **Zero Infrastructure + Cross-System Joins**
790
+
791
+ - Most tools require clusters (Spark, Flink, Drill)
792
+ - Or require specific infrastructure (ksqlDB needs Kafka)
793
+ - Streaming SQL Engine: Just Python
794
+
795
+ 2. **Any Python Iterator as Data Source**
796
+
797
+ - Most tools require specific connectors
798
+ - Streaming SQL Engine: Any Python function works
799
+
800
+ 3. **Direct API Joins**
801
+
802
+ - Most tools can't join REST APIs directly
803
+ - Streaming SQL Engine: Native support
804
+
805
+ 4. **Python-Native Architecture**
806
+ - Most tools are Java/Rust with Python wrappers
807
+ - Streaming SQL Engine: Pure Python, seamless integration
808
+
809
+ ### Similar Tools (But Different)
810
+
811
+ **Apache Drill** — Similar cross-system capability, but requires cluster and Java
812
+
813
+ **ksqlDB** — Streaming SQL, but Kafka-only and requires infrastructure
814
+
815
+ **Materialize** — Streaming database, but requires database server
816
+
817
+ **DataFusion** — Fast SQL engine, but limited to Arrow/Parquet data
818
+
819
+ **Polars SQL** — Fast SQL, but requires loading data into DataFrames first
820
+
821
+ **Presto/Trino** — Cross-system SQL, but requires cluster infrastructure
822
+
823
+ **None of these** combine:
824
+
825
+ - Zero infrastructure
826
+ - Any Python iterator as source
827
+ - Direct API joins
828
+ - Pure Python implementation
829
+ - Simple deployment
830
+
831
+ **That's what makes Streaming SQL Engine unique.**
832
+
833
+ ---
834
+
835
+ ## Key Wins
836
+
837
+ ### 1. Cross-System Joins
838
+
839
+ The **only tool** that can join MySQL + PostgreSQL + MongoDB + REST API + CSV files in a single SQL query without data export/import.
840
+
841
+ ### 2. Zero Infrastructure
842
+
843
+ No clusters, no setup, just Python. Install and use immediately:
844
+
845
+ ```bash
846
+ pip install streaming-sql-engine
847
+ ```
848
+
849
+ ### 3. Memory Efficient
850
+
851
+ Processes 39 million records with only 400 MB RAM. True streaming architecture means you can process data larger than available RAM.
852
+
853
+ ### 4. Python-Native
854
+
855
+ Seamless integration with Python ecosystem. Use any Python function as a data source, apply ML models, use any library.
856
+
857
+ ### 5. Real-Time Processing
858
+
859
+ Join live streaming data with static reference data. No buffering required — true streaming execution.
860
+
861
+ ### 6. Automatic Optimizations
862
+
863
+ Filter pushdown, column pruning, and vectorization applied automatically. No configuration needed — the engine detects protocol support.
864
+
865
+ ---
866
+
867
+ ## When to Use Streaming SQL Engine
868
+
869
+ **Perfect for:**
870
+
871
+ - Joining data from different systems (databases, APIs, files)
872
+ - Microservices data aggregation
873
+ - Real-time data integration
874
+ - Memory-constrained environments
875
+ - Python-native workflows
876
+ - Ad-hoc cross-system queries
877
+
878
+ **Not for:**
879
+
880
+ - All data in same database (use direct SQL - 10-100x faster)
881
+ - Need GROUP BY or aggregations (use database)
882
+ - Maximum performance for same-database queries (use database)
883
+ - Distributed processing (use Spark/Flink)
884
+
885
+ ---
886
+
887
+ ## 🎯 Start Here: The Most Secure Way
888
+
889
+ ### Step 1: Install and Basic Setup
890
+
891
+ ```bash
892
+ pip install streaming-sql-engine
893
+ ```
894
+
895
+ ### Step 2: Use the Default Configuration (Most Stable)
896
+
897
+ **This is the safest way to start** — it handles all edge cases, works with any data types, and requires no special configuration:
898
+
899
+ ```python
900
+ from streaming_sql_engine import Engine
901
+
902
+ # Default configuration: Most stable and reliable
903
+ engine = Engine() # use_polars=False (default)
904
+
905
+ # Register your data sources
906
+ def postgres_users():
907
+ # Your PostgreSQL connection code
908
+ for row in cursor:
909
+ yield {"id": row[0], "name": row[1]}
910
+
911
+ def mysql_orders():
912
+ # Your MySQL connection code
913
+ for row in cursor:
914
+ yield {"id": row[0], "user_id": row[1], "total": row[2]}
915
+
916
+ engine.register("users", postgres_users)
917
+ engine.register("orders", mysql_orders)
918
+
919
+ # Write SQL queries
920
+ query = """
921
+ SELECT users.name, orders.total
922
+ FROM users
923
+ JOIN orders ON users.id = orders.user_id
924
+ WHERE orders.total > 100
925
+ """
926
+
927
+ # Execute and iterate results
928
+ for row in engine.query(query):
929
+ print(row)
930
+ ```
931
+
932
+ **Why This Configuration is Best to Start:**
933
+
934
+ - **Most Stable**: Handles mixed data types gracefully
935
+ - **No Schema Errors**: No type inference issues
936
+ - **Works Everywhere**: No external dependencies required
937
+ - **Reliable**: Battle-tested Python code
938
+ - **Fast for Small-Medium Data**: 0.72s for 10K rows
939
+
940
+ **Use this when:**
941
+
942
+ - You're just getting started
943
+ - Your datasets are < 100K rows
944
+ - You have mixed data types
945
+ - You need maximum reliability
946
+ - Polars is not available
947
+
948
+ ---
949
+
950
+ ## Experimenting with Options
951
+
952
+ Once you're comfortable with the basics, you can experiment with different options to optimize for your specific use case.
953
+
954
+ ### Option 1: Enable Debug Mode
955
+
956
+ See what's happening under the hood:
957
+
958
+ ```python
959
+ engine = Engine(debug=True) # Shows execution details
960
+ ```
961
+
962
+ **Output:**
963
+
964
+ ```
965
+ ============================================================
966
+ STREAMING SQL ENGINE - DEBUG MODE
967
+ ============================================================
968
+
969
+ [1/3] PARSING SQL QUERY...
970
+ SQL parsed successfully
971
+
972
+ [2/3] BUILDING LOGICAL PLAN...
973
+ Logical plan built
974
+
975
+ [3/3] EXECUTING QUERY...
976
+ Using LOOKUP JOIN (building index...)
977
+ ```
978
+
979
+ ---
980
+
981
+ ### Option 2: Enable Polars (For Large Datasets)
982
+
983
+ **When to use**: Large datasets (> 100K rows), consistent data types
984
+
985
+ ```python
986
+ engine = Engine(use_polars=True) # Enable Polars for speed
987
+ ```
988
+
989
+ **Benefits:**
990
+
991
+ - Faster for large datasets (vectorized operations)
992
+ - SIMD acceleration
993
+ - Better for consistent schemas
994
+
995
+ **Trade-offs:**
996
+
997
+ - Requires data normalization (consistent types)
998
+ - Can fail on mixed types
999
+ - Requires Polars dependency
1000
+
1001
+ **Example:**
1002
+
1003
+ ```python
1004
+ engine = Engine(use_polars=True)
1005
+
1006
+ # Make sure your data has consistent types
1007
+ def normalized_source():
1008
+ for row in raw_source():
1009
+ yield {
1010
+ "id": int(row.get("id", 0)),
1011
+ "price": float(row.get("price", 0.0)),
1012
+ "name": str(row.get("name", "")),
1013
+ }
1014
+
1015
+ engine.register("products", normalized_source)
1016
+ ```
1017
+
1018
+ ---
1019
+
1020
+ ### Option 3: Enable MMAP (For Large Files)
1021
+
1022
+ **When to use**: Large files (> 100MB), memory-constrained systems
1023
+
1024
+ ```python
1025
+ engine = Engine()
1026
+ engine.register("products", source, filename="products.jsonl") # MMAP enabled
1027
+ ```
1028
+
1029
+ **Benefits:**
1030
+
1031
+ - 90-99% memory reduction
1032
+ - Works with files larger than RAM
1033
+ - OS-managed memory mapping
1034
+
1035
+ **Trade-offs:**
1036
+
1037
+ - Requires file-based sources
1038
+ - Slower for small files (overhead)
1039
+
1040
+ **Example:**
1041
+
1042
+ ```python
1043
+ engine = Engine()
1044
+
1045
+ def jsonl_source():
1046
+ with open("products.jsonl", "r") as f:
1047
+ for line in f:
1048
+ if line.strip():
1049
+ yield json.loads(line)
1050
+
1051
+ engine.register("products", jsonl_source, filename="products.jsonl")
1052
+ ```
1053
+
1054
+ ---
1055
+
1056
+ ### Option 4: Enable Merge Join (For Sorted Data)
1057
+
1058
+ **When to use**: Pre-sorted data, memory-constrained environments
1059
+
1060
+ ```python
1061
+ engine = Engine()
1062
+ engine.register("products", source, ordered_by="id") # Merge join enabled
1063
+ ```
1064
+
1065
+ **Benefits:**
1066
+
1067
+ - Lowest memory usage (no index needed)
1068
+ - Fast for sorted data
1069
+ - Streaming algorithm
1070
+
1071
+ **Trade-offs:**
1072
+
1073
+ - Requires pre-sorted data
1074
+ - Both tables must be sorted
1075
+
1076
+ **Example:**
1077
+
1078
+ ```python
1079
+ engine = Engine()
1080
+
1081
+ # Data must be sorted by join key
1082
+ def sorted_users():
1083
+ # Users sorted by id
1084
+ return iter([
1085
+ {"id": 1, "name": "Alice"},
1086
+ {"id": 2, "name": "Bob"},
1087
+ {"id": 3, "name": "Charlie"},
1088
+ ])
1089
+
1090
+ def sorted_orders():
1091
+ # Orders sorted by user_id
1092
+ return iter([
1093
+ {"id": 1, "user_id": 1, "total": 100},
1094
+ {"id": 2, "user_id": 2, "total": 200},
1095
+ ])
1096
+
1097
+ engine.register("users", sorted_users, ordered_by="id")
1098
+ engine.register("orders", sorted_orders, ordered_by="user_id")
1099
+ ```
1100
+
1101
+ ---
1102
+
1103
+ ## Advanced: Mixing Options
1104
+
1105
+ ### Mix 1: MMAP with Polars Index Building (Best for Large Files)
1106
+
1107
+ **Important Note:** When `use_polars=False` (default), the engine uses **MMAP Join** or **Merge Join** when available. When `use_polars=True` is explicitly set, the engine uses **Polars Join** (not MMAP Join).
1108
+
1109
+ However, **MMAP can use Polars internally** for faster index building even when `use_polars=False`:
1110
+
1111
+ ```python
1112
+ engine = Engine(use_polars=False) # MMAP Join will be used
1113
+ engine.register("products", source, filename="products.jsonl") # MMAP for memory
1114
+ # MMAP will use Polars internally for index building if available
1115
+ ```
1116
+
1117
+ **What You Get:**
1118
+
1119
+ - Low memory (MMAP 90-99% reduction)
1120
+ - Fast index building (if Polars is installed, used internally)
1121
+ - Best balance for large files with memory constraints
1122
+
1123
+ **Performance:**
1124
+
1125
+ - Time: 8-15s for 500MB files (with Polars for index building)
1126
+ - Memory: 0.01 MB (vs 500MB+ without MMAP)
1127
+
1128
+ **When to Use:**
1129
+
1130
+ - Large files (> 100MB)
1131
+ - Memory-constrained systems
1132
+ - When you want MMAP Join (not Polars Join)
1133
+
1134
+ **Note:** If you set `use_polars=True`, the engine will use **Polars Join** instead of MMAP Join, prioritizing speed over memory efficiency.
1135
+
1136
+ ---
1137
+
1138
+ ### Mix 2: Polars + Column Pruning (For Wide Tables)
1139
+
1140
+ **Optimize for tables with many columns:**
1141
+
1142
+ ```python
1143
+ engine = Engine(use_polars=True)
1144
+
1145
+ def optimized_source(dynamic_columns=None):
1146
+ # Only read requested columns
1147
+ if dynamic_columns:
1148
+ columns = dynamic_columns
1149
+ else:
1150
+ columns = ["id", "name", "price", "description", "category", ...] # All columns
1151
+
1152
+ for row in read_data(columns):
1153
+ yield row
1154
+
1155
+ engine.register("products", optimized_source)
1156
+ ```
1157
+
1158
+ **What You Get:**
1159
+
1160
+ - Reduced I/O (only reads needed columns)
1161
+ - Faster queries (less data to process)
1162
+ - Lower memory usage
1163
+
1164
+ ---
1165
+
1166
+ ### Mix 3: Polars + Filter Pushdown (For Selective Queries)
1167
+
1168
+ **Optimize when queries filter most rows:**
1169
+
1170
+ ```python
1171
+ engine = Engine(use_polars=True)
1172
+
1173
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1174
+ # Apply WHERE clause at source level
1175
+ query = "SELECT * FROM products"
1176
+ if dynamic_where:
1177
+ query += f" WHERE {dynamic_where}"
1178
+
1179
+ for row in execute_query(query):
1180
+ yield row
1181
+
1182
+ engine.register("products", optimized_source)
1183
+ ```
1184
+
1185
+ **What You Get:**
1186
+
1187
+ - Early filtering (reduces data volume)
1188
+ - Faster execution (less data to process)
1189
+ - Lower memory usage
1190
+
1191
+ ---
1192
+
1193
+ ### Mix 4: All Optimizations Combined
1194
+
1195
+ **The Ultimate Configuration** for maximum performance:
1196
+
1197
+ ```python
1198
+ engine = Engine(use_polars=True)
1199
+
1200
+ def ultimate_source(dynamic_where=None, dynamic_columns=None):
1201
+ """
1202
+ Source with all optimizations:
1203
+ - Filter pushdown (dynamic_where)
1204
+ - Column pruning (dynamic_columns)
1205
+ - Data normalization (for Polars)
1206
+ """
1207
+ # Build optimized query
1208
+ query = build_query(dynamic_where, dynamic_columns)
1209
+
1210
+ for row in execute_query(query):
1211
+ # Normalize types for Polars stability
1212
+ yield normalize_types(row)
1213
+
1214
+ engine.register("products", ultimate_source, filename="products.jsonl")
1215
+ ```
1216
+
1217
+ **What You Get:**
1218
+
1219
+ - Polars Join (speed) - when `use_polars=True`
1220
+ - Column Pruning (I/O)
1221
+ - Filter Pushdown (early filtering)
1222
+
1223
+ **Best for:** Very large datasets (> 1M rows) when speed is priority
1224
+
1225
+ **Note:** This uses Polars Join, not MMAP Join. For memory-constrained scenarios, use `use_polars=False` with `filename` parameter instead.
1226
+
1227
+ ---
1228
+
1229
+ ## Performance Guide
1230
+
1231
+ ### By Dataset Size
1232
+
1233
+ | Size | Configuration | Why |
1234
+ | ----------------- | ------------------------------- | ----------------------------------------- |
1235
+ | **< 10K rows** | `use_polars=False` (default) | Fastest, most stable |
1236
+ | **10K-100K rows** | `use_polars=False` (default) | Still fastest, handles mixed types |
1237
+ | **100K-1M rows** | `use_polars=True` OR `filename` | Polars Join (speed) OR MMAP Join (memory) |
1238
+ | **> 1M rows** | All optimizations | Maximum performance |
1239
+
1240
+ ### By Priority
1241
+
1242
+ **Priority: Stability** - Use default (`use_polars=False`)
1243
+
1244
+ ```python
1245
+ engine = Engine() # Most stable
1246
+ ```
1247
+
1248
+ **Priority: Speed** - Use Polars
1249
+
1250
+ ```python
1251
+ engine = Engine(use_polars=True) # Fastest for large datasets
1252
+ ```
1253
+
1254
+ **Priority: Memory** - Use MMAP
1255
+
1256
+ ```python
1257
+ engine = Engine()
1258
+ engine.register("table", source, filename="data.jsonl") # Lowest memory
1259
+ ```
1260
+
1261
+ **Priority: Both** - Choose based on priority:
1262
+
1263
+ **If speed is more important:**
1264
+
1265
+ ```python
1266
+ engine = Engine(use_polars=True) # Uses Polars Join (fastest)
1267
+ engine.register("table", source) # No filename - Polars Join
1268
+ ```
1269
+
1270
+ **If memory is more important:**
1271
+
1272
+ ```python
1273
+ engine = Engine(use_polars=False) # Uses MMAP Join (lowest memory)
1274
+ engine.register("table", source, filename="data.jsonl") # MMAP Join
1275
+ ```
1276
+
1277
+ **Note:** Polars Join and MMAP Join are mutually exclusive - the engine chooses one based on `use_polars` flag. MMAP Join can use Polars internally for index building, but the join algorithm itself is MMAP.
1278
+
1279
+ ---
1280
+
1281
+ ## Learning Path
1282
+
1283
+ ### Level 1: Beginner (Start Here)
1284
+
1285
+ ```python
1286
+ # Most stable configuration
1287
+ engine = Engine() # Default: use_polars=False
1288
+ engine.register("table1", source1)
1289
+ engine.register("table2", source2)
1290
+ ```
1291
+
1292
+ **Learn:**
1293
+
1294
+ - Basic source registration
1295
+ - Simple SQL queries
1296
+ - How joins work
1297
+
1298
+ ---
1299
+
1300
+ ### Level 2: Intermediate
1301
+
1302
+ ```python
1303
+ # Add debug mode to see what's happening
1304
+ engine = Engine(debug=True)
1305
+
1306
+ # Experiment with Polars for large datasets
1307
+ engine = Engine(use_polars=True)
1308
+ ```
1309
+
1310
+ **Learn:**
1311
+
1312
+ - Debug output
1313
+ - When to use Polars
1314
+ - Data normalization
1315
+
1316
+ ---
1317
+
1318
+ ### Level 3: Advanced
1319
+
1320
+ ```python
1321
+ # Use MMAP for large files (requires use_polars=False)
1322
+ engine = Engine(use_polars=False) # MMAP Join requires use_polars=False
1323
+ engine.register("table", source, filename="data.jsonl")
1324
+
1325
+ # Use Merge Join for sorted data
1326
+ engine.register("table", source, ordered_by="key")
1327
+ ```
1328
+
1329
+ **Learn:**
1330
+
1331
+ - MMAP for memory efficiency
1332
+ - Merge Join for sorted data
1333
+ - Protocol optimizations
1334
+
1335
+ ---
1336
+
1337
+ ### Level 4: Expert
1338
+
1339
+ ```python
1340
+ # All optimizations combined
1341
+ engine = Engine(use_polars=True)
1342
+
1343
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1344
+ # Filter pushdown + Column pruning
1345
+ pass
1346
+
1347
+ engine.register("table", optimized_source, filename="data.jsonl")
1348
+ ```
1349
+
1350
+ **Learn:**
1351
+
1352
+ - Protocol-based optimizations
1353
+ - Combining all options
1354
+ - Maximum performance tuning
1355
+
1356
+ ---
1357
+
1358
+ ## Common Pitfalls
1359
+
1360
+ ### Pitfall 1: Using Polars Without Normalization
1361
+
1362
+ **Problem:**
1363
+
1364
+ ```python
1365
+ engine = Engine(use_polars=True)
1366
+ # Mixed types cause schema inference errors
1367
+ ```
1368
+
1369
+ **Solution:**
1370
+
1371
+ ```python
1372
+ def normalized_source():
1373
+ for row in raw_source():
1374
+ yield {
1375
+ "id": int(row.get("id", 0)),
1376
+ "price": float(row.get("price", 0.0)),
1377
+ }
1378
+ ```
1379
+
1380
+ ---
1381
+
1382
+ ### Pitfall 2: Using MMAP Without Polars (Very Slow)
1383
+
1384
+ **Problem:**
1385
+
1386
+ ```python
1387
+ engine = Engine(use_polars=False)
1388
+ engine.register("table", source, filename="data.jsonl") # Very slow!
1389
+ ```
1390
+
1391
+ **Solution:**
1392
+
1393
+ ```python
1394
+ engine = Engine(use_polars=True) # Polars speeds up MMAP index building
1395
+ engine.register("table", source, filename="data.jsonl")
1396
+ ```
1397
+
1398
+ ---
1399
+
1400
+ ### Pitfall 3: Using MMAP for Small Files
1401
+
1402
+ **Problem:**
1403
+
1404
+ ```python
1405
+ # MMAP overhead > benefit for small files
1406
+ engine.register("table", source, filename="small.jsonl") # Slower!
1407
+ ```
1408
+
1409
+ **Solution:**
1410
+
1411
+ ```python
1412
+ # No filename for small files
1413
+ engine.register("table", source) # Faster for < 100MB
1414
+ ```
1415
+
1416
+ ---
1417
+
1418
+ ## Quick Decision Guide
1419
+
1420
+ - **Just starting?** Use default (`Engine()`)
1421
+ - **Have large datasets?** Use `use_polars=True`
1422
+ - **Memory constrained?** Use `filename` parameter (MMAP)
1423
+ - **Data is sorted?** Use `ordered_by` parameter (Merge Join)
1424
+ - **Want maximum performance?** Use `use_polars=True` + protocols (Polars Join) OR `use_polars=False` + `filename` (MMAP Join) + protocols
1425
+
1426
+ ---
1427
+
1428
+ ## Real-World Example: Complete Workflow
1429
+
1430
+ ### Step 1: Start Simple (Most Secure)
1431
+
1432
+ ```python
1433
+ from streaming_sql_engine import Engine
1434
+
1435
+ # Start with default (most stable)
1436
+ engine = Engine()
1437
+
1438
+ def postgres_users():
1439
+ # Your PostgreSQL code
1440
+ pass
1441
+
1442
+ def mysql_orders():
1443
+ # Your MySQL code
1444
+ pass
1445
+
1446
+ engine.register("users", postgres_users)
1447
+ engine.register("orders", mysql_orders)
1448
+
1449
+ results = engine.query("SELECT * FROM users JOIN orders ON users.id = orders.user_id")
1450
+ ```
1451
+
1452
+ ### Step 2: Add Debug Mode (Understand What's Happening)
1453
+
1454
+ ```python
1455
+ engine = Engine(debug=True) # See execution details
1456
+ ```
1457
+
1458
+ ### Step 3: Optimize for Your Use Case
1459
+
1460
+ **If you have large datasets:**
1461
+
1462
+ ```python
1463
+ engine = Engine(use_polars=True) # Enable Polars
1464
+ ```
1465
+
1466
+ **If you have large files:**
1467
+
1468
+ ```python
1469
+ engine = Engine(use_polars=False) # MMAP Join requires use_polars=False
1470
+ engine.register("table", source, filename="data.jsonl") # Enable MMAP
1471
+ ```
1472
+
1473
+ **If you have sorted data:**
1474
+
1475
+ ```python
1476
+ engine.register("table", source, ordered_by="key") # Enable Merge Join
1477
+ ```
1478
+
1479
+ ### Step 4: Combine Optimizations
1480
+
1481
+ **For Speed Priority (Polars Join):**
1482
+
1483
+ ```python
1484
+ engine = Engine(use_polars=True) # Uses Polars Join
1485
+
1486
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1487
+ # Supports all optimizations
1488
+ pass
1489
+
1490
+ engine.register("table", optimized_source) # No filename - Polars Join
1491
+ ```
1492
+
1493
+ **For Memory Priority (MMAP Join):**
1494
+
1495
+ ```python
1496
+ engine = Engine(use_polars=False) # Uses MMAP Join
1497
+
1498
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1499
+ # Supports all optimizations
1500
+ pass
1501
+
1502
+ engine.register("table", optimized_source, filename="data.jsonl") # MMAP Join
1503
+ ```
1504
+
1505
+ ---
1506
+
1507
+ ## Summary
1508
+
1509
+ ### Start Here (Most Secure)
1510
+
1511
+ ```python
1512
+ engine = Engine() # Default: use_polars=False
1513
+ engine.register("table1", source1)
1514
+ engine.register("table2", source2)
1515
+ ```
1516
+
1517
+ **Why:** Most stable, handles all edge cases, works with any data types
1518
+
1519
+ ---
1520
+
1521
+ ### Then Experiment
1522
+
1523
+ 1. **Add debug mode**: `Engine(debug=True)` - See what's happening
1524
+ 2. **Try Polars**: `Engine(use_polars=True)` - For large datasets
1525
+ 3. **Try MMAP**: `filename="data.jsonl"` - For large files
1526
+ 4. **Try Merge Join**: `ordered_by="key"` - For sorted data
1527
+
1528
+ ---
1529
+
1530
+ ### Advanced: Mix Options
1531
+
1532
+ **Best Mix for Large Files:**
1533
+
1534
+ **Option 1: Speed Priority (Polars Join)**
1535
+
1536
+ ```python
1537
+ engine = Engine(use_polars=True) # Uses Polars Join (fastest)
1538
+ engine.register("table", source) # No filename needed
1539
+ ```
1540
+
1541
+ **Option 2: Memory Priority (MMAP Join)**
1542
+
1543
+ ```python
1544
+ engine = Engine(use_polars=False) # Uses MMAP Join (lowest memory)
1545
+ engine.register("table", source, filename="data.jsonl") # MMAP enabled
1546
+ ```
1547
+
1548
+ **Best Mix for Maximum Performance:**
1549
+
1550
+ **Option 1: Speed Priority (Polars Join + Protocols)**
1551
+
1552
+ ```python
1553
+ engine = Engine(use_polars=True) # Uses Polars Join
1554
+
1555
+ def source(dynamic_where=None, dynamic_columns=None):
1556
+ # All optimizations (filter pushdown + column pruning)
1557
+ pass
1558
+
1559
+ engine.register("table", source) # No filename - Polars Join
1560
+ ```
1561
+
1562
+ **Option 2: Memory Priority (MMAP Join + Protocols)**
1563
+
1564
+ ```python
1565
+ engine = Engine(use_polars=False) # Uses MMAP Join
1566
+
1567
+ def source(dynamic_where=None, dynamic_columns=None):
1568
+ # All optimizations (filter pushdown + column pruning)
1569
+ pass
1570
+
1571
+ engine.register("table", source, filename="data.jsonl") # MMAP Join
1572
+ ```
1573
+
1574
+ ---
1575
+
1576
+ ## Key Takeaways
1577
+
1578
+ 1. **Start Simple**: Use default configuration (`Engine()`) - it's the most stable
1579
+ 2. **Experiment Gradually**: Add options one at a time to understand their impact
1580
+ 3. **Mix Wisely**: Choose Polars Join (speed) OR MMAP Join (memory) based on priority
1581
+ 4. **Know When to Use Each**: Small files: default, Large files: Polars Join (speed) OR MMAP Join (memory)
1582
+
1583
+ ---
1584
+
1585
+ **Remember**: Start with the default configuration, then experiment with options as you understand your data and performance needs better.
1586
+
1587
+ ## Getting Started
1588
+
1589
+ Installation:
1590
+
1591
+ ```bash
1592
+ pip install streaming-sql-engine
1593
+ ```
1594
+
1595
+ Quick start:
1596
+
1597
+ ```python
1598
+ from streaming_sql_engine import Engine
1599
+
1600
+ engine = Engine()
1601
+
1602
+ # Register data sources (any Python function that returns an iterator)
1603
+ def users_source():
1604
+ return iter([
1605
+ {"id": 1, "name": "Alice", "dept_id": 10},
1606
+ {"id": 2, "name": "Bob", "dept_id": 20},
1607
+ ])
1608
+
1609
+ def departments_source():
1610
+ return iter([
1611
+ {"id": 10, "name": "Engineering"},
1612
+ {"id": 20, "name": "Sales"},
1613
+ ])
1614
+
1615
+ engine.register("users", users_source)
1616
+ engine.register("departments", departments_source)
1617
+
1618
+ # Execute SQL query
1619
+ query = """
1620
+ SELECT users.name, departments.name AS dept
1621
+ FROM users
1622
+ JOIN departments ON users.dept_id = departments.id
1623
+ """
1624
+
1625
+ for row in engine.query(query):
1626
+ print(row)
1627
+ # Output:
1628
+ # {'users.name': 'Alice', 'departments.name': 'Engineering'}
1629
+ # {'users.name': 'Bob', 'departments.name': 'Sales'}
1630
+ ```
1631
+
1632
+ **For database connections**, create iterator functions:
1633
+
1634
+ ```python
1635
+ from streaming_sql_engine import Engine
1636
+ import psycopg2
1637
+
1638
+ engine = Engine()
1639
+
1640
+ # Register database table (iterator function)
1641
+ def users_source():
1642
+ conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")
1643
+ cursor = conn.cursor()
1644
+ cursor.execute("SELECT id, name, email FROM users WHERE active = true")
1645
+ for row in cursor:
1646
+ yield {"id": row[0], "name": row[1], "email": row[2]}
1647
+ conn.close()
1648
+
1649
+ engine.register("users", users_source)
1650
+
1651
+ # Query
1652
+ for row in engine.query("SELECT * FROM users WHERE users.active = true"):
1653
+ print(row)
1654
+ ```
1655
+
1656
+ ---
1657
+
1658
+ ## Conclusion
1659
+
1660
+ 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.
1661
+
1662
+ **Key strengths:**
1663
+
1664
+ - Cross-system joins (databases, APIs, files)
1665
+ - Zero infrastructure requirements
1666
+ - Memory-efficient streaming architecture
1667
+ - Python-native integration
1668
+ - Automatic optimizations
1669
+ - Simple deployment
1670
+
1671
+ **Best suited for:**
1672
+
1673
+ - Microservices data aggregation
1674
+ - Cross-system ETL pipelines
1675
+ - Real-time data integration
1676
+ - Memory-constrained environments
1677
+ - Python-native workflows
1678
+
1679
+ For cross-system data integration, the Streaming SQL Engine provides a unique solution that balances performance, simplicity, and flexibility.
1680
+
1681
+ ---
1682
+
1683
+ ## Resources
1684
+
1685
+ - **PyPI:** `pip install streaming-sql-engine`
1686
+ - **Bug Reports:** `"https://github.com/Ierofantis/streaming_sql_engine/issues"`,
1687
+ - **Source":** `"https://github.com/Ierofantis/streaming_sql_engine/"`,
1688
+ - **Documentation":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/README.md"`,
1689
+ - **Scientific Paper":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/Streaming_SQL_Engine_Paper.pdf"`
1690
+
1691
+ ---