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
6 changes: 5 additions & 1 deletion src/postgrest/src/postgrest/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import json
from collections.abc import Iterable
from typing import Any, TypeVar

Expand Down Expand Up @@ -78,10 +79,13 @@ def rpc_query_param(value: Any) -> Any:
"""Format an RPC argument sent in the query string, as in GET or HEAD calls.

Lists and tuples become PostgreSQL array literals, since PostgREST keeps only
one value when a non-variadic argument is repeated.
one value when a non-variadic argument is repeated. Dictionaries become JSON
for named json/jsonb arguments.
"""
if isinstance(value, (list, tuple)):
return sanitize_array_param(value)
if isinstance(value, dict):
return json.dumps(value, separators=(",", ":"))
return value


Expand Down
48 changes: 48 additions & 0 deletions src/postgrest/tests/_async/test_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import re
from collections.abc import AsyncIterator
from typing import Any
Expand All @@ -10,6 +11,7 @@
BasicAuth,
Headers,
Limits,
MockTransport,
Request,
Response,
Timeout,
Expand Down Expand Up @@ -257,3 +259,49 @@ def test_rpc_query_params_quote_array_elements(
assert builder.request.params.get_list("tags") == [
'{"a,b","c d","","say \\"hi\\"","x}","null",NULL}'
]


@pytest.mark.parametrize("method", ["GET", "HEAD", "POST"])
@pytest.mark.parametrize(
("options", "encoded"),
[
({"enabled": True}, '{"enabled":true}'),
(
{"nested": {"items": [1, None, "a&b"]}},
'{"nested":{"items":[1,null,"a&b"]}}',
),
({}, "{}"),
],
)
async def test_rpc_serializes_dictionary_arguments(
method: str, options: dict, encoded: str
) -> None:
requests: list[Request] = []

def handler(request: Request) -> Response:
requests.append(request)
return Response(200, json=[])

params: Any = {
"options": options,
"raw": '{"preserved": true}',
"ids": [1, 2],
"text": "keep",
}
async with AsyncClient(transport=MockTransport(handler)) as http:
client = AsyncPostgrestClient("https://example.com", http_client=http)
await client.rpc(
"example", params, get=method == "GET", head=method == "HEAD"
).execute()

assert len(requests) == 1
request = requests[0]
assert request.method == method
if method == "POST":
assert json.loads(request.content) == params
assert "options" not in request.url.params
else:
assert request.url.params.get_list("options") == [encoded]
assert request.url.params["raw"] == params["raw"]
assert request.url.params["ids"] == "{1,2}"
assert request.url.params["text"] == "keep"
48 changes: 48 additions & 0 deletions src/postgrest/tests/_sync/test_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import re
from collections.abc import Iterator
from typing import Any
Expand All @@ -10,6 +11,7 @@
Headers,
HTTPTransport,
Limits,
MockTransport,
Request,
Response,
Timeout,
Expand Down Expand Up @@ -253,3 +255,49 @@ def test_rpc_query_params_quote_array_elements(
assert builder.request.params.get_list("tags") == [
'{"a,b","c d","","say \\"hi\\"","x}","null",NULL}'
]


@pytest.mark.parametrize("method", ["GET", "HEAD", "POST"])
@pytest.mark.parametrize(
("options", "encoded"),
[
({"enabled": True}, '{"enabled":true}'),
(
{"nested": {"items": [1, None, "a&b"]}},
'{"nested":{"items":[1,null,"a&b"]}}',
),
({}, "{}"),
],
)
def test_rpc_serializes_dictionary_arguments(
method: str, options: dict, encoded: str
) -> None:
requests: list[Request] = []

def handler(request: Request) -> Response:
requests.append(request)
return Response(200, json=[])

params: Any = {
"options": options,
"raw": '{"preserved": true}',
"ids": [1, 2],
"text": "keep",
}
with Client(transport=MockTransport(handler)) as http:
client = SyncPostgrestClient("https://example.com", http_client=http)
client.rpc(
"example", params, get=method == "GET", head=method == "HEAD"
).execute()

assert len(requests) == 1
request = requests[0]
assert request.method == method
if method == "POST":
assert json.loads(request.content) == params
assert "options" not in request.url.params
else:
assert request.url.params.get_list("options") == [encoded]
assert request.url.params["raw"] == params["raw"]
assert request.url.params["ids"] == "{1,2}"
assert request.url.params["text"] == "keep"
Loading