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