From 2bc39b1c89aee526b279896d25cc91e6176eb00f Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Wed, 25 Nov 2026 14:45:38 +0530 Subject: [PATCH] REST: Fetch list results lazily with PaginationList Return a PaginationList from list_namespaces, list_tables, and list_views. Later pages are fetched only when iteration or indexing moves past the loaded items. Operations that need the full result set, such as len, contains, slicing, and repr, fetch all pages first. --- pyiceberg/catalog/rest/__init__.py | 80 +++++++-------- pyiceberg/typedef.py | 156 ++++++++++++++++++++++++++++- tests/catalog/test_rest.py | 31 ++++++ tests/utils/test_pagination.py | 139 +++++++++++++++++++++++++ 4 files changed, 366 insertions(+), 40 deletions(-) create mode 100644 tests/utils/test_pagination.py diff --git a/pyiceberg/catalog/rest/__init__.py b/pyiceberg/catalog/rest/__init__.py index 4f9a6230ae..aa7aa2cb55 100644 --- a/pyiceberg/catalog/rest/__init__.py +++ b/pyiceberg/catalog/rest/__init__.py @@ -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 ( @@ -1452,12 +1452,9 @@ 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() @@ -1465,13 +1462,17 @@ def list_tables(self, namespace: str | Identifier) -> list[Identifier]: _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 @@ -1593,13 +1594,9 @@ 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() @@ -1607,13 +1604,17 @@ def list_views(self, namespace: str | Identifier) -> list[Identifier]: _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 @@ -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 diff --git a/pyiceberg/typedef.py b/pyiceberg/typedef.py index de4d036fe7..f064bb14bf 100644 --- a/pyiceberg/typedef.py +++ b/pyiceberg/typedef.py @@ -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 ( @@ -28,9 +29,11 @@ Literal, Protocol, Self, + SupportsIndex, TypeAlias, TypeVar, Union, + overload, runtime_checkable, ) from uuid import UUID @@ -154,6 +157,7 @@ def model_dump_json( T = TypeVar("T") +S = TypeVar("S") class IcebergRootModel(RootModel[T], Generic[T]): @@ -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) diff --git a/tests/catalog/test_rest.py b/tests/catalog/test_rest.py index 0d8ca00257..dabb7d489a 100644 --- a/tests/catalog/test_rest.py +++ b/tests/catalog/test_rest.py @@ -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 diff --git a/tests/utils/test_pagination.py b/tests/utils/test_pagination.py new file mode 100644 index 0000000000..9ef102d6c5 --- /dev/null +++ b/tests/utils/test_pagination.py @@ -0,0 +1,139 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from pyiceberg.typedef import PaginationList + + +def _pagination_list(pages: list[list[int]], fetched: list[str] | None = None) -> PaginationList[int]: + fetched_tokens = fetched if fetched is not None else [] + next_tokens = [f"page{i}" for i in range(1, len(pages))] + [None] + + def fetch(token: str) -> tuple[list[int], str | None]: + fetched_tokens.append(token) + page = int(token.removeprefix("page")) + return pages[page], next_tokens[page] + + next_page_token = next_tokens[0] if len(pages) > 1 else None + return PaginationList(pages[0], next_page_token, fetch) + + +def test_single_page_behaves_like_list() -> None: + pagination = _pagination_list([[10, 20, 30]]) + + assert isinstance(pagination, list) + assert list(pagination) == [10, 20, 30] + assert len(pagination) == 3 + assert pagination[0] == 10 + assert pagination[-1] == 30 + assert pagination[1:] == [20, 30] + assert 20 in pagination + assert 99 not in pagination + assert pagination.count(20) == 1 + assert pagination.index(30) == 2 + assert list(reversed(pagination)) == [30, 20, 10] + assert pagination.copy() == [10, 20, 30] + assert pagination + [40] == [10, 20, 30, 40] + assert [0] + pagination == [0, 10, 20, 30] + assert pagination * 2 == [10, 20, 30, 10, 20, 30] + assert 2 * pagination == [10, 20, 30, 10, 20, 30] + assert pagination == [10, 20, 30] + assert pagination != [10, 20] + assert repr(pagination) == "PaginationList([10, 20, 30])" + + +def test_iteration_fetches_pages_lazily() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3], [4, 5]], fetched) + + assert list(pagination) == [1, 2, 3, 4, 5] + assert fetched == ["page1", "page2"] + + +def test_iteration_stops_without_fetching_remaining_pages() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3, 4]], fetched) + + seen = [] + for item in pagination: + seen.append(item) + if item == 2: + break + + assert seen == [1, 2] + assert fetched == [] + + +def test_index_fetches_only_up_to_the_requested_item() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3, 4], [5]], fetched) + + assert pagination[2] == 3 + assert fetched == ["page1"] + + +def test_negative_index_fetches_all_pages() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3, 4], [5]], fetched) + + assert pagination[-1] == 5 + assert fetched == ["page1", "page2"] + + +def test_len_fetches_all_pages() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3, 4], [5]], fetched) + + assert len(pagination) == 5 + assert fetched == ["page1", "page2"] + + +def test_contains_fetches_all_pages() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3, 4]], fetched) + + assert 4 in pagination + assert fetched == ["page1"] + + +def test_slice_fetches_all_pages() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[1, 2], [3, 4], [5]], fetched) + + assert pagination[1:4] == [2, 3, 4] + assert fetched == ["page1", "page2"] + + +def test_sort_and_reverse_fetch_all_pages() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[3, 1], [2]], fetched) + + pagination.sort() + assert pagination == [1, 2, 3] + assert fetched == ["page1"] + + pagination.reverse() + assert pagination == [3, 2, 1] + + +def test_empty_first_page_fetches_on_iteration() -> None: + fetched: list[str] = [] + pagination = _pagination_list([[], [1, 2]], fetched) + + assert list(pagination) == [1, 2] + assert fetched == ["page1"]