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: 6 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,12 @@ Every filter on the table counts, including `match()`, `in_()`, `or_()` and a ne

`filter()` takes the operator as `Filters | str`, which shows that the `Filters` members are the expected values. A string still works for operators `Filters` does not list, such as `match`, so a misspelled string is not caught before PostgREST rejects it.

## PostgREST `datetime` filter values carry their UTC offset

A `datetime` filter value was sent as `str(value)`, like `2024-01-01 12:00:00`, which PostgREST read in the database time zone when the value had no offset. It is now sent as ISO 8601 with its offset, like `2024-01-01T12:00:00+01:00`. An aware `datetime` keeps its offset. A naive `datetime` is taken as UTC, so pass an aware `datetime` to filter on a time in another zone. `date` and `time` values are sent as before. This applies to every filter, including the members of `in_()` and of an array.

The members of an array sent by `cs()`, `cd()`, `contains()`, `contained_by()`, `overlaps()` or as an RPC query argument are rendered as any other filter value: a boolean as `true` or `false` instead of `True` or `False`, and a `dict` or `list` as compact JSON instead of its Python representation.

## Realtime heartbeat intervals are used as given

`heartbeat_interval` was raised to 15 seconds when it was lower. It is now used as given, so an interval below 15 seconds sends heartbeats more often than before. To keep the old timing, pass 15 or more.
Expand Down
11 changes: 1 addition & 10 deletions src/postgrest/src/postgrest/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,15 +476,6 @@ def _containment_operand(value: object, method: str) -> object:
return _members(value, method)


def _array_literal(members: tuple[Any, ...]) -> str:
"""`members` as the array literal `{a,b}`, each rendered as any other
operand is, apart from `None`, which is the SQL `NULL` of the literal."""
return _sanitize_array_param(
None if member is None else _serialize_filter_value(member)
for member in members
)


@dataclass(frozen=True)
class _Comparison(Generic[Row]):
"""One operator applied to one column expression."""
Expand Down Expand Up @@ -656,7 +647,7 @@ def _operand(node: _Comparison[Any]) -> str:
)
return f"({members})"
if node.operator in _ARRAY_OPERATORS and isinstance(node.value, tuple):
return _array_literal(node.value)
return _sanitize_array_param(node.value)
return _serialize_filter_value(node.value)


Expand Down
4 changes: 3 additions & 1 deletion src/postgrest/src/postgrest/request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,9 @@ def wfts(self: Self, column: str, query: Any) -> Self:
return self.filter(column, Filters.WFTS, query)

def in_(self: Self, column: str, values: Iterable[FilterValue]) -> Self:
stringified_values = ",".join(map(sanitize_param, values))
stringified_values = ",".join(
sanitize_param(_serialize_filter_value(value)) for value in values
)
return self.filter(column, Filters.IN, f"({stringified_values})")

def cs(self: Self, column: str, values: Iterable[FilterValue]) -> Self:
Expand Down
19 changes: 13 additions & 6 deletions src/postgrest/src/postgrest/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import json
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
Expand All @@ -14,13 +15,21 @@ def _serialize_filter_value(value: Any) -> str:

``None`` maps to ``null``, booleans to ``true``/``false``, and dicts/lists
to compact JSON, instead of the plain ``str()`` result (e.g. ``"None"``).

A ``datetime`` becomes ISO 8601 with its UTC offset, so the server does
not read it in the database time zone. A naive ``datetime`` is taken as
UTC.
"""
if value is None:
return "null"
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (dict, list)):
return json.dumps(value, separators=(",", ":"))
if isinstance(value, datetime):
if value.utcoffset() is None:
value = value.replace(tzinfo=UTC)
return value.isoformat()
return str(value)


Expand Down Expand Up @@ -51,7 +60,7 @@ def _sanitize_array_element(element: Any) -> str:
"""
if element is None:
return "NULL"
element_str = str(element)
element_str = _serialize_filter_value(element)
needs_quoting = (
element_str == ""
or element_str.lower() == "null"
Expand Down Expand Up @@ -80,11 +89,9 @@ def _rpc_query_param(value: Any) -> Any:
return _sanitize_array_param(value)
if value is None:
return ""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, dict):
return json.dumps(value, separators=(",", ":"))
return value
if isinstance(value, (str, int, float)) and not isinstance(value, bool):
return value
return _serialize_filter_value(value)


def is_http_url(url: URL) -> bool:
Expand Down
8 changes: 8 additions & 0 deletions src/postgrest/tests/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,14 @@ def test_boolean_is_checks(self) -> None:
assert rendered(Todos.is_urgent.is_true()) == ["is_urgent=is.true"]
assert rendered(Todos.is_urgent.is_null()) == ["is_urgent=is.null"]

def test_a_datetime_renders_as_iso_8601_with_its_offset(self) -> None:
due = datetime(2024, 1, 15, 12, tzinfo=UTC)

assert rendered(Todos.due.lt(due)) == ["due=lt.2024-01-15T12:00:00+00:00"]
assert rendered(Todos.due.lt(due) | Todos.id.eq(1)) == [
'or=(due.lt."2024-01-15T12:00:00+00:00",id.eq.1)'
]

def test_is_null_on_a_nullable_column_and_a_computed_field(self) -> None:
assert rendered(Todos.due.is_null()) == ["due=is.null"]
assert rendered(~Todos.due.is_null()) == ["due=not.is.null"]
Expand Down
10 changes: 10 additions & 0 deletions src/postgrest/tests/test_filter_builder.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime
from typing import Any

import pytest
Expand Down Expand Up @@ -374,6 +375,15 @@ def test_in_(filter_request_builder: BaseFilterRequestBuilder) -> None:
assert builder.request.query.get("x") == "in.(a,b)"


def test_in_renders_datetimes_as_iso_8601(
filter_request_builder: BaseFilterRequestBuilder,
) -> None:
values: Any = [datetime(2024, 1, 1, 12, tzinfo=UTC)]
builder = filter_request_builder.in_("x", values)

assert builder.request.query.get("x") == 'in.("2024-01-01T12:00:00+00:00")'


def test_or_(filter_request_builder: BaseFilterRequestBuilder) -> None:
builder = filter_request_builder.or_("x.eq.1")

Expand Down
4 changes: 2 additions & 2 deletions src/postgrest/tests/test_filter_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,9 @@ def test_bounds_render_as_filter_values(self) -> None:
datetime(2024, 1, 1, tzinfo=UTC), datetime(2025, 1, 1, tzinfo=UTC)
)
)
) == ["during=ov.[2024-01-01 00:00:00+00:00,2025-01-01 00:00:00+00:00)"]
) == ["during=ov.[2024-01-01T00:00:00+00:00,2025-01-01T00:00:00+00:00)"]
assert rendered(Posts.during.contains(datetime(2024, 6, 1, tzinfo=UTC))) == [
"during=cs.2024-06-01 00:00:00+00:00"
"during=cs.2024-06-01T00:00:00+00:00"
]
assert rendered(
Posts.season.contained_by(Range(date(2024, 1, 1), date(2024, 2, 1)))
Expand Down
2 changes: 1 addition & 1 deletion src/postgrest/tests/test_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def test_bounds_render_as_filter_values() -> None:
datetime(2024, 2, 1, 12, 30, tzinfo=UTC),
)
)
== "[2024-01-01 00:00:00+00:00,2024-02-01 12:30:00+00:00)"
== "[2024-01-01T00:00:00+00:00,2024-02-01T12:30:00+00:00)"
)
assert str(Range(Decimal("1.5"), Decimal("2.25"))) == "[1.5,2.25)"
assert str(Range(1.5, 2.0)) == "[1.5,2.0)"
Expand Down
14 changes: 14 additions & 0 deletions src/postgrest/tests/test_rpc_query_params.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import UTC, datetime
from typing import Any
from unittest.mock import patch

Expand Down Expand Up @@ -167,3 +168,16 @@ def handler(request: Request) -> Response:

assert response.data == []
assert response.count == 42


def test_rpc_query_params_send_datetimes_as_iso_8601() -> None:
with Client() as http:
client = SyncPostgrestClient(
"https://example.com", http_session=HttpxSession(client=http)
)
at = datetime(2024, 1, 1, 12, tzinfo=UTC)
params: Any = {"at": at, "ats": [at]}
builder = client.rpc("fn", params, get=True)

assert builder.request.query["at"] == "2024-01-01T12:00:00+00:00"
assert builder.request.query.get_list("ats") == ["{2024-01-01T12:00:00+00:00}"]
47 changes: 46 additions & 1 deletion src/postgrest/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from datetime import UTC, date, datetime, time, timedelta, timezone

import pytest

from postgrest.utils import sanitize_param
from postgrest.utils import (
_sanitize_array_param,
_serialize_filter_value,
sanitize_param,
)


@pytest.mark.parametrize(
Expand All @@ -16,3 +22,42 @@
)
def test_sanitize_params(value: str, expected: str) -> None:
assert sanitize_param(value) == expected


@pytest.mark.parametrize(
("value", "expected"),
[
(datetime(2024, 1, 1, 12, tzinfo=UTC), "2024-01-01T12:00:00+00:00"),
(
datetime(2024, 1, 1, 12, 30, 15, 500, tzinfo=timezone(timedelta(hours=5))),
"2024-01-01T12:30:15.000500+05:00",
),
(date(2024, 1, 1), "2024-01-01"),
(time(12, 30), "12:30:00"),
(time(12, 30, tzinfo=UTC), "12:30:00+00:00"),
],
)
def test_serialize_filter_value_renders_dates_and_times_as_iso_8601(
value: object, expected: str
) -> None:
assert _serialize_filter_value(value) == expected


@pytest.mark.parametrize(
("value", "expected"),
[
(datetime(2024, 7, 1, 12), "2024-07-01T12:00:00+00:00"), # noqa: DTZ001
(datetime.min, "0001-01-01T00:00:00+00:00"), # noqa: DTZ901
(datetime.max, "9999-12-31T23:59:59.999999+00:00"), # noqa: DTZ901
],
)
def test_serialize_filter_value_takes_a_naive_datetime_as_utc(
value: datetime, expected: str
) -> None:
assert _serialize_filter_value(value) == expected


def test_array_elements_render_datetimes_as_iso_8601() -> None:
value = datetime(2024, 1, 1, 12, tzinfo=UTC)

assert _sanitize_array_param([value]) == "{2024-01-01T12:00:00+00:00}"
Loading