streaming-sql-engine 0.1.0__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.
- streaming_sql_engine/__init__.py +30 -0
- streaming_sql_engine/db_connector.py +353 -0
- streaming_sql_engine/engine.py +109 -0
- streaming_sql_engine/evaluator.py +218 -0
- streaming_sql_engine/executor.py +133 -0
- streaming_sql_engine/jsonl_executor.py +393 -0
- streaming_sql_engine/operators.py +479 -0
- streaming_sql_engine/parser.py +93 -0
- streaming_sql_engine/planner.py +156 -0
- streaming_sql_engine-0.1.0.dist-info/METADATA +289 -0
- streaming_sql_engine-0.1.0.dist-info/RECORD +13 -0
- streaming_sql_engine-0.1.0.dist-info/WHEEL +5 -0
- streaming_sql_engine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Rivulet - Streaming SQL Join Engine
|
|
3
|
+
|
|
4
|
+
A lightweight SQL execution engine that processes queries row-by-row
|
|
5
|
+
without loading full tables into memory.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .engine import Engine
|
|
9
|
+
from .db_connector import (
|
|
10
|
+
PostgreSQLPool,
|
|
11
|
+
MySQLPool,
|
|
12
|
+
create_pool_from_env,
|
|
13
|
+
create_mysql_pool_from_env,
|
|
14
|
+
create_postgresql_pool_from_env,
|
|
15
|
+
stream_query,
|
|
16
|
+
create_table_source
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Engine",
|
|
22
|
+
"PostgreSQLPool",
|
|
23
|
+
"MySQLPool",
|
|
24
|
+
"create_pool_from_env",
|
|
25
|
+
"create_mysql_pool_from_env",
|
|
26
|
+
"create_postgresql_pool_from_env",
|
|
27
|
+
"stream_query",
|
|
28
|
+
"create_table_source"
|
|
29
|
+
]
|
|
30
|
+
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Database connector utilities for PostgreSQL and MySQL.
|
|
3
|
+
Provides connection pooling and streaming row iterators.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
|
|
9
|
+
# PostgreSQL imports
|
|
10
|
+
try:
|
|
11
|
+
import psycopg2
|
|
12
|
+
from psycopg2 import pool
|
|
13
|
+
from psycopg2.extras import RealDictCursor as PgRealDictCursor
|
|
14
|
+
PSYCOPG2_AVAILABLE = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
PSYCOPG2_AVAILABLE = False
|
|
17
|
+
|
|
18
|
+
# MySQL imports
|
|
19
|
+
try:
|
|
20
|
+
import pymysql
|
|
21
|
+
from dbutils.pooled_db import PooledDB
|
|
22
|
+
PYMYSQL_AVAILABLE = True
|
|
23
|
+
except ImportError:
|
|
24
|
+
PYMYSQL_AVAILABLE = False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class PostgreSQLPool:
|
|
28
|
+
"""
|
|
29
|
+
PostgreSQL connection pool manager.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
host,
|
|
35
|
+
port,
|
|
36
|
+
user,
|
|
37
|
+
password,
|
|
38
|
+
database,
|
|
39
|
+
minconn=1,
|
|
40
|
+
maxconn=200
|
|
41
|
+
):
|
|
42
|
+
"""
|
|
43
|
+
Initialize PostgreSQL connection pool.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
host: Database host
|
|
47
|
+
port: Database port
|
|
48
|
+
user: Database user
|
|
49
|
+
password: Database password
|
|
50
|
+
database: Database name
|
|
51
|
+
minconn: Minimum number of connections
|
|
52
|
+
maxconn: Maximum number of connections
|
|
53
|
+
"""
|
|
54
|
+
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
|
55
|
+
minconn=minconn,
|
|
56
|
+
maxconn=maxconn,
|
|
57
|
+
host=host,
|
|
58
|
+
port=port,
|
|
59
|
+
user=user,
|
|
60
|
+
password=password,
|
|
61
|
+
database=database
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
@contextmanager
|
|
65
|
+
def get_connection(self):
|
|
66
|
+
"""Get a connection from the pool (context manager)."""
|
|
67
|
+
conn = self.pool.getconn()
|
|
68
|
+
try:
|
|
69
|
+
yield conn
|
|
70
|
+
finally:
|
|
71
|
+
self.pool.putconn(conn)
|
|
72
|
+
|
|
73
|
+
def closeall(self):
|
|
74
|
+
"""Close all connections in the pool."""
|
|
75
|
+
self.pool.closeall()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class MySQLPool:
|
|
79
|
+
"""
|
|
80
|
+
MySQL connection pool manager using pymysql and PooledDB.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
host,
|
|
86
|
+
port,
|
|
87
|
+
user,
|
|
88
|
+
password,
|
|
89
|
+
database,
|
|
90
|
+
maxconnections=200
|
|
91
|
+
):
|
|
92
|
+
"""
|
|
93
|
+
Initialize MySQL connection pool.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
host: Database host
|
|
97
|
+
port: Database port
|
|
98
|
+
user: Database user
|
|
99
|
+
password: Database password
|
|
100
|
+
database: Database name
|
|
101
|
+
maxconnections: Maximum number of connections
|
|
102
|
+
"""
|
|
103
|
+
if not PYMYSQL_AVAILABLE:
|
|
104
|
+
raise ImportError(
|
|
105
|
+
"pymysql and dbutils are required for MySQL support. "
|
|
106
|
+
"Install with: pip install pymysql dbutils"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
self.pool = PooledDB(
|
|
110
|
+
creator=pymysql,
|
|
111
|
+
maxconnections=maxconnections,
|
|
112
|
+
host=host,
|
|
113
|
+
port=port,
|
|
114
|
+
user=user,
|
|
115
|
+
password=password,
|
|
116
|
+
database=database,
|
|
117
|
+
cursorclass=pymysql.cursors.DictCursor
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
@contextmanager
|
|
121
|
+
def get_connection(self):
|
|
122
|
+
"""Get a connection from the pool (context manager)."""
|
|
123
|
+
conn = self.pool.connection()
|
|
124
|
+
try:
|
|
125
|
+
yield conn
|
|
126
|
+
finally:
|
|
127
|
+
conn.close()
|
|
128
|
+
|
|
129
|
+
def closeall(self):
|
|
130
|
+
"""Close all connections in the pool."""
|
|
131
|
+
self.pool.close()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def create_pool_from_env(db_type=None):
|
|
135
|
+
"""
|
|
136
|
+
Create a database pool from environment variables.
|
|
137
|
+
Auto-detects database type based on port if not specified.
|
|
138
|
+
|
|
139
|
+
Expected environment variables:
|
|
140
|
+
- db_host
|
|
141
|
+
- db_port
|
|
142
|
+
- db_user
|
|
143
|
+
- db_password
|
|
144
|
+
- db_name
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
db_type: Optional database type ('postgresql' or 'mysql').
|
|
148
|
+
If None, auto-detects based on port (3306=MySQL, 5432=PostgreSQL)
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
PostgreSQLPool or MySQLPool instance
|
|
152
|
+
|
|
153
|
+
Raises:
|
|
154
|
+
ValueError: If port/db_type mismatch or unsupported database type
|
|
155
|
+
ImportError: If required database driver is not installed
|
|
156
|
+
"""
|
|
157
|
+
host = os.environ.get('db_host', 'localhost')
|
|
158
|
+
port = int(os.environ.get('db_port', 5432))
|
|
159
|
+
user = os.environ.get('db_user', 'postgres')
|
|
160
|
+
password = os.environ.get('db_password', '')
|
|
161
|
+
database = os.environ.get('db_name', 'postgres')
|
|
162
|
+
|
|
163
|
+
# Auto-detect database type if not specified
|
|
164
|
+
if db_type is None:
|
|
165
|
+
if port == 3306:
|
|
166
|
+
db_type = 'mysql'
|
|
167
|
+
elif port == 5432:
|
|
168
|
+
db_type = 'postgresql'
|
|
169
|
+
else:
|
|
170
|
+
# Default to PostgreSQL for unknown ports, but warn
|
|
171
|
+
import warnings
|
|
172
|
+
warnings.warn(
|
|
173
|
+
f"Port {port} is not a standard database port. "
|
|
174
|
+
"Defaulting to PostgreSQL. If using MySQL, set db_type='mysql' or use port 3306.",
|
|
175
|
+
UserWarning
|
|
176
|
+
)
|
|
177
|
+
db_type = 'postgresql'
|
|
178
|
+
|
|
179
|
+
# Validate port/db_type combination
|
|
180
|
+
if db_type == 'mysql' and port != 3306:
|
|
181
|
+
import warnings
|
|
182
|
+
warnings.warn(
|
|
183
|
+
f"MySQL typically uses port 3306, but port {port} is specified. "
|
|
184
|
+
"Continuing anyway...",
|
|
185
|
+
UserWarning
|
|
186
|
+
)
|
|
187
|
+
elif db_type == 'postgresql' and port == 3306:
|
|
188
|
+
raise ValueError(
|
|
189
|
+
f"Port 3306 is typically MySQL, but db_type='postgresql' was specified. "
|
|
190
|
+
"If you're using MySQL, set db_type='mysql' or use create_mysql_pool_from_env()."
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
if db_type == 'mysql':
|
|
194
|
+
if not PYMYSQL_AVAILABLE:
|
|
195
|
+
raise ImportError(
|
|
196
|
+
"pymysql and dbutils are required for MySQL support. "
|
|
197
|
+
"Install with: pip install pymysql dbutils"
|
|
198
|
+
)
|
|
199
|
+
return MySQLPool(host, port, user, password, database)
|
|
200
|
+
elif db_type == 'postgresql':
|
|
201
|
+
if not PSYCOPG2_AVAILABLE:
|
|
202
|
+
raise ImportError(
|
|
203
|
+
"psycopg2 is required for PostgreSQL support. "
|
|
204
|
+
"Install with: pip install psycopg2-binary"
|
|
205
|
+
)
|
|
206
|
+
return PostgreSQLPool(host, port, user, password, database)
|
|
207
|
+
else:
|
|
208
|
+
raise ValueError(f"Unsupported database type: {db_type}. Use 'postgresql' or 'mysql'.")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def create_mysql_pool_from_env():
|
|
212
|
+
"""
|
|
213
|
+
Create a MySQL pool from environment variables.
|
|
214
|
+
Convenience function for MySQL connections.
|
|
215
|
+
|
|
216
|
+
Expected environment variables:
|
|
217
|
+
- db_host
|
|
218
|
+
- db_port (defaults to 3306 if not set)
|
|
219
|
+
- db_user
|
|
220
|
+
- db_password
|
|
221
|
+
- db_name
|
|
222
|
+
"""
|
|
223
|
+
return create_pool_from_env(db_type='mysql')
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def create_postgresql_pool_from_env():
|
|
227
|
+
"""
|
|
228
|
+
Create a PostgreSQL pool from environment variables.
|
|
229
|
+
Convenience function for PostgreSQL connections.
|
|
230
|
+
|
|
231
|
+
Expected environment variables:
|
|
232
|
+
- db_host
|
|
233
|
+
- db_port (defaults to 5432 if not set)
|
|
234
|
+
- db_user
|
|
235
|
+
- db_password
|
|
236
|
+
- db_name
|
|
237
|
+
"""
|
|
238
|
+
return create_pool_from_env(db_type='postgresql')
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def stream_query(
|
|
242
|
+
pool,
|
|
243
|
+
query,
|
|
244
|
+
params=None,
|
|
245
|
+
fetch_size=1000
|
|
246
|
+
):
|
|
247
|
+
"""
|
|
248
|
+
Stream rows from a database query as a generator.
|
|
249
|
+
Supports both PostgreSQL and MySQL.
|
|
250
|
+
|
|
251
|
+
Args:
|
|
252
|
+
pool: Database connection pool (PostgreSQLPool or MySQLPool)
|
|
253
|
+
query: SQL query string
|
|
254
|
+
params: Optional query parameters (for parameterized queries)
|
|
255
|
+
fetch_size: Number of rows to fetch at a time
|
|
256
|
+
|
|
257
|
+
Yields:
|
|
258
|
+
Dictionary representing each row
|
|
259
|
+
|
|
260
|
+
Example:
|
|
261
|
+
pool = create_pool_from_env()
|
|
262
|
+
for row in stream_query(pool, "SELECT * FROM users WHERE active = %s", (True,)):
|
|
263
|
+
print(row)
|
|
264
|
+
"""
|
|
265
|
+
with pool.get_connection() as conn:
|
|
266
|
+
if isinstance(pool, PostgreSQLPool):
|
|
267
|
+
# PostgreSQL: Use server-side cursor for efficient streaming
|
|
268
|
+
cursor = conn.cursor(
|
|
269
|
+
name='streaming_cursor',
|
|
270
|
+
cursor_factory=PgRealDictCursor
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
try:
|
|
274
|
+
# Execute query with server-side cursor
|
|
275
|
+
if params:
|
|
276
|
+
cursor.execute(query, params)
|
|
277
|
+
else:
|
|
278
|
+
cursor.execute(query)
|
|
279
|
+
|
|
280
|
+
# Stream rows in batches
|
|
281
|
+
while True:
|
|
282
|
+
rows = cursor.fetchmany(fetch_size)
|
|
283
|
+
if not rows:
|
|
284
|
+
break
|
|
285
|
+
|
|
286
|
+
for row in rows:
|
|
287
|
+
# Convert RealDictRow to regular dict
|
|
288
|
+
yield dict(row)
|
|
289
|
+
finally:
|
|
290
|
+
cursor.close()
|
|
291
|
+
|
|
292
|
+
elif isinstance(pool, MySQLPool):
|
|
293
|
+
# MySQL: Use regular cursor with fetchmany
|
|
294
|
+
cursor = conn.cursor()
|
|
295
|
+
|
|
296
|
+
try:
|
|
297
|
+
# Execute query
|
|
298
|
+
if params:
|
|
299
|
+
cursor.execute(query, params)
|
|
300
|
+
else:
|
|
301
|
+
cursor.execute(query)
|
|
302
|
+
|
|
303
|
+
# Stream rows in batches
|
|
304
|
+
while True:
|
|
305
|
+
rows = cursor.fetchmany(fetch_size)
|
|
306
|
+
if not rows:
|
|
307
|
+
break
|
|
308
|
+
|
|
309
|
+
for row in rows:
|
|
310
|
+
# pymysql DictCursor already returns dicts
|
|
311
|
+
yield dict(row)
|
|
312
|
+
finally:
|
|
313
|
+
cursor.close()
|
|
314
|
+
|
|
315
|
+
else:
|
|
316
|
+
raise ValueError(f"Unsupported pool type: {type(pool)}")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def create_table_source(
|
|
320
|
+
pool,
|
|
321
|
+
table_name,
|
|
322
|
+
where_clause=None,
|
|
323
|
+
order_by=None
|
|
324
|
+
):
|
|
325
|
+
"""
|
|
326
|
+
Create a source function for a database table.
|
|
327
|
+
Supports both PostgreSQL and MySQL.
|
|
328
|
+
|
|
329
|
+
Args:
|
|
330
|
+
pool: Database connection pool (PostgreSQLPool or MySQLPool)
|
|
331
|
+
table_name: Name of the table
|
|
332
|
+
where_clause: Optional WHERE clause (without WHERE keyword)
|
|
333
|
+
order_by: Optional ORDER BY clause (without ORDER BY keyword)
|
|
334
|
+
|
|
335
|
+
Returns:
|
|
336
|
+
A function that returns an iterator of row dictionaries
|
|
337
|
+
|
|
338
|
+
Example:
|
|
339
|
+
pool = create_pool_from_env()
|
|
340
|
+
source_fn = create_table_source(pool, "users", "active = 1", "id")
|
|
341
|
+
engine.register("users", source_fn, ordered_by="id")
|
|
342
|
+
"""
|
|
343
|
+
def source_fn():
|
|
344
|
+
query = f"SELECT * FROM {table_name}"
|
|
345
|
+
if where_clause:
|
|
346
|
+
query += f" WHERE {where_clause}"
|
|
347
|
+
if order_by:
|
|
348
|
+
query += f" ORDER BY {order_by}"
|
|
349
|
+
|
|
350
|
+
return stream_query(pool, query)
|
|
351
|
+
|
|
352
|
+
return source_fn
|
|
353
|
+
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Main Engine class - public API for the streaming SQL engine.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
from .parser import parse_sql
|
|
7
|
+
from .planner import build_logical_plan
|
|
8
|
+
from .executor import execute_plan
|
|
9
|
+
from .jsonl_executor import execute_plan_jsonl
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Engine:
|
|
13
|
+
"""
|
|
14
|
+
Main interface for the streaming SQL execution engine.
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
engine = Engine(debug=True) # Enable debug mode
|
|
18
|
+
engine.register("users", lambda: iter([{"id": 1, "name": "Alice"}]))
|
|
19
|
+
results = engine.query("SELECT users.name FROM users WHERE users.id = 1")
|
|
20
|
+
for row in results:
|
|
21
|
+
print(row)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, debug=False, use_jsonl_mode=False):
|
|
25
|
+
"""
|
|
26
|
+
Initialize a new engine instance.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
debug: If True, enables verbose logging of execution stages
|
|
30
|
+
use_jsonl_mode: If True, uses JSONL-based execution (export tables to JSONL, then merge)
|
|
31
|
+
This is simpler and can reduce CPU usage for complex queries
|
|
32
|
+
"""
|
|
33
|
+
self._sources = {}
|
|
34
|
+
self._source_metadata = {}
|
|
35
|
+
self.debug = debug
|
|
36
|
+
self.use_jsonl_mode = use_jsonl_mode
|
|
37
|
+
|
|
38
|
+
def register(
|
|
39
|
+
self,
|
|
40
|
+
table_name,
|
|
41
|
+
source_fn,
|
|
42
|
+
ordered_by=None
|
|
43
|
+
):
|
|
44
|
+
"""
|
|
45
|
+
Register a table source.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
table_name: Name of the table as used in SQL queries
|
|
49
|
+
source_fn: Function that returns an iterator of row dictionaries
|
|
50
|
+
ordered_by: Optional column name if the source is sorted by this column
|
|
51
|
+
(enables merge joins)
|
|
52
|
+
"""
|
|
53
|
+
if not callable(source_fn):
|
|
54
|
+
raise ValueError(f"source_fn must be callable, got {type(source_fn)}")
|
|
55
|
+
|
|
56
|
+
self._sources[table_name] = source_fn
|
|
57
|
+
self._source_metadata[table_name] = {
|
|
58
|
+
"ordered_by": ordered_by
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
def query(self, sql):
|
|
62
|
+
"""
|
|
63
|
+
Execute a SQL query and return a generator of result rows.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
sql: SQL query string
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Generator yielding dictionaries representing result rows
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
ValueError: If query contains unsupported constructs
|
|
73
|
+
KeyError: If referenced table is not registered
|
|
74
|
+
"""
|
|
75
|
+
if self.debug:
|
|
76
|
+
print("=" * 60)
|
|
77
|
+
print("STREAMING SQL ENGINE - DEBUG MODE")
|
|
78
|
+
print("=" * 60)
|
|
79
|
+
print(f"\n[1/3] PARSING SQL QUERY...")
|
|
80
|
+
print(f"Query:\n{sql}\n")
|
|
81
|
+
|
|
82
|
+
# Parse SQL into AST
|
|
83
|
+
ast = parse_sql(sql)
|
|
84
|
+
|
|
85
|
+
if self.debug:
|
|
86
|
+
print(f"✓ SQL parsed successfully")
|
|
87
|
+
print(f"\n[2/3] BUILDING LOGICAL PLAN...")
|
|
88
|
+
|
|
89
|
+
# Build logical plan
|
|
90
|
+
logical_plan = build_logical_plan(ast, self._sources.keys())
|
|
91
|
+
|
|
92
|
+
if self.debug:
|
|
93
|
+
print(f"✓ Logical plan built:")
|
|
94
|
+
print(f" - Root table: {logical_plan.root_table} (alias: {logical_plan.root_alias})")
|
|
95
|
+
print(f" - Joins: {len(logical_plan.joins)}")
|
|
96
|
+
for i, join in enumerate[Any](logical_plan.joins, 1):
|
|
97
|
+
print(f" {i}. {join.join_type} JOIN {join.table} ON {join.left_key} = {join.right_key}")
|
|
98
|
+
print(f" - WHERE clause: {'Yes' if logical_plan.where_expr else 'No'}")
|
|
99
|
+
print(f" - Projections: {len(logical_plan.projections)}")
|
|
100
|
+
print(f"\n[3/3] EXECUTING QUERY...")
|
|
101
|
+
print(f"Building execution pipeline...\n")
|
|
102
|
+
|
|
103
|
+
# Execute plan
|
|
104
|
+
if self.use_jsonl_mode:
|
|
105
|
+
if self.debug:
|
|
106
|
+
print(f"\nUsing JSONL-based execution mode (simpler, lower CPU)\n")
|
|
107
|
+
return execute_plan_jsonl(logical_plan, self._sources, self._source_metadata, debug=self.debug)
|
|
108
|
+
else:
|
|
109
|
+
return execute_plan(logical_plan, self._sources, self._source_metadata, debug=self.debug)
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Expression evaluator for WHERE clauses and SELECT projections.
|
|
3
|
+
Optimized to reduce isinstance() checks using expression type caching.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from sqlglot import expressions as exp
|
|
7
|
+
|
|
8
|
+
# Cache expression type classes for faster isinstance checks
|
|
9
|
+
_COLUMN_TYPE = exp.Column
|
|
10
|
+
_LITERAL_TYPE = exp.Literal
|
|
11
|
+
_EQ_TYPE = exp.EQ
|
|
12
|
+
_NEQ_TYPE = exp.NEQ
|
|
13
|
+
_LT_TYPE = exp.LT
|
|
14
|
+
_GT_TYPE = exp.GT
|
|
15
|
+
_LTE_TYPE = exp.LTE
|
|
16
|
+
_GTE_TYPE = exp.GTE
|
|
17
|
+
_AND_TYPE = exp.And
|
|
18
|
+
_OR_TYPE = exp.Or
|
|
19
|
+
_NOT_TYPE = exp.Not
|
|
20
|
+
_IS_TYPE = exp.Is
|
|
21
|
+
_ALIAS_TYPE = exp.Alias
|
|
22
|
+
_PAREN_TYPE = exp.Paren
|
|
23
|
+
_IN_TYPE = exp.In
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _coerce_comparable_types(left, right):
|
|
27
|
+
"""
|
|
28
|
+
Coerce two values to comparable types for comparison operations.
|
|
29
|
+
|
|
30
|
+
Handles cases where one value is a number (int/float) and the other is a string
|
|
31
|
+
that can be converted to a number.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
left: Left operand
|
|
35
|
+
right: Right operand
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Tuple of (left, right) with coerced types
|
|
39
|
+
"""
|
|
40
|
+
# If both are same type or both None, no coercion needed
|
|
41
|
+
if type(left) == type(right) or (left is None and right is None):
|
|
42
|
+
return left, right
|
|
43
|
+
|
|
44
|
+
# If one is None, comparisons are False (except !=)
|
|
45
|
+
if left is None or right is None:
|
|
46
|
+
return left, right
|
|
47
|
+
|
|
48
|
+
# Try to coerce string to number if one is numeric
|
|
49
|
+
if isinstance(left, (int, float)) and isinstance(right, str):
|
|
50
|
+
try:
|
|
51
|
+
# Try to convert string to number
|
|
52
|
+
if '.' in right or 'e' in right.lower() or 'E' in right:
|
|
53
|
+
right = float(right)
|
|
54
|
+
else:
|
|
55
|
+
right = int(right)
|
|
56
|
+
except (ValueError, TypeError):
|
|
57
|
+
# Can't convert, keep as string (will raise TypeError on comparison)
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
elif isinstance(right, (int, float)) and isinstance(left, str):
|
|
61
|
+
try:
|
|
62
|
+
# Try to convert string to number
|
|
63
|
+
if '.' in left or 'e' in left.lower() or 'E' in left:
|
|
64
|
+
left = float(left)
|
|
65
|
+
else:
|
|
66
|
+
left = int(left)
|
|
67
|
+
except (ValueError, TypeError):
|
|
68
|
+
# Can't convert, keep as string (will raise TypeError on comparison)
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
return left, right
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def evaluate_expression(expr, row):
|
|
75
|
+
"""
|
|
76
|
+
Evaluate a SQL expression against a row.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
expr: SQL expression AST node
|
|
80
|
+
row: Row dictionary with prefixed column names (e.g., "alias.column")
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
Evaluated value
|
|
84
|
+
"""
|
|
85
|
+
# Use cached type references for faster isinstance checks
|
|
86
|
+
expr_type = type(expr)
|
|
87
|
+
|
|
88
|
+
if expr_type is _COLUMN_TYPE:
|
|
89
|
+
# Column reference
|
|
90
|
+
col_name = f"{expr.table}.{expr.name}" if expr.table else expr.name
|
|
91
|
+
if col_name in row:
|
|
92
|
+
return row[col_name]
|
|
93
|
+
# Try without table prefix
|
|
94
|
+
if expr.name in row:
|
|
95
|
+
return row[expr.name]
|
|
96
|
+
raise KeyError(f"Column {col_name} not found in row")
|
|
97
|
+
|
|
98
|
+
elif expr_type is _LITERAL_TYPE:
|
|
99
|
+
# Literal value
|
|
100
|
+
return expr.this
|
|
101
|
+
|
|
102
|
+
elif expr_type is _EQ_TYPE:
|
|
103
|
+
# Equality: left = right
|
|
104
|
+
left = evaluate_expression(expr.this, row)
|
|
105
|
+
right = evaluate_expression(expr.expression, row)
|
|
106
|
+
return left == right
|
|
107
|
+
|
|
108
|
+
elif expr_type is _NEQ_TYPE:
|
|
109
|
+
# Inequality: left != right
|
|
110
|
+
left = evaluate_expression(expr.this, row)
|
|
111
|
+
right = evaluate_expression(expr.expression, row)
|
|
112
|
+
return left != right
|
|
113
|
+
|
|
114
|
+
elif expr_type is _LT_TYPE:
|
|
115
|
+
# Less than: left < right
|
|
116
|
+
left = evaluate_expression(expr.this, row)
|
|
117
|
+
right = evaluate_expression(expr.expression, row)
|
|
118
|
+
left, right = _coerce_comparable_types(left, right)
|
|
119
|
+
return left < right
|
|
120
|
+
|
|
121
|
+
elif expr_type is _GT_TYPE:
|
|
122
|
+
# Greater than: left > right
|
|
123
|
+
left = evaluate_expression(expr.this, row)
|
|
124
|
+
right = evaluate_expression(expr.expression, row)
|
|
125
|
+
left, right = _coerce_comparable_types(left, right)
|
|
126
|
+
return left > right
|
|
127
|
+
|
|
128
|
+
elif expr_type is _LTE_TYPE:
|
|
129
|
+
# Less than or equal: left <= right
|
|
130
|
+
left = evaluate_expression(expr.this, row)
|
|
131
|
+
right = evaluate_expression(expr.expression, row)
|
|
132
|
+
left, right = _coerce_comparable_types(left, right)
|
|
133
|
+
return left <= right
|
|
134
|
+
|
|
135
|
+
elif expr_type is _GTE_TYPE:
|
|
136
|
+
# Greater than or equal: left >= right
|
|
137
|
+
left = evaluate_expression(expr.this, row)
|
|
138
|
+
right = evaluate_expression(expr.expression, row)
|
|
139
|
+
left, right = _coerce_comparable_types(left, right)
|
|
140
|
+
return left >= right
|
|
141
|
+
|
|
142
|
+
elif expr_type is _AND_TYPE:
|
|
143
|
+
# AND: left AND right
|
|
144
|
+
left = evaluate_expression(expr.this, row)
|
|
145
|
+
if not left:
|
|
146
|
+
return False
|
|
147
|
+
right = evaluate_expression(expr.expression, row)
|
|
148
|
+
return bool(right)
|
|
149
|
+
|
|
150
|
+
elif expr_type is _OR_TYPE:
|
|
151
|
+
# OR: left OR right
|
|
152
|
+
left = evaluate_expression(expr.this, row)
|
|
153
|
+
if left:
|
|
154
|
+
return True
|
|
155
|
+
right = evaluate_expression(expr.expression, row)
|
|
156
|
+
return bool(right)
|
|
157
|
+
|
|
158
|
+
elif expr_type is _NOT_TYPE:
|
|
159
|
+
# NOT: NOT expr
|
|
160
|
+
value = evaluate_expression(expr.this, row)
|
|
161
|
+
return not value
|
|
162
|
+
|
|
163
|
+
elif expr_type is _IS_TYPE:
|
|
164
|
+
# IS NULL / IS NOT NULL
|
|
165
|
+
value = evaluate_expression(expr.this, row)
|
|
166
|
+
if expr.expression is None:
|
|
167
|
+
# IS NULL
|
|
168
|
+
return value is None
|
|
169
|
+
elif isinstance(expr.expression, exp.Null):
|
|
170
|
+
# IS NULL
|
|
171
|
+
return value is None
|
|
172
|
+
elif isinstance(expr.expression, exp.Not) and isinstance(expr.expression.this, exp.Null):
|
|
173
|
+
# IS NOT NULL
|
|
174
|
+
return value is not None
|
|
175
|
+
else:
|
|
176
|
+
raise ValueError(f"Unsupported IS expression: {expr}")
|
|
177
|
+
|
|
178
|
+
elif expr_type is _ALIAS_TYPE:
|
|
179
|
+
# Alias - evaluate the inner expression
|
|
180
|
+
return evaluate_expression(expr.this, row)
|
|
181
|
+
|
|
182
|
+
elif expr_type is _PAREN_TYPE:
|
|
183
|
+
# Parentheses - evaluate inner expression
|
|
184
|
+
return evaluate_expression(expr.this, row)
|
|
185
|
+
|
|
186
|
+
elif expr_type is _IN_TYPE:
|
|
187
|
+
# IN clause: column IN (value1, value2, ...)
|
|
188
|
+
left = evaluate_expression(expr.this, row)
|
|
189
|
+
# Get the list of values from the expression
|
|
190
|
+
if isinstance(expr.expression, exp.Tuple):
|
|
191
|
+
values = [evaluate_expression(e, row) for e in expr.expression.expressions]
|
|
192
|
+
elif isinstance(expr.expression, (list, tuple)):
|
|
193
|
+
values = [evaluate_expression(e, row) for e in expr.expression]
|
|
194
|
+
else:
|
|
195
|
+
# Could be a subquery (not supported)
|
|
196
|
+
raise ValueError("IN clause with subqueries is not supported")
|
|
197
|
+
return left in values
|
|
198
|
+
|
|
199
|
+
elif isinstance(expr, exp.Not) and isinstance(expr.this, exp.In):
|
|
200
|
+
# NOT IN clause
|
|
201
|
+
in_expr = expr.this
|
|
202
|
+
left = evaluate_expression(in_expr.this, row)
|
|
203
|
+
if isinstance(in_expr.expression, exp.Tuple):
|
|
204
|
+
values = [evaluate_expression(e, row) for e in in_expr.expression.expressions]
|
|
205
|
+
elif isinstance(in_expr.expression, (list, tuple)):
|
|
206
|
+
values = [evaluate_expression(e, row) for e in in_expr.expression]
|
|
207
|
+
else:
|
|
208
|
+
raise ValueError("NOT IN clause with subqueries is not supported")
|
|
209
|
+
return left not in values
|
|
210
|
+
|
|
211
|
+
elif isinstance(expr, exp.Where):
|
|
212
|
+
# Where node should be unwrapped before reaching evaluator
|
|
213
|
+
# If it reaches here, unwrap it and evaluate the inner expression
|
|
214
|
+
return evaluate_expression(expr.this, row)
|
|
215
|
+
|
|
216
|
+
else:
|
|
217
|
+
raise ValueError(f"Unsupported expression type: {type(expr).__name__}")
|
|
218
|
+
|