Skip to content

Commit

Permalink
Fix removing nulls when encoding events for PostgreSQL (home-assistan…
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored and KoBOLL committed Oct 1, 2024
1 parent 9588197 commit 99d282a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
5 changes: 2 additions & 3 deletions homeassistant/components/recorder/db_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,8 @@ def shared_data_bytes_from_event(
event: Event, dialect: SupportedDialect | None
) -> bytes:
"""Create shared_data from an event."""
if dialect == SupportedDialect.POSTGRESQL:
bytes_result = json_bytes_strip_null(event.data)
bytes_result = json_bytes(event.data)
encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes
bytes_result = encoder(event.data)
if len(bytes_result) > MAX_EVENT_DATA_BYTES:
_LOGGER.warning(
"Event data for %s exceed maximum size of %s bytes. "
Expand Down
28 changes: 28 additions & 0 deletions tests/components/recorder/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import homeassistant.core as ha
from homeassistant.exceptions import InvalidEntityFormatError
from homeassistant.util import dt as dt_util
from homeassistant.util.json import json_loads


def test_from_event_to_db_event() -> None:
Expand All @@ -41,6 +42,18 @@ def test_from_event_to_db_event() -> None:
assert event.as_dict() == db_event.to_native().as_dict()


def test_from_event_to_db_event_with_null() -> None:
"""Test converting event to EventData with a null with PostgreSQL."""
event = ha.Event(
"test_event",
{"some_data": "withnull\0terminator"},
)
dialect = SupportedDialect.POSTGRESQL
event_data = EventData.shared_data_bytes_from_event(event, dialect)
decoded = json_loads(event_data)
assert decoded["some_data"] == "withnull"


def test_from_event_to_db_state() -> None:
"""Test converting event to db state."""
state = ha.State(
Expand Down Expand Up @@ -78,6 +91,21 @@ def test_from_event_to_db_state_attributes() -> None:
assert db_attrs.to_native() == attrs


def test_from_event_to_db_state_attributes_with_null() -> None:
"""Test converting a state to StateAttributes with a null with PostgreSQL."""
attrs = {"this_attr": "withnull\0terminator"}
state = ha.State("sensor.temperature", "18", attrs)
event = ha.Event(
EVENT_STATE_CHANGED,
{"entity_id": "sensor.temperature", "old_state": None, "new_state": state},
context=state.context,
)
dialect = SupportedDialect.POSTGRESQL
shared_attrs = StateAttributes.shared_attrs_bytes_from_event(event, dialect)
decoded = json_loads(shared_attrs)
assert decoded["this_attr"] == "withnull"


def test_repr() -> None:
"""Test converting event to db state repr."""
attrs = {"this_attr": True}
Expand Down

0 comments on commit 99d282a

Please sign in to comment.