:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): convert postgres range and multirange columns to text (#104463)
Tom Owersb026b33b24c1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.pyindex e29073002df7..314e7cb79ec9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py@@ -1,5 +1,6 @@from __future__ import annotations+import reimport jsonimport mathimport uuid@@ -19,6 +20,8 @@ from arro3.core.types import ArrowSchemaExportablefrom circular_dict import CircularDictfrom dateutil import parserfrom dlt.common.libs.deltalake import ensure_delta_compatible_arrow_schema+from psycopg.types.multirange import Multirange+from psycopg.types.range import Rangefrom structlog.types import FilteringBoundLoggerfrom posthog.temporal.common.errors import NonReportableError@@ -755,9 +758,58 @@ def _convert_uuid_to_string(row: dict) -> dict:return {key: str(value) if isinstance(value, uuid.UUID) else value for key, value in row.items()}+RANGE_TYPES = (Range, Multirange)++# Postgres quotes a bound in its range text output when the bound is empty or holds a character+# that range syntax itself uses.+_RANGE_BOUND_NEEDS_QUOTES = re.compile(r'[\s",\\()\[\]]')+++def _format_range_bound(value: Any) -> str:+ # An infinite bound is written as nothing at all, so "[5,)" is a range with no upper bound.+ if value is None:+ return ""++ text = str(value)+ if text == "" or _RANGE_BOUND_NEEDS_QUOTES.search(text):+ return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'++ return text+++def _format_range(value: Range | Multirange) -> str:+ """Render a psycopg range or multirange the way Postgres writes it as text.++ pyarrow has no type for either object, so the column has to be stored as a string. The Postgres+ text form ("[4,5)", "empty", "{[1,4),[7,9)}") is what the Postgres source's own range loader+ already produces for the range types it covers, so every range column reads the same way in the+ warehouse. `str()` on these objects gives a Python rendering instead, which writes an infinite+ bound as "None" and cannot be read back as a range.+ """+ if isinstance(value, Multirange):+ return "{" + ",".join(_format_range(item) for item in value) + "}"++ if value.isempty:+ return "empty"++ lower_bracket = "[" if value.lower_inc else "("+ upper_bracket = "]" if value.upper_inc else ")"++ return f"{lower_bracket}{_format_range_bound(value.lower)},{_format_range_bound(value.upper)}{upper_bracket}"+++def _json_default(obj: Any) -> str:+ if isinstance(obj, RANGE_TYPES):+ return _format_range(obj)++ # orjson reads a TypeError from `default` as "still not serializable", so the caller falls+ # through to its own fallbacks.+ raise TypeError++def _json_dumps(obj: Any) -> str:try:- return orjson.dumps(obj).decode()+ return orjson.dumps(obj, default=_json_default).decode()except TypeError:try:return json.dumps(obj)@@ -1296,6 +1348,11 @@ def _python_type_to_pyarrow_type(type_: type, value: Any):if issubclass(type_, uuid.UUID):return pa.string()+ # Range and multirange values are rendered as Postgres text later in `_process_batch`, for the+ # same reason.+ if issubclass(type_, RANGE_TYPES):+ return pa.string()+raise ValueError(f"Python type {type_} has no pyarrow mapping")@@ -1747,6 +1804,18 @@ def _process_batch(if arrow_schema:arrow_schema = arrow_schema.set(field_index, arrow_schema.field(field_index).with_type(pa.string()))+ # Convert Postgres range and multirange values to their text form. The source declares such+ # a column as a string, and pyarrow rejects the psycopg object with "Expected bytes, got a+ # 'Range'/'Multirange' object" when it builds the column array.+ if issubclass(py_type, RANGE_TYPES):+ range_str_array = pa.array(+ [None if s is None else _format_range(s) for s in _to_list_array(columnar_table_data[field_name])]+ )+ columnar_table_data[field_name] = range_str_array+ py_type = str+ if arrow_schema:+ arrow_schema = arrow_schema.set(field_index, arrow_schema.field(field_index).with_type(pa.string()))+# Same keep-or-drop rule as the schema-typed binary branch above; this one catches# columns whose binary type is only visible from the Python values (e.g. inferred# schemas, or a declared type the values don't match).diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.pyindex 0a465e0ec03f..87973543e7e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py@@ -13,6 +13,8 @@ import pyarrow as paimport deltalakeimport structlogfrom dateutil import parser+from psycopg.types.multirange import Multirange+from psycopg.types.range import Rangefrom structlog.types import FilteringBoundLoggerfrom posthog.temporal.common.errors import NonReportableError@@ -645,6 +647,43 @@ def test_table_from_py_list_with_ipv6_address():)+ "value, expected",+ [+ (Range(4, 5, "[)"), "[4,5)"),+ (Range(4, 5, "[]"), "[4,5]"),+ (Range(empty=True), "empty"),+ (Range(None, None, "()"), "(,)"),+ (Range(5, None, "[)"), "[5,)"),+ # A bound holding a space is quoted, the way Postgres writes a timestamp range+ (+ Range(datetime.datetime(2020, 1, 1), datetime.datetime(2020, 2, 1), "[)"),+ '["2020-01-01 00:00:00","2020-02-01 00:00:00")',+ ),+ (Multirange([Range(1, 4, "[)"), Range(7, 9, "[)")]), "{[1,4),[7,9)}"),+ (Multirange([]), "{}"),+ ],+)+def test_table_from_py_list_with_postgres_range(value, expected):+ # The Postgres source declares a range or multirange column as a string, so without a+ # conversion pyarrow rejects the psycopg object with "Expected bytes, got a 'Range' object".+ declared_schema = pa.schema(cast(Any, [pa.field("column", pa.string())]))++ for schema in (None, declared_schema):+ table = table_from_py_list([{"column": value}, {"column": None}], schema)++ assert table.schema.field("column").type == pa.string()+ assert table.column("column").to_pylist() == [expected, None]+++def test_table_from_py_list_list_of_ranges_is_json_of_range_text():+ # A Postgres array of ranges reaches the JSON fallback, which must render each element as+ # range text rather than as the psycopg object's Python repr.+ table = table_from_py_list([{"column": [Range(1, 2, "[)"), Range(3, 4, "[]")]}])++ assert table.column("column").to_pylist() == ['["[1,2)","[3,4]"]']++def test_normalize_table_column_names_prevents_collisions():# Create a table with columns that would collide when normalizedtable = pa.table({"foo___bar": ["value1"], "foo_bar": ["value2"], "another___field": ["value3"]})