Skip to content
Open
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
80 changes: 41 additions & 39 deletions pyiceberg/catalog/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@
TableRequirement,
TableUpdate,
)
from pyiceberg.typedef import EMPTY_DICT, UTF8, IcebergBaseModel, Identifier, Properties
from pyiceberg.typedef import EMPTY_DICT, UTF8, IcebergBaseModel, Identifier, PaginationList, Properties
from pyiceberg.types import transform_dict_value_to_str
from pyiceberg.utils.deprecated import deprecation_message
from pyiceberg.utils.properties import (
Expand Down Expand Up @@ -1452,26 +1452,27 @@ def list_tables(self, namespace: str | Identifier) -> list[Identifier]:
raise ValueError(f"{PAGE_SIZE} must be a positive integer")
params["pageSize"] = str(page_size)

tables: list[Identifier] = []
page_token: str | None = None

while True:
if page_token:
params["pageToken"] = page_token
@retry(**_RETRY_ARGS)
def _fetch_page(page_token: str) -> tuple[list[Identifier], str | None]:
params["pageToken"] = page_token
response = self._session.get(url, params=params)
try:
response.raise_for_status()
except HTTPError as exc:
_handle_non_200_response(exc, {404: NoSuchNamespaceError})

parsed = ListTablesResponse.model_validate_json(response.text)
tables.extend([(*table.namespace, table.name) for table in parsed.identifiers])
return [(*table.namespace, table.name) for table in parsed.identifiers], parsed.next_page_token

if not parsed.next_page_token:
break
page_token = parsed.next_page_token
response = self._session.get(url, params=params)
try:
response.raise_for_status()
except HTTPError as exc:
_handle_non_200_response(exc, {404: NoSuchNamespaceError})

return tables
parsed = ListTablesResponse.model_validate_json(response.text)
first_page: list[Identifier] = [(*table.namespace, table.name) for table in parsed.identifiers]
return PaginationList(first_page, parsed.next_page_token, _fetch_page)

@retry(**_RETRY_ARGS)
@override
Expand Down Expand Up @@ -1593,27 +1594,27 @@ def list_views(self, namespace: str | Identifier) -> list[Identifier]:
raise ValueError(f"{PAGE_SIZE} must be a positive integer")
params["pageSize"] = str(page_size)

views: list[Identifier] = []
page_token: str | None = None

while True:
if page_token:
params["pageToken"] = page_token

@retry(**_RETRY_ARGS)
def _fetch_page(page_token: str) -> tuple[list[Identifier], str | None]:
params["pageToken"] = page_token
response = self._session.get(url, params=params)
try:
response.raise_for_status()
except HTTPError as exc:
_handle_non_200_response(exc, {404: NoSuchNamespaceError})

parsed = ListViewsResponse.model_validate_json(response.text)
views.extend([(*view.namespace, view.name) for view in parsed.identifiers])
return [(*view.namespace, view.name) for view in parsed.identifiers], parsed.next_page_token

if not parsed.next_page_token:
break
page_token = parsed.next_page_token
response = self._session.get(url, params=params)
try:
response.raise_for_status()
except HTTPError as exc:
_handle_non_200_response(exc, {404: NoSuchNamespaceError})

return views
parsed = ListViewsResponse.model_validate_json(response.text)
first_page: list[Identifier] = [(*view.namespace, view.name) for view in parsed.identifiers]
return PaginationList(first_page, parsed.next_page_token, _fetch_page)

@retry(**_RETRY_ARGS)
@override
Expand Down Expand Up @@ -1717,30 +1718,31 @@ def list_namespaces(self, namespace: str | Identifier = ()) -> list[Identifier]:
raise ValueError(f"{PAGE_SIZE} must be a positive integer")
params["pageSize"] = str(page_size)

namespaces: list[Identifier] = []
page_token: str | None = None

while True:
if namespace_tuple:
# Query parameters are URL-encoded by requests, so the parts must not be quoted here as well
params["parent"] = self._namespace_separator.join(namespace_tuple)
if page_token:
params["pageToken"] = page_token
response = self._session.get(self.url(Endpoints.list_namespaces), params=params)
namespaces_url = self.url(Endpoints.list_namespaces)
if namespace_tuple:
# Query parameters are URL-encoded by requests, so the parts must not be quoted here as well
params["parent"] = self._namespace_separator.join(namespace_tuple)

@retry(**_RETRY_ARGS)
def _fetch_page(page_token: str) -> tuple[list[Identifier], str | None]:
params["pageToken"] = page_token
response = self._session.get(namespaces_url, params=params)
try:
response.raise_for_status()
except HTTPError as exc:
_handle_non_200_response(exc, {404: NoSuchNamespaceError})

parsed = ListNamespaceResponse.model_validate_json(response.text)
namespaces.extend(parsed.namespaces)
return list(parsed.namespaces), parsed.next_page_token

if not parsed.next_page_token:
break
page_token = parsed.next_page_token
response = self._session.get(namespaces_url, params=params)
try:
response.raise_for_status()
except HTTPError as exc:
_handle_non_200_response(exc, {404: NoSuchNamespaceError})

return namespaces
parsed = ListNamespaceResponse.model_validate_json(response.text)
return PaginationList(list(parsed.namespaces), parsed.next_page_token, _fetch_page)

@retry(**_RETRY_ARGS)
@override
Expand Down
156 changes: 155 additions & 1 deletion pyiceberg/typedef.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
from __future__ import annotations

import math
import sys
from abc import abstractmethod
from collections.abc import Callable
from collections.abc import Callable, Iterator
from datetime import date, datetime, time
from decimal import Decimal
from typing import (
Expand All @@ -28,9 +29,11 @@
Literal,
Protocol,
Self,
SupportsIndex,
TypeAlias,
TypeVar,
Union,
overload,
runtime_checkable,
)
from uuid import UUID
Expand Down Expand Up @@ -154,6 +157,7 @@ def model_dump_json(


T = TypeVar("T")
S = TypeVar("S")


class IcebergRootModel(RootModel[T], Generic[T]):
Expand Down Expand Up @@ -225,3 +229,153 @@ def __hash__(self) -> int:

TableVersion: TypeAlias = Literal[1, 2, 3]
ViewVersion: TypeAlias = Literal[1]

FetchNextPage: TypeAlias = Callable[[str], tuple[list[T], str | None]]


class PaginationList(list[T]):
"""A list that lazily fetches subsequent pages from a paginated API.

The first page is loaded when the list is created. Later pages are fetched
only when iteration or indexing moves past the items already in memory.
Operations that need the complete result set, such as ``len()``, ``in``,
slicing, and ``repr()``, fetch every remaining page first.

Args:
first_page: Items from the first API response.
next_page_token: Token for the next page, or ``None`` when there are no more pages.
fetch_next_page: Callable that takes a page token and returns the next
page's items together with its next page token.
"""

def __init__(
self,
first_page: list[T],
next_page_token: str | None,
fetch_next_page: FetchNextPage[T],
) -> None:
super().__init__(first_page)
self._next_page_token = next_page_token
self._fetch_next_page = fetch_next_page

def _fetch_all(self) -> None:
while self._next_page_token:
items, self._next_page_token = self._fetch_next_page(self._next_page_token)
list.extend(self, items)

def _fetch_through_index(self, index: int) -> None:
while list.__len__(self) <= index and self._next_page_token:
items, self._next_page_token = self._fetch_next_page(self._next_page_token)
list.extend(self, items)

def __iter__(self) -> Iterator[T]:
"""Iterate lazily, fetching a page only when the current one is exhausted."""
index = 0
while True:
if index < list.__len__(self):
yield list.__getitem__(self, index)
index += 1
elif self._next_page_token:
items, self._next_page_token = self._fetch_next_page(self._next_page_token)
list.extend(self, items)
else:
return

def __len__(self) -> int:
"""Return the total number of items, fetching all pages first."""
self._fetch_all()
return list.__len__(self)

def __contains__(self, item: object) -> bool:
"""Return whether the item is present, fetching all pages first."""
self._fetch_all()
return list.__contains__(self, item)

def __repr__(self) -> str:
"""Return the representation after fetching all pages."""
self._fetch_all()
return f"PaginationList({list.__repr__(self)})"

def __eq__(self, other: object) -> bool:
"""Compare for equality after fetching all pages."""
self._fetch_all()
return list.__eq__(self, other)

def __ne__(self, other: object) -> bool:
"""Compare for inequality after fetching all pages."""
result = self.__eq__(other)
return result if result is NotImplemented else not result

@overload
def __getitem__(self, index: SupportsIndex) -> T: ...

@overload
def __getitem__(self, index: slice) -> list[T]: ...

def __getitem__(self, index: SupportsIndex | slice) -> T | list[T]:
"""Fetch pages as needed before returning the requested item or slice."""
if isinstance(index, slice):
self._fetch_all()
else:
item_index = index.__index__()
if item_index < 0:
self._fetch_all()
else:
self._fetch_through_index(item_index)
return list.__getitem__(self, index)

def count(self, value: T) -> int:
"""Return the number of occurrences of the value, fetching all pages first."""
self._fetch_all()
return list.count(self, value)

def index(self, value: T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int:
"""Return the first index of the value, fetching all pages first."""
self._fetch_all()
return list.index(self, value, start, stop)

def __reversed__(self) -> Iterator[T]:
"""Return a reverse iterator, fetching all pages first."""
self._fetch_all()
return list.__reversed__(self)

def copy(self) -> list[T]:
"""Return a plain list with all items, fetching all pages first."""
self._fetch_all()
return list.copy(self)

def sort(self, *, key: Callable[[T], Any] | None = None, reverse: bool = False) -> None:
"""Sort the items in place, fetching all pages first."""
self._fetch_all()
list.__setitem__(self, slice(None), sorted(self, key=key, reverse=reverse))

def reverse(self) -> None:
"""Reverse the items in place, fetching all pages first."""
self._fetch_all()
list.reverse(self)

@overload
def __add__(self, other: list[T]) -> list[T]: ...

@overload
def __add__(self, other: list[S]) -> list[S | T]: ...

def __add__(self, other: list[Any]) -> list[Any]:
"""Return self plus other as a plain list, fetching all pages first."""
self._fetch_all()
return list.__add__(self, other)

def __radd__(self, other: list[T]) -> list[T]:
"""Return other plus self as a plain list, fetching all pages first."""
self._fetch_all()
return list.__add__(other, self)

def __mul__(self, count: SupportsIndex) -> list[T]:
"""Return self repeated count times as a plain list, fetching all pages first."""
self._fetch_all()
return list.__mul__(self, count)

def __rmul__(self, count: SupportsIndex) -> list[T]:
"""Return self repeated count times as a plain list, fetching all pages first."""
self._fetch_all()
return list.__mul__(self, count)
31 changes: 31 additions & 0 deletions tests/catalog/test_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,37 @@ def test_list_tables_paginated_200(rest_mock: Mocker) -> None:
]


def test_list_tables_paginated_is_lazy(rest_mock: Mocker) -> None:
namespace = "examples"
rest_mock.get(
f"{TEST_URI}v1/namespaces/{namespace}/tables",
json={
"identifiers": [{"namespace": ["examples"], "name": "table1"}],
"next-page-token": "page2token",
},
status_code=200,
request_headers=TEST_HEADERS,
)
second_page = rest_mock.get(
f"{TEST_URI}v1/namespaces/{namespace}/tables?pageToken=page2token",
json={"identifiers": [{"namespace": ["examples"], "name": "table2"}]},
status_code=200,
request_headers=TEST_HEADERS,
)

tables = RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN).list_tables(namespace)

assert tables[0] == ("examples", "table1")
assert second_page.call_count == 0

seen = []
for table in tables:
seen.append(table)

assert seen == [("examples", "table1"), ("examples", "table2")]
assert second_page.call_count == 1


def test_list_tables_paginated_200_none_next_page_token(rest_mock: Mocker) -> None:
namespace = "examples"
# First page with next-page-token
Expand Down
Loading
Loading