streaming-sql-engine 0.1.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,493 @@
1
+ """
2
+ Protocol Helpers - Automate Protocol Implementation
3
+
4
+ These helpers make it easy to add protocol support to any source function
5
+ without manual SQL parsing or evaluation.
6
+ """
7
+
8
+ from typing import Iterator, Dict, Optional, Callable
9
+ from functools import wraps
10
+
11
+
12
+ def add_protocol_support(source_fn: Callable) -> Callable:
13
+ """
14
+ Decorator that automatically adds protocol support to any source function.
15
+
16
+ Usage:
17
+ @add_protocol_support
18
+ def my_source(filepath: str) -> Iterator[Dict]:
19
+ with open(filepath) as f:
20
+ for line in f:
21
+ yield json.loads(line)
22
+
23
+ # Now it automatically supports dynamic_where and dynamic_columns!
24
+ engine.register("products", lambda dynamic_where=None, dynamic_columns=None:
25
+ my_source("data.jsonl", dynamic_where, dynamic_columns))
26
+
27
+ The decorator handles:
28
+ - Parsing WHERE clause using sqlglot
29
+ - Evaluating filters using engine's evaluator
30
+ - Column pruning
31
+ """
32
+ @wraps(source_fn)
33
+ def wrapper(*args, dynamic_where: Optional[str] = None,
34
+ dynamic_columns: Optional[list] = None, **kwargs):
35
+ # Get iterator from original source
36
+ iterator = source_fn(*args, **kwargs)
37
+
38
+ # Apply filter pushdown if WHERE clause provided
39
+ if dynamic_where:
40
+ iterator = _apply_filter(iterator, dynamic_where)
41
+
42
+ # Apply column pruning if columns specified
43
+ if dynamic_columns:
44
+ iterator = _apply_column_pruning(iterator, dynamic_columns)
45
+
46
+ return iterator
47
+
48
+ return wrapper
49
+
50
+
51
+ def _apply_filter(iterator: Iterator[Dict], where_clause: str) -> Iterator[Dict]:
52
+ """Apply WHERE clause filter to iterator using engine's evaluator."""
53
+ # Parse WHERE clause
54
+ try:
55
+ from sqlglot import parse_one
56
+ parsed = parse_one(f"SELECT * FROM dummy WHERE {where_clause}")
57
+ where_expr = parsed.args.get('where')
58
+ if where_expr:
59
+ where_expr = where_expr.this
60
+ else:
61
+ return iterator
62
+ except Exception:
63
+ # If parsing fails, return iterator unchanged
64
+ return iterator
65
+
66
+ # Apply filter using evaluator
67
+ try:
68
+ from streaming_sql_engine.evaluator import evaluate_expression
69
+
70
+ for row in iterator:
71
+ # Prepare row for evaluation (remove table prefix)
72
+ eval_row = {k.split('.')[-1]: v for k, v in row.items()}
73
+ eval_row.update(row) # Keep original keys too
74
+
75
+ try:
76
+ if evaluate_expression(where_expr, eval_row):
77
+ yield row
78
+ except Exception:
79
+ # If evaluation fails, skip row (conservative)
80
+ continue
81
+ except ImportError:
82
+ # If evaluator not available, return iterator unchanged
83
+ return iterator
84
+
85
+
86
+ def _apply_column_pruning(iterator: Iterator[Dict], columns: list) -> Iterator[Dict]:
87
+ """Apply column pruning to iterator."""
88
+ for row in iterator:
89
+ yield {k: v for k, v in row.items() if k in columns}
90
+
91
+
92
+ def wrap_simple_source(source_fn: Callable) -> Callable:
93
+ """
94
+ Wrap a simple source function to add protocol support.
95
+
96
+ Usage:
97
+ def my_csv_source(filepath: str) -> Iterator[Dict]:
98
+ with open(filepath) as f:
99
+ reader = csv.DictReader(f)
100
+ for row in reader:
101
+ yield row
102
+
103
+ # Wrap it
104
+ protocol_source = wrap_simple_source(my_csv_source)
105
+
106
+ # Register with protocol support
107
+ engine.register("products",
108
+ lambda dynamic_where=None, dynamic_columns=None:
109
+ protocol_source("data.csv", dynamic_where, dynamic_columns))
110
+ """
111
+ @wraps(source_fn)
112
+ def protocol_wrapper(*args, dynamic_where: Optional[str] = None,
113
+ dynamic_columns: Optional[list] = None, **kwargs):
114
+ iterator = source_fn(*args, **kwargs)
115
+
116
+ if dynamic_where:
117
+ iterator = _apply_filter(iterator, dynamic_where)
118
+
119
+ if dynamic_columns:
120
+ iterator = _apply_column_pruning(iterator, dynamic_columns)
121
+
122
+ return iterator
123
+
124
+ return protocol_wrapper
125
+
126
+
127
+ def create_protocol_source(filepath: str, file_type: str = 'auto') -> Callable:
128
+ """
129
+ Create a protocol-enabled source function from a file path.
130
+
131
+ Usage:
132
+ # Auto-detect file type
133
+ source = create_protocol_source("data/products.jsonl")
134
+ engine.register("products", source)
135
+
136
+ # Specify file type
137
+ source = create_protocol_source("data/products.csv", file_type='csv')
138
+ engine.register("products", source)
139
+
140
+ Supported file types: 'jsonl', 'csv', 'auto' (detects from extension)
141
+ """
142
+ import os
143
+
144
+ # Auto-detect file type
145
+ if file_type == 'auto':
146
+ ext = os.path.splitext(filepath)[1].lower()
147
+ if ext == '.jsonl':
148
+ file_type = 'jsonl'
149
+ elif ext == '.csv':
150
+ file_type = 'csv'
151
+ else:
152
+ raise ValueError(f"Could not auto-detect file type for {filepath}")
153
+
154
+ def jsonl_source(dynamic_where: Optional[str] = None,
155
+ dynamic_columns: Optional[list] = None) -> Iterator[Dict]:
156
+ import json
157
+ print(f" 📂 Reading JSONL: {filepath}")
158
+ if dynamic_where:
159
+ print(f" ✅ Filter pushdown: {dynamic_where}")
160
+ if dynamic_columns:
161
+ print(f" ✅ Column pruning: {dynamic_columns}")
162
+
163
+ # Parse WHERE clause ONCE (not for every row!)
164
+ where_expr = None
165
+ if dynamic_where:
166
+ try:
167
+ from sqlglot import parse_one
168
+ parsed = parse_one(f"SELECT * FROM dummy WHERE {dynamic_where}")
169
+ where_expr = parsed.args.get('where')
170
+ if where_expr:
171
+ where_expr = where_expr.this
172
+ except Exception:
173
+ where_expr = None
174
+
175
+ # Import evaluator ONCE
176
+ evaluate_expression = None
177
+ if where_expr:
178
+ try:
179
+ from streaming_sql_engine.evaluator import evaluate_expression as eval_fn
180
+ evaluate_expression = eval_fn
181
+ except ImportError:
182
+ evaluate_expression = None
183
+
184
+ count = 0
185
+ with open(filepath, 'r', encoding='utf-8') as f:
186
+ for line in f:
187
+ if not line.strip():
188
+ continue
189
+ try:
190
+ row = json.loads(line)
191
+
192
+ # Apply filter directly (no iterator creation!)
193
+ if where_expr and evaluate_expression:
194
+ # Prepare row for evaluation (remove table prefix)
195
+ eval_row = {k.split('.')[-1]: v for k, v in row.items()}
196
+ eval_row.update(row) # Keep original keys too
197
+
198
+ try:
199
+ if not evaluate_expression(where_expr, eval_row):
200
+ continue # Skip row
201
+ except Exception:
202
+ continue # Skip row on evaluation error
203
+
204
+ # Apply column pruning
205
+ if dynamic_columns:
206
+ row = {k: v for k, v in row.items() if k in dynamic_columns}
207
+
208
+ count += 1
209
+ if count % 1_000_000 == 0:
210
+ print(f" Processed {count:,} rows from JSONL...")
211
+
212
+ yield row
213
+ except json.JSONDecodeError:
214
+ continue
215
+
216
+ if count > 0:
217
+ print(f" ✓ Read {count:,} rows from JSONL")
218
+
219
+ def csv_source(dynamic_where: Optional[str] = None,
220
+ dynamic_columns: Optional[list] = None) -> Iterator[Dict]:
221
+ import csv
222
+ print(f" 📂 Reading CSV: {filepath}")
223
+ if dynamic_where:
224
+ print(f" ✅ Filter pushdown: {dynamic_where}")
225
+ if dynamic_columns:
226
+ print(f" ✅ Column pruning: {dynamic_columns}")
227
+
228
+ # Parse WHERE clause ONCE (not for every row!)
229
+ where_expr = None
230
+ if dynamic_where:
231
+ try:
232
+ from sqlglot import parse_one
233
+ parsed = parse_one(f"SELECT * FROM dummy WHERE {dynamic_where}")
234
+ where_expr = parsed.args.get('where')
235
+ if where_expr:
236
+ where_expr = where_expr.this
237
+ except Exception:
238
+ where_expr = None
239
+
240
+ # Import evaluator ONCE
241
+ evaluate_expression = None
242
+ if where_expr:
243
+ try:
244
+ from streaming_sql_engine.evaluator import evaluate_expression as eval_fn
245
+ evaluate_expression = eval_fn
246
+ except ImportError:
247
+ evaluate_expression = None
248
+
249
+ count = 0
250
+ with open(filepath, 'r', encoding='utf-8') as f:
251
+ reader = csv.DictReader(f)
252
+ for row in reader:
253
+ # Apply filter directly (no iterator creation!)
254
+ if where_expr and evaluate_expression:
255
+ # Prepare row for evaluation (remove table prefix)
256
+ eval_row = {k.split('.')[-1]: v for k, v in row.items()}
257
+ eval_row.update(row) # Keep original keys too
258
+
259
+ try:
260
+ if not evaluate_expression(where_expr, eval_row):
261
+ continue # Skip row
262
+ except Exception:
263
+ continue # Skip row on evaluation error
264
+
265
+ # Apply column pruning
266
+ if dynamic_columns:
267
+ row = {k: v for k, v in row.items() if k in dynamic_columns}
268
+
269
+ count += 1
270
+ if count % 1_000_000 == 0:
271
+ print(f" Processed {count:,} rows from CSV...")
272
+
273
+ yield row
274
+
275
+ if count > 0:
276
+ print(f" ✓ Read {count:,} rows from CSV")
277
+
278
+ if file_type == 'jsonl':
279
+ return jsonl_source
280
+ elif file_type == 'csv':
281
+ return csv_source
282
+ else:
283
+ raise ValueError(f"Unsupported file type: {file_type}")
284
+
285
+
286
+ # Convenience function for common use case
287
+ def register_file_source(engine, table_name: str, filepath: str,
288
+ filename: Optional[str] = None, ordered_by: Optional[str] = None):
289
+ """
290
+ Register a file source with automatic protocol support.
291
+
292
+ Usage:
293
+ register_file_source(engine, "products", "data/products.jsonl")
294
+ register_file_source(engine, "categories", "data/categories.csv")
295
+
296
+ # With mmap support
297
+ register_file_source(engine, "products", "data/products.jsonl",
298
+ filename="data/products.jsonl")
299
+ """
300
+ source_fn = create_protocol_source(filepath)
301
+ engine.register(table_name, source_fn, ordered_by=ordered_by, filename=filename)
302
+
303
+
304
+ def _default_where_to_params(where_clause: str) -> dict:
305
+ """
306
+ Default automatic WHERE-to-params converter.
307
+ Parses SQL WHERE clause and converts to API query parameters.
308
+
309
+ Handles common patterns automatically:
310
+ - Equality: column = value → params[column] = value
311
+ - Boolean: active = true → params[active] = 'true'
312
+ - Comparisons: price > 100 → params[min_price] = 100
313
+ """
314
+ params = {}
315
+
316
+ try:
317
+ # Parse SQL WHERE clause using sqlglot
318
+ from sqlglot import parse_one
319
+ parsed = parse_one(f"SELECT * FROM dummy WHERE {where_clause}")
320
+ where_expr = parsed.args.get('where')
321
+
322
+ if not where_expr:
323
+ return params
324
+
325
+ where_expr = where_expr.this
326
+
327
+ # Handle different expression types
328
+ from sqlglot import expressions as exp
329
+
330
+ def extract_value(expr):
331
+ """Extract literal value from expression."""
332
+ if isinstance(expr, exp.Literal):
333
+ value = expr.this
334
+ # Remove quotes if string
335
+ if isinstance(value, str):
336
+ return value.strip("'\"")
337
+ return value
338
+ return None
339
+
340
+ def extract_column(expr):
341
+ """Extract column name from expression."""
342
+ if isinstance(expr, exp.Column):
343
+ return expr.name
344
+ return None
345
+
346
+ # Handle equality: column = value
347
+ if isinstance(where_expr, exp.EQ):
348
+ col = extract_column(where_expr.this)
349
+ val = extract_value(where_expr.expression)
350
+ if col and val is not None:
351
+ params[col] = str(val)
352
+
353
+ # Handle AND conditions (multiple filters)
354
+ elif isinstance(where_expr, exp.And):
355
+ # Recursively process both sides
356
+ left_params = _default_where_to_params(str(where_expr.this))
357
+ right_params = _default_where_to_params(str(where_expr.expression))
358
+ params.update(left_params)
359
+ params.update(right_params)
360
+
361
+ # Handle comparisons: column > value, column < value
362
+ elif isinstance(where_expr, exp.GT):
363
+ col = extract_column(where_expr.this)
364
+ val = extract_value(where_expr.expression)
365
+ if col and val is not None:
366
+ params[f'min_{col}'] = str(val)
367
+
368
+ elif isinstance(where_expr, exp.LT):
369
+ col = extract_column(where_expr.this)
370
+ val = extract_value(where_expr.expression)
371
+ if col and val is not None:
372
+ params[f'max_{col}'] = str(val)
373
+
374
+ elif isinstance(where_expr, exp.GTE):
375
+ col = extract_column(where_expr.this)
376
+ val = extract_value(where_expr.expression)
377
+ if col and val is not None:
378
+ params[f'min_{col}'] = str(val)
379
+
380
+ elif isinstance(where_expr, exp.LTE):
381
+ col = extract_column(where_expr.this)
382
+ val = extract_value(where_expr.expression)
383
+ if col and val is not None:
384
+ params[f'max_{col}'] = str(val)
385
+
386
+ except Exception:
387
+ # Fallback to simple string matching for common patterns
388
+ where_lower = where_clause.lower()
389
+
390
+ # Boolean patterns
391
+ if 'active = true' in where_lower or "active = 'true'" in where_lower or "active = 1" in where_lower:
392
+ params['active'] = 'true'
393
+ elif 'active = false' in where_lower or "active = 'false'" in where_lower or "active = 0" in where_lower:
394
+ params['active'] = 'false'
395
+
396
+ # Country patterns
397
+ if "country = 'us'" in where_lower or "country = \"us\"" in where_lower:
398
+ params['country'] = 'US'
399
+ elif "country = 'uk'" in where_lower or "country = \"uk\"" in where_lower:
400
+ params['country'] = 'UK'
401
+
402
+ return params
403
+
404
+
405
+ def register_api_source(engine, table_name: str, api_url: str, endpoint: str,
406
+ where_to_params: Optional[Callable] = None):
407
+ """
408
+ Register an API source with automatic protocol support.
409
+
410
+ Usage:
411
+ # Simple API source (automatic WHERE-to-params conversion!)
412
+ register_api_source(engine, "customers", "http://localhost:8000", "customers")
413
+
414
+ # With custom WHERE-to-params converter (only if API has special format)
415
+ def my_converter(where_clause: str) -> dict:
416
+ params = {}
417
+ # Custom conversion logic for your API
418
+ return params
419
+
420
+ register_api_source(engine, "customers", "http://localhost:8000", "customers",
421
+ where_to_params=my_converter)
422
+
423
+ The default converter automatically handles:
424
+ - Equality: column = value → params[column] = value
425
+ - Boolean: active = true → params[active] = 'true'
426
+ - Comparisons: price > 100 → params[min_price] = 100
427
+ - Multiple conditions: AND clauses
428
+
429
+ Only provide custom converter if your API uses a different format.
430
+ """
431
+ import requests
432
+
433
+ def api_source(dynamic_where: Optional[str] = None,
434
+ dynamic_columns: Optional[list] = None) -> Iterator[Dict]:
435
+ print(f" 🌐 Reading from API: {api_url}/{endpoint}")
436
+ if dynamic_where:
437
+ print(f" ✅ Filter pushdown: {dynamic_where}")
438
+ if dynamic_columns:
439
+ print(f" ✅ Column pruning: {dynamic_columns}")
440
+
441
+ params = {}
442
+
443
+ # Convert WHERE clause to params
444
+ if dynamic_where:
445
+ if where_to_params:
446
+ # Use custom converter
447
+ params.update(where_to_params(dynamic_where))
448
+ else:
449
+ # Use automatic default converter
450
+ params.update(_default_where_to_params(dynamic_where))
451
+
452
+ # Convert columns to fields param
453
+ if dynamic_columns:
454
+ params['fields'] = ','.join(dynamic_columns)
455
+
456
+ # Make requests
457
+ page = 1
458
+ page_size = 1000
459
+ total_count = 0
460
+
461
+ while True:
462
+ params['page'] = page
463
+ params['page_size'] = page_size
464
+
465
+ try:
466
+ response = requests.get(f"{api_url}/{endpoint}", params=params, timeout=30)
467
+ response.raise_for_status()
468
+
469
+ data = response.json()
470
+ items = data.get('items', data.get('data', [])) if isinstance(data, dict) else data
471
+
472
+ if not items:
473
+ break
474
+
475
+ for item in items:
476
+ total_count += 1
477
+ if total_count % 10_000 == 0:
478
+ print(f" Fetched {total_count:,} records from API...")
479
+ yield item
480
+
481
+ if isinstance(data, dict) and not data.get('has_more', True):
482
+ break
483
+
484
+ page += 1
485
+ except requests.exceptions.RequestException as e:
486
+ print(f" ⚠️ API error: {e}")
487
+ break
488
+
489
+ if total_count > 0:
490
+ print(f" ✓ Fetched {total_count:,} records from API")
491
+
492
+ engine.register(table_name, api_source)
493
+
@@ -0,0 +1,7 @@
1
+ sqlglot>=23.0.0
2
+ psycopg2-binary>=2.9.0
3
+ python-dotenv>=1.0.0
4
+ pymysql>=1.0.0
5
+ DBUtils>=3.0.0
6
+ requests>=2.28.0
7
+ polars>=0.19.0
@@ -0,0 +1,69 @@
1
+ """
2
+ Setup script for streaming-sql-engine
3
+ """
4
+
5
+ from setuptools import setup, find_packages
6
+
7
+ with open("README.md", "r", encoding="utf-8") as fh:
8
+ long_description = fh.read()
9
+
10
+ with open("requirements.txt", "r", encoding="utf-8") as fh:
11
+ requirements = [line.strip() for line in fh if line.strip() and not line.startswith("#")]
12
+
13
+ setup(
14
+ name="streaming-sql-engine",
15
+ version="0.1.6",
16
+ author="Theodore Pantazopoulo",
17
+ author_email="your.email@example.com",
18
+ description="A lightweight SQL execution engine for streaming row-by-row queries with joins across multiple data sources",
19
+ long_description=long_description,
20
+ long_description_content_type="text/markdown",
21
+ url="https://github.com/Ierofantis/streaming-sql-engine/tree/master",
22
+ # Package structure: files are in root directory
23
+ packages=["streaming_sql_engine"],
24
+ package_dir={"streaming_sql_engine": "."},
25
+ py_modules=[
26
+ "streaming_sql_engine.engine",
27
+ "streaming_sql_engine.executor",
28
+ "streaming_sql_engine.parser",
29
+ "streaming_sql_engine.planner",
30
+ "streaming_sql_engine.optimizer",
31
+ "streaming_sql_engine.evaluator",
32
+ "streaming_sql_engine.operators",
33
+ "streaming_sql_engine.operators_polars",
34
+ "streaming_sql_engine.operators_mmap",
35
+ "streaming_sql_engine.mmap_index",
36
+ "streaming_sql_engine.polars_expression_translator",
37
+ "streaming_sql_engine.protocol_helpers",
38
+ ],
39
+ include_package_data=True,
40
+ classifiers=[
41
+ "Development Status :: 3 - Alpha",
42
+ "Intended Audience :: Developers",
43
+ "Topic :: Software Development :: Libraries :: Python Modules",
44
+ "Topic :: Database",
45
+ "Programming Language :: Python :: 3",
46
+ "Programming Language :: Python :: 3.8",
47
+ "Programming Language :: Python :: 3.9",
48
+ "Programming Language :: Python :: 3.10",
49
+ "Programming Language :: Python :: 3.11",
50
+ "Programming Language :: Python :: 3.12",
51
+ ],
52
+ python_requires=">=3.8",
53
+ install_requires=requirements,
54
+ extras_require={
55
+ "dev": [
56
+ "pytest>=7.0.0",
57
+ "pytest-cov>=4.0.0",
58
+ "black>=23.0.0",
59
+ "flake8>=6.0.0",
60
+ ],
61
+ },
62
+ keywords="sql streaming join database query engine",
63
+ project_urls={
64
+ "Bug Reports": "https://github.com/Ierofantis/streaming-sql-engine/issues",
65
+ "Source": "https://github.com/Ierofantis/streaming-sql-engine/tree/master",
66
+ "Documentation": "https://github.com/Ierofantis/streaming-sql-engine/tree/master#readme",
67
+ },
68
+ )
69
+