streaming-sql-engine 0.1.22__tar.gz → 0.1.24__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/PKG-INFO +729 -367
  2. streaming_sql_engine-0.1.22/streaming_sql_engine.egg-info/PKG-INFO → streaming_sql_engine-0.1.24/README.md +1796 -1480
  3. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/engine.py +2 -2
  4. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/executor.py +2 -2
  5. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/pyproject.toml +2 -2
  6. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/setup.py +1 -1
  7. streaming_sql_engine-0.1.22/README.md → streaming_sql_engine-0.1.24/streaming_sql_engine.egg-info/PKG-INFO +1842 -1434
  8. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/streaming_sql_engine.egg-info/SOURCES.txt +2 -1
  9. streaming_sql_engine-0.1.24/tests/test_readme_cases.py +923 -0
  10. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/DEPLOYMENT.md +0 -0
  11. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/MANIFEST.in +0 -0
  12. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/QUICK_DEPLOY.md +0 -0
  13. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/QUICK_FIX.md +0 -0
  14. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/RELEASE_READINESS_1.0.0.md +0 -0
  15. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/__init__.py +0 -0
  16. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/debug_tests.py +0 -0
  17. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/APACHE_DRILL_COMPARISON.md +0 -0
  18. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/API_JOIN_OPERATIONS.md +0 -0
  19. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/ARCHITECTURAL_RECOMMENDATION.md +0 -0
  20. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/ARCHITECTURE_DECISION.md +0 -0
  21. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/ARCHITECTURE_SYNCED.md +0 -0
  22. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/BEST_USE_CASES.md +0 -0
  23. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/BETTER_FILTER_APPROACH.md +0 -0
  24. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/CARTESIAN_PRODUCTS_CAUSES.md +0 -0
  25. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/CHANGES_SUMMARY.md +0 -0
  26. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/COMPREHENSIVE_ARTICLE.md +0 -0
  27. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/COMPREHENSIVE_DOCUMENTATION.md +0 -0
  28. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/DEVELOPER_GUIDE.md +0 -0
  29. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/DUCKDB_COMPARISON.md +0 -0
  30. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/ENGINE_OPTIONS_REFERENCE.md +0 -0
  31. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/FINAL_IMPLEMENTATION_RECOMMENDATIONS.md +0 -0
  32. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/FINAL_RECOMMENDATION.md +0 -0
  33. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/FIRST_MATCH_ONLY_WARNINGS.md +0 -0
  34. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/HANDLING_DUPLICATES_WITHOUT_CARTESIAN.md +0 -0
  35. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/HOW_PROTOCOL_DETECTION_WORKS.md +0 -0
  36. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/HOW_TO_ADD_TO_PROJECT.md +0 -0
  37. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/INSTALLATION.md +0 -0
  38. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/JSONL_EXECUTOR_ANALYSIS.md +0 -0
  39. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/JSONL_EXECUTOR_REMOVED.md +0 -0
  40. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/LIBRARY_DOCUMENTATION.md +0 -0
  41. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MEDIUM_ARTICLE.md +0 -0
  42. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MEDIUM_ARTICLE_SIMPLIFIED.md +0 -0
  43. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MIGRATION_GUIDE.md +0 -0
  44. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MMAP_WITHOUT_POLARS_SLOW.md +0 -0
  45. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MOST_STABLE_AND_PERFORMANT.md +0 -0
  46. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MULTI_SOURCE_EXAMPLE_README.md +0 -0
  47. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/MYSQL_USAGE.md +0 -0
  48. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/OPTIMIZATIONS_BREAKDOWN.md +0 -0
  49. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/OPTIMIZATIONS_NOT_DATABASE_ONLY.md +0 -0
  50. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/OPTIMIZATIONS_VS_POLARS.md +0 -0
  51. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/OPTIMIZER_AUTOMATED.md +0 -0
  52. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/PERFORMANCE.md +0 -0
  53. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/PERFORMANCE_COMPARISON.md +0 -0
  54. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/POLARS_AND_MMAP_GUIDE.md +0 -0
  55. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/POLARS_VS_POLARS_MMAP.md +0 -0
  56. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/PROTOCOL_AND_OPTIMIZATIONS_EXPLAINED.md +0 -0
  57. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/PROTOCOL_EXPLANATION.md +0 -0
  58. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/PUBLISHING.md +0 -0
  59. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/PYPI_CHECKLIST.md +0 -0
  60. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/QUICK_PUBLISH.md +0 -0
  61. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/QUICK_START.md +0 -0
  62. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/SIMPLE_PROTOCOL_GUIDE.md +0 -0
  63. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/SIMPLE_SOURCE_FUNCTIONS.md +0 -0
  64. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/SOURCE_COMBINATIONS_GUIDE.md +0 -0
  65. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/TECHNICAL_DOCUMENTATION.md +0 -0
  66. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/USER_GUIDE.md +0 -0
  67. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHAT_IS_WHERE_TO_PARAMS.md +0 -0
  68. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHEN_POLARS_IS_USED.md +0 -0
  69. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHERE_POLARS_IS_USED.md +0 -0
  70. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHY_API_CONVERTER_NEEDED.md +0 -0
  71. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHY_MANUAL_PARSING.md +0 -0
  72. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHY_ORIGINAL_IS_FASTER.md +0 -0
  73. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/WHY_PROTOCOL_IN_SOURCES.md +0 -0
  74. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/documentation/XML_MONGO_USE_CASE.md +0 -0
  75. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/evaluator.py +0 -0
  76. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/mmap_index.py +0 -0
  77. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/operators.py +0 -0
  78. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/operators_mmap.py +0 -0
  79. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/operators_polars.py +0 -0
  80. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/optimizer.py +0 -0
  81. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/parser.py +0 -0
  82. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/planner.py +0 -0
  83. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/polars_expression_translator.py +0 -0
  84. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/polars_operators.py +0 -0
  85. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/pre_release_test.py +0 -0
  86. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/protocol_helpers.py +0 -0
  87. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/quick_test.py +0 -0
  88. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/requirements.txt +0 -0
  89. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/setup.cfg +0 -0
  90. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/streaming_sql_engine.egg-info/dependency_links.txt +0 -0
  91. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/streaming_sql_engine.egg-info/requires.txt +0 -0
  92. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/streaming_sql_engine.egg-info/top_level.txt +0 -0
  93. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/test_full_pipeline.py +0 -0
  94. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/test_polars_fixes.py +0 -0
  95. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/test_polars_schema_fix.py +0 -0
  96. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/test_where_debug.py +0 -0
  97. {streaming_sql_engine-0.1.22 → streaming_sql_engine-0.1.24}/tests/test_engine_options.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streaming-sql-engine
3
- Version: 0.1.22
3
+ Version: 0.1.24
4
4
  Summary: A lightweight SQL execution engine for streaming row-by-row queries with joins across multiple data sources
5
5
  Home-page: https://github.com/Ierofantis/streaming-sql-engine/tree/master
6
6
  Author: Theodore Pantazopoulo
@@ -46,11 +46,9 @@ Dynamic: requires-python
46
46
 
47
47
  # Join Data from Anywhere: The Streaming SQL Engine That Bridges Databases, APIs, and Files
48
48
 
49
- ## How I Built a Python Library That Lets You Join MySQL, PostgreSQL, MongoDB, REST APIs, and Files in a Single SQL Query
50
-
51
49
  ---
52
50
 
53
- _Have you ever needed to join data from a MySQL database with a PostgreSQL database, a MongoDB collection, and a REST API — all in one query? Traditional databases can't do this. That's why I built the Streaming SQL Engine._
51
+ Have you ever needed to join data from a MySQL database with a PostgreSQL database, a MongoDB collection, and a REST API — all in one query? Traditional databases can't do this. That's why I built the Streaming SQL Engine.\_
54
52
 
55
53
  ---
56
54
 
@@ -193,284 +191,6 @@ The engine follows a **pipeline architecture** inspired by database query execut
193
191
 
194
192
  **Key insight:** Python's iterator protocol is perfect for streaming data. Each operator in the pipeline is an iterator that processes rows one at a time.
195
193
 
196
- ### The Architecture: Four Layers
197
-
198
- #### Layer 1: SQL Parsing
199
-
200
- **Technology:** Uses `sqlglot` library for SQL parsing
201
-
202
- **Why sqlglot:**
203
-
204
- - Supports multiple SQL dialects (MySQL, PostgreSQL, SQLite)
205
- - Produces a standard AST (Abstract Syntax Tree)
206
- - Handles SQL parsing edge cases
207
- - No need to write a parser from scratch
208
-
209
- **How it works:**
210
-
211
- ```python
212
- def parse_sql(sql: str):
213
- # Try multiple dialects
214
- for dialect in ['mysql', 'postgres', 'sqlite']:
215
- try:
216
- ast = sqlglot.parse_one(sql, dialect=dialect)
217
- return ast
218
- except:
219
- continue
220
- raise ValueError("Could not parse SQL")
221
- ```
222
-
223
- **Logic:** The parser converts SQL string into an AST, which is a tree structure representing the query. This AST is then used by the planner to build an execution plan.
224
-
225
- #### Layer 2: Logical Planning
226
-
227
- **Purpose:** Convert AST into a logical execution plan
228
-
229
- **What it extracts:**
230
-
231
- - Root table (the table in FROM clause)
232
- - Join information (which tables to join, on what keys)
233
- - WHERE clause conditions
234
- - SELECT projections (which columns to return)
235
-
236
- **Key design decision:** Separate logical planning from execution. This allows:
237
-
238
- - Query optimization before execution
239
- - Reuse of planning logic
240
- - Easier testing and debugging
241
-
242
- **How it works:**
243
-
244
- ```python
245
- class LogicalPlan:
246
- root_table: str
247
- joins: List[JoinInfo]
248
- where_expr: Optional[Expression]
249
- projections: List[str]
250
- required_columns: Dict[str, List[str]] # Column pruning
251
- pushable_where_expr: Optional[Expression] # Filter pushdown
252
- ```
253
-
254
- **Logic:** The planner walks the AST tree, extracting information about tables, joins, filters, and projections. It identifies which columns are needed from each table (for column pruning) and which WHERE conditions can be pushed to sources (for filter pushdown).
255
-
256
- #### Layer 3: Optimization
257
-
258
- **Two main optimizations:**
259
-
260
- **1. Column Pruning**
261
-
262
- - Identifies which columns are actually needed
263
- - Only requests those columns from sources
264
- - Reduces I/O and memory usage
265
-
266
- **Logic:**
267
-
268
- ```python
269
- # Analyze SELECT clause
270
- required_columns = {}
271
- for projection in plan.projections:
272
- table_name = extract_table_name(projection)
273
- column_name = extract_column_name(projection)
274
- required_columns[table_name].add(column_name)
275
-
276
- # Also check WHERE clause - columns used in filters are needed
277
- for condition in plan.where_expr:
278
- table_name = extract_table_name(condition)
279
- column_name = extract_column_name(condition)
280
- required_columns[table_name].add(column_name)
281
- ```
282
-
283
- **2. Filter Pushdown**
284
-
285
- - Identifies WHERE conditions that reference only the root table
286
- - Pushes these conditions to the source function
287
- - Reduces data transfer from databases
288
-
289
- **Logic:**
290
-
291
- ```python
292
- # Check if WHERE condition only references root table
293
- def can_push_where(where_expr, root_table):
294
- referenced_tables = extract_table_references(where_expr)
295
- return len(referenced_tables) == 1 and root_table in referenced_tables
296
-
297
- if can_push_where(plan.where_expr, plan.root_table):
298
- pushable_where_expr = plan.where_expr
299
- ```
300
-
301
- **Protocol-based detection:** The engine automatically detects if a source function supports optimizations by checking if it accepts `dynamic_where` and `dynamic_columns` parameters:
302
-
303
- ```python
304
- import inspect
305
-
306
- def source_supports_optimizations(source_fn):
307
- sig = inspect.signature(source_fn)
308
- params = list(sig.parameters.keys())
309
- return 'dynamic_where' in params or 'dynamic_columns' in params
310
- ```
311
-
312
- **Why this approach:** No flags needed. If your source function accepts these parameters, optimizations apply automatically. This makes the engine flexible - any Python function can be a source, and optimizations work if the source supports them.
313
-
314
- #### Layer 4: Execution Pipeline
315
-
316
- **The iterator pipeline:** Each operator is a Python iterator that processes rows incrementally.
317
-
318
- **Pipeline structure:**
319
-
320
- ```
321
- ScanIterator → FilterIterator → JoinIterators → ProjectIterator → Results
322
- ```
323
-
324
- **How each iterator works:**
325
-
326
- **1. ScanIterator**
327
-
328
- - Reads rows from source function
329
- - Prefixes columns with table name (e.g., `id` becomes `users.id`)
330
- - Applies column pruning (only includes requested columns)
331
-
332
- **Logic:**
333
-
334
- ```python
335
- class ScanIterator:
336
- def __init__(self, source_fn, table_name, required_columns):
337
- self.source_fn = source_fn
338
- self.table_name = table_name
339
- self.required_columns = required_columns
340
-
341
- def __next__(self):
342
- row = next(self.source_iterator)
343
- # Column pruning
344
- if self.required_columns:
345
- row = {k: v for k, v in row.items() if k in self.required_columns}
346
- # Prefix columns with table name
347
- return {f"{self.table_name}.{k}": v for k, v in row.items()}
348
- ```
349
-
350
- **2. FilterIterator**
351
-
352
- - Applies WHERE clause conditions
353
- - Evaluates expressions row-by-row
354
- - Only yields rows that match conditions
355
-
356
- **Logic:**
357
-
358
- ```python
359
- class FilterIterator:
360
- def __init__(self, source_iterator, where_expr):
361
- self.source_iterator = source_iterator
362
- self.where_expr = where_expr
363
-
364
- def __next__(self):
365
- while True:
366
- row = next(self.source_iterator)
367
- if evaluate_expression(self.where_expr, row):
368
- return row
369
- # Skip rows that don't match
370
- ```
371
-
372
- **3. JoinIterators (LookupJoinIterator, MergeJoinIterator)**
373
-
374
- - **LookupJoinIterator:** Builds hash index on right side, looks up each left row
375
- - **MergeJoinIterator:** Both sides sorted, merges like merge sort algorithm
376
-
377
- **LookupJoinIterator logic:**
378
-
379
- ```python
380
- class LookupJoinIterator:
381
- def __init__(self, left_iterator, right_source_fn, left_key, right_key):
382
- self.left_iterator = left_iterator
383
- self.right_source_fn = right_source_fn
384
- self.left_key = left_key
385
- self.right_key = right_key
386
- self.index = None # Hash index on right side
387
-
388
- def _build_index(self):
389
- """Build hash index on right side - O(n) time, O(n) space"""
390
- self.index = {}
391
- for right_row in self.right_source_fn():
392
- key = right_row[self.right_key]
393
- if key not in self.index:
394
- self.index[key] = []
395
- self.index[key].append(right_row)
396
-
397
- def __next__(self):
398
- if self.index is None:
399
- self._build_index()
400
-
401
- left_row = next(self.left_iterator)
402
- left_key_value = left_row[self.left_key]
403
-
404
- # Lookup in index - O(1) time
405
- matching_right_rows = self.index.get(left_key_value, [])
406
-
407
- for right_row in matching_right_rows:
408
- # Merge left and right rows
409
- merged_row = {**left_row, **right_row}
410
- yield merged_row
411
- ```
412
-
413
- **Why hash index:** O(1) lookup time per left row. Trade-off: O(n) memory for right side, but this is necessary for efficient joins.
414
-
415
- **MergeJoinIterator logic:**
416
-
417
- ```python
418
- class MergeJoinIterator:
419
- def __init__(self, left_iterator, right_iterator, left_key, right_key):
420
- self.left_iterator = left_iterator
421
- self.right_iterator = right_iterator
422
- self.left_key = left_key
423
- self.right_key = right_key
424
- self.right_buffer = [] # Buffer for right side
425
-
426
- def __next__(self):
427
- left_row = next(self.left_iterator)
428
- left_key_value = left_row[self.left_key]
429
-
430
- # Advance right iterator until we find matching key
431
- while True:
432
- if not self.right_buffer:
433
- right_row = next(self.right_iterator)
434
- self.right_buffer.append(right_row)
435
-
436
- right_key_value = self.right_buffer[0][self.right_key]
437
-
438
- if right_key_value == left_key_value:
439
- # Match found - merge and yield
440
- right_row = self.right_buffer.pop(0)
441
- return {**left_row, **right_row}
442
- elif right_key_value > left_key_value:
443
- # Right side ahead - no match for this left row
444
- return None
445
- else:
446
- # Right side behind - advance right
447
- self.right_buffer.pop(0)
448
- ```
449
-
450
- **Why merge join:** O(n+m) time complexity, O(1) memory. Perfect for pre-sorted data.
451
-
452
- **4. ProjectIterator**
453
-
454
- - Applies SELECT clause
455
- - Only includes requested columns
456
- - Handles column aliases
457
-
458
- **Logic:**
459
-
460
- ```python
461
- class ProjectIterator:
462
- def __init__(self, source_iterator, projections):
463
- self.source_iterator = source_iterator
464
- self.projections = projections # List of (table.col, alias) tuples
465
-
466
- def __next__(self):
467
- row = next(self.source_iterator)
468
- result = {}
469
- for table_col, alias in self.projections:
470
- result[alias or table_col] = row[table_col]
471
- return result
472
- ```
473
-
474
194
  ### Why Iterator-Based Architecture?
475
195
 
476
196
  **Key advantages:**
@@ -493,74 +213,35 @@ class ProjectIterator:
493
213
 
494
214
  The engine uses recursive AST traversal to evaluate expressions:
495
215
 
496
- ```python
497
- def evaluate_expression(expr, row):
498
- """Recursively evaluate SQL expression against row data"""
499
-
500
- if isinstance(expr, exp.Column):
501
- # Column reference: lookup value in row
502
- return row[expr.sql()]
503
-
504
- elif isinstance(expr, exp.Literal):
505
- # Literal value: return as-is
506
- return expr.this
507
-
508
- elif isinstance(expr, exp.EQ):
509
- # Equality: evaluate left and right, compare
510
- left = evaluate_expression(expr.this, row)
511
- right = evaluate_expression(expr.expression, row)
512
- return left == right
513
-
514
- elif isinstance(expr, exp.GT):
515
- # Greater than: evaluate and compare
516
- left = evaluate_expression(expr.this, row)
517
- right = evaluate_expression(expr.expression, row)
518
- return left > right
519
-
520
- # ... handle other operators (AND, OR, NOT, etc.)
521
- ```
522
-
523
216
  **Why recursive:** SQL expressions are trees. Recursive evaluation naturally handles nested expressions like `(a > 10 AND b < 20) OR c = 5`.
524
217
 
525
218
  ### Join Algorithm Selection
526
219
 
527
220
  **How the engine chooses join algorithms:**
528
221
 
222
+ The engine follows this priority order when selecting a join algorithm:
223
+
529
224
  1. **Check if both sides are sorted** (`ordered_by` metadata)
530
225
 
531
- - If yes → Use MergeJoinIterator
532
- - If no → Use LookupJoinIterator
226
+ - If yes, use `MergeJoinIterator` (most memory-efficient for sorted data)
227
+ - Only used when `use_polars=False`
533
228
 
534
229
  2. **Check if right side is a file** (`filename` metadata)
535
230
 
536
- - If yes → Use MmapLookupJoinIterator (memory-mapped)
231
+ - If yes, use `MmapLookupJoinIterator` (memory-mapped, 90-99% memory reduction)
232
+ - Only used when `use_polars=False`
537
233
 
538
234
  3. **Check if Polars is available** (`use_polars` flag)
539
- - If yes → Use PolarsLookupJoinIterator (vectorized)
540
235
 
541
- **Logic:**
236
+ - If yes, use `PolarsLookupJoinIterator` (vectorized, SIMD-accelerated)
237
+ - Used when `use_polars=True` is explicitly set
542
238
 
543
- ```python
544
- def _build_join_iterator(left_iterator, right_source_fn, left_key, right_key,
545
- right_metadata, use_polars):
546
- # Check for merge join (both sides sorted)
547
- if left_metadata.get('ordered_by') == left_key and \
548
- right_metadata.get('ordered_by') == right_key:
549
- return MergeJoinIterator(left_iterator, right_source_fn, left_key, right_key)
239
+ 4. **Default fallback**
240
+ - Use `LookupJoinIterator` (Python hash-based, most compatible)
550
241
 
551
- # Check for mmap join (file-based)
552
- if right_metadata.get('filename') and MMAP_AVAILABLE:
553
- return MmapLookupJoinIterator(left_iterator, right_source_fn,
554
- right_metadata['filename'], left_key, right_key)
555
-
556
- # Check for Polars join (vectorized)
557
- if use_polars and POLARS_AVAILABLE:
558
- return PolarsLookupJoinIterator(left_iterator, right_source_fn,
559
- left_key, right_key)
242
+ **Logic:**
560
243
 
561
- # Default: standard lookup join
562
- return LookupJoinIterator(left_iterator, right_source_fn, left_key, right_key)
563
- ```
244
+ **Note:** When `use_polars=False` (default), Merge Join and MMAP Join are checked first before falling back to Python Lookup Join. When `use_polars=True` is explicitly set, the engine prioritizes Polars over MMAP and Merge Join.
564
245
 
565
246
  ### Protocol-Based Optimization
566
247
 
@@ -663,27 +344,7 @@ with open('large_file.jsonl', 'rb') as f:
663
344
 
664
345
  **3. First Match Only Optimization**
665
346
 
666
- For joins where only the first match matters (prevents Cartesian products):
667
-
668
- ```python
669
- class LookupJoinIterator:
670
- def __init__(self, ..., first_match_only=False):
671
- self.first_match_only = first_match_only
672
-
673
- def _build_index(self):
674
- self.index = {}
675
- for right_row in self.right_source_fn():
676
- key = right_row[self.right_key]
677
- if self.first_match_only:
678
- # Only keep first match per key
679
- if key not in self.index:
680
- self.index[key] = right_row
681
- else:
682
- # Keep all matches
683
- if key not in self.index:
684
- self.index[key] = []
685
- self.index[key].append(right_row)
686
- ```
347
+ For joins where only the first match matters (prevents Cartesian products).
687
348
 
688
349
  **Why useful:** Prevents Cartesian products when right side has duplicate keys. Significantly reduces output size and processing time.
689
350
 
@@ -779,20 +440,20 @@ The engine processes data **row-by-row**, never loading entire tables into memor
779
440
 
780
441
  ```
781
442
  SQL Query
782
- ↓
783
- Parser → AST
784
- ↓
785
- Planner → Logical Plan
786
- ↓
787
- Executor → Iterator Pipeline
788
- ↓
443
+ |
444
+ Parser -> AST
445
+ |
446
+ Planner -> Logical Plan
447
+ |
448
+ Executor -> Iterator Pipeline
449
+ |
789
450
  Results (Generator)
790
451
  ```
791
452
 
792
453
  **Iterator Pipeline:**
793
454
 
794
455
  ```
795
- ScanIterator → FilterIterator → JoinIterators → ProjectIterator → Results
456
+ ScanIterator -> FilterIterator -> JoinIterators -> ProjectIterator -> Results
796
457
  ```
797
458
 
798
459
  Each iterator processes rows incrementally, enabling true streaming execution. This means:
@@ -926,12 +587,13 @@ def source(dynamic_where=None):
926
587
  10-200x faster processing for large datasets using SIMD-accelerated operations:
927
588
 
928
589
  ```python
929
- engine = Engine(use_polars=True) # Enabled by default
590
+ engine = Engine() # use_polars=False (default)
930
591
 
931
- # Automatically uses Polars for:
932
- # - Vectorized filtering
933
- # - Vectorized projections
934
- # - Batch processing
592
+ # Automatically uses Polars when available for:
593
+ # - Vectorized joins (PolarsLookupJoinIterator) - when right side >= 10K rows
594
+ # - Vectorized filtering (PolarsBatchFilterIterator) - when expression is translatable
595
+ # - Vectorized projections (PolarsBatchProjectIterator) - batch column selection
596
+ # Falls back to Python iterators if Polars fails or isn't available
935
597
  ```
936
598
 
937
599
  ### 4. Memory-Mapped Joins
@@ -1377,6 +1039,706 @@ Filter pushdown, column pruning, and vectorization applied automatically. No con
1377
1039
 
1378
1040
  ---
1379
1041
 
1042
+ ## 🎯 Start Here: The Most Secure Way
1043
+
1044
+ ### Step 1: Install and Basic Setup
1045
+
1046
+ ```bash
1047
+ pip install streaming-sql-engine
1048
+ ```
1049
+
1050
+ ### Step 2: Use the Default Configuration (Most Stable)
1051
+
1052
+ **This is the safest way to start** — it handles all edge cases, works with any data types, and requires no special configuration:
1053
+
1054
+ ```python
1055
+ from streaming_sql_engine import Engine
1056
+
1057
+ # Default configuration: Most stable and reliable
1058
+ engine = Engine() # use_polars=False (default)
1059
+
1060
+ # Register your data sources
1061
+ def postgres_users():
1062
+ # Your PostgreSQL connection code
1063
+ for row in cursor:
1064
+ yield {"id": row[0], "name": row[1]}
1065
+
1066
+ def mysql_orders():
1067
+ # Your MySQL connection code
1068
+ for row in cursor:
1069
+ yield {"id": row[0], "user_id": row[1], "total": row[2]}
1070
+
1071
+ engine.register("users", postgres_users)
1072
+ engine.register("orders", mysql_orders)
1073
+
1074
+ # Write SQL queries
1075
+ query = """
1076
+ SELECT users.name, orders.total
1077
+ FROM users
1078
+ JOIN orders ON users.id = orders.user_id
1079
+ WHERE orders.total > 100
1080
+ """
1081
+
1082
+ # Execute and iterate results
1083
+ for row in engine.query(query):
1084
+ print(row)
1085
+ ```
1086
+
1087
+ **Why This Configuration is Best to Start:**
1088
+
1089
+ - **Most Stable**: Handles mixed data types gracefully
1090
+ - **No Schema Errors**: No type inference issues
1091
+ - **Works Everywhere**: No external dependencies required
1092
+ - **Reliable**: Battle-tested Python code
1093
+ - **Fast for Small-Medium Data**: 0.72s for 10K rows
1094
+
1095
+ **Use this when:**
1096
+
1097
+ - You're just getting started
1098
+ - Your datasets are < 100K rows
1099
+ - You have mixed data types
1100
+ - You need maximum reliability
1101
+ - Polars is not available
1102
+
1103
+ ---
1104
+
1105
+ ## Experimenting with Options
1106
+
1107
+ Once you're comfortable with the basics, you can experiment with different options to optimize for your specific use case.
1108
+
1109
+ ### Option 1: Enable Debug Mode
1110
+
1111
+ See what's happening under the hood:
1112
+
1113
+ ```python
1114
+ engine = Engine(debug=True) # Shows execution details
1115
+ ```
1116
+
1117
+ **Output:**
1118
+
1119
+ ```
1120
+ ============================================================
1121
+ STREAMING SQL ENGINE - DEBUG MODE
1122
+ ============================================================
1123
+
1124
+ [1/3] PARSING SQL QUERY...
1125
+ SQL parsed successfully
1126
+
1127
+ [2/3] BUILDING LOGICAL PLAN...
1128
+ Logical plan built
1129
+
1130
+ [3/3] EXECUTING QUERY...
1131
+ Using LOOKUP JOIN (building index...)
1132
+ ```
1133
+
1134
+ ---
1135
+
1136
+ ### Option 2: Enable Polars (For Large Datasets)
1137
+
1138
+ **When to use**: Large datasets (> 100K rows), consistent data types
1139
+
1140
+ ```python
1141
+ engine = Engine(use_polars=True) # Enable Polars for speed
1142
+ ```
1143
+
1144
+ **Benefits:**
1145
+
1146
+ - Faster for large datasets (vectorized operations)
1147
+ - SIMD acceleration
1148
+ - Better for consistent schemas
1149
+
1150
+ **Trade-offs:**
1151
+
1152
+ - Requires data normalization (consistent types)
1153
+ - Can fail on mixed types
1154
+ - Requires Polars dependency
1155
+
1156
+ **Example:**
1157
+
1158
+ ```python
1159
+ engine = Engine(use_polars=True)
1160
+
1161
+ # Make sure your data has consistent types
1162
+ def normalized_source():
1163
+ for row in raw_source():
1164
+ yield {
1165
+ "id": int(row.get("id", 0)),
1166
+ "price": float(row.get("price", 0.0)),
1167
+ "name": str(row.get("name", "")),
1168
+ }
1169
+
1170
+ engine.register("products", normalized_source)
1171
+ ```
1172
+
1173
+ ---
1174
+
1175
+ ### Option 3: Enable MMAP (For Large Files)
1176
+
1177
+ **When to use**: Large files (> 100MB), memory-constrained systems
1178
+
1179
+ ```python
1180
+ engine = Engine()
1181
+ engine.register("products", source, filename="products.jsonl") # MMAP enabled
1182
+ ```
1183
+
1184
+ **Benefits:**
1185
+
1186
+ - 90-99% memory reduction
1187
+ - Works with files larger than RAM
1188
+ - OS-managed memory mapping
1189
+
1190
+ **Trade-offs:**
1191
+
1192
+ - Requires file-based sources
1193
+ - Slower for small files (overhead)
1194
+
1195
+ **Example:**
1196
+
1197
+ ```python
1198
+ engine = Engine()
1199
+
1200
+ def jsonl_source():
1201
+ with open("products.jsonl", "r") as f:
1202
+ for line in f:
1203
+ if line.strip():
1204
+ yield json.loads(line)
1205
+
1206
+ engine.register("products", jsonl_source, filename="products.jsonl")
1207
+ ```
1208
+
1209
+ ---
1210
+
1211
+ ### Option 4: Enable Merge Join (For Sorted Data)
1212
+
1213
+ **When to use**: Pre-sorted data, memory-constrained environments
1214
+
1215
+ ```python
1216
+ engine = Engine()
1217
+ engine.register("products", source, ordered_by="id") # Merge join enabled
1218
+ ```
1219
+
1220
+ **Benefits:**
1221
+
1222
+ - Lowest memory usage (no index needed)
1223
+ - Fast for sorted data
1224
+ - Streaming algorithm
1225
+
1226
+ **Trade-offs:**
1227
+
1228
+ - Requires pre-sorted data
1229
+ - Both tables must be sorted
1230
+
1231
+ **Example:**
1232
+
1233
+ ```python
1234
+ engine = Engine()
1235
+
1236
+ # Data must be sorted by join key
1237
+ def sorted_users():
1238
+ # Users sorted by id
1239
+ return iter([
1240
+ {"id": 1, "name": "Alice"},
1241
+ {"id": 2, "name": "Bob"},
1242
+ {"id": 3, "name": "Charlie"},
1243
+ ])
1244
+
1245
+ def sorted_orders():
1246
+ # Orders sorted by user_id
1247
+ return iter([
1248
+ {"id": 1, "user_id": 1, "total": 100},
1249
+ {"id": 2, "user_id": 2, "total": 200},
1250
+ ])
1251
+
1252
+ engine.register("users", sorted_users, ordered_by="id")
1253
+ engine.register("orders", sorted_orders, ordered_by="user_id")
1254
+ ```
1255
+
1256
+ ---
1257
+
1258
+ ## Advanced: Mixing Options
1259
+
1260
+ ### Mix 1: MMAP with Polars Index Building (Best for Large Files)
1261
+
1262
+ **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).
1263
+
1264
+ However, **MMAP can use Polars internally** for faster index building even when `use_polars=False`:
1265
+
1266
+ ```python
1267
+ engine = Engine(use_polars=False) # MMAP Join will be used
1268
+ engine.register("products", source, filename="products.jsonl") # MMAP for memory
1269
+ # MMAP will use Polars internally for index building if available
1270
+ ```
1271
+
1272
+ **What You Get:**
1273
+
1274
+ - Low memory (MMAP 90-99% reduction)
1275
+ - Fast index building (if Polars is installed, used internally)
1276
+ - Best balance for large files with memory constraints
1277
+
1278
+ **Performance:**
1279
+
1280
+ - Time: 8-15s for 500MB files (with Polars for index building)
1281
+ - Memory: 0.01 MB (vs 500MB+ without MMAP)
1282
+
1283
+ **When to Use:**
1284
+
1285
+ - Large files (> 100MB)
1286
+ - Memory-constrained systems
1287
+ - When you want MMAP Join (not Polars Join)
1288
+
1289
+ **Note:** If you set `use_polars=True`, the engine will use **Polars Join** instead of MMAP Join, prioritizing speed over memory efficiency.
1290
+
1291
+ ---
1292
+
1293
+ ### Mix 2: Polars + Column Pruning (For Wide Tables)
1294
+
1295
+ **Optimize for tables with many columns:**
1296
+
1297
+ ```python
1298
+ engine = Engine(use_polars=True)
1299
+
1300
+ def optimized_source(dynamic_columns=None):
1301
+ # Only read requested columns
1302
+ if dynamic_columns:
1303
+ columns = dynamic_columns
1304
+ else:
1305
+ columns = ["id", "name", "price", "description", "category", ...] # All columns
1306
+
1307
+ for row in read_data(columns):
1308
+ yield row
1309
+
1310
+ engine.register("products", optimized_source)
1311
+ ```
1312
+
1313
+ **What You Get:**
1314
+
1315
+ - Reduced I/O (only reads needed columns)
1316
+ - Faster queries (less data to process)
1317
+ - Lower memory usage
1318
+
1319
+ ---
1320
+
1321
+ ### Mix 3: Polars + Filter Pushdown (For Selective Queries)
1322
+
1323
+ **Optimize when queries filter most rows:**
1324
+
1325
+ ```python
1326
+ engine = Engine(use_polars=True)
1327
+
1328
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1329
+ # Apply WHERE clause at source level
1330
+ query = "SELECT * FROM products"
1331
+ if dynamic_where:
1332
+ query += f" WHERE {dynamic_where}"
1333
+
1334
+ for row in execute_query(query):
1335
+ yield row
1336
+
1337
+ engine.register("products", optimized_source)
1338
+ ```
1339
+
1340
+ **What You Get:**
1341
+
1342
+ - Early filtering (reduces data volume)
1343
+ - Faster execution (less data to process)
1344
+ - Lower memory usage
1345
+
1346
+ ---
1347
+
1348
+ ### Mix 4: All Optimizations Combined
1349
+
1350
+ **The Ultimate Configuration** for maximum performance:
1351
+
1352
+ ```python
1353
+ engine = Engine(use_polars=True)
1354
+
1355
+ def ultimate_source(dynamic_where=None, dynamic_columns=None):
1356
+ """
1357
+ Source with all optimizations:
1358
+ - Filter pushdown (dynamic_where)
1359
+ - Column pruning (dynamic_columns)
1360
+ - Data normalization (for Polars)
1361
+ """
1362
+ # Build optimized query
1363
+ query = build_query(dynamic_where, dynamic_columns)
1364
+
1365
+ for row in execute_query(query):
1366
+ # Normalize types for Polars stability
1367
+ yield normalize_types(row)
1368
+
1369
+ engine.register("products", ultimate_source, filename="products.jsonl")
1370
+ ```
1371
+
1372
+ **What You Get:**
1373
+
1374
+ - Polars Join (speed) - when `use_polars=True`
1375
+ - Column Pruning (I/O)
1376
+ - Filter Pushdown (early filtering)
1377
+
1378
+ **Best for:** Very large datasets (> 1M rows) when speed is priority
1379
+
1380
+ **Note:** This uses Polars Join, not MMAP Join. For memory-constrained scenarios, use `use_polars=False` with `filename` parameter instead.
1381
+
1382
+ ---
1383
+
1384
+ ## Performance Guide
1385
+
1386
+ ### By Dataset Size
1387
+
1388
+ | Size | Configuration | Why |
1389
+ | ----------------- | ------------------------------- | ----------------------------------------- |
1390
+ | **< 10K rows** | `use_polars=False` (default) | Fastest, most stable |
1391
+ | **10K-100K rows** | `use_polars=False` (default) | Still fastest, handles mixed types |
1392
+ | **100K-1M rows** | `use_polars=True` OR `filename` | Polars Join (speed) OR MMAP Join (memory) |
1393
+ | **> 1M rows** | All optimizations | Maximum performance |
1394
+
1395
+ ### By Priority
1396
+
1397
+ **Priority: Stability** - Use default (`use_polars=False`)
1398
+
1399
+ ```python
1400
+ engine = Engine() # Most stable
1401
+ ```
1402
+
1403
+ **Priority: Speed** - Use Polars
1404
+
1405
+ ```python
1406
+ engine = Engine(use_polars=True) # Fastest for large datasets
1407
+ ```
1408
+
1409
+ **Priority: Memory** - Use MMAP
1410
+
1411
+ ```python
1412
+ engine = Engine()
1413
+ engine.register("table", source, filename="data.jsonl") # Lowest memory
1414
+ ```
1415
+
1416
+ **Priority: Both** - Choose based on priority:
1417
+
1418
+ **If speed is more important:**
1419
+
1420
+ ```python
1421
+ engine = Engine(use_polars=True) # Uses Polars Join (fastest)
1422
+ engine.register("table", source) # No filename - Polars Join
1423
+ ```
1424
+
1425
+ **If memory is more important:**
1426
+
1427
+ ```python
1428
+ engine = Engine(use_polars=False) # Uses MMAP Join (lowest memory)
1429
+ engine.register("table", source, filename="data.jsonl") # MMAP Join
1430
+ ```
1431
+
1432
+ **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.
1433
+
1434
+ ---
1435
+
1436
+ ## Learning Path
1437
+
1438
+ ### Level 1: Beginner (Start Here)
1439
+
1440
+ ```python
1441
+ # Most stable configuration
1442
+ engine = Engine() # Default: use_polars=False
1443
+ engine.register("table1", source1)
1444
+ engine.register("table2", source2)
1445
+ ```
1446
+
1447
+ **Learn:**
1448
+
1449
+ - Basic source registration
1450
+ - Simple SQL queries
1451
+ - How joins work
1452
+
1453
+ ---
1454
+
1455
+ ### Level 2: Intermediate
1456
+
1457
+ ```python
1458
+ # Add debug mode to see what's happening
1459
+ engine = Engine(debug=True)
1460
+
1461
+ # Experiment with Polars for large datasets
1462
+ engine = Engine(use_polars=True)
1463
+ ```
1464
+
1465
+ **Learn:**
1466
+
1467
+ - Debug output
1468
+ - When to use Polars
1469
+ - Data normalization
1470
+
1471
+ ---
1472
+
1473
+ ### Level 3: Advanced
1474
+
1475
+ ```python
1476
+ # Use MMAP for large files (requires use_polars=False)
1477
+ engine = Engine(use_polars=False) # MMAP Join requires use_polars=False
1478
+ engine.register("table", source, filename="data.jsonl")
1479
+
1480
+ # Use Merge Join for sorted data
1481
+ engine.register("table", source, ordered_by="key")
1482
+ ```
1483
+
1484
+ **Learn:**
1485
+
1486
+ - MMAP for memory efficiency
1487
+ - Merge Join for sorted data
1488
+ - Protocol optimizations
1489
+
1490
+ ---
1491
+
1492
+ ### Level 4: Expert
1493
+
1494
+ ```python
1495
+ # All optimizations combined
1496
+ engine = Engine(use_polars=True)
1497
+
1498
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1499
+ # Filter pushdown + Column pruning
1500
+ pass
1501
+
1502
+ engine.register("table", optimized_source, filename="data.jsonl")
1503
+ ```
1504
+
1505
+ **Learn:**
1506
+
1507
+ - Protocol-based optimizations
1508
+ - Combining all options
1509
+ - Maximum performance tuning
1510
+
1511
+ ---
1512
+
1513
+ ## Common Pitfalls
1514
+
1515
+ ### Pitfall 1: Using Polars Without Normalization
1516
+
1517
+ **Problem:**
1518
+
1519
+ ```python
1520
+ engine = Engine(use_polars=True)
1521
+ # Mixed types cause schema inference errors
1522
+ ```
1523
+
1524
+ **Solution:**
1525
+
1526
+ ```python
1527
+ def normalized_source():
1528
+ for row in raw_source():
1529
+ yield {
1530
+ "id": int(row.get("id", 0)),
1531
+ "price": float(row.get("price", 0.0)),
1532
+ }
1533
+ ```
1534
+
1535
+ ---
1536
+
1537
+ ### Pitfall 2: Using MMAP Without Polars (Very Slow)
1538
+
1539
+ **Problem:**
1540
+
1541
+ ```python
1542
+ engine = Engine(use_polars=False)
1543
+ engine.register("table", source, filename="data.jsonl") # Very slow!
1544
+ ```
1545
+
1546
+ **Solution:**
1547
+
1548
+ ```python
1549
+ engine = Engine(use_polars=True) # Polars speeds up MMAP index building
1550
+ engine.register("table", source, filename="data.jsonl")
1551
+ ```
1552
+
1553
+ ---
1554
+
1555
+ ### Pitfall 3: Using MMAP for Small Files
1556
+
1557
+ **Problem:**
1558
+
1559
+ ```python
1560
+ # MMAP overhead > benefit for small files
1561
+ engine.register("table", source, filename="small.jsonl") # Slower!
1562
+ ```
1563
+
1564
+ **Solution:**
1565
+
1566
+ ```python
1567
+ # No filename for small files
1568
+ engine.register("table", source) # Faster for < 100MB
1569
+ ```
1570
+
1571
+ ---
1572
+
1573
+ ## Quick Decision Guide
1574
+
1575
+ - **Just starting?** Use default (`Engine()`)
1576
+ - **Have large datasets?** Use `use_polars=True`
1577
+ - **Memory constrained?** Use `filename` parameter (MMAP)
1578
+ - **Data is sorted?** Use `ordered_by` parameter (Merge Join)
1579
+ - **Want maximum performance?** Use `use_polars=True` + protocols (Polars Join) OR `use_polars=False` + `filename` (MMAP Join) + protocols
1580
+
1581
+ ---
1582
+
1583
+ ## Real-World Example: Complete Workflow
1584
+
1585
+ ### Step 1: Start Simple (Most Secure)
1586
+
1587
+ ```python
1588
+ from streaming_sql_engine import Engine
1589
+
1590
+ # Start with default (most stable)
1591
+ engine = Engine()
1592
+
1593
+ def postgres_users():
1594
+ # Your PostgreSQL code
1595
+ pass
1596
+
1597
+ def mysql_orders():
1598
+ # Your MySQL code
1599
+ pass
1600
+
1601
+ engine.register("users", postgres_users)
1602
+ engine.register("orders", mysql_orders)
1603
+
1604
+ results = engine.query("SELECT * FROM users JOIN orders ON users.id = orders.user_id")
1605
+ ```
1606
+
1607
+ ### Step 2: Add Debug Mode (Understand What's Happening)
1608
+
1609
+ ```python
1610
+ engine = Engine(debug=True) # See execution details
1611
+ ```
1612
+
1613
+ ### Step 3: Optimize for Your Use Case
1614
+
1615
+ **If you have large datasets:**
1616
+
1617
+ ```python
1618
+ engine = Engine(use_polars=True) # Enable Polars
1619
+ ```
1620
+
1621
+ **If you have large files:**
1622
+
1623
+ ```python
1624
+ engine = Engine(use_polars=False) # MMAP Join requires use_polars=False
1625
+ engine.register("table", source, filename="data.jsonl") # Enable MMAP
1626
+ ```
1627
+
1628
+ **If you have sorted data:**
1629
+
1630
+ ```python
1631
+ engine.register("table", source, ordered_by="key") # Enable Merge Join
1632
+ ```
1633
+
1634
+ ### Step 4: Combine Optimizations
1635
+
1636
+ **For Speed Priority (Polars Join):**
1637
+
1638
+ ```python
1639
+ engine = Engine(use_polars=True) # Uses Polars Join
1640
+
1641
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1642
+ # Supports all optimizations
1643
+ pass
1644
+
1645
+ engine.register("table", optimized_source) # No filename - Polars Join
1646
+ ```
1647
+
1648
+ **For Memory Priority (MMAP Join):**
1649
+
1650
+ ```python
1651
+ engine = Engine(use_polars=False) # Uses MMAP Join
1652
+
1653
+ def optimized_source(dynamic_where=None, dynamic_columns=None):
1654
+ # Supports all optimizations
1655
+ pass
1656
+
1657
+ engine.register("table", optimized_source, filename="data.jsonl") # MMAP Join
1658
+ ```
1659
+
1660
+ ---
1661
+
1662
+ ## Summary
1663
+
1664
+ ### Start Here (Most Secure)
1665
+
1666
+ ```python
1667
+ engine = Engine() # Default: use_polars=False
1668
+ engine.register("table1", source1)
1669
+ engine.register("table2", source2)
1670
+ ```
1671
+
1672
+ **Why:** Most stable, handles all edge cases, works with any data types
1673
+
1674
+ ---
1675
+
1676
+ ### Then Experiment
1677
+
1678
+ 1. **Add debug mode**: `Engine(debug=True)` - See what's happening
1679
+ 2. **Try Polars**: `Engine(use_polars=True)` - For large datasets
1680
+ 3. **Try MMAP**: `filename="data.jsonl"` - For large files
1681
+ 4. **Try Merge Join**: `ordered_by="key"` - For sorted data
1682
+
1683
+ ---
1684
+
1685
+ ### Advanced: Mix Options
1686
+
1687
+ **Best Mix for Large Files:**
1688
+
1689
+ **Option 1: Speed Priority (Polars Join)**
1690
+
1691
+ ```python
1692
+ engine = Engine(use_polars=True) # Uses Polars Join (fastest)
1693
+ engine.register("table", source) # No filename needed
1694
+ ```
1695
+
1696
+ **Option 2: Memory Priority (MMAP Join)**
1697
+
1698
+ ```python
1699
+ engine = Engine(use_polars=False) # Uses MMAP Join (lowest memory)
1700
+ engine.register("table", source, filename="data.jsonl") # MMAP enabled
1701
+ ```
1702
+
1703
+ **Best Mix for Maximum Performance:**
1704
+
1705
+ **Option 1: Speed Priority (Polars Join + Protocols)**
1706
+
1707
+ ```python
1708
+ engine = Engine(use_polars=True) # Uses Polars Join
1709
+
1710
+ def source(dynamic_where=None, dynamic_columns=None):
1711
+ # All optimizations (filter pushdown + column pruning)
1712
+ pass
1713
+
1714
+ engine.register("table", source) # No filename - Polars Join
1715
+ ```
1716
+
1717
+ **Option 2: Memory Priority (MMAP Join + Protocols)**
1718
+
1719
+ ```python
1720
+ engine = Engine(use_polars=False) # Uses MMAP Join
1721
+
1722
+ def source(dynamic_where=None, dynamic_columns=None):
1723
+ # All optimizations (filter pushdown + column pruning)
1724
+ pass
1725
+
1726
+ engine.register("table", source, filename="data.jsonl") # MMAP Join
1727
+ ```
1728
+
1729
+ ---
1730
+
1731
+ ## Key Takeaways
1732
+
1733
+ 1. **Start Simple**: Use default configuration (`Engine()`) - it's the most stable
1734
+ 2. **Experiment Gradually**: Add options one at a time to understand their impact
1735
+ 3. **Mix Wisely**: Choose Polars Join (speed) OR MMAP Join (memory) based on priority
1736
+ 4. **Know When to Use Each**: Small files: default, Large files: Polars Join (speed) OR MMAP Join (memory)
1737
+
1738
+ ---
1739
+
1740
+ **Remember**: Start with the default configuration, then experiment with options as you understand your data and performance needs better.
1741
+
1380
1742
  ## Getting Started
1381
1743
 
1382
1744
  Installation: