-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathtest_multi_statement_limits.py
More file actions
329 lines (269 loc) · 11.6 KB
/
test_multi_statement_limits.py
File metadata and controls
329 lines (269 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"""Integration test for multi-statement LIMIT enforcement.
Regression test for https://github.com/fredrikaverpil/sqlit/issues/132:
When running multiple queries with different LIMIT clauses via "Run All",
each result table should have the correct number of rows.
Tests against real MySQL (via Docker) and SQLite to catch driver-specific issues.
"""
from __future__ import annotations
import sqlite3
import pytest
from sqlit.domains.query.app.multi_statement import MultiStatementExecutor
from sqlit.domains.query.app.query_service import (
KeywordQueryAnalyzer,
NonQueryResult,
QueryKind,
QueryResult,
)
class CursorBasedExecutor:
"""Executor using CursorBasedAdapter's execute_query/execute_non_query logic.
This mirrors how MultiStatementExecutor calls TransactionExecutor,
which calls _execute_on_connection, which calls adapter.execute_query.
The logic is copied verbatim from CursorBasedAdapter to test the exact
same code path against real database connections.
"""
def __init__(self, conn) -> None:
self._conn = conn
self._analyzer = KeywordQueryAnalyzer()
def execute(self, sql: str, max_rows: int | None = None) -> QueryResult | NonQueryResult:
if self._analyzer.classify(sql) == QueryKind.RETURNS_ROWS:
# Verbatim from CursorBasedAdapter.execute_query
cursor = self._conn.cursor()
cursor.execute(sql)
if cursor.description:
columns = [col[0] for col in cursor.description]
if max_rows is not None:
rows = cursor.fetchmany(max_rows + 1)
truncated = len(rows) > max_rows
if truncated:
rows = rows[:max_rows]
else:
rows = cursor.fetchall()
truncated = False
return QueryResult(
columns=columns,
rows=[tuple(row) for row in rows],
row_count=len(rows),
truncated=truncated,
)
return QueryResult(columns=[], rows=[], row_count=0, truncated=False)
else:
# Verbatim from CursorBasedAdapter.execute_non_query
cursor = self._conn.cursor()
cursor.execute(sql)
rowcount = int(cursor.rowcount)
self._conn.commit()
return NonQueryResult(rows_affected=rowcount)
# ---------------------------------------------------------------------------
# MySQL tests
# ---------------------------------------------------------------------------
def _mysql_connect():
"""Connect to MySQL test instance, skip if unavailable."""
try:
import pymysql
except ImportError:
pytest.skip("PyMySQL not installed")
from tests.fixtures.mysql import MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD
try:
conn = pymysql.connect(
host=MYSQL_HOST,
port=MYSQL_PORT,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
connect_timeout=5,
autocommit=True,
charset="utf8mb4",
)
except Exception as e:
pytest.skip(f"MySQL not available: {e}")
return conn
@pytest.fixture
def mysql_limit_db():
"""Create a MySQL test database with enough rows for LIMIT testing."""
conn = _mysql_connect()
cursor = conn.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS test_limit_bug")
cursor.execute("USE test_limit_bug")
cursor.execute("DROP TABLE IF EXISTS users")
cursor.execute("CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100))")
for i in range(1, 21):
cursor.execute("INSERT INTO users (id, name) VALUES (%s, %s)", (i, f"user_{i}"))
conn.commit()
yield conn
cursor = conn.cursor()
cursor.execute("DROP DATABASE IF EXISTS test_limit_bug")
conn.close()
class TestMySQLMultiStatementLimits:
"""Test LIMIT enforcement against real MySQL via CursorBasedAdapter."""
def test_issue_132_limit_2_and_3(self, mysql_limit_db) -> None:
"""Exact reproduction of issue #132: LIMIT 2 and LIMIT 3 on same table."""
conn = mysql_limit_db
executor = CursorBasedExecutor(conn)
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 2; SELECT * FROM users LIMIT 3;",
max_rows=100000,
)
assert result.completed is True
assert len(result.results) == 2
r1 = result.results[0].result
r2 = result.results[1].result
assert isinstance(r1, QueryResult)
assert isinstance(r2, QueryResult)
assert r1.row_count == 2, (
f"Issue #132: LIMIT 2 should return 2 rows, got {r1.row_count}"
)
assert r2.row_count == 3, (
f"Issue #132: LIMIT 3 should return 3 rows, got {r2.row_count}"
)
def test_limits_5_and_1(self, mysql_limit_db) -> None:
"""LIMIT 5 then LIMIT 1 should return 5 and 1 rows."""
conn = mysql_limit_db
executor = CursorBasedExecutor(conn)
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 5; SELECT * FROM users LIMIT 1;",
max_rows=100000,
)
assert result.completed is True
assert result.results[0].result.row_count == 5
assert result.results[1].result.row_count == 1
def test_three_different_limits(self, mysql_limit_db) -> None:
"""Three queries with LIMIT 1, 3, 7."""
conn = mysql_limit_db
executor = CursorBasedExecutor(conn)
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 1; SELECT * FROM users LIMIT 3; SELECT * FROM users LIMIT 7;",
max_rows=100000,
)
assert result.completed is True
assert len(result.results) == 3
assert result.results[0].result.row_count == 1
assert result.results[1].result.row_count == 3
assert result.results[2].result.row_count == 7
def test_correct_data_not_mixed(self, mysql_limit_db) -> None:
"""Verify row data is correct, not mixed between results."""
conn = mysql_limit_db
executor = CursorBasedExecutor(conn)
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users WHERE id <= 2; SELECT * FROM users WHERE id > 18;",
max_rows=100000,
)
assert result.completed is True
r1_ids = [row[0] for row in result.results[0].result.rows]
r2_ids = [row[0] for row in result.results[1].result.rows]
assert r1_ids == [1, 2], f"Expected [1, 2], got {r1_ids}"
assert r2_ids == [19, 20], f"Expected [19, 20], got {r2_ids}"
class TestMySQLMultiStatementViaTransactionExecutor:
"""Test using the actual TransactionExecutor — the real TUI code path."""
def test_issue_132_via_transaction_executor(self, mysql_limit_db) -> None:
"""Reproduce #132 using the full TransactionExecutor + MultiStatementExecutor path."""
from sqlit.domains.connections.providers.registry import get_provider
from sqlit.domains.query.app.transaction import TransactionExecutor
from tests.fixtures.mysql import (
MYSQL_DATABASE,
MYSQL_HOST,
MYSQL_PASSWORD,
MYSQL_PORT,
MYSQL_USER,
)
from tests.helpers import ConnectionConfig
config = ConnectionConfig(
name="test-limit-bug",
db_type="mysql",
server=MYSQL_HOST,
port=str(MYSQL_PORT),
database="test_limit_bug",
username=MYSQL_USER,
password=MYSQL_PASSWORD,
)
provider = get_provider("mysql")
executor = TransactionExecutor(config=config, provider=provider)
try:
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 2; SELECT * FROM users LIMIT 3;",
max_rows=100000,
)
assert result.completed is True
assert len(result.results) == 2
r1 = result.results[0].result
r2 = result.results[1].result
assert isinstance(r1, QueryResult)
assert isinstance(r2, QueryResult)
assert r1.row_count == 2, (
f"Issue #132: LIMIT 2 should return 2 rows, got {r1.row_count}"
)
assert r2.row_count == 3, (
f"Issue #132: LIMIT 3 should return 3 rows, got {r2.row_count}"
)
finally:
executor.close()
def test_three_limits_via_transaction_executor(self, mysql_limit_db) -> None:
"""Three different LIMITs through TransactionExecutor."""
from sqlit.domains.connections.providers.registry import get_provider
from sqlit.domains.query.app.transaction import TransactionExecutor
from tests.fixtures.mysql import (
MYSQL_HOST,
MYSQL_PASSWORD,
MYSQL_PORT,
MYSQL_USER,
)
from tests.helpers import ConnectionConfig
config = ConnectionConfig(
name="test-limit-bug",
db_type="mysql",
server=MYSQL_HOST,
port=str(MYSQL_PORT),
database="test_limit_bug",
username=MYSQL_USER,
password=MYSQL_PASSWORD,
)
provider = get_provider("mysql")
executor = TransactionExecutor(config=config, provider=provider)
try:
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 1; SELECT * FROM users LIMIT 3; SELECT * FROM users LIMIT 7;",
max_rows=100000,
)
assert result.completed is True
assert len(result.results) == 3
assert result.results[0].result.row_count == 1
assert result.results[1].result.row_count == 3
assert result.results[2].result.row_count == 7
finally:
executor.close()
# ---------------------------------------------------------------------------
# SQLite baseline tests (same logic, should always pass)
# ---------------------------------------------------------------------------
@pytest.fixture
def sqlite_limit_db():
"""Create a SQLite test database with enough rows for LIMIT testing."""
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
for i in range(1, 21):
conn.execute("INSERT INTO users (id, name) VALUES (?, ?)", (i, f"user_{i}"))
conn.commit()
return conn
class TestSQLiteMultiStatementLimits:
"""Baseline: same tests against SQLite to confirm the core logic is correct."""
def test_issue_132_limit_2_and_3(self, sqlite_limit_db) -> None:
executor = CursorBasedExecutor(sqlite_limit_db)
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 2; SELECT * FROM users LIMIT 3;",
max_rows=100000,
)
assert result.results[0].result.row_count == 2
assert result.results[1].result.row_count == 3
def test_limits_5_and_1(self, sqlite_limit_db) -> None:
executor = CursorBasedExecutor(sqlite_limit_db)
multi = MultiStatementExecutor(executor)
result = multi.execute(
"SELECT * FROM users LIMIT 5; SELECT * FROM users LIMIT 1;",
max_rows=100000,
)
assert result.results[0].result.row_count == 5
assert result.results[1].result.row_count == 1