Skip to content

: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.

fix(bigquery): format incremental cursor literal against the live column type (#68012)

Tom Owers426a2110f764
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
index 4432706d70aa..e24472b280cf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
@@ -726,6 +726,38 @@ def _bq_row_filter_conditions(
return conditions, parameters
+def _format_incremental_cursor_literal(
+ last_value: datetime | date,
+ incremental_field: str,
+ incremental_field_type: IncrementalFieldType,
+ bq_table: bigquery.Table,
+) -> str:
+ """Render the incremental cursor bound as a SQL literal matching the column's live type.
+
+ The `incremental_field_type` recorded at source setup can lag the column's actual BigQuery
+ type — a column retyped in BigQuery after schema discovery — so drive formatting off the live
+ schema, falling back to the stored type when the column isn't in it:
+ - DATE: date component only. A datetime literal (`1970-01-01T00:00:00`) can't be cast to DATE.
+ - DATETIME: timezone-naive. The type is tz-naive and rejects an offset literal.
+ - TIMESTAMP: keep the offset. The type is timezone-aware.
+ """
+ column_field_types = {field.name: field.field_type for field in bq_table.schema}
+ actual_type = _BQ_FIELD_TYPE_NORMALIZATION.get(column_field_types.get(incremental_field, "").upper())
+
+ if isinstance(last_value, datetime):
+ if actual_type == "DATE":
+ return f"'{last_value.date().isoformat()}'"
+ naive = actual_type == "DATETIME" or (
+ actual_type is None and incremental_field_type == IncrementalFieldType.DateTime
+ )
+ if naive and last_value.tzinfo is not None:
+ last_value = last_value.replace(tzinfo=None)
+ return f"'{last_value.isoformat()}'"
+
+ # A plain `date` cursor casts cleanly to DATE, DATETIME, and TIMESTAMP alike.
+ return f"'{last_value.isoformat()}'"
+
+
def _get_query(
should_use_incremental_field: bool,
db_incremental_field_last_value: typing.Any,
@@ -749,17 +781,10 @@ def _get_query(
else:
last_value = db_incremental_field_last_value
- if isinstance(last_value, datetime):
- # BigQuery DATETIME columns are timezone-naive and reject a literal that carries
- # a UTC offset (e.g. `1970-01-01T00:00:00+00:00`), failing with "Could not cast
- # literal ... to type DATETIME". The shared initial cursor value is tz-aware UTC,
- # so drop the offset for DATETIME fields. TIMESTAMP columns are timezone-aware and
- # keep it.
- if incremental_field_type == IncrementalFieldType.DateTime and last_value.tzinfo is not None:
- last_value = last_value.replace(tzinfo=None)
- last_value = f"'{last_value.isoformat()}'"
- elif isinstance(last_value, date):
- last_value = f"'{last_value.isoformat()}'"
+ if isinstance(last_value, date):
+ last_value = _format_incremental_cursor_literal(
+ last_value, incremental_field, incremental_field_type, bq_table
+ )
operator = incremental_type_to_operator(incremental_field_type)
conditions = [f"`{incremental_field}` {operator} {last_value}", *filter_conditions]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
index 8e7706292843..9e0304a1a647 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -449,26 +449,30 @@ def test_bigquery_get_query_row_filters_compose_with_incremental():
@pytest.mark.parametrize(
- "field_type,last_value,expected_clause,offset_present",
+ "field_type,column_bq_type,last_value,expected_clause,offset_present",
[
# DATETIME columns are timezone-naive — a tz-aware literal can't be cast and BigQuery rejects it
# with "Could not cast literal ... to type DATETIME". On the first incremental sync the cursor
# defaults to the 1970-01-01 UTC initial value, whose isoformat carries a '+00:00' offset; for a
# DATETIME field the literal must be naive.
- (IncrementalFieldType.DateTime, None, "WHERE `cursor` > '1970-01-01T00:00:00'", False),
+ (IncrementalFieldType.DateTime, "DATETIME", None, "WHERE `cursor` > '1970-01-01T00:00:00'", False),
# A tz-aware value carried over from a previous sync is also rendered naive for DATETIME fields.
(
IncrementalFieldType.DateTime,
+ "DATETIME",
parser.parse("2024-03-11T09:26:04+00:00"),
"WHERE `cursor` > '2024-03-11T09:26:04'",
False,
),
# TIMESTAMP columns are timezone-aware, so the offset must be preserved in the literal.
- (IncrementalFieldType.Timestamp, None, "WHERE `cursor` > '1970-01-01T00:00:00+00:00'", True),
+ (IncrementalFieldType.Timestamp, "TIMESTAMP", None, "WHERE `cursor` > '1970-01-01T00:00:00+00:00'", True),
],
)
-def test_bigquery_get_query_datetime_cursor_timezone_offset(field_type, last_value, expected_clause, offset_present):
+def test_bigquery_get_query_datetime_cursor_timezone_offset(
+ field_type, column_bq_type, last_value, expected_clause, offset_present
+):
bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
+ bq_table.schema = [SimpleNamespace(name="cursor", field_type=column_bq_type)]
sql, _ = _get_query(
should_use_incremental_field=True,
db_incremental_field_last_value=last_value,
@@ -480,6 +484,36 @@ def test_bigquery_get_query_datetime_cursor_timezone_offset(field_type, last_val
assert ("+00:00" in sql) is offset_present
+ "field_type,last_value,expected_clause",
+ [
+ (IncrementalFieldType.DateTime, None, "WHERE `cursor` > '1970-01-01'"),
+ (IncrementalFieldType.Timestamp, None, "WHERE `cursor` > '1970-01-01'"),
+ (
+ IncrementalFieldType.DateTime,
+ parser.parse("2024-03-11T09:26:04+00:00"),
+ "WHERE `cursor` > '2024-03-11'",
+ ),
+ ],
+)
+def test_bigquery_get_query_date_column_with_datetime_cursor(field_type, last_value, expected_clause):
+ # A column retyped to DATE in BigQuery after discovery still carries a DateTime/Timestamp cursor
+ # here, whose datetime-shaped literal ("1970-01-01T00:00:00") BigQuery refuses to cast to DATE
+ # ("Could not cast literal ... to type DATE"). The literal must follow the column's live type.
+ bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
+ bq_table.schema = [SimpleNamespace(name="cursor", field_type="DATE")]
+ sql, _ = _get_query(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ bq_table=bq_table,
+ incremental_field="cursor",
+ incremental_field_type=field_type,
+ )
+ assert expected_clause in sql
+ assert "T00:00:00" not in sql
+ assert "+00:00" not in sql
+
+
@pytest.mark.parametrize(
"malicious_column",
[