Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions examples/aio/advanced/walkthrough.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,16 @@ async def _run_walkthrough(client):
record_ids = [r.get("new_walkthroughdemoid")[:8] + "..." for r in page]
print(f" Page {page_num}: {len(page)} records - IDs: {record_ids}")

log_call(
"async for record in await client.query.builder(...).top(5).execute() — QueryResult supports async iteration"
)
print("Iterating a QueryResult with `async for` (top 5 by quantity)...")
top_result = await backoff(
lambda: client.query.builder(table_name).order_by("new_Quantity", descending=True).top(5).execute()
)
async for record in top_result:
print(f" - Qty={record.get('new_quantity')} Title={record.get('new_title')}")

# ============================================================================
# 7. QUERYBUILDER - FLUENT QUERIES
# ============================================================================
Expand Down
6 changes: 5 additions & 1 deletion src/PowerPlatform/Dataverse/models/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, Iterator, KeysView, List, Optional, Union, ValuesView, ItemsView
from typing import Any, AsyncIterator, Dict, Iterator, KeysView, List, Optional, Union, ValuesView, ItemsView

__all__ = ["Record", "QueryResult"]

Expand Down Expand Up @@ -132,6 +132,10 @@ def __init__(self, records: List[Record]) -> None:
def __iter__(self) -> Iterator[Record]:
return iter(self.records)

async def __aiter__(self) -> AsyncIterator[Record]:
for record in self.records:
yield record

def __len__(self) -> int:
return len(self.records)

Expand Down
32 changes: 32 additions & 0 deletions tests/unit/aio/test_async_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,3 +529,35 @@ def _make_page_resp(page_num: int):
warnings.simplefilter("always")
with pytest.raises(ValidationError, match="exceeded"):
await async_client.query.fetchxml(_SIMPLE_FETCHXML).execute()


class TestQueryResultAsyncIteration:
"""QueryResult must support ``async for`` so callers can write
``async for r in page`` after ``async for page in q.execute_pages()``.
"""

def _records(self, n=3):
return [Record(id=f"id-{i}", table="account", data={"name": f"R{i}"}) for i in range(n)]

async def test_has_aiter(self):
qr = QueryResult(self._records())
assert hasattr(qr, "__aiter__")

async def test_async_for_yields_all_records(self):
qr = QueryResult(self._records(3))
result = [r async for r in qr]
assert len(result) == 3
assert [r["name"] for r in result] == ["R0", "R1", "R2"]

async def test_async_for_empty(self):
qr = QueryResult([])
result = [r async for r in qr]
assert result == []

async def test_sync_and_async_return_same_records(self):
qr = QueryResult(self._records(5))
sync_result = list(qr)
async_result = [r async for r in qr]
assert len(sync_result) == len(async_result)
for s, a in zip(sync_result, async_result):
assert s is a
Loading