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
2 changes: 2 additions & 0 deletions src/postgrest/src/postgrest/_async/request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ def text_search(

def csv(self) -> AsyncSingleRequestBuilder:
"""Specify that the query must retrieve data as a single CSV string."""
self.request._reject_strip_nulls("csv")
self.request.headers["Accept"] = "text/csv"
return AsyncSingleRequestBuilder(self.request)

Expand Down Expand Up @@ -274,6 +275,7 @@ def explain(
wal: bool = False,
format: Literal["text", "json"] = "text",
) -> AsyncExplainRequestBuilder | AsyncSingleRequestBuilder:
self.request._reject_strip_nulls("explain")
options = [
key
for key, value in locals().items()
Expand Down
2 changes: 2 additions & 0 deletions src/postgrest/src/postgrest/_sync/request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ def text_search(

def csv(self) -> SyncSingleRequestBuilder:
"""Specify that the query must retrieve data as a single CSV string."""
self.request._reject_strip_nulls("csv")
self.request.headers["Accept"] = "text/csv"
return SyncSingleRequestBuilder(self.request)

Expand Down Expand Up @@ -274,6 +275,7 @@ def explain(
wal: bool = False,
format: Literal["text", "json"] = "text",
) -> SyncExplainRequestBuilder | SyncSingleRequestBuilder:
self.request._reject_strip_nulls("explain")
options = [
key
for key, value in locals().items()
Expand Down
5 changes: 5 additions & 0 deletions src/postgrest/src/postgrest/base_request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ def __init__(
self.retry_enabled = retry_enabled
self.strip_nulls = False

def _reject_strip_nulls(self, method: str) -> None:
if self.strip_nulls:
raise ValueError(f"strip_nulls() cannot be used with {method}()")

@overload
def send(
self: RequestConfig[Client], additional_headers: Headers
Expand Down Expand Up @@ -726,5 +730,6 @@ def single(self) -> Self:

def csv(self) -> Self:
"""Specify that the query must retrieve data as a single CSV string."""
self.request._reject_strip_nulls("csv")
self.request.headers["Accept"] = "text/csv"
return self
94 changes: 83 additions & 11 deletions src/postgrest/tests/test_strip_nulls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,48 @@
import inspect
from collections.abc import AsyncIterator

import pytest
from httpx import Client, MockTransport, Request, Response
from httpx import AsyncClient, Client, MockTransport, Request, Response

from postgrest import AsyncPostgrestClient, SyncPostgrestClient


@pytest.fixture
def accept_headers() -> list[str]:
return []


from postgrest import SyncPostgrestClient
@pytest.fixture(params=["sync", "async"])
async def client(
request, accept_headers: list[str]
) -> AsyncIterator[SyncPostgrestClient | AsyncPostgrestClient]:
def handler(http_request: Request) -> Response:
accept_headers.append(http_request.headers["Accept"])
if http_request.headers["Accept"] == "text/csv":
return Response(200, text="id,name\n1,Luke")
return Response(200, json=[{"id": 1}])

transport = MockTransport(handler)
if request.param == "sync":
with (
Client(transport=transport) as http,
SyncPostgrestClient("https://example.com", http_client=http) as client,
):
yield client
else:
async with (
AsyncClient(transport=transport) as async_http,
AsyncPostgrestClient(
"https://example.com", http_client=async_http
) as async_client,
):
yield async_client


async def execute(query) -> None:
result = query.execute()
if inspect.isawaitable(result):
await result


@pytest.mark.parametrize(
Expand All @@ -11,12 +52,43 @@
(True, "application/vnd.pgrst.object+json;nulls=stripped"),
],
)
def test_strip_nulls_sets_accept_header(single: bool, expected: str) -> None:
def handler(request: Request) -> Response:
assert request.headers["Accept"] == expected
return Response(200, json=[])

with Client(transport=MockTransport(handler)) as http:
client = SyncPostgrestClient("https://example.com", http_client=http)
query = client.from_("users").select("*").strip_nulls()
(query.single() if single else query).execute()
async def test_strip_nulls_sets_accept_header(
client, accept_headers: list[str], single: bool, expected: str
) -> None:
query = client.from_("users").select("*").strip_nulls()
await execute(query.single() if single else query)
assert accept_headers == [expected]


async def test_csv_without_strip_nulls_requests_csv(
client, accept_headers: list[str]
) -> None:
await execute(client.from_("users").select("*").csv())
assert accept_headers == ["text/csv"]


@pytest.mark.parametrize("method", ["csv", "explain"])
def test_format_after_strip_nulls_is_rejected(client, method: str) -> None:
query = client.from_("users").select("*").strip_nulls()
with pytest.raises(
ValueError, match=rf"strip_nulls\(\) cannot be used with {method}"
):
getattr(query, method)()


def test_strip_nulls_after_csv_is_rejected(client) -> None:
query = client.from_("users").select("*").csv()
with pytest.raises((AttributeError, ValueError)):
query.strip_nulls()


def test_rpc_csv_after_strip_nulls_is_rejected(client) -> None:
query = client.rpc("get_users", {}).strip_nulls()
with pytest.raises(ValueError, match=r"strip_nulls\(\) cannot be used with csv"):
query.csv()


def test_rpc_strip_nulls_after_csv_is_rejected(client) -> None:
query = client.rpc("get_users", {}).csv()
with pytest.raises(ValueError, match=r"strip_nulls\(\) cannot be used with csv"):
query.strip_nulls()
Loading