Skip to content

Commit 08ddcdd

Browse files
committed
Fixed pagination bug
1 parent 9f68eb5 commit 08ddcdd

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

pymongosql/result_set.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,6 @@ def fetchall(self) -> List[Sequence[Any]]:
272272

273273
# Now get everything from cache
274274
all_results.extend(self._cached_results)
275-
self._total_fetched += len(self._cached_results)
276275
self._cached_results.clear()
277276
self._cache_exhausted = True
278277

tests/test_cursor.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,56 @@ def test_fetchall_with_result(self, conn):
261261
names = [row[name_idx] for row in rows]
262262
assert "John Doe" in names # First user from dataset
263263

264+
def test_cursor_pagination_fetchmany_triggers_getmore(self, conn, monkeypatch):
265+
"""Test that cursor.fetchmany triggers getMore when executing SQL that yields a paginated cursor
266+
267+
We monkeypatch the underlying database.command to force a small server batch size
268+
so that pagination/getMore behaviour is triggered while still using SQL via cursor.execute.
269+
"""
270+
db = conn.database
271+
original_cmd = db.command
272+
273+
def wrapper(cmd, *args, **kwargs):
274+
# Force small batchSize for find on users to simulate pagination
275+
if isinstance(cmd, dict) and cmd.get("find") == "users" and "batchSize" not in cmd:
276+
cmd = dict(cmd)
277+
cmd["batchSize"] = 3
278+
return original_cmd(cmd, *args, **kwargs)
279+
280+
monkeypatch.setattr(db, "command", wrapper)
281+
282+
cursor = conn.cursor()
283+
cursor.execute("SELECT * FROM users")
284+
285+
# Fetch many rows through cursor - should span multiple batches
286+
rows = cursor.fetchmany(10)
287+
assert len(rows) == 10
288+
assert cursor.rowcount >= 10
289+
290+
def test_cursor_pagination_fetchall_triggers_getmore(self, conn, monkeypatch):
291+
"""Test that cursor.fetchall retrieves all rows across multiple batches using SQL
292+
293+
Same approach: monkeypatch to force a small server batch size while using cursor.execute.
294+
"""
295+
db = conn.database
296+
original_cmd = db.command
297+
298+
def wrapper(cmd, *args, **kwargs):
299+
if isinstance(cmd, dict) and cmd.get("find") == "users" and "batchSize" not in cmd:
300+
cmd = dict(cmd)
301+
cmd["batchSize"] = 4
302+
return original_cmd(cmd, *args, **kwargs)
303+
304+
monkeypatch.setattr(db, "command", wrapper)
305+
306+
cursor = conn.cursor()
307+
cursor.execute("SELECT * FROM users")
308+
309+
rows = cursor.fetchall()
310+
# There are 22 users in test dataset
311+
assert len(rows) == 22
312+
assert cursor.rowcount == 22
313+
264314
def test_close(self, conn):
265315
"""Test cursor close"""
266316
# Should not raise any exception

0 commit comments

Comments
 (0)