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.

feat(warehouse): add row filters to SQL data warehouse sources (#62773)

Daniel RCcb14ca1de328
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index a571ee291382..a45c11e682a3 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6060,6 +6060,16 @@ export interface AvailableColumn {
nullable: boolean
}
+/** The comparison operators a row filter may use. Mirrors the backend allowlist. */
+export type RowFilterOperator = '>' | '>=' | '<' | '<=' | '=' | '!=' | 'IN' | 'NOT IN'
+
+/** A `{column, operator, value}` predicate ANDed onto a schema's source query. For `IN` / `NOT IN`, `value` is a comma-separated string. */
+export interface RowFilter {
+ column: string
+ operator: RowFilterOperator
+ value: string | number | boolean
+}
+
export type SchemaIncrementalFieldsResponse = {
incremental_fields: IncrementalField[]
incremental_available: boolean
@@ -6123,6 +6133,11 @@ export interface ExternalDataSourceSyncSchema {
* PK columns and the active incremental field are always retained server-side.
*/
enabled_columns?: string[] | null
+ /**
+ * Predicates ANDed onto the source query so only matching rows sync.
+ * `null`/undefined/empty = sync all rows.
+ */
+ row_filters?: RowFilter[] | null
}
export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema {
@@ -6145,6 +6160,11 @@ export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema
*/
enabled_columns?: string[] | null
available_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]
+ /**
+ * Predicates ANDed onto the source query so only matching rows sync.
+ * `null` means "sync all rows". Applied on the next sync — not retroactive.
+ */
+ row_filters?: RowFilter[] | null
}
/** Lightweight parent-source summary embedded in the single-schema retrieve endpoint. */
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/typings.py b/posthog/temporal/data_imports/pipelines/pipeline/typings.py
index bb15c7781fa4..33d6fa13c2bb 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/typings.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/typings.py
@@ -12,15 +12,21 @@ from products.data_warehouse.backend.types import IncrementalFieldType
if TYPE_CHECKING:
from dlt.common.data_types.typing import TDataType
+
+ from posthog.temporal.data_imports.sources.common.sql.predicates import ValidatedRowFilter
else:
- # Runtime stub so get_type_hints() on the dataclasses below resolves without importing dlt (kept
- # type-only above). Deliberately not `str` — nothing should rely on the runtime value, and a named
+ # Runtime stubs so get_type_hints() on the dataclasses below resolves without importing dlt or the
+ # predicates module. Deliberately not `str` — nothing should rely on the runtime value, and a named
# stub makes accidental use obvious rather than silently passing as a plausible type. The real,
- # mypy-visible type comes from the TYPE_CHECKING branch.
+ # mypy-visible types come from the TYPE_CHECKING branch.
class TDataType:
def __repr__(self) -> str:
return "<TDataType: type-checking-only stub for dlt.common.data_types.typing.TDataType>"
+ class ValidatedRowFilter:
+ def __repr__(self) -> str:
+ return "<ValidatedRowFilter: type-checking-only stub>"
+
SortMode = Literal["asc", "desc"]
PartitionMode = Literal["md5", "numerical", "datetime"]
@@ -72,6 +78,7 @@ class SourceInputs:
logger: FilteringBoundLogger
reset_pipeline: bool
enabled_columns: Optional[list[str]] = None
+ row_filters: Optional[list[ValidatedRowFilter]] = None
# Multi-schema import context, read by `resolve_source_location`.
schema_metadata: Optional[dict[str, Any]] = None
s3_folder_name: Optional[str] = None
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index 35bed62d7185..052e103f83c5 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -18,6 +18,7 @@ import collections.abc
from collections.abc import Iterator
from contextlib import contextmanager
from datetime import date, datetime
+from decimal import Decimal
from typing import Any
import pyarrow as pa
@@ -41,7 +42,12 @@ from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInput
from posthog.temporal.data_imports.pipelines.pipeline.utils import DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES
from posthog.temporal.data_imports.sources.common.grpc import make_tracked_channel
from posthog.temporal.data_imports.sources.common.http import DEFAULT_RETRY, TrackedHTTPAdapter
-from posthog.temporal.data_imports.sources.common.sql import compute_projected_columns
+from posthog.temporal.data_imports.sources.common.sql import (
+ ColumnTypeCategory,
+ ValidatedRowFilter,
+ compute_projected_columns,
+ is_multi_value_operator,
+)
from posthog.temporal.data_imports.sources.common.sql.identifiers import BacktickIdentifierQuoter
from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation
from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter
@@ -459,26 +465,30 @@ def _get_rows_to_sync(
logger: FilteringBoundLogger,
incremental_field: str | None = None,
incremental_field_type: IncrementalFieldType | None = None,
+ row_filters: list[ValidatedRowFilter] | None = None,
) -> int:
try:
- if not should_use_incremental_field:
+ # `num_rows` is the whole-table count, so it's only a valid shortcut when nothing
+ # filters the rows — row filters (like incremental) require an actual COUNT query.
+ if not should_use_incremental_field and not row_filters:
table = client.get_table(table)
if table.num_rows:
logger.debug(f"_get_rows_to_sync: table.num_rows={table.num_rows}")
return table.num_rows
- inner_query = _get_query(
+ inner_query, query_parameters = _get_query(
should_use_incremental_field,
db_incremental_field_last_value,
table,
incremental_field,
incremental_field_type,
+ row_filters=row_filters,
)
query = f"SELECT COUNT(*) FROM ({inner_query}) as t"
- job_config = QueryJobConfig()
+ job_config = QueryJobConfig(query_parameters=query_parameters)
job = client.query(query, job_config=job_config, project=table.project)
rows = job.result(page_size=1)
@@ -512,6 +522,79 @@ def _bq_select_clause(
return format_projected_select_clause(projected, _BQ_QUOTER)
+# Map a column type category onto a BigQuery scalar-parameter type, used as a fallback
+# when the column isn't found in the table schema.
+_BQ_PARAM_TYPE_BY_CATEGORY = {
+ ColumnTypeCategory.INTEGER: "INT64",
+ ColumnTypeCategory.NUMERIC: "NUMERIC",
+ ColumnTypeCategory.STRING: "STRING",
+ ColumnTypeCategory.BOOLEAN: "BOOL",
+ ColumnTypeCategory.DATE: "DATE",
+ ColumnTypeCategory.TIMESTAMP: "TIMESTAMP",
+}
+
+_BQ_FIELD_TYPE_NORMALIZATION = {
+ "INTEGER": "INT64",
+ "INT64": "INT64",
+ "FLOAT": "FLOAT64",
+ "FLOAT64": "FLOAT64",
+ "NUMERIC": "NUMERIC",
+ "BIGNUMERIC": "BIGNUMERIC",
+ "BOOLEAN": "BOOL",
+ "BOOL": "BOOL",
+ "STRING": "STRING",
+ "DATE": "DATE",
+ "DATETIME": "DATETIME",
+ "TIMESTAMP": "TIMESTAMP",
+ "TIME": "TIME",
+}
+
+
+def _adapt_bq_value(value: typing.Any, bq_type: str) -> typing.Any:
+ """Coerce a coerced filter value to what the BigQuery client expects for `bq_type`."""
+ if bq_type == "FLOAT64" and isinstance(value, Decimal):
+ return float(value)
+ if bq_type == "DATETIME" and isinstance(value, datetime) and value.tzinfo is not None:
+ return value.replace(tzinfo=None)
+ return value
+
+
+def _bq_row_filter_conditions(
+ row_filters: list[ValidatedRowFilter] | None,
+ bq_table: bigquery.Table,
+) -> tuple[list[str], list[bigquery.ScalarQueryParameter]]:
+ """Build row-filter SQL conditions + bound BigQuery scalar parameters.
+
+ Columns are quoted; values leave only as named params (`@row_filter_i`, or
+ `@row_filter_i_j` per element for IN). The param type follows the column's actual
+ BigQuery type so DATETIME vs TIMESTAMP don't mismatch.
+ """
+ if not row_filters:
+ return [], []
+
+ column_field_types = {field.name: field.field_type for field in bq_table.schema}
+ conditions: list[str] = []
+ parameters: list[bigquery.ScalarQueryParameter] = []
+ for index, row_filter in enumerate(row_filters):
+ quoted = _BQ_QUOTER.quote(row_filter.column)
+ bq_type = _BQ_FIELD_TYPE_NORMALIZATION.get(
+ column_field_types.get(row_filter.column, "").upper()
+ ) or _BQ_PARAM_TYPE_BY_CATEGORY.get(row_filter.category, "STRING")
+
+ if is_multi_value_operator(row_filter.operator):
+ placeholders = []
+ for position, element in enumerate(row_filter.value):
+ name = f"row_filter_{index}_{position}"
+ placeholders.append(f"@{name}")
+ parameters.append(bigquery.ScalarQueryParameter(name, bq_type, _adapt_bq_value(element, bq_type)))
+ conditions.append(f"{quoted} {row_filter.operator} ({', '.join(placeholders)})")
+ else:
+ name = f"row_filter_{index}"
+ conditions.append(f"{quoted} {row_filter.operator} @{name}")
+ parameters.append(bigquery.ScalarQueryParameter(name, bq_type, _adapt_bq_value(row_filter.value, bq_type)))
+ return conditions, parameters
+
+
def _get_query(
should_use_incremental_field: bool,
db_incremental_field_last_value: typing.Any,
@@ -520,8 +603,11 @@ def _get_query(
incremental_field_type: IncrementalFieldType | None = None,
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
-) -> str:
+ row_filters: list[ValidatedRowFilter] | None = None,
+) -> tuple[str, list[bigquery.ScalarQueryParameter]]:
select_clause = _bq_select_clause(enabled_columns, primary_keys, incremental_field)
+ table_ref = f"`{bq_table.dataset_id}`.`{bq_table.table_id}`"
+ filter_conditions, query_parameters = _bq_row_filter_conditions(row_filters, bq_table)
if should_use_incremental_field:
if incremental_field is None or incremental_field_type is None:
@@ -545,13 +631,18 @@ def _get_query(
last_value = f"'{last_value.isoformat()}'"
operator = incremental_type_to_operator(incremental_field_type)
- return f"""
- SELECT {select_clause} FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`
- WHERE `{incremental_field}` {operator} {last_value}
- ORDER BY `{incremental_field}` ASC
- """
+ conditions = [f"`{incremental_field}` {operator} {last_value}", *filter_conditions]
+ query = (
+ f"SELECT {select_clause} FROM {table_ref} "
+ f"WHERE {' AND '.join(conditions)} "
+ f"ORDER BY `{incremental_field}` ASC"
+ )
+ return query, query_parameters
+
+ if filter_conditions:
+ return f"SELECT {select_clause} FROM {table_ref} WHERE {' AND '.join(filter_conditions)}", query_parameters
- return f"SELECT {select_clause} FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`"
+ return f"SELECT {select_clause} FROM {table_ref}", query_parameters
class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquery.Client, Any]):
@@ -822,6 +913,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
inputs.db_incremental_field_last_value if should_use_incremental_field else None
)
enabled_columns = inputs.enabled_columns
+ row_filters = inputs.row_filters
logger = inputs.logger
project_id = _resolve_project_id(config)
@@ -855,6 +947,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
logger,
incremental_field,
incremental_field_type,
+ row_filters=row_filters,
)
def get_rows(max_table_size: int) -> collections.abc.Iterator[pa.Table]:
@@ -882,7 +975,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
# TODO: Think about whether this is at all necessary. We (and our users)
# are paying a (potentially high) cost to run this query job and store
# this data, when we could instead give up tracking and read it.
- query = _get_query(
+ query, query_parameters = _get_query(
should_use_incremental_field,
db_incremental_field_last_value,
bq_table,
@@ -890,22 +983,22 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
incremental_field_type,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
destination_table = bigquery.Table(bq_destination_table_id)
- job_config = QueryJobConfig(destination=destination_table)
+ job_config = QueryJobConfig(destination=destination_table, query_parameters=query_parameters)
job = bq_client.query(query, job_config=job_config, project=bq_table.project)
_ = job.result()
bq_table = bq_client.get_table(destination_table)
- elif bq_table.table_type in ("VIEW", "MATERIALIZED_VIEW", "EXTERNAL"):
+ elif bq_table.table_type in ("VIEW", "MATERIALIZED_VIEW", "EXTERNAL") or row_filters:
# BigQuery storage API does not support reading directly from views or
- # materialized views. So, similarly to incremental runs, we must copy the
- # results to a temporary table first. In the case of an incremental sync,
- # we already do this for all tables and views, so here we just handle the
- # views or materialized views that are not incremental.
- query = _get_query(
+ # materialized views, nor can it apply row filters. So, similarly to
+ # incremental runs, we copy the (optionally filtered) results to a temporary
+ # table first, then read that table via the storage API.
+ query, query_parameters = _get_query(
should_use_incremental_field,
db_incremental_field_last_value,
bq_table,
@@ -913,10 +1006,11 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
incremental_field_type,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
destination_table = bigquery.Table(bq_destination_table_id)
- job_config = QueryJobConfig(destination=destination_table)
+ job_config = QueryJobConfig(destination=destination_table, query_parameters=query_parameters)
job = bq_client.query(query, job_config=job_config, project=bq_table.project)
_ = job.result()
diff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
index 779b53ce1b22..f6bcc5ac736d 100644
--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -1,3 +1,5 @@
+from types import SimpleNamespace
+
import pytest
from freezegun import freeze_time
from unittest import mock
@@ -13,6 +15,7 @@ from posthog.temporal.data_imports.sources.bigquery.bigquery import (
BigQueryTokenRefreshError,
_bq_select_clause,
_get_query,
+ _get_rows_to_sync,
_has_duplicate_primary_keys,
_resolve_dataset_id,
_resolve_dataset_project_id,
@@ -24,6 +27,7 @@ from posthog.temporal.data_imports.sources.bigquery.bigquery import (
)
from posthog.temporal.data_imports.sources.bigquery.source import BigQuerySource
from posthog.temporal.data_imports.sources.common.sql.identifiers import InvalidIdentifierError
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.generated_configs import (
BigQueryDatasetProjectConfig,
BigQueryKeyFileConfig,
@@ -205,7 +209,7 @@ def test_bigquery_select_clause(enabled_columns, primary_keys, incremental_field
def test_bigquery_get_query_projects_enabled_columns():
bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
- query = _get_query(
+ query, params = _get_query(
should_use_incremental_field=False,
db_incremental_field_last_value=None,
bq_table=bq_table,
@@ -213,11 +217,12 @@ def test_bigquery_get_query_projects_enabled_columns():
primary_keys=["id"],
)
assert "SELECT `email`, `id` FROM" in query
+ assert params == []
def test_bigquery_get_query_keeps_incremental_field_in_projection():
bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
- query = _get_query(
+ query, params = _get_query(
should_use_incremental_field=True,
db_incremental_field_last_value=42,
bq_table=bq_table,
@@ -228,6 +233,95 @@ def test_bigquery_get_query_keeps_incremental_field_in_projection():
)
assert "SELECT `email`, `id`, `updated_at` FROM" in query
assert "WHERE `updated_at` > 42" in query
+ assert params == []
+
+
+def test_bigquery_get_query_binds_row_filters_as_parameters():
+ bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
+ bq_table.schema = [
+ SimpleNamespace(name="age", field_type="INTEGER"),
+ SimpleNamespace(name="name", field_type="STRING"),
+ ]
+ query, params = _get_query(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ bq_table=bq_table,
+ row_filters=[
+ ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER),
+ ValidatedRowFilter(
+ column="name", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ ),
+ ],
+ )
+ # Values are bound as @params, never inlined.
+ assert "WHERE `age` > @row_filter_0 AND `name` = @row_filter_1" in query
+ assert "DROP TABLE" not in query
+ assert [(p.name, p.type_, p.value) for p in params] == [
+ ("row_filter_0", "INT64", 21),
+ ("row_filter_1", "STRING", "x'; DROP TABLE y; --"),
+ ]
+
+
+def test_bigquery_get_rows_to_sync_runs_count_query_when_filtered():
+ # With row filters present the whole-table `num_rows` shortcut is invalid, so a COUNT(*)
+ # query with bound parameters runs instead.
+ table = mock.MagicMock(project="proj", dataset_id="ds", table_id="t")
+ table.schema = [SimpleNamespace(name="age", field_type="INTEGER")]
+ client = mock.MagicMock()
+ job = mock.MagicMock()
+ job.result.return_value = iter([[123]])
+ client.query.return_value = job
+
+ result = _get_rows_to_sync(
+ table=table,
+ client=client,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ logger=mock.MagicMock(),
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+
+ assert result == 123
+ client.get_table.assert_not_called() # num_rows shortcut skipped when filtered
+ count_query = client.query.call_args.args[0]
+ assert "COUNT(*)" in count_query
+ job_config = client.query.call_args.kwargs["job_config"]
+ assert [p.name for p in job_config.query_parameters] == ["row_filter_0_0", "row_filter_0_1"]
+
+
+def test_bigquery_get_query_in_filter_expands_to_one_param_per_value():
+ bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
+ bq_table.schema = [SimpleNamespace(name="age", field_type="INTEGER")]
+ query, params = _get_query(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ bq_table=bq_table,
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+ assert "WHERE `age` IN (@row_filter_0_0, @row_filter_0_1)" in query
+ assert [(p.name, p.type_, p.value) for p in params] == [
+ ("row_filter_0_0", "INT64", 21),
+ ("row_filter_0_1", "INT64", 30),
+ ]
+
+
+def test_bigquery_get_query_row_filters_compose_with_incremental():
+ bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
+ bq_table.schema = [SimpleNamespace(name="age", field_type="INTEGER")]
+ query, params = _get_query(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=42,
+ bq_table=bq_table,
+ incremental_field="updated_at",
+ incremental_field_type=IncrementalFieldType.Integer,
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ assert "WHERE `updated_at` > 42 AND `age` > @row_filter_0 ORDER BY `updated_at` ASC" in query
+ assert [(p.name, p.value) for p in params] == [("row_filter_0", 21)]
@pytest.mark.parametrize(
@@ -251,15 +345,15 @@ def test_bigquery_get_query_keeps_incremental_field_in_projection():
)
def test_bigquery_get_query_datetime_cursor_timezone_offset(field_type, last_value, expected_clause, offset_present):
bq_table = mock.MagicMock(dataset_id="ds", table_id="t")
- query = _get_query(
+ 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 query
- assert ("+00:00" in query) is offset_present
+ assert expected_clause in sql
+ assert ("+00:00" in sql) is offset_present
@pytest.mark.parametrize(
diff --git a/posthog/temporal/data_imports/sources/common/sql/__init__.py b/posthog/temporal/data_imports/sources/common/sql/__init__.py
index 9091b4e65ee2..67854c6b7bc1 100644
--- a/posthog/temporal/data_imports/sources/common/sql/__init__.py
+++ b/posthog/temporal/data_imports/sources/common/sql/__init__.py
@@ -28,6 +28,18 @@ from posthog.temporal.data_imports.sources.common.sql.metadata import (
extract_available_column_names,
sql_schema_metadata,
)
+from posthog.temporal.data_imports.sources.common.sql.predicates import (
+ ColumnTypeCategory,
+ RowFilter,
+ RowFilterValidationError,
+ ValidatedRowFilter,
+ classify_column_type,
+ is_multi_value_operator,
+ normalize_operator,
+ render_named_conditions,
+ render_positional_conditions,
+ validate_and_coerce_row_filters,
+)
from posthog.temporal.data_imports.sources.common.sql.projection import (
compute_projected_columns,
filter_columns_by_enabled_columns,
@@ -53,10 +65,13 @@ __all__ = [
"BracketIdentifierQuoter",
"Column",
"ColumnType",
+ "ColumnTypeCategory",
"IdentifierQuoter",
"IncrementalFieldFilter",
"InvalidIdentifierError",
"ParamStyle",
+ "RowFilter",
+ "RowFilterValidationError",
"SafeSQL",
"SelectQueryBuilder",
"Table",
@@ -64,15 +79,22 @@ __all__ = [
"TableReference",
"TableSchemas",
"TableStats",
+ "ValidatedRowFilter",
"build_incremental_fields",
+ "classify_column_type",
"compute_projected_columns",
"extract_available_column_names",
"filter_columns_by_enabled_columns",
"filter_dwh_columns_by_enabled_columns",
"format_projected_select_clause",
"initial_value_for_incremental_type",
+ "is_multi_value_operator",
+ "normalize_operator",
"project_arrow_columns",
"prune_enabled_columns",
+ "render_named_conditions",
+ "render_positional_conditions",
"resolve_detected_primary_keys",
"sql_schema_metadata",
+ "validate_and_coerce_row_filters",
]
diff --git a/posthog/temporal/data_imports/sources/common/sql/predicates.py b/posthog/temporal/data_imports/sources/common/sql/predicates.py
new file mode 100644
index 000000000000..eb9a1a136349
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/common/sql/predicates.py
@@ -0,0 +1,515 @@
+"""Schema-level row-filter predicates for SQL sources.
+
+A row filter is a `{column, operator, value}` triple ANDed onto a source query's
+`WHERE` clause so a sync only pulls matching rows. This is the driver-free safety
+boundary: it validates a filter against the schema's columns and coerces the value.
+
+Three rails make SQL injection impossible by construction:
+
+1. Column must exist in the schema's `schema_metadata`, and is quoted via `IdentifierQuoter`.
+2. Operator is looked up from `_CANONICAL_OPERATORS`, never passed through from input.
+3. Value is type-checked against the column's `ColumnTypeCategory` and always leaves as
+ a bound parameter — the render helpers emit placeholders only.
+"""
+
+from __future__ import annotations
+
+import enum
+from dataclasses import dataclass
+from datetime import date, datetime, time
+from decimal import Decimal, InvalidOperation
+from typing import Any, TypedDict
+
+from posthog.temporal.data_imports.sources.common.sql.identifiers import IdentifierQuoter
+from posthog.temporal.data_imports.sources.common.sql.metadata import extract_available_column_names
+
+
+class RowFilterValidationError(ValueError):
+ """Raised when a row filter fails validation (bad column, operator, or value type)."""
+
+
+class ColumnTypeCategory(enum.Enum):
+ """Coarse type category a column's `data_type` maps onto. `UNKNOWN` is a hard
+ failure — we won't filter on a column whose value we can't type-check."""
+
+ INTEGER = "integer"
+ NUMERIC = "numeric"
+ STRING = "string"
+ BOOLEAN = "boolean"
+ DATE = "date"
+ TIMESTAMP = "timestamp"
+ UNKNOWN = "unknown"
+
+
+class RowFilter(TypedDict):
+ """A row filter as it is persisted on the schema (raw JSON shape)."""
+
+ column: str
+ operator: str
+ value: Any
+
+
+@dataclass(frozen=True)
+class ValidatedRowFilter:
+ """A row filter after validation: canonical operator + coerced, typed value."""
+
+ column: str
+ operator: str
+ value: Any
+ category: ColumnTypeCategory
+
+
+# The only operators that may reach SQL; input aliases normalize to these.
+_SCALAR_OPERATORS = frozenset({">", ">=", "<", "<=", "=", "!="})
+# Take a list of values, emitted as `(%s, %s, ...)`. Case-insensitive on input.
+_MULTI_VALUE_OPERATORS = frozenset({"IN", "NOT IN"})
+_CANONICAL_OPERATORS = _SCALAR_OPERATORS | _MULTI_VALUE_OPERATORS
+_OPERATOR_ALIASES = {"==": "=", "<>": "!="}
+
+MAX_ROW_FILTERS = 20
+# Bound the number of parameters a single IN / NOT IN filter can emit.
+MAX_IN_VALUES = 1000
+
+
+def is_multi_value_operator(operator: str) -> bool:
+ """True for `IN` / `NOT IN` — operators whose value is a list, not a scalar."""
+ return operator in _MULTI_VALUE_OPERATORS
+
+
+def normalize_operator(operator: Any) -> str:
+ """Return the canonical operator for `operator`, or raise.
+
+ Accepts the six scalar operators (plus `==`/`<>` aliases) and `IN`/`NOT IN`
+ (case-insensitive). The result is always a member of `_CANONICAL_OPERATORS`,
+ so callers can interpolate it directly.
+ """
+ if not isinstance(operator, str):
+ raise RowFilterValidationError(f"Operator must be a string, got {type(operator).__name__}")
+ stripped = operator.strip()
+ # `IN` / `NOT IN`: case-insensitive, collapse runs of internal whitespace.
+ collapsed = " ".join(stripped.upper().split())
+ if collapsed in _MULTI_VALUE_OPERATORS:
+ return collapsed
+ candidate = _OPERATOR_ALIASES.get(stripped, stripped)
+ if candidate in _SCALAR_OPERATORS:
+ return candidate
+ allowed = ", ".join([*sorted(_SCALAR_OPERATORS), *sorted(_MULTI_VALUE_OPERATORS)])
+ raise RowFilterValidationError(f"Unsupported operator {operator!r}. Allowed operators: {allowed}")
+
+
+def _strip_nullable_wrappers(data_type: str) -> str:
+ """Unwrap ClickHouse `Nullable(...)` / `LowCardinality(...)` wrappers."""
+ current = data_type.strip()
+ while True:
+ if current.startswith("Nullable(") and current.endswith(")"):
+ current = current[len("Nullable(") : -1].strip()
+ elif current.startswith("LowCardinality(") and current.endswith(")"):
+ current = current[len("LowCardinality(") : -1].strip()
+ else:
+ return current
+
+
+def _strip_type_params(data_type: str) -> str:
+ """Drop trailing parameters, e.g. `varchar(255)` -> `varchar`, `numeric(10,2)` -> `numeric`."""
+ paren = data_type.find("(")
+ base = data_type if paren == -1 else data_type[:paren]
+ return base.strip()
+
+
+# Type vocabularies harvested from every SQL source's incremental-field classifier
+# (postgres, mysql, mssql, snowflake, bigquery, redshift, clickhouse), widened to
+# cover the non-incremental types a user may legitimately filter on.
+_INTEGER_TYPES = {
+ "int",
+ "int2",
+ "int4",
+ "int8",
+ "int16",
+ "int32",
+ "int64",
+ "int128",
+ "int256",
+ "integer",
+ "smallint",
+ "mediumint",
+ "bigint",
+ "tinyint",
+ "byteint",
+ "serial",
+ "smallserial",
+ "bigserial",
+ "uint8",
+ "uint16",
+ "uint32",
+ "uint64",
+ "uint128",
+ "uint256",
+}
+_NUMERIC_TYPES = {
+ "numeric",
+ "decimal",
+ "real",
+ "double",
+ "double precision",
+ "float",
+ "float4",
+ "float8",
+ "float32",
+ "float64",
+ "number",
+ "money",
+ "smallmoney",
+ "bignumeric",
+ "dec",
+ "fixed",
+}
+_STRING_TYPES = {
+ "char",
+ "character",
+ "character varying",
+ "varchar",
+ "varchar2",
+ "nchar",
+ "nvarchar",
+ "nvarchar2",
+ "text",
+ "tinytext",
+ "mediumtext",
+ "longtext",
+ "ntext",
+ "string",
+ "fixedstring",
+ "clob",
+ "nclob",
+ "uuid",
+ "uniqueidentifier",
+ "name",
+ "citext",
+ "enum",
+ # json / jsonb excluded: `jsonb <op> $text_param` fails at sync time without a cast, so we
+ # treat them as UNKNOWN (unfilterable) rather than pass validation and break the sync.
+}
+_BOOLEAN_TYPES = {"bool", "boolean", "bit"}
+_DATE_TYPES = {"date", "date32"}
+_TIMESTAMP_TYPES = {
+ "timestamp",
+ "timestamptz",
+ "timestamp with time zone",
+ "timestamp without time zone",
+ "datetime",
+ "datetime2",
+ "datetime64",
+ "smalldatetime",
+ "datetimeoffset",
+}
+
+
+def classify_column_type(data_type: Any) -> ColumnTypeCategory:
+ """Map a driver-native `data_type` onto a `ColumnTypeCategory`, or `UNKNOWN`.
+
+ Case-insensitive, after unwrapping `Nullable(...)` and dropping length/precision
+ params. Prefix matches cover parameterized timestamp/datetime spellings.
+ """
+ if not isinstance(data_type, str) or not data_type.strip():
+ return ColumnTypeCategory.UNKNOWN
+
+ inner = _strip_nullable_wrappers(data_type)
+ base = _strip_type_params(inner).lower()
+
+ if base in _INTEGER_TYPES:
+ return ColumnTypeCategory.INTEGER
+ if base in _NUMERIC_TYPES:
+ return ColumnTypeCategory.NUMERIC
+ if base in _BOOLEAN_TYPES:
+ return ColumnTypeCategory.BOOLEAN
+ if base in _DATE_TYPES:
+ return ColumnTypeCategory.DATE
+ if base in _STRING_TYPES:
+ return ColumnTypeCategory.STRING
+ if base in _TIMESTAMP_TYPES or base.startswith("timestamp") or base.startswith("datetime"):
+ return ColumnTypeCategory.TIMESTAMP
+ return ColumnTypeCategory.UNKNOWN
+
+
+def _coerce_integer(value: Any) -> int:
+ if isinstance(value, bool):
+ raise RowFilterValidationError("Expected an integer value, got a boolean")
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ if value.is_integer():
+ return int(value)
+ raise RowFilterValidationError(f"Expected an integer value, got non-integral {value!r}")
+ if isinstance(value, str):
+ try:
+ return int(value.strip())
+ except ValueError:
+ raise RowFilterValidationError(f"Expected an integer value, got {value!r}")
+ raise RowFilterValidationError(f"Expected an integer value, got {type(value).__name__}")
+
+
+def _coerce_numeric(value: Any) -> int | float | Decimal:
+ if isinstance(value, bool):
+ raise RowFilterValidationError("Expected a numeric value, got a boolean")
+ if isinstance(value, int | float):
+ return value
+ if isinstance(value, str):
+ try:
+ return Decimal(value.strip())
+ except InvalidOperation:
+ raise RowFilterValidationError(f"Expected a numeric value, got {value!r}")
+ raise RowFilterValidationError(f"Expected a numeric value, got {type(value).__name__}")
+
+
+def _coerce_string(value: Any) -> str:
+ if isinstance(value, str):
+ return value
+ raise RowFilterValidationError(f"Expected a string value, got {type(value).__name__}")
+
+
+def _coerce_boolean(value: Any) -> bool:
+ if isinstance(value, bool):
+ return value
+ # Accept 0/1 — a direct API caller may send these for a boolean column.
+ if isinstance(value, int) and value in (0, 1):
+ return bool(value)
+ if isinstance(value, str):
+ lowered = value.strip().lower()
+ if lowered == "true":
+ return True
+ if lowered == "false":
+ return False
+ raise RowFilterValidationError(f"Expected a boolean value (true/false), got {value!r}")
+
+
+def _coerce_date(value: Any) -> date:
+ if not isinstance(value, str):
+ raise RowFilterValidationError(f"Expected an ISO date string (YYYY-MM-DD), got {type(value).__name__}")
+ try:
+ return date.fromisoformat(value.strip())
+ except ValueError:
+ raise RowFilterValidationError(f"Expected an ISO date string (YYYY-MM-DD), got {value!r}")
+
+
+def _coerce_timestamp(value: Any) -> datetime:
+ if not isinstance(value, str):
+ raise RowFilterValidationError(f"Expected an ISO datetime string, got {type(value).__name__}")
+ raw = value.strip()
+ # Accept a trailing "Z" (UTC) which older `fromisoformat` rejects.
+ normalized = raw[:-1] + "+00:00" if raw.endswith("Z") else raw
+ try:
+ return datetime.fromisoformat(normalized)
+ except ValueError:
+ # A plain date is a valid timestamp boundary (midnight).
+ try:
+ return datetime.combine(date.fromisoformat(raw), time())
+ except ValueError:
+ raise RowFilterValidationError(f"Expected an ISO datetime string, got {value!r}")
+
+
+_COERCERS = {
+ ColumnTypeCategory.INTEGER: _coerce_integer,
+ ColumnTypeCategory.NUMERIC: _coerce_numeric,
+ ColumnTypeCategory.STRING: _coerce_string,
+ ColumnTypeCategory.BOOLEAN: _coerce_boolean,
+ ColumnTypeCategory.DATE: _coerce_date,
+ ColumnTypeCategory.TIMESTAMP: _coerce_timestamp,
+}
+
+
+def _split_top_level_commas(raw: str) -> list[str]:
+ """Split on commas that are not inside single quotes; quote chars stay in each piece."""
+ pieces: list[str] = []
+ buf: list[str] = []
+ in_quote = False
+ i = 0
+ n = len(raw)
+ while i < n:
+ ch = raw[i]
+ if ch == "'":
+ buf.append(ch)
+ if in_quote and i + 1 < n and raw[i + 1] == "'": # escaped '' -> keep both
+ buf.append("'")
+ i += 2
+ continue
+ in_quote = not in_quote
+ elif ch == "," and not in_quote:
+ pieces.append("".join(buf))
+ buf = []
+ else:
+ buf.append(ch)
+ i += 1
+ if in_quote:
+ raise RowFilterValidationError("Unterminated quote in IN list")
+ pieces.append("".join(buf))
+ return pieces
+
+
+def _split_in_list(raw: str) -> list[str]:
+ """Split a comma-separated IN list into trimmed element strings.
+
+ A single-quoted element keeps its contents verbatim (may hold commas/spaces),
+ with `''` read as an escaped quote. Blank input yields an empty list.
+ """
+ if not raw.strip():
+ return []
+ elements: list[str] = []
+ for piece in _split_top_level_commas(raw):
+ token = piece.strip()
+ if len(token) >= 2 and token.startswith("'") and token.endswith("'"):
+ elements.append(token[1:-1].replace("''", "'"))
+ else:
+ elements.append(token)
+ return elements
+
+
+def _coerce_in_values(value: Any, category: ColumnTypeCategory) -> list[Any]:
+ """Parse and coerce an `IN` / `NOT IN` value into a typed list.
+
+ Accepts a comma-separated string or an already-structured list. Each element is
+ coerced with the same per-type rules as a scalar. Raises on an empty list, a blank
+ element, too many values, or a coercion failure.
+ """
+ coercer = _COERCERS[category]
+ if isinstance(value, list):
+ elements: list[Any] = value
+ elif isinstance(value, str):
+ elements = _split_in_list(value)
+ else:
+ raise RowFilterValidationError(
+ f"IN operator expects a comma-separated string or a list, got {type(value).__name__}"
+ )
+
+ if not elements:
+ raise RowFilterValidationError("IN operator requires at least one value")
+ if len(elements) > MAX_IN_VALUES:
+ raise RowFilterValidationError(f"Too many values for IN (max {MAX_IN_VALUES})")
+
+ coerced: list[Any] = []
+ for element in elements:
+ if isinstance(element, str) and element == "":
+ raise RowFilterValidationError("IN list has an empty value")
+ coerced.append(coercer(element))
+ return coerced
+
+
+def _column_types(schema_metadata: dict[str, Any] | None) -> dict[str, str]:
+ """Map column name -> native `data_type` from a `schema_metadata` row."""
+ if not isinstance(schema_metadata, dict):
+ return {}
+ columns = schema_metadata.get("columns")
+ if not isinstance(columns, list):
+ return {}
+ result: dict[str, str] = {}
+ for column in columns:
+ if (
+ isinstance(column, dict)
+ and isinstance(column.get("name"), str)
+ and isinstance(column.get("data_type"), str)
+ ):
+ result[column["name"]] = column["data_type"]
+ return result
+
+
+def validate_and_coerce_row_filters(
+ row_filters: Any,
+ schema_metadata: dict[str, Any] | None,
+) -> list[ValidatedRowFilter]:
+ """Validate raw row filters against a schema's columns and coerce their values.
+
+ Returns an empty list for `None`/empty input. Raises `RowFilterValidationError`
+ on a malformed structure, unknown column, disallowed operator, unclassifiable
+ type, or a value that doesn't match the column's type.
+ """
+ if row_filters is None:
+ return []
+ if not isinstance(row_filters, list):
+ raise RowFilterValidationError("row_filters must be a list")
+ if len(row_filters) > MAX_ROW_FILTERS:
+ raise RowFilterValidationError(f"Too many row filters (max {MAX_ROW_FILTERS})")
+
+ available_columns = extract_available_column_names(schema_metadata)
+ column_types = _column_types(schema_metadata)
+
+ validated: list[ValidatedRowFilter] = []
+ for index, row_filter in enumerate(row_filters):
+ if not isinstance(row_filter, dict):
+ raise RowFilterValidationError(f"Row filter at index {index} must be an object")
+
+ column = row_filter.get("column")
+ if not isinstance(column, str) or not column:
+ raise RowFilterValidationError(f"Row filter at index {index} is missing a column")
+ if available_columns and column not in available_columns:
+ raise RowFilterValidationError(f"Unknown column {column!r} for this schema")
+
+ operator = normalize_operator(row_filter.get("operator"))
+
+ data_type = column_types.get(column)
+ category = classify_column_type(data_type)
+ if category is ColumnTypeCategory.UNKNOWN:
+ raise RowFilterValidationError(
+ f"Cannot filter on column {column!r}: its type {data_type!r} is not supported for filtering"
+ )
+
+ if "value" not in row_filter:
+ raise RowFilterValidationError(f"Row filter on column {column!r} is missing a value")
+ if is_multi_value_operator(operator):
+ # `value` becomes a typed list; render helpers expand it to N placeholders.
+ coerced: Any = _coerce_in_values(row_filter["value"], category)
+ else:
+ coerced = _COERCERS[category](row_filter["value"])
+
+ validated.append(ValidatedRowFilter(column=column, operator=operator, value=coerced, category=category))
+
+ return validated
+
+
+def render_named_conditions(
+ filters: list[ValidatedRowFilter],
+ quoter: IdentifierQuoter,
+ *,
+ prefix: str = "row_filter",
+) -> tuple[list[str], dict[str, Any]]:
+ """Render filters as pyformat-named conditions (`%(name)s`) + a params dict.
+
+ Used by MySQL/MSSQL. Columns are quoted via `quoter`; values leave only as params.
+ """
+ conditions: list[str] = []
+ params: dict[str, Any] = {}
+ for index, row_filter in enumerate(filters):
+ quoted = quoter.quote(row_filter.column)
+ if is_multi_value_operator(row_filter.operator):
+ placeholders = []
+ for position, element in enumerate(row_filter.value):
+ name = f"{prefix}_{index}_{position}"
+ params[name] = element
+ placeholders.append(f"%({name})s")
+ conditions.append(f"{quoted} {row_filter.operator} ({', '.join(placeholders)})")
+ else:
+ name = f"{prefix}_{index}"
+ params[name] = row_filter.value
+ conditions.append(f"{quoted} {row_filter.operator} %({name})s")
+ return conditions, params
+
+
+def render_positional_conditions(
+ filters: list[ValidatedRowFilter],
+ quoter: IdentifierQuoter,
+) -> tuple[list[str], list[Any]]:
+ """Render filters as positional conditions (`%s`) + an ordered values list.
+
+ Used by Snowflake; the caller must append these values after any earlier
+ positional params (e.g. the incremental value).
+ """
+ conditions: list[str] = []
+ values: list[Any] = []
+ for row_filter in filters:
+ quoted = quoter.quote(row_filter.column)
+ if is_multi_value_operator(row_filter.operator):
+ placeholders = ", ".join(["%s"] * len(row_filter.value))
+ conditions.append(f"{quoted} {row_filter.operator} ({placeholders})")
+ values.extend(row_filter.value)
+ else:
+ conditions.append(f"{quoted} {row_filter.operator} %s")
+ values.append(row_filter.value)
+ return conditions, values
diff --git a/posthog/temporal/data_imports/sources/common/sql/predicates_psycopg.py b/posthog/temporal/data_imports/sources/common/sql/predicates_psycopg.py
new file mode 100644
index 000000000000..a87ac80b5ba0
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/common/sql/predicates_psycopg.py
@@ -0,0 +1,34 @@
+"""psycopg rendering of row-filter predicates for Postgres / Redshift.
+
+Separate from `predicates.py` so the psycopg import stays off the serializer path.
+
+Values are `sql.Literal` (psycopg adapts them server-side, never interpolated),
+columns are `sql.Identifier`, and the operator is already canonical so `sql.SQL` is safe.
+"""
+
+from __future__ import annotations
+
+from psycopg import sql
+
+from posthog.temporal.data_imports.sources.common.sql.predicates import ValidatedRowFilter, is_multi_value_operator
+
+
+def _render_one(row_filter: ValidatedRowFilter) -> sql.Composable:
+ col = sql.Identifier(row_filter.column)
+ op = sql.SQL(row_filter.operator)
+ if is_multi_value_operator(row_filter.operator):
+ # `<col> IN (lit, lit, ...)` — each element is a psycopg-adapted literal.
+ values = sql.SQL(", ").join(sql.Literal(element) for element in row_filter.value)
+ return sql.SQL("{col} {op} ({vals})").format(col=col, op=op, vals=values)
+ return sql.SQL("{col} {op} {val}").format(col=col, op=op, val=sql.Literal(row_filter.value))
+
+
+def render_psycopg_row_filter_conditions(filters: list[ValidatedRowFilter]) -> list[sql.Composable]:
+ """Render each row filter as a psycopg composable (`<col> <op> <literal>`, or
+ `<col> IN (<literal>, ...)` for multi-value operators)."""
+ return [_render_one(row_filter) for row_filter in filters]
+
+
+def and_join(conditions: list[sql.Composable]) -> sql.Composable:
+ """AND-join a list of composable conditions into one composable."""
+ return sql.SQL(" AND ").join(conditions)
diff --git a/posthog/temporal/data_imports/sources/common/sql/query_builder.py b/posthog/temporal/data_imports/sources/common/sql/query_builder.py
index 82ca4c1aae72..a4c226c93600 100644
--- a/posthog/temporal/data_imports/sources/common/sql/query_builder.py
+++ b/posthog/temporal/data_imports/sources/common/sql/query_builder.py
@@ -30,6 +30,7 @@ from posthog.temporal.data_imports.pipelines.helpers import (
incremental_type_to_operator,
)
from posthog.temporal.data_imports.sources.common.sql.identifiers import IdentifierQuoter
+from posthog.temporal.data_imports.sources.common.sql.predicates import ValidatedRowFilter, is_multi_value_operator
from posthog.temporal.data_imports.sources.common.sql.projection import (
compute_projected_columns,
format_projected_select_clause,
@@ -84,6 +85,7 @@ class SelectQueryBuilder:
order_by_incremental: bool = True,
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
+ row_filters: list[ValidatedRowFilter] | None = None,
) -> SafeSQL:
"""Build a `SELECT … FROM schema.table` with optional incremental predicate.
@@ -97,6 +99,10 @@ class SelectQueryBuilder:
`enabled_columns=None` (default) emits `SELECT *`. Otherwise projects to listed columns;
PKs + active incremental field always retained. See `compute_projected_columns`.
+ `row_filters` are ANDed onto the `WHERE` clause as `<col> <op> <value>`
+ conditions. The value is always emitted as a bound parameter, never
+ interpolated. Filters compose with the incremental predicate (both ANDed).
+
`extra_table_hint` is appended verbatim after the table reference
(e.g. MySQL `FORCE INDEX (...)`). Callers who use it must have
already validated it through their quoter — the builder itself
@@ -108,27 +114,40 @@ class SelectQueryBuilder:
projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
select_clause = format_projected_select_clause(projected, self.quoter)
- if incremental_field is None:
- return SafeSQL(sql=f"SELECT {select_clause} FROM {table_ref}{hint}", params=self._empty_params())
-
- if incremental_field_type is None:
- raise ValueError("incremental_field_type is required when incremental_field is set")
-
- value = (
- incremental_last_value
- if incremental_last_value is not None
- else incremental_type_to_initial_value(incremental_field_type)
- )
- quoted_field = self.quoter.quote(incremental_field)
- placeholder, params = self._single_param("incremental_value", value)
- operator = incremental_type_to_operator(incremental_field_type)
-
- parts = [
- f"SELECT {select_clause} FROM {table_ref}{hint}",
- f"WHERE {quoted_field} {operator} {placeholder}",
- ]
- if order_by_incremental:
- parts.append(f"ORDER BY {quoted_field} ASC")
+ params = self._empty_params()
+ conditions: list[str] = []
+ quoted_incremental_field: str | None = None
+
+ if incremental_field is not None:
+ if incremental_field_type is None:
+ raise ValueError("incremental_field_type is required when incremental_field is set")
+ value = (
+ incremental_last_value
+ if incremental_last_value is not None
+ else incremental_type_to_initial_value(incremental_field_type)
+ )
+ quoted_incremental_field = self.quoter.quote(incremental_field)
+ placeholder = self._append_param("incremental_value", value, params)
+ operator = incremental_type_to_operator(incremental_field_type)
+ conditions.append(f"{quoted_incremental_field} {operator} {placeholder}")
+
+ for index, row_filter in enumerate(row_filters or []):
+ quoted_column = self.quoter.quote(row_filter.column)
+ if is_multi_value_operator(row_filter.operator):
+ placeholders = [
+ self._append_param(f"row_filter_{index}_{position}", element, params)
+ for position, element in enumerate(row_filter.value)
+ ]
+ conditions.append(f"{quoted_column} {row_filter.operator} ({', '.join(placeholders)})")
+ else:
+ placeholder = self._append_param(f"row_filter_{index}", row_filter.value, params)
+ conditions.append(f"{quoted_column} {row_filter.operator} {placeholder}")
+
+ parts = [f"SELECT {select_clause} FROM {table_ref}{hint}"]
+ if conditions:
+ parts.append("WHERE " + " AND ".join(conditions))
+ if quoted_incremental_field is not None and order_by_incremental:
+ parts.append(f"ORDER BY {quoted_incremental_field} ASC")
return SafeSQL(sql=" ".join(parts), params=params)
@@ -137,13 +156,26 @@ class SelectQueryBuilder:
return {}
return []
- def _single_param(self, name: str, value: Any) -> tuple[str, dict[str, Any] | list[Any]]:
+ def _append_param(self, name: str, value: Any, params: dict[str, Any] | list[Any]) -> str:
+ """Add a value to `params` and return the placeholder that references it.
+
+ Positional styles (`QMARK`, `NUMERIC`) index by current list length, so
+ callers must add params in the same order the placeholders appear in the SQL.
+ """
if self.param_style == ParamStyle.PYFORMAT_NAMED:
- return f"%({name})s", {name: value}
+ assert isinstance(params, dict)
+ params[name] = value
+ return f"%({name})s"
if self.param_style == ParamStyle.NAMED:
- return f":{name}", {name: value}
+ assert isinstance(params, dict)
+ params[name] = value
+ return f":{name}"
if self.param_style == ParamStyle.QMARK:
- return "?", [value]
+ assert isinstance(params, list)
+ params.append(value)
+ return "?"
if self.param_style == ParamStyle.NUMERIC:
- return ":1", [value]
+ assert isinstance(params, list)
+ params.append(value)
+ return f":{len(params)}"
raise ValueError(f"Unsupported param style: {self.param_style}")
diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_predicates.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_predicates.py
new file mode 100644
index 000000000000..11afa59ac66a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_predicates.py
@@ -0,0 +1,495 @@
+from __future__ import annotations
+
+import re
+from datetime import date, datetime
+from decimal import Decimal
+from pathlib import Path
+
+import pytest
+
+from posthog.temporal.data_imports.sources.common.sql.identifiers import AnsiIdentifierQuoter, BacktickIdentifierQuoter
+from posthog.temporal.data_imports.sources.common.sql.predicates import (
+ _BOOLEAN_TYPES,
+ _DATE_TYPES,
+ _INTEGER_TYPES,
+ _NUMERIC_TYPES,
+ _STRING_TYPES,
+ _TIMESTAMP_TYPES,
+ ColumnTypeCategory,
+ RowFilterValidationError,
+ ValidatedRowFilter,
+ classify_column_type,
+ normalize_operator,
+ render_named_conditions,
+ render_positional_conditions,
+ validate_and_coerce_row_filters,
+)
+
+
+def _metadata(columns: list[tuple[str, str]]) -> dict:
+ return {"columns": [{"name": name, "data_type": data_type} for name, data_type in columns]}
+
+
+class TestNormalizeOperator:
+ @pytest.mark.parametrize("operator", [">", ">=", "<", "<=", "=", "!="])
+ def test_canonical_operators_pass_through(self, operator: str) -> None:
+ assert normalize_operator(operator) == operator
+
+ def test_aliases_are_normalized(self) -> None:
+ assert normalize_operator("==") == "="
+ assert normalize_operator("<>") == "!="
+
+ def test_whitespace_is_stripped(self) -> None:
+ assert normalize_operator(" >= ") == ">="
+
+ @pytest.mark.parametrize(
+ "operator,expected",
+ [
+ ("IN", "IN"),
+ ("in", "IN"),
+ ("In", "IN"),
+ (" in ", "IN"),
+ ("NOT IN", "NOT IN"),
+ ("not in", "NOT IN"),
+ ("Not In", "NOT IN"), # collapsed internal whitespace
+ ],
+ )
+ def test_in_operators_are_normalized(self, operator: str, expected: str) -> None:
+ assert normalize_operator(operator) == expected
+
+ @pytest.mark.parametrize("operator", ["LIKE", "=;DROP", "", "OR 1=1", ">>", "NOTIN", "IN;DROP"])
+ def test_disallowed_operators_raise(self, operator: str) -> None:
+ with pytest.raises(RowFilterValidationError):
+ normalize_operator(operator)
+
+ @pytest.mark.parametrize("operator", [1, None, [">"], {">": 1}])
+ def test_non_string_operators_raise(self, operator: object) -> None:
+ with pytest.raises(RowFilterValidationError):
+ normalize_operator(operator)
+
+
+class TestClassifyColumnType:
+ @pytest.mark.parametrize(
+ "data_type,expected",
+ [
+ ("integer", ColumnTypeCategory.INTEGER),
+ ("bigint", ColumnTypeCategory.INTEGER),
+ ("int8", ColumnTypeCategory.INTEGER),
+ ("smallint", ColumnTypeCategory.INTEGER),
+ ("UInt64", ColumnTypeCategory.INTEGER),
+ ("numeric(10,2)", ColumnTypeCategory.NUMERIC),
+ ("decimal", ColumnTypeCategory.NUMERIC),
+ ("double precision", ColumnTypeCategory.NUMERIC),
+ ("Float64", ColumnTypeCategory.NUMERIC),
+ ("NUMBER", ColumnTypeCategory.NUMERIC),
+ ("varchar(255)", ColumnTypeCategory.STRING),
+ ("text", ColumnTypeCategory.STRING),
+ ("uuid", ColumnTypeCategory.STRING),
+ ("FixedString(8)", ColumnTypeCategory.STRING),
+ # json / jsonb are unfilterable: a text-bound comparison fails at sync time.
+ ("json", ColumnTypeCategory.UNKNOWN),
+ ("jsonb", ColumnTypeCategory.UNKNOWN),
+ ("boolean", ColumnTypeCategory.BOOLEAN),
+ ("bool", ColumnTypeCategory.BOOLEAN),
+ ("bit", ColumnTypeCategory.BOOLEAN),
+ ("date", ColumnTypeCategory.DATE),
+ ("Date32", ColumnTypeCategory.DATE),
+ ("timestamp", ColumnTypeCategory.TIMESTAMP),
+ ("timestamp with time zone", ColumnTypeCategory.TIMESTAMP),
+ ("timestamp(6)", ColumnTypeCategory.TIMESTAMP),
+ ("datetime", ColumnTypeCategory.TIMESTAMP),
+ ("DateTime64(3, 'UTC')", ColumnTypeCategory.TIMESTAMP),
+ ("smalldatetime", ColumnTypeCategory.TIMESTAMP),
+ ],
+ )
+ def test_classification(self, data_type: str, expected: ColumnTypeCategory) -> None:
+ assert classify_column_type(data_type) == expected
+
+ def test_case_insensitive(self) -> None:
+ assert classify_column_type("INTEGER") == ColumnTypeCategory.INTEGER
+ assert classify_column_type("VarChar(10)") == ColumnTypeCategory.STRING
+
+
+class TestTypeVocabularyParity:
+ """The classifier's type sets are duplicated in the frontend (rowFilterUtils.ts). Assert the
+ two stay in sync so a column type can't be filterable on one side and not the other."""
+
+ _TS_PATH = (
+ Path(__file__).resolve().parents[7]
+ / "products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.ts"
+ )
+
+ def _ts_set(self, name: str) -> set[str]:
+ source = self._TS_PATH.read_text()
+ match = re.search(rf"const {name} = new Set\(\[(.*?)\]\)", source, re.DOTALL)
+ assert match, f"{name} not found in rowFilterUtils.ts"
+ body = re.sub(r"//[^\n]*", "", match.group(1)) # drop line comments first
+ return set(re.findall(r"'([^']*)'", body))
+
+ @pytest.mark.parametrize(
+ "ts_name,py_set",
+ [
+ ("INTEGER_TYPES", _INTEGER_TYPES),
+ ("NUMERIC_TYPES", _NUMERIC_TYPES),
+ ("STRING_TYPES", _STRING_TYPES),
+ ("BOOLEAN_TYPES", _BOOLEAN_TYPES),
+ ("DATE_TYPES", _DATE_TYPES),
+ ("TIMESTAMP_TYPES", _TIMESTAMP_TYPES),
+ ],
+ )
+ def test_python_and_typescript_type_sets_match(self, ts_name: str, py_set: set[str]) -> None:
+ assert self._ts_set(ts_name) == py_set
+
+ def test_nullable_wrapper_is_stripped(self) -> None:
+ assert classify_column_type("Nullable(Int64)") == ColumnTypeCategory.INTEGER
+ assert classify_column_type("Nullable(DateTime64(3))") == ColumnTypeCategory.TIMESTAMP
+ assert classify_column_type("LowCardinality(Nullable(String))") == ColumnTypeCategory.STRING
+
+ @pytest.mark.parametrize("data_type", ["", " ", "geometry", "bytea", "array", "hstore", None, 123])
+ def test_unknown_types(self, data_type: object) -> None:
+ assert classify_column_type(data_type) == ColumnTypeCategory.UNKNOWN
+
+
+class TestValidateAndCoerce:
+ def test_none_returns_empty(self) -> None:
+ assert validate_and_coerce_row_filters(None, _metadata([("id", "integer")])) == []
+
+ def test_empty_list_returns_empty(self) -> None:
+ assert validate_and_coerce_row_filters([], _metadata([("id", "integer")])) == []
+
+ def test_non_list_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="must be a list"):
+ validate_and_coerce_row_filters({"column": "id"}, _metadata([("id", "integer")]))
+
+ def test_too_many_filters_raises(self) -> None:
+ metadata = _metadata([("id", "integer")])
+ filters = [{"column": "id", "operator": ">", "value": 1} for _ in range(21)]
+ with pytest.raises(RowFilterValidationError, match="Too many row filters"):
+ validate_and_coerce_row_filters(filters, metadata)
+
+ def test_unknown_column_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="Unknown column"):
+ validate_and_coerce_row_filters(
+ [{"column": "nope", "operator": ">", "value": 1}], _metadata([("id", "integer")])
+ )
+
+ def test_missing_column_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="missing a column"):
+ validate_and_coerce_row_filters([{"operator": ">", "value": 1}], _metadata([("id", "integer")]))
+
+ def test_missing_value_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="missing a value"):
+ validate_and_coerce_row_filters([{"column": "id", "operator": ">"}], _metadata([("id", "integer")]))
+
+ def test_unsupported_column_type_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="not supported for filtering"):
+ validate_and_coerce_row_filters(
+ [{"column": "geo", "operator": "=", "value": "x"}], _metadata([("geo", "geometry")])
+ )
+
+ def test_filter_at_index_must_be_object(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="must be an object"):
+ validate_and_coerce_row_filters(["not a dict"], _metadata([("id", "integer")]))
+
+ def test_integer_coercion(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "id", "operator": ">", "value": "42"}], _metadata([("id", "integer")])
+ )
+ assert result == [ValidatedRowFilter(column="id", operator=">", value=42, category=ColumnTypeCategory.INTEGER)]
+
+ @pytest.mark.parametrize("value", [True, False, "3.5", "abc", 3.5])
+ def test_integer_rejects_bad_values(self, value: object) -> None:
+ with pytest.raises(RowFilterValidationError):
+ validate_and_coerce_row_filters(
+ [{"column": "id", "operator": ">", "value": value}], _metadata([("id", "integer")])
+ )
+
+ def test_numeric_coercion_from_string(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "amount", "operator": ">=", "value": "3.14"}], _metadata([("amount", "numeric")])
+ )
+ assert result[0].value == Decimal("3.14")
+ assert result[0].category == ColumnTypeCategory.NUMERIC
+
+ def test_numeric_rejects_non_number(self) -> None:
+ with pytest.raises(RowFilterValidationError):
+ validate_and_coerce_row_filters(
+ [{"column": "amount", "operator": ">", "value": "not-a-number"}], _metadata([("amount", "numeric")])
+ )
+
+ def test_string_coercion(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "name", "operator": "=", "value": "alice"}], _metadata([("name", "varchar(50)")])
+ )
+ assert result[0].value == "alice"
+
+ @pytest.mark.parametrize("value", [1, 1.5, True, None])
+ def test_string_rejects_non_string(self, value: object) -> None:
+ with pytest.raises(RowFilterValidationError):
+ validate_and_coerce_row_filters(
+ [{"column": "name", "operator": "=", "value": value}], _metadata([("name", "text")])
+ )
+
+ @pytest.mark.parametrize(
+ "value,expected",
+ [(True, True), (False, False), ("true", True), ("false", False), (1, True), (0, False)],
+ )
+ def test_boolean_coercion(self, value: object, expected: bool) -> None:
+ # Integers 0/1 are accepted (valid JSON encodings of booleans a direct API caller may send).
+ result = validate_and_coerce_row_filters(
+ [{"column": "active", "operator": "=", "value": value}], _metadata([("active", "boolean")])
+ )
+ assert result[0].value is expected
+
+ @pytest.mark.parametrize("value", ["yes", "1", 2, -1, None])
+ def test_boolean_rejects_bad_values(self, value: object) -> None:
+ with pytest.raises(RowFilterValidationError):
+ validate_and_coerce_row_filters(
+ [{"column": "active", "operator": "=", "value": value}], _metadata([("active", "boolean")])
+ )
+
+ def test_date_coercion(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "d", "operator": ">", "value": "2026-01-01"}], _metadata([("d", "date")])
+ )
+ assert result[0].value == date(2026, 1, 1)
+
+ @pytest.mark.parametrize("value", ["2026-13-01", "not-a-date", "01/01/2026", 20260101])
+ def test_date_rejects_bad_values(self, value: object) -> None:
+ with pytest.raises(RowFilterValidationError):
+ validate_and_coerce_row_filters(
+ [{"column": "d", "operator": ">", "value": value}], _metadata([("d", "date")])
+ )
+
+ def test_timestamp_coercion_iso(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "ts", "operator": ">", "value": "2026-01-01T12:30:00"}], _metadata([("ts", "timestamp")])
+ )
+ assert result[0].value == datetime(2026, 1, 1, 12, 30, 0)
+
+ def test_timestamp_accepts_trailing_z(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "ts", "operator": ">", "value": "2026-01-01T12:30:00Z"}], _metadata([("ts", "timestamp")])
+ )
+ assert result[0].value.year == 2026
+
+ def test_timestamp_accepts_plain_date(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "ts", "operator": ">", "value": "2026-01-01"}], _metadata([("ts", "timestamp")])
+ )
+ assert result[0].value == datetime(2026, 1, 1, 0, 0, 0)
+
+ def test_multiple_filters(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [
+ {"column": "id", "operator": ">", "value": 10},
+ {"column": "name", "operator": "!=", "value": "bob"},
+ ],
+ _metadata([("id", "integer"), ("name", "text")]),
+ )
+ assert len(result) == 2
+ assert result[0].operator == ">"
+ assert result[1].operator == "!="
+
+ def test_alias_operator_is_normalized_in_result(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "==", "value": 1}], _metadata([("id", "integer")])
+ )
+ assert result[0].operator == "="
+
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("1,2,3", [1, 2, 3]),
+ ("1, 2, 3", [1, 2, 3]),
+ (" 1 , 2 ,3 ", [1, 2, 3]),
+ ("42", [42]),
+ ],
+ )
+ def test_in_integer_list_coercion(self, raw: str, expected: list[int]) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "IN", "value": raw}], _metadata([("id", "integer")])
+ )
+ assert result[0].operator == "IN"
+ assert result[0].value == expected
+
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("'abc','cde'", ["abc", "cde"]),
+ ("'abc', 'cde'", ["abc", "cde"]),
+ ("abc,cde", ["abc", "cde"]), # quotes are optional when there's no embedded comma
+ ("'a,b','c'", ["a,b", "c"]), # commas inside quotes are preserved
+ ("'o''brien'", ["o'brien"]), # doubled quote escapes
+ ],
+ )
+ def test_in_string_list_coercion(self, raw: str, expected: list[str]) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "name", "operator": "IN", "value": raw}], _metadata([("name", "text")])
+ )
+ assert result[0].value == expected
+
+ def test_not_in_operator(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "not in", "value": "1,2"}], _metadata([("id", "integer")])
+ )
+ assert result[0].operator == "NOT IN"
+ assert result[0].value == [1, 2]
+
+ def test_in_accepts_structured_list(self) -> None:
+ result = validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "IN", "value": [1, "2", 3]}], _metadata([("id", "integer")])
+ )
+ assert result[0].value == [1, 2, 3]
+
+ def test_in_empty_list_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="at least one value"):
+ validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "IN", "value": ""}], _metadata([("id", "integer")])
+ )
+
+ def test_in_blank_element_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="empty value"):
+ validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "IN", "value": "1,,2"}], _metadata([("id", "integer")])
+ )
+
+ def test_in_bad_element_type_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError):
+ validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "IN", "value": "1,abc,3"}], _metadata([("id", "integer")])
+ )
+
+ def test_in_unterminated_quote_raises(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="Unterminated quote"):
+ validate_and_coerce_row_filters(
+ [{"column": "name", "operator": "IN", "value": "'abc"}], _metadata([("name", "text")])
+ )
+
+ def test_in_too_many_values_raises(self) -> None:
+ raw = ",".join(str(n) for n in range(1001))
+ with pytest.raises(RowFilterValidationError, match="Too many values"):
+ validate_and_coerce_row_filters(
+ [{"column": "id", "operator": "IN", "value": raw}], _metadata([("id", "integer")])
+ )
+
+ def test_no_metadata_columns_skips_existence_check(self) -> None:
+ # With no discovered columns we can't classify the type, so it fails the type rail
+ # rather than the column-existence rail.
+ with pytest.raises(RowFilterValidationError, match="not supported for filtering"):
+ validate_and_coerce_row_filters([{"column": "id", "operator": ">", "value": 1}], None)
+
+
+class TestRenderNamedConditions:
+ quoter = BacktickIdentifierQuoter()
+
+ def test_renders_placeholders_and_params(self) -> None:
+ filters = [
+ ValidatedRowFilter(column="id", operator=">", value=10, category=ColumnTypeCategory.INTEGER),
+ ValidatedRowFilter(column="name", operator="!=", value="bob", category=ColumnTypeCategory.STRING),
+ ]
+ conditions, params = render_named_conditions(filters, self.quoter)
+ assert conditions == ["`id` > %(row_filter_0)s", "`name` != %(row_filter_1)s"]
+ assert params == {"row_filter_0": 10, "row_filter_1": "bob"}
+
+ def test_value_never_in_condition_text(self) -> None:
+ filters = [
+ ValidatedRowFilter(
+ column="name", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ]
+ conditions, params = render_named_conditions(filters, self.quoter)
+ assert "DROP TABLE" not in conditions[0]
+ assert params["row_filter_0"] == "x'; DROP TABLE y; --"
+
+ def test_custom_prefix(self) -> None:
+ filters = [ValidatedRowFilter(column="id", operator=">", value=1, category=ColumnTypeCategory.INTEGER)]
+ conditions, params = render_named_conditions(filters, self.quoter, prefix="rf")
+ assert conditions == ["`id` > %(rf_0)s"]
+ assert "rf_0" in params
+
+ def test_in_expands_to_one_placeholder_per_value(self) -> None:
+ filters = [
+ ValidatedRowFilter(column="id", operator="IN", value=[1, 2, 3], category=ColumnTypeCategory.INTEGER),
+ ]
+ conditions, params = render_named_conditions(filters, self.quoter)
+ assert conditions == ["`id` IN (%(row_filter_0_0)s, %(row_filter_0_1)s, %(row_filter_0_2)s)"]
+ assert params == {"row_filter_0_0": 1, "row_filter_0_1": 2, "row_filter_0_2": 3}
+
+ def test_not_in_renders_operator(self) -> None:
+ filters = [
+ ValidatedRowFilter(column="name", operator="NOT IN", value=["a", "b"], category=ColumnTypeCategory.STRING),
+ ]
+ conditions, params = render_named_conditions(filters, self.quoter)
+ assert conditions == ["`name` NOT IN (%(row_filter_0_0)s, %(row_filter_0_1)s)"]
+ assert params == {"row_filter_0_0": "a", "row_filter_0_1": "b"}
+
+
+class TestRenderPositionalConditions:
+ quoter = AnsiIdentifierQuoter()
+
+ def test_renders_in_order(self) -> None:
+ filters = [
+ ValidatedRowFilter(column="id", operator=">", value=10, category=ColumnTypeCategory.INTEGER),
+ ValidatedRowFilter(column="name", operator="=", value="bob", category=ColumnTypeCategory.STRING),
+ ]
+ conditions, values = render_positional_conditions(filters, self.quoter)
+ assert conditions == ['"id" > %s', '"name" = %s']
+ assert values == [10, "bob"]
+
+ def test_value_never_in_condition_text(self) -> None:
+ filters = [
+ ValidatedRowFilter(
+ column="name", operator="=", value="'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ]
+ conditions, values = render_positional_conditions(filters, self.quoter)
+ assert "DROP TABLE" not in conditions[0]
+ assert values == ["'; DROP TABLE y; --"]
+
+ def test_in_expands_in_order(self) -> None:
+ filters = [
+ ValidatedRowFilter(column="id", operator="IN", value=[10, 20], category=ColumnTypeCategory.INTEGER),
+ ValidatedRowFilter(column="name", operator="=", value="bob", category=ColumnTypeCategory.STRING),
+ ]
+ conditions, values = render_positional_conditions(filters, self.quoter)
+ assert conditions == ['"id" IN (%s, %s)', '"name" = %s']
+ assert values == [10, 20, "bob"]
+
+ def test_in_injection_value_stays_a_bound_param(self) -> None:
+ # A malicious element survives as data only — it's one bound value, never SQL.
+ filters = [
+ ValidatedRowFilter(
+ column="name",
+ operator="IN",
+ value=["ok", "'); DROP SCHEMA s CASCADE; --"],
+ category=ColumnTypeCategory.STRING,
+ )
+ ]
+ conditions, values = render_positional_conditions(filters, self.quoter)
+ assert conditions == ['"name" IN (%s, %s)']
+ assert "DROP SCHEMA" not in conditions[0]
+ assert values == ["ok", "'); DROP SCHEMA s CASCADE; --"]
+
+
+class TestInjectionGuards:
+ """A malicious column name never reaches SQL: it's rejected by the quoter or the column allowlist."""
+
+ def test_malicious_column_rejected_by_allowlist(self) -> None:
+ with pytest.raises(RowFilterValidationError, match="Unknown column"):
+ validate_and_coerce_row_filters(
+ [{"column": "id; DROP TABLE x", "operator": ">", "value": 1}],
+ _metadata([("id", "integer")]),
+ )
+
+ def test_malicious_column_rejected_by_quoter_at_render(self) -> None:
+ from posthog.temporal.data_imports.sources.common.sql.identifiers import InvalidIdentifierError
+
+ # Even if a bad identifier somehow reaches render, the quoter rejects it.
+ filters = [
+ ValidatedRowFilter(
+ column='id"; DROP TABLE x; --', operator=">", value=1, category=ColumnTypeCategory.INTEGER
+ )
+ ]
+ with pytest.raises(InvalidIdentifierError):
+ render_named_conditions(filters, BacktickIdentifierQuoter())
diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.py
index f51ef785edd8..766b91d02c01 100644
--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.py
+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_query_builder.py
@@ -9,6 +9,7 @@ from posthog.temporal.data_imports.sources.common.sql.identifiers import (
BacktickIdentifierQuoter,
InvalidIdentifierError,
)
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.common.sql.query_builder import ParamStyle, SelectQueryBuilder
from products.data_warehouse.backend.types import IncrementalFieldType
@@ -195,3 +196,109 @@ class TestParamStyles:
named = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.PYFORMAT_NAMED)
assert qmark.select_all(schema="public", table_name="t").params == []
assert named.select_all(schema="public", table_name="t").params == {}
+
+
+class TestSelectAllRowFilters:
+ builder = SelectQueryBuilder(quoter=BacktickIdentifierQuoter())
+
+ def _filter(self, column: str, operator: str, value: object) -> ValidatedRowFilter:
+ return ValidatedRowFilter(column=column, operator=operator, value=value, category=ColumnTypeCategory.INTEGER)
+
+ def test_single_filter_emits_where_and_param(self) -> None:
+ result = self.builder.select_all(
+ schema="db",
+ table_name="t",
+ row_filters=[self._filter("age", ">", 21)],
+ )
+ assert "WHERE `age` > %(row_filter_0)s" in result.sql
+ assert result.params == {"row_filter_0": 21}
+
+ def test_multiple_filters_are_anded(self) -> None:
+ result = self.builder.select_all(
+ schema="db",
+ table_name="t",
+ row_filters=[self._filter("age", ">", 21), self._filter("score", "<=", 100)],
+ )
+ assert "WHERE `age` > %(row_filter_0)s AND `score` <= %(row_filter_1)s" in result.sql
+ assert result.params == {"row_filter_0": 21, "row_filter_1": 100}
+
+ def test_filters_compose_with_incremental(self) -> None:
+ result = self.builder.select_all(
+ schema="db",
+ table_name="t",
+ incremental_field="updated_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ incremental_last_value=datetime.datetime(2025, 1, 1),
+ row_filters=[self._filter("age", ">", 21)],
+ )
+ # Incremental condition first, then the row filter, both ANDed; ORDER BY still present.
+ assert (
+ "WHERE `updated_at` > %(incremental_value)s AND `age` > %(row_filter_0)s ORDER BY `updated_at` ASC"
+ in result.sql
+ )
+ assert isinstance(result.params, dict)
+ assert result.params["incremental_value"] == datetime.datetime(2025, 1, 1)
+ assert result.params["row_filter_0"] == 21
+
+ def test_value_never_interpolated(self) -> None:
+ result = self.builder.select_all(
+ schema="db",
+ table_name="t",
+ row_filters=[
+ ValidatedRowFilter(
+ column="name", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ],
+ )
+ assert "DROP TABLE" not in result.sql
+ assert isinstance(result.params, dict)
+ assert result.params["row_filter_0"] == "x'; DROP TABLE y; --"
+
+ def test_positional_style_orders_filters_after_incremental(self) -> None:
+ builder = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.NUMERIC)
+ result = builder.select_all(
+ schema="public",
+ table_name="users",
+ incremental_field="id",
+ incremental_field_type=IncrementalFieldType.Integer,
+ incremental_last_value=5,
+ row_filters=[self._filter("age", ">", 21)],
+ )
+ # Incremental value is bound first (:1), row filter second (:2) — order matters for positional params.
+ assert result.params == [5, 21]
+ assert ":1" in result.sql and ":2" in result.sql
+
+ def test_in_filter_expands_to_one_placeholder_per_value(self) -> None:
+ result = self.builder.select_all(
+ schema="db",
+ table_name="t",
+ row_filters=[self._filter("age", "IN", [21, 30, 40])],
+ )
+ assert "WHERE `age` IN (%(row_filter_0_0)s, %(row_filter_0_1)s, %(row_filter_0_2)s)" in result.sql
+ assert result.params == {"row_filter_0_0": 21, "row_filter_0_1": 30, "row_filter_0_2": 40}
+
+ def test_in_filter_positional_order_after_incremental(self) -> None:
+ builder = SelectQueryBuilder(quoter=AnsiIdentifierQuoter(), param_style=ParamStyle.NUMERIC)
+ result = builder.select_all(
+ schema="public",
+ table_name="users",
+ incremental_field="id",
+ incremental_field_type=IncrementalFieldType.Integer,
+ incremental_last_value=5,
+ row_filters=[self._filter("age", "NOT IN", [21, 30])],
+ )
+ # Incremental value bound first, then each IN element in order.
+ assert result.params == [5, 21, 30]
+ assert '"age" NOT IN (:2, :3)' in result.sql
+
+ def test_none_row_filters_no_where(self) -> None:
+ result = self.builder.select_all(schema="db", table_name="t", row_filters=None)
+ assert "WHERE" not in result.sql
+
+ def test_malicious_column_rejected(self) -> None:
+ with pytest.raises(InvalidIdentifierError):
+ self.builder.select_all(
+ schema="db",
+ table_name="t",
+ row_filters=[self._filter("age`; DROP TABLE x; --", ">", 21)],
+ )
diff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.py
index 16e0c8eedbe6..9598ddf680f7 100644
--- a/posthog/temporal/data_imports/sources/mssql/mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py
@@ -36,9 +36,11 @@ from posthog.temporal.data_imports.sources.common.sql import (
BracketIdentifierQuoter,
Column,
Table,
+ ValidatedRowFilter,
compute_projected_columns,
format_projected_select_clause,
project_arrow_columns,
+ render_named_conditions,
)
from posthog.temporal.data_imports.sources.common.sql.implementation import (
SourceMetadata,
@@ -127,6 +129,7 @@ def _build_query(
add_limit: bool = False,
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
+ row_filters: list[ValidatedRowFilter] | None = None,
) -> tuple[str, dict[str, Any]]:
# Every identifier interpolated below is validated by the bracket
# quoter — bad input (`;`, `]`, whitespace, etc.) raises before any
@@ -137,7 +140,11 @@ def _build_query(
select_clause = format_projected_select_clause(projected, _IDENTIFIER_QUOTER)
base_query = f"SELECT {top}{select_clause} FROM {qualified_table}"
+ filter_conditions, filter_params = render_named_conditions(row_filters or [], _IDENTIFIER_QUOTER)
+
if not should_use_incremental_field:
+ if filter_conditions:
+ return f"{base_query} WHERE {' AND '.join(filter_conditions)}", filter_params
return base_query, {}
if incremental_field is None or incremental_field_type is None:
@@ -148,15 +155,14 @@ def _build_query(
operator = incremental_type_to_operator(incremental_field_type)
quoted_incremental = _IDENTIFIER_QUOTER.quote(incremental_field)
- query = f"{base_query} WHERE {quoted_incremental} {operator} %(incremental_value)s"
+ conditions = [f"{quoted_incremental} {operator} %(incremental_value)s", *filter_conditions]
+ query = f"{base_query} WHERE {' AND '.join(conditions)}"
# it is only safe to have this order by nested in a CTE if TOP is also specified
# ordering for incremental sync purposes where TOP is not specified is handled in get_rows()
if add_limit:
query = f"{query} ORDER BY {quoted_incremental} ASC"
- return query, {
- "incremental_value": db_incremental_field_last_value,
- }
+ return query, {"incremental_value": db_incremental_field_last_value, **filter_params}
class MSSQLColumn(Column):
@@ -713,6 +719,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
incremental_field_type = inputs.incremental_field_type
db_incremental_field_last_value = inputs.db_incremental_field_last_value
enabled_columns = inputs.enabled_columns
+ row_filters = inputs.row_filters
with self.connect(config) as connection:
with connection.cursor() as cursor:
@@ -737,6 +744,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)
@@ -759,6 +767,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
if incremental_field:
query = f"{query} ORDER BY {_IDENTIFIER_QUOTER.quote(incremental_field)} ASC"
diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
index 07bdc91422e0..b23e3e9ddaae 100644
--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
from posthog.temporal.data_imports.sources.common.sql import Table, TableStats
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig
from posthog.temporal.data_imports.sources.mssql.mssql import (
MSSQLColumn,
@@ -110,6 +111,64 @@ class TestBuildQuery:
assert "%(incremental_value)s" in query
assert args == {"incremental_value": "2025-01-01"}
+ def test_row_filters_full_refresh(self):
+ query, args = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ assert "WHERE [age] > %(row_filter_0)s" in query
+ assert args == {"row_filter_0": 21}
+
+ def test_in_filter_expands_to_named_placeholders(self):
+ query, args = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+ assert "WHERE [age] IN (%(row_filter_0_0)s, %(row_filter_0_1)s)" in query
+ assert args == {"row_filter_0_0": 21, "row_filter_0_1": 30}
+
+ def test_row_filters_compose_with_incremental(self):
+ query, args = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2025-01-01",
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ assert "WHERE [created_at] > %(incremental_value)s AND [age] > %(row_filter_0)s" in query
+ assert args == {"incremental_value": "2025-01-01", "row_filter_0": 21}
+
+ def test_row_filter_value_never_interpolated(self):
+ query, args = _build_query(
+ schema="dbo",
+ table_name="users",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[
+ ValidatedRowFilter(
+ column="name", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ],
+ )
+ assert "DROP TABLE" not in query
+ assert args == {"row_filter_0": "x'; DROP TABLE y; --"}
+
def test_add_limit_uses_top_100(self):
query, _ = _build_query(
schema="dbo",
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.py
index 771e81d228ea..34b8b2ad773e 100644
--- a/posthog/temporal/data_imports/sources/mysql/mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py
@@ -48,6 +48,7 @@ from posthog.temporal.data_imports.sources.common.sql import (
InvalidIdentifierError,
SelectQueryBuilder,
Table,
+ ValidatedRowFilter,
compute_projected_columns,
project_arrow_columns,
)
@@ -171,6 +172,7 @@ def _build_query(
force_index_name: str | None = None,
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
+ row_filters: list[ValidatedRowFilter] | None = None,
) -> tuple[str, dict[str, Any]]:
hint: str | None = None
if force_index_name is not None:
@@ -184,6 +186,7 @@ def _build_query(
extra_table_hint=hint,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
params = result.params if isinstance(result.params, dict) else {}
return result.sql, params
@@ -200,6 +203,7 @@ def _build_query(
extra_table_hint=hint,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
params = result.params if isinstance(result.params, dict) else {}
return result.sql, params
@@ -803,6 +807,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
incremental_field_type = inputs.incremental_field_type
db_incremental_field_last_value = inputs.db_incremental_field_last_value
enabled_columns = inputs.enabled_columns
+ row_filters = inputs.row_filters
with self.connect(config) as connection:
with connection.cursor() as cursor:
@@ -827,6 +832,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)
@@ -870,6 +876,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
force_index_name=force_index_name,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
logger.debug(f"MySQL query: {query.format(args)}")
diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
index e452ee2a9798..f6c822d73a07 100644
--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -9,6 +9,7 @@ import pymysql
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
from posthog.temporal.data_imports.sources.common.sql import Table, TableStats
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig
from posthog.temporal.data_imports.sources.mysql.mysql import (
STATEMENT_TIMEOUT_SECONDS,
@@ -804,6 +805,66 @@ class TestBuildQueryEnabledColumns:
assert "WHERE `created_at` > %(incremental_value)s" in query
+class TestBuildQueryRowFilters:
+ def test_full_refresh_row_filter(self):
+ query, params = _build_query(
+ schema="mydb",
+ table_name="message",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ assert "WHERE `age` > %(row_filter_0)s" in query
+ assert params == {"row_filter_0": 21}
+
+ def test_in_filter_expands_to_named_placeholders(self):
+ query, params = _build_query(
+ schema="mydb",
+ table_name="message",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+ assert "WHERE `age` IN (%(row_filter_0_0)s, %(row_filter_0_1)s)" in query
+ assert params == {"row_filter_0_0": 21, "row_filter_0_1": 30}
+
+ def test_row_filters_compose_with_incremental(self):
+ query, params = _build_query(
+ schema="mydb",
+ table_name="message",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2025-01-01",
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ assert "WHERE `created_at` > %(incremental_value)s AND `age` > %(row_filter_0)s" in query
+ assert params == {"incremental_value": "2025-01-01", "row_filter_0": 21}
+
+ def test_value_never_interpolated(self):
+ query, params = _build_query(
+ schema="mydb",
+ table_name="message",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[
+ ValidatedRowFilter(
+ column="name", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ],
+ )
+ assert "DROP TABLE" not in query
+ assert params == {"row_filter_0": "x'; DROP TABLE y; --"}
+
+
class TestMySQLSourceNonRetryableErrors:
@pytest.fixture
def source(self):
diff --git a/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py b/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
index 6d453a69c3aa..0d10d1cfff07 100644
--- a/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
+++ b/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
@@ -21,7 +21,11 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (
QueryTimeoutException,
table_from_iterator,
)
-from posthog.temporal.data_imports.sources.common.sql import compute_projected_columns
+from posthog.temporal.data_imports.sources.common.sql import ValidatedRowFilter, compute_projected_columns
+from posthog.temporal.data_imports.sources.common.sql.predicates_psycopg import (
+ and_join,
+ render_psycopg_row_filter_conditions,
+)
from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
@@ -499,6 +503,7 @@ def build_partition_query(
*,
enabled_columns: Optional[list[str]] = None,
primary_keys: Optional[list[str]] = None,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
) -> sql.Composed:
"""Build a SELECT against one child partition.
@@ -513,13 +518,17 @@ def build_partition_query(
select_clause: sql.Composable = (
sql.SQL("*") if projected is None else sql.SQL(", ").join(sql.Identifier(c) for c in projected)
)
+ row_filter_conditions = render_psycopg_row_filter_conditions(row_filters or [])
if not should_use_incremental_field:
- return sql.SQL("SELECT {cols} FROM {schema}.{table}").format(
+ query = sql.SQL("SELECT {cols} FROM {schema}.{table}").format(
cols=select_clause,
schema=sql.Identifier(child_schema),
table=sql.Identifier(child_name),
)
+ if row_filter_conditions:
+ query = query + sql.SQL(" WHERE ") + and_join(row_filter_conditions)
+ return query
if incremental_field is None or incremental_field_type is None:
raise ValueError("incremental_field and incremental_field_type can't be None")
@@ -528,7 +537,7 @@ def build_partition_query(
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
operator = sql.SQL(incremental_type_to_operator(incremental_field_type))
- return sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {field} {op} {last_value} ORDER BY {field} ASC").format(
+ query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {field} {op} {last_value}").format(
cols=select_clause,
schema=sql.Identifier(child_schema),
table=sql.Identifier(child_name),
@@ -536,6 +545,9 @@ def build_partition_query(
op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
+ if row_filter_conditions:
+ query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)
+ return query + sql.SQL(" ORDER BY {field} ASC").format(field=sql.Identifier(incremental_field))
def iterate_partitions(
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index e8ec1d2b421a..077927bef6bc 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -50,9 +50,18 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (
table_from_iterator,
)
from posthog.temporal.data_imports.sources.common.mixins import open_ssh_tunnel
-from posthog.temporal.data_imports.sources.common.sql import Column, Table, compute_projected_columns
+from posthog.temporal.data_imports.sources.common.sql import (
+ Column,
+ Table,
+ ValidatedRowFilter,
+ compute_projected_columns,
+)
from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation
from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter
+from posthog.temporal.data_imports.sources.common.sql.predicates_psycopg import (
+ and_join,
+ render_psycopg_row_filter_conditions,
+)
from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig
from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
build_partition_query,
@@ -1261,11 +1270,15 @@ def _build_query(
upper_bound_inclusive: Optional[Any] = None,
enabled_columns: Optional[list[str]] = None,
primary_keys: Optional[list[str]] = None,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
) -> sql.Composed:
projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
select_clause: sql.Composable = (
sql.SQL("*") if projected is None else sql.SQL(", ").join(sql.Identifier(c) for c in projected)
)
+ # Row filters apply only to the real data path; sampling/row-count queries stay unfiltered
+ # (an over-estimate is harmless).
+ row_filter_conditions = render_psycopg_row_filter_conditions(row_filters or [])
if not should_use_incremental_field:
if add_sampling:
@@ -1277,15 +1290,14 @@ def _build_query(
query = sql.SQL("SELECT {cols} FROM {table} TABLESAMPLE SYSTEM (1)").format(
cols=select_clause, table=sql.Identifier(schema, table_name)
)
- else:
- query = sql.SQL("SELECT {cols} FROM {table}").format(
- cols=select_clause, table=sql.Identifier(schema, table_name)
- )
-
- if add_sampling:
query_with_limit = cast(LiteralString, f"{query.as_string()} LIMIT 1000")
return sql.SQL(query_with_limit).format()
+ query = sql.SQL("SELECT {cols} FROM {table}").format(
+ cols=select_clause, table=sql.Identifier(schema, table_name)
+ )
+ if row_filter_conditions:
+ query = query + sql.SQL(" WHERE ") + and_join(row_filter_conditions)
return query
if incremental_field is None or incremental_field_type is None:
@@ -1346,6 +1358,9 @@ def _build_query(
upper=sql.Literal(upper_bound_inclusive),
)
+ if row_filter_conditions:
+ query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)
+
query_str = cast(LiteralString, f"{query.as_string()} ORDER BY {{incremental_field}} ASC")
return sql.SQL(query_str).format(incremental_field=sql.Identifier(incremental_field))
@@ -2084,6 +2099,7 @@ def postgres_source(
require_ssl: bool = False,
is_initial_sync: bool = False,
enabled_columns: Optional[list[str]] = None,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
) -> SourceResponse:
table_name = table_names[0]
if not table_name:
@@ -2462,6 +2478,7 @@ def postgres_source(
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
successive_errors = 0
@@ -2584,6 +2601,7 @@ def postgres_source(
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
yield from iterate_partitions(
@@ -2615,6 +2633,7 @@ def postgres_source(
upper_bound_inclusive=hi,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
yield from iterate_date_windows(
@@ -2654,6 +2673,7 @@ def postgres_source(
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
logger.debug(f"Postgres query: {query.as_string()}")
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.py
index ac7d7f300786..df3695532bbe 100644
--- a/posthog/temporal/data_imports/sources/postgres/source.py
+++ b/posthog/temporal/data_imports/sources/postgres/source.py
@@ -732,6 +732,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
require_ssl=require_ssl,
is_initial_sync=not schema.initial_sync_complete,
enabled_columns=inputs.enabled_columns,
+ row_filters=inputs.row_filters,
)
# `SourceResponse.name` must match `DataWarehouseTable.url_pattern` (both derived from the
# storage key when present, otherwise the row name) so HogQL reads from where we wrote.
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index a89addd0ccb7..e2d4546ccdfc 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -23,6 +23,7 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (
QueryTimeoutException,
TemporaryFileSizeExceedsLimitException,
)
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
WINDOW_MAX_QUERY_CANCELED_RETRIES,
WINDOW_MAX_SERIALIZATION_RETRIES,
@@ -2008,6 +2009,103 @@ class TestBuildQuery:
assert '"cursor" > ' in rendered
assert '"cursor" >= ' not in rendered
+ def test_row_filter_full_refresh(self):
+ query = _build_query(
+ "public",
+ "users",
+ False,
+ "table",
+ None,
+ None,
+ None,
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ rendered = self._render(query)
+ assert 'WHERE "age" > 21' in rendered
+
+ def test_row_filter_composes_with_incremental(self):
+ query = _build_query(
+ "public",
+ "events",
+ True,
+ "table",
+ "created_at",
+ IncrementalFieldType.Timestamp,
+ "2024-01-01",
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ rendered = self._render(query)
+ assert '"created_at"' in rendered
+ assert 'AND "age" > 21' in rendered
+ assert rendered.rstrip().endswith('ORDER BY "created_at" ASC')
+
+ def test_row_filter_in_list_renders_parenthesized(self):
+ query = _build_query(
+ "public",
+ "users",
+ False,
+ "table",
+ None,
+ None,
+ None,
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30, 40], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+ rendered = self._render(query)
+ assert 'WHERE "age" IN (21, 30, 40)' in rendered
+
+ def test_row_filter_composes_with_windowed_upper_bound(self):
+ query = _build_query(
+ "public",
+ "events",
+ True,
+ "table",
+ "cursor",
+ IncrementalFieldType.Date,
+ date(2026, 5, 13),
+ upper_bound_inclusive=date(2026, 5, 14),
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ rendered = self._render(query)
+ # Row filter is ANDed after the window's upper bound, before ORDER BY.
+ assert '"cursor" <= ' in rendered
+ assert 'AND "age" > 21' in rendered
+ assert rendered.index('"cursor" <= ') < rendered.index('"age" > 21')
+
+ def test_row_filter_not_applied_to_sampling(self):
+ query = _build_query(
+ "public",
+ "users",
+ False,
+ "table",
+ None,
+ None,
+ None,
+ add_sampling=True,
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ rendered = self._render(query)
+ assert '"age"' not in rendered
+
+ def test_row_filter_string_value_is_escaped_literal(self):
+ query = _build_query(
+ "public",
+ "users",
+ False,
+ "table",
+ None,
+ None,
+ None,
+ row_filters=[
+ ValidatedRowFilter(
+ column="name", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ],
+ )
+ rendered = self._render(query)
+ assert "'x''; DROP TABLE y; --'" in rendered
+
class TestBuildPartitionQuery:
def _render(self, composed: sql.Composed) -> str:
@@ -2072,6 +2170,34 @@ class TestBuildPartitionQuery:
rendered = self._render(query)
assert f'"cursor" {expected_operator} ' in rendered
+ def test_row_filter_full_refresh(self):
+ query = build_partition_query(
+ "public",
+ "events_2026_01",
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ rendered = self._render(query)
+ assert 'WHERE "age" > 21' in rendered
+
+ def test_row_filter_composes_with_incremental(self):
+ query = build_partition_query(
+ "public",
+ "events_2026_01",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ incremental_field_type=IncrementalFieldType.Timestamp,
+ db_incremental_field_last_value="2026-01-15",
+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ )
+ rendered = self._render(query)
+ assert '"created_at" > ' in rendered
+ assert 'AND "age" > 21' in rendered
+ assert rendered.rstrip().endswith('ORDER BY "created_at" ASC')
+
class TestBuildCountQuery:
def _render(self, composed: sql.Composed) -> str:
diff --git a/posthog/temporal/data_imports/sources/redshift/redshift.py b/posthog/temporal/data_imports/sources/redshift/redshift.py
index 5a3b2ab83412..da16f0262aab 100644
--- a/posthog/temporal/data_imports/sources/redshift/redshift.py
+++ b/posthog/temporal/data_imports/sources/redshift/redshift.py
@@ -41,6 +41,7 @@ from posthog.temporal.data_imports.sources.common.mixins import open_ssh_tunnel
from posthog.temporal.data_imports.sources.common.sql import (
Column,
Table,
+ ValidatedRowFilter,
compute_projected_columns,
project_arrow_columns,
)
@@ -51,6 +52,10 @@ from posthog.temporal.data_imports.sources.common.sql.implementation import (
)
from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter
from posthog.temporal.data_imports.sources.common.sql.location import normalize_namespace, resolve_source_location
+from posthog.temporal.data_imports.sources.common.sql.predicates_psycopg import (
+ and_join,
+ render_psycopg_row_filter_conditions,
+)
from posthog.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig
from products.data_warehouse.backend.types import IncrementalFieldType
@@ -177,8 +182,12 @@ def _build_query(
add_sampling: Optional[bool] = False,
enabled_columns: Optional[list[str]] = None,
primary_keys: Optional[list[str]] = None,
+ row_filters: Optional[list[ValidatedRowFilter]] = None,
) -> sql.Composed:
select_clause = _redshift_select_clause(enabled_columns, primary_keys, incremental_field)
+ # Row filters apply only to the real data path; sampling/row-count queries stay unfiltered
+ # (an over-estimate is harmless).
+ row_filter_conditions = render_psycopg_row_filter_conditions(row_filters or [])
if not should_use_incremental_field:
if add_sampling:
@@ -186,15 +195,14 @@ def _build_query(
query = sql.SQL("SELECT {cols} FROM {table} WHERE random() < 0.01").format(
cols=select_clause, table=sql.Identifier(schema, table_name)
)
- else:
- query = sql.SQL("SELECT {cols} FROM {table}").format(
- cols=select_clause, table=sql.Identifier(schema, table_name)
- )
-
- if add_sampling:
query_with_limit = cast(LiteralString, f"{query.as_string()} LIMIT 1000")
return sql.SQL(query_with_limit).format()
+ query = sql.SQL("SELECT {cols} FROM {table}").format(
+ cols=select_clause, table=sql.Identifier(schema, table_name)
+ )
+ if row_filter_conditions:
+ query = query + sql.SQL(" WHERE ") + and_join(row_filter_conditions)
return query
if incremental_field is None or incremental_field_type is None:
@@ -217,22 +225,21 @@ def _build_query(
op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
- else:
- query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
- cols=select_clause,
- schema=sql.Identifier(schema),
- table=sql.Identifier(table_name),
- incremental_field=sql.Identifier(incremental_field),
- op=operator,
- last_value=sql.Literal(db_incremental_field_last_value),
- )
-
- if add_sampling:
query_with_limit = cast(LiteralString, f"{query.as_string()} LIMIT 1000")
return sql.SQL(query_with_limit).format()
- else:
- query_str = cast(LiteralString, f"{query.as_string()} ORDER BY {{incremental_field}} ASC")
- return sql.SQL(query_str).format(incremental_field=sql.Identifier(incremental_field))
+
+ query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
+ cols=select_clause,
+ schema=sql.Identifier(schema),
+ table=sql.Identifier(table_name),
+ incremental_field=sql.Identifier(incremental_field),
+ op=operator,
+ last_value=sql.Literal(db_incremental_field_last_value),
+ )
+ if row_filter_conditions:
+ query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)
+ query_str = cast(LiteralString, f"{query.as_string()} ORDER BY {{incremental_field}} ASC")
+ return sql.SQL(query_str).format(incremental_field=sql.Identifier(incremental_field))
def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: FilteringBoundLogger):
@@ -991,6 +998,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
incremental_field_type = inputs.incremental_field_type
db_incremental_field_last_value = inputs.db_incremental_field_last_value
enabled_columns = inputs.enabled_columns
+ row_filters = inputs.row_filters
with self.connect(config) as connection:
# Autocommit so each best-effort discovery probe runs in its own transaction. A probe
@@ -1043,6 +1051,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
logger.debug("Getting table chunk size...")
if chunk_size_override is not None:
@@ -1097,6 +1106,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
logger.debug(f"Redshift query: {query.as_string()}")
diff --git a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py
index eafdf9318eb6..32b7815a2283 100644
--- a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -8,6 +8,7 @@ from psycopg.pq import TransactionStatus
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
from posthog.temporal.data_imports.pipelines.pipeline.utils import TemporaryFileSizeExceedsLimitException
from posthog.temporal.data_imports.sources.common.sql import Table, TableStats
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig
from posthog.temporal.data_imports.sources.redshift.redshift import (
RedshiftColumn,
@@ -129,6 +130,103 @@ class TestBuildQueryEnabledColumns:
assert 'WHERE "created_at"' in rendered
+class TestBuildQueryRowFilters:
+ def _filter(self, column, operator, value, category=ColumnTypeCategory.INTEGER):
+ return ValidatedRowFilter(column=column, operator=operator, value=value, category=category)
+
+ def test_full_refresh_row_filter(self):
+ composed = _build_query(
+ schema="public",
+ table_name="users",
+ should_use_incremental_field=False,
+ table_type=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[self._filter("age", ">", 21)],
+ )
+ rendered = composed.as_string()
+ assert 'WHERE "age" > 21' in rendered
+
+ def test_row_filters_compose_with_incremental(self):
+ composed = _build_query(
+ schema="public",
+ table_name="users",
+ should_use_incremental_field=True,
+ table_type=None,
+ incremental_field="created_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ db_incremental_field_last_value="2025-01-01",
+ row_filters=[self._filter("age", ">", 21)],
+ )
+ rendered = composed.as_string()
+ assert 'WHERE "created_at"' in rendered
+ assert 'AND "age" > 21' in rendered
+ assert rendered.rstrip().endswith('ORDER BY "created_at" ASC')
+
+ def test_sampling_query_is_not_filtered(self):
+ # Row filters apply only to the real data path; the sampling/estimation query stays unfiltered.
+ composed = _build_query(
+ schema="public",
+ table_name="users",
+ should_use_incremental_field=False,
+ table_type=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ add_sampling=True,
+ row_filters=[self._filter("age", ">", 21)],
+ )
+ rendered = composed.as_string()
+ assert '"age"' not in rendered
+
+ def test_in_filter_renders_parenthesized_list(self):
+ composed = _build_query(
+ schema="public",
+ table_name="users",
+ should_use_incremental_field=False,
+ table_type=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[self._filter("age", "IN", [21, 30, 40])],
+ )
+ rendered = composed.as_string()
+ assert 'WHERE "age" IN (21, 30, 40)' in rendered
+
+ def test_not_in_string_list_values_are_escaped_literals(self):
+ composed = _build_query(
+ schema="public",
+ table_name="users",
+ should_use_incremental_field=False,
+ table_type=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[
+ self._filter("name", "NOT IN", ["a", "'; DROP TABLE y; --"], category=ColumnTypeCategory.STRING)
+ ],
+ )
+ rendered = composed.as_string()
+ assert "\"name\" NOT IN ('a', '''; DROP TABLE y; --')" in rendered
+
+ def test_string_value_is_escaped_literal_not_injectable(self):
+ # psycopg's sql.Literal inlines values, but escapes them: the `;` stays inside a quoted
+ # literal (single quote doubled), so it can't break out into executable SQL.
+ composed = _build_query(
+ schema="public",
+ table_name="users",
+ should_use_incremental_field=False,
+ table_type=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ row_filters=[self._filter("name", "=", "x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING)],
+ )
+ rendered = composed.as_string()
+ assert "'x''; DROP TABLE y; --'" in rendered
+
+
class TestRedshiftColumnToArrowField:
def test_decimal_requires_precision(self):
col = RedshiftColumn(name="x", data_type="decimal", nullable=True)
diff --git a/posthog/temporal/data_imports/sources/snowflake/snowflake.py b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
index 5f27dc69d8b2..065a5116dbbe 100644
--- a/posthog/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
@@ -29,8 +29,10 @@ from posthog.temporal.data_imports.pipelines.helpers import (
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.sql import (
AnsiIdentifierQuoter,
+ ValidatedRowFilter,
compute_projected_columns,
format_projected_select_clause,
+ render_positional_conditions,
)
from posthog.temporal.data_imports.sources.common.sql.implementation import SourceMetadata, SQLSourceImplementation
from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter
@@ -104,12 +106,22 @@ def _build_query(
db_incremental_field_last_value: Optional[Any],
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
+ row_filters: list[ValidatedRowFilter] | None = None,
) -> tuple[str, tuple[Any, ...]]:
projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
select_clause = format_projected_select_clause(projected, _SNOWFLAKE_IDENTIFIER_QUOTER)
+ table_ref = f"{database}.{schema}.{table_name}"
+
+ # Positional param order: IDENTIFIER(%s), then any incremental value, then row-filter values.
+ filter_conditions, filter_values = render_positional_conditions(row_filters or [], _SNOWFLAKE_IDENTIFIER_QUOTER)
if not should_use_incremental_field:
- return f"SELECT {select_clause} FROM IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",)
+ if filter_conditions:
+ return (
+ f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE {' AND '.join(filter_conditions)}",
+ (table_ref, *filter_values),
+ )
+ return f"SELECT {select_clause} FROM IDENTIFIER(%s)", (table_ref,)
if incremental_field is None or incremental_field_type is None:
raise ValueError("incremental_field and incremental_field_type can't be None")
@@ -119,12 +131,10 @@ def _build_query(
operator = incremental_type_to_operator(incremental_field_type)
quoted_field = _SNOWFLAKE_IDENTIFIER_QUOTER.quote(incremental_field)
+ conditions = [f"{quoted_field} {operator} %s", *filter_conditions]
return (
- f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE {quoted_field} {operator} %s ORDER BY {quoted_field} ASC",
- (
- f"{database}.{schema}.{table_name}",
- db_incremental_field_last_value,
- ),
+ f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE {' AND '.join(conditions)} ORDER BY {quoted_field} ASC",
+ (table_ref, db_incremental_field_last_value, *filter_values),
)
@@ -521,6 +531,7 @@ class SnowflakeImplementation(
incremental_field_type = inputs.incremental_field_type
db_incremental_field_last_value = inputs.db_incremental_field_last_value
enabled_columns = inputs.enabled_columns
+ row_filters = inputs.row_filters
with self.connect(config) as connection:
with connection.cursor() as cursor:
@@ -537,6 +548,7 @@ class SnowflakeImplementation(
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_params, logger)
@@ -555,6 +567,7 @@ class SnowflakeImplementation(
db_incremental_field_last_value,
enabled_columns=enabled_columns,
primary_keys=primary_keys,
+ row_filters=row_filters,
)
logger.debug(f"Snowflake query: {query.format(params)}")
streaming_cursor.execute(query, params)
diff --git a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
index cce1c8e54655..482b6ab34715 100644
--- a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
@@ -6,6 +6,7 @@ from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter
from posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig
from posthog.temporal.data_imports.sources.snowflake.snowflake import (
SnowflakeImplementation,
@@ -165,6 +166,67 @@ class TestBuildQuery:
assert params[1] is not None
+class TestBuildQueryRowFilters:
+ def _filter(self, column, operator, value, category=ColumnTypeCategory.INTEGER):
+ return ValidatedRowFilter(column=column, operator=operator, value=value, category=category)
+
+ def test_full_refresh_appends_filters_after_table_ref(self):
+ sql, params = _build_query(
+ "DB", "PUBLIC", "t", False, None, None, None, row_filters=[self._filter("AGE", ">", 21)]
+ )
+ assert 'WHERE "AGE" > %s' in sql
+ # Positional order: IDENTIFIER table ref first, then the filter value.
+ assert params == ("DB.PUBLIC.t", 21)
+
+ def test_incremental_orders_table_then_incremental_then_filters(self):
+ sql, params = _build_query(
+ "DB",
+ "PUBLIC",
+ "t",
+ True,
+ "created_at",
+ IncrementalFieldType.DateTime,
+ "2025-01-01",
+ row_filters=[self._filter("AGE", ">", 21), self._filter("SCORE", "<=", 100)],
+ )
+ assert 'WHERE "created_at" > %s AND "AGE" > %s AND "SCORE" <= %s ORDER BY "created_at" ASC' in sql
+ # Critical: positional values must be (table_ref, incremental_value, *filter_values) in order.
+ assert params == ("DB.PUBLIC.t", "2025-01-01", 21, 100)
+
+ def test_value_never_interpolated(self):
+ sql, params = _build_query(
+ "DB",
+ "PUBLIC",
+ "t",
+ False,
+ None,
+ None,
+ None,
+ row_filters=[
+ ValidatedRowFilter(
+ column="NAME", operator="=", value="x'; DROP TABLE y; --", category=ColumnTypeCategory.STRING
+ )
+ ],
+ )
+ assert "DROP TABLE" not in sql
+ assert params == ("DB.PUBLIC.t", "x'; DROP TABLE y; --")
+
+ def test_in_filter_positional_values_in_order(self):
+ sql, params = _build_query(
+ "DB",
+ "PUBLIC",
+ "t",
+ True,
+ "created_at",
+ IncrementalFieldType.DateTime,
+ "2025-01-01",
+ row_filters=[self._filter("AGE", "IN", [21, 30, 40])],
+ )
+ assert 'WHERE "created_at" > %s AND "AGE" IN (%s, %s, %s)' in sql
+ # table_ref, incremental_value, then each IN element in order.
+ assert params == ("DB.PUBLIC.t", "2025-01-01", 21, 30, 40)
+
+
class TestBuildQueryEnabledColumns:
def test_full_refresh_none_uses_select_star(self):
sql, _ = _build_query("DB", "PUBLIC", "t", False, None, None, None, enabled_columns=None, primary_keys=["id"])
diff --git a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py
index 00cd0b41413e..efa8a70a525d 100644
--- a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -28,6 +28,10 @@ from posthog.temporal.data_imports.sources import SourceRegistry
from posthog.temporal.data_imports.sources.common.base import ResumableSource, SimpleSource
from posthog.temporal.data_imports.sources.common.job_context import bind_job_context
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.sql.predicates import (
+ RowFilterValidationError,
+ validate_and_coerce_row_filters,
+)
from posthog.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -142,6 +146,16 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
if processed_incremental_earliest_value:
await logger.adebug(f"Incremental earliest value being used is: {processed_incremental_earliest_value}")
+ # Re-validate against current metadata so a stale filter (dropped column, changed type)
+ # fails here with an actionable message rather than emitting a broken query downstream.
+ try:
+ row_filters = validate_and_coerce_row_filters(schema.row_filters, schema.schema_metadata)
+ except RowFilterValidationError as e:
+ raise RowFilterValidationError(
+ f"Row filter on schema '{schema.name}' no longer matches the current table schema ({e}). "
+ f"Fix or remove the row filter in the schema's configuration to resume syncing."
+ ) from e
+
if SourceRegistry.is_registered(source_type):
source_inputs = SourceInputs(
schema_name=schema.name,
@@ -161,6 +175,7 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
job_id=inputs.run_id,
reset_pipeline=reset_pipeline,
enabled_columns=schema.enabled_columns,
+ row_filters=row_filters,
schema_metadata=schema.schema_metadata,
s3_folder_name=schema.resolved_s3_folder_name,
)
diff --git a/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index cc10be68adf9..5948600f35c2 100644
--- a/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -40,6 +40,7 @@ def _patched_activity(source_mock):
schema = mock.MagicMock()
schema.should_use_incremental_field = False
+ schema.row_filters = None
with (
mock.patch.object(module, "tag_queries"),
diff --git a/posthog/temporal/tests/data_imports/test_import_data.py b/posthog/temporal/tests/data_imports/test_import_data.py
index 8eb4ab220b60..cf5a485156d8 100644
--- a/posthog/temporal/tests/data_imports/test_import_data.py
+++ b/posthog/temporal/tests/data_imports/test_import_data.py
@@ -103,6 +103,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):
require_ssl=True,
is_initial_sync=True,
enabled_columns=None,
+ row_filters=[],
)
@@ -145,6 +146,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **
require_ssl=True,
is_initial_sync=True,
enabled_columns=None,
+ row_filters=[],
)
@@ -199,6 +201,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, te
require_ssl=True,
is_initial_sync=True,
enabled_columns=None,
+ row_filters=[],
)
@@ -268,6 +271,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, tea
require_ssl=True,
is_initial_sync=True,
enabled_columns=None,
+ row_filters=[],
)
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.py
index a2dd6294ff89..95a5a6ba2844 100644
--- a/products/data_warehouse/backend/api/external_data_schema.py
+++ b/products/data_warehouse/backend/api/external_data_schema.py
@@ -19,7 +19,9 @@ from posthog.temporal.data_imports.cdc.adapters import get_cdc_adapter
from posthog.temporal.data_imports.sources import SourceRegistry
from posthog.temporal.data_imports.sources.common.base import WebhookSource
from posthog.temporal.data_imports.sources.common.sql import (
+ RowFilterValidationError,
filter_dwh_columns_by_enabled_columns as _filter_dwh_columns_by_enabled_columns,
+ validate_and_coerce_row_filters,
)
from products.data_warehouse.backend.data_load.service import (
@@ -126,6 +128,55 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
CDC_ONLY_SYNC_FREQUENCIES = {"1min"}
+@extend_schema_field(
+ {
+ "type": "array",
+ "nullable": True,
+ "items": {
+ "type": "object",
+ "properties": {
+ "column": {"type": "string"},
+ # Not an OpenAPI `enum`: the operators are punctuation with no nameable identifier,
+ # so orval collapses the enum to duplicate empty-string keys (`'': '>'`, …) in the
+ # generated clients. Keep it a plain string and list the allowed values in the
+ # description; validation is enforced server-side regardless.
+ "operator": {
+ "type": "string",
+ "description": 'One of: > >= < <= = != IN "NOT IN".',
+ },
+ "value": {
+ "description": (
+ "Comparison value; must match the column's type. For `IN` / `NOT IN`, a "
+ "comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ )
+ },
+ },
+ "required": ["column", "operator", "value"],
+ },
+ }
+)
+class RowFiltersField(serializers.JSONField):
+ """Typed JSON field for the list of `{column, operator, value}` row-filter predicates."""
+
+
+def unsupported_row_filter_reason(*, is_direct_postgres: bool, is_cdc: bool) -> str | None:
+ """Row filters are only enforced on snapshot-style syncs, which apply them as a `WHERE`
+ clause. Direct Postgres queries tables live and CDC streams WAL changes — both bypass that
+ query, so a saved filter would silently leave excluded rows visible. Reject those up front.
+ """
+ if is_direct_postgres:
+ return (
+ "Row filters are not supported for direct Postgres sources — "
+ "tables are queried live and filters cannot be enforced at the source."
+ )
+ if is_cdc:
+ return (
+ "Row filters are not supported for CDC schemas — change-stream rows are "
+ "replicated without these predicates, so filtered rows would still sync."
+ )
+ return None
+
+
class ExternalDataSchemaSerializer(serializers.ModelSerializer):
table = serializers.SerializerMethodField(read_only=True)
incremental = serializers.SerializerMethodField(read_only=True)
@@ -188,6 +239,17 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"even if not listed here."
),
)
+ row_filters = RowFiltersField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is "
+ "`{column, operator, value}`; `null`/empty (default) syncs all rows. The operator "
+ 'must be one of `> >= < <= = != IN "NOT IN"` and the value must match the column\'s '
+ "type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). "
+ "Applied on the next sync — not retroactive to already-synced rows."
+ ),
+ )
available_columns = serializers.SerializerMethodField(
read_only=True,
help_text="Source-side column metadata (name, data type, nullable) discovered for this schema. "
@@ -224,6 +286,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"primary_key_columns",
"cdc_table_mode",
"enabled_columns",
+ "row_filters",
"available_columns",
"source",
]
@@ -401,6 +464,21 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"Run `Pull new schemas` to refresh available columns."
)
+ # Validate against the schema's columns; raw filters are persisted as-is and re-coerced at sync time.
+ if "row_filters" in validated_data and validated_data["row_filters"] is not None:
+ incoming_sync_type = data.get("sync_type")
+ target_is_cdc = (
+ incoming_sync_type == ExternalDataSchema.SyncType.CDC if "sync_type" in data else instance.is_cdc
+ )
+ if reason := unsupported_row_filter_reason(
+ is_direct_postgres=instance.source.is_direct_postgres, is_cdc=target_is_cdc
+ ):
+ raise ValidationError(reason)
+ try:
+ validate_and_coerce_row_filters(validated_data["row_filters"], instance.schema_metadata)
+ except RowFilterValidationError as e:
+ raise ValidationError(f"Invalid row filter: {e}")
+
sync_type = data.get("sync_type")
if sync_type == ExternalDataSchema.SyncType.CDC:
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 07f823345bcd..e5ff2afb7b59 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -47,7 +47,12 @@ from posthog.temporal.data_imports.sources import SourceRegistry
from posthog.temporal.data_imports.sources.common.base import AnySource, ExternalWebhookInfo, FieldType, WebhookSource
from posthog.temporal.data_imports.sources.common.config import Config
from posthog.temporal.data_imports.sources.common.schema import SourceSchema, build_default_schemas
-from posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_by_enabled_columns, sql_schema_metadata
+from posthog.temporal.data_imports.sources.common.sql import (
+ RowFilterValidationError,
+ filter_dwh_columns_by_enabled_columns,
+ sql_schema_metadata,
+ validate_and_coerce_row_filters,
+)
from posthog.temporal.data_imports.sources.common.sql.base import SQLSource
from posthog.temporal.data_imports.sources.custom.source import MAX_CUSTOM_SOURCES_PER_TEAM, manifest_request_hosts
from posthog.temporal.data_imports.sources.postgres.cdc.config import (
@@ -67,8 +72,10 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.data_modeling.backend.models.datawarehouse_managed_viewset import DataWarehouseManagedViewSet
from products.data_warehouse.backend.api.external_data_schema import (
ExternalDataSchemaSerializer,
+ RowFiltersField,
SimpleExternalDataSchemaSerializer,
source_supports_column_selection,
+ unsupported_row_filter_reason,
)
from products.data_warehouse.backend.data_load.service import (
bulk_create_external_data_job_schedules,
@@ -494,6 +501,11 @@ class ExternalDataSourceBulkUpdateSchemaSerializer(serializers.Serializer):
allow_empty=True,
help_text="Columns to sync. Null means sync all columns.",
)
+ row_filters = RowFiltersField(
+ required=False,
+ allow_null=True,
+ help_text="Row-filter predicates ANDed onto the source query. Null/empty means sync all rows.",
+ )
class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):
@@ -1531,6 +1543,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
else:
enabled_columns = None
+ payload_row_filters = schema.get("row_filters")
+ row_filters: list[dict[str, Any]] | None = (
+ payload_row_filters if isinstance(payload_row_filters, list) and payload_row_filters else None
+ )
+
if should_sync and requires_incremental_fields and incremental_field is None:
new_source_model.delete()
return Response(
@@ -1576,6 +1593,24 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
else {}
)
+ if row_filters is not None:
+ if reason := unsupported_row_filter_reason(
+ is_direct_postgres=new_source_model.is_direct_postgres, is_cdc=sync_type == "cdc"
+ ):
+ new_source_model.delete()
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": f"Row filter not allowed for schema '{schema_name}': {reason}"},
+ )
+ try:
+ validate_and_coerce_row_filters(row_filters, schema_metadata)
+ except RowFilterValidationError as e:
+ new_source_model.delete()
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": f"Invalid row filter for schema '{schema_name}': {e}"},
+ )
+
is_cdc_schema = sync_type == "cdc"
# A CDC table the user isn't enabling hasn't been "set up" — leave its sync method
# blank so the schemas UI prompts the user to configure it before it can sync, rather
@@ -1626,6 +1661,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
label=schema_label_by_name.get(schema_name),
sync_frequency_interval=schema_sync_frequency_interval,
enabled_columns=enabled_columns,
+ row_filters=row_filters,
)
# CDC + direct-postgres paths are Postgres-only — `get_postgres_source_table_location`
diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.py
index 042df51de827..01b8475f126e 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py
@@ -2217,3 +2217,126 @@ class TestExternalDataSchemaRetrieveSource(APIBaseTest):
schema = ExternalDataSchema.objects.create(name="Customers", team=other_team, source=source)
response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/")
assert response.status_code == 404
+
+
+class TestExternalDataSchemaRowFilters(APIBaseTest):
+ """PATCH-level validation for the row_filters field. A plain row_filters update needs no
+ source DB connection or temporal schedule — it only reads the schema's discovered columns."""
+
+ SCHEMA_METADATA = {
+ "columns": [
+ {"name": "id", "data_type": "integer", "is_nullable": False},
+ {"name": "created_at", "data_type": "timestamp", "is_nullable": True},
+ {"name": "name", "data_type": "varchar(255)", "is_nullable": True},
+ {"name": "geom", "data_type": "geometry", "is_nullable": True},
+ ]
+ }
+
+ def _create(self) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.POSTGRES,
+ job_inputs={"host": "h", "port": "5432", "database": "d", "user": "u", "password": "p", "schema": "public"},
+ )
+ # schema_metadata is a read-only property backed by sync_type_config.
+ return ExternalDataSchema.objects.create(
+ name="Customers",
+ team=self.team,
+ source=source,
+ sync_type_config={"schema_metadata": self.SCHEMA_METADATA},
+ )
+
+ def _patch(self, schema: ExternalDataSchema, row_filters: Any):
+ return self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",
+ data={"row_filters": row_filters},
+ )
+
+ def test_valid_row_filters_persist(self):
+ schema = self._create()
+ filters = [
+ {"column": "id", "operator": ">", "value": 10},
+ {"column": "created_at", "operator": ">=", "value": "2026-01-01"},
+ ]
+ response = self._patch(schema, filters)
+ assert response.status_code == 200, response.json()
+ schema.refresh_from_db()
+ assert schema.row_filters == filters
+
+ def test_null_clears_row_filters(self):
+ schema = self._create()
+ schema.row_filters = [{"column": "id", "operator": ">", "value": 1}]
+ schema.save(update_fields=["row_filters"])
+ response = self._patch(schema, None)
+ assert response.status_code == 200, response.json()
+ schema.refresh_from_db()
+ assert schema.row_filters is None
+
+ def test_row_filters_returned_in_serializer(self):
+ schema = self._create()
+ filters = [{"column": "id", "operator": "<=", "value": 5}]
+ schema.row_filters = filters
+ schema.save(update_fields=["row_filters"])
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/")
+ assert response.status_code == 200
+ assert response.json()["row_filters"] == filters
+
+ def test_unknown_column_rejected(self):
+ schema = self._create()
+ response = self._patch(schema, [{"column": "does_not_exist", "operator": ">", "value": 1}])
+ assert response.status_code == 400
+ assert "Unknown column" in str(response.json())
+
+ def test_disallowed_operator_rejected(self):
+ schema = self._create()
+ response = self._patch(schema, [{"column": "id", "operator": "LIKE", "value": 1}])
+ assert response.status_code == 400
+
+ def test_type_mismatch_rejected(self):
+ schema = self._create()
+ response = self._patch(schema, [{"column": "id", "operator": ">", "value": "not-an-int"}])
+ assert response.status_code == 400
+
+ def test_bad_date_value_rejected(self):
+ schema = self._create()
+ response = self._patch(schema, [{"column": "created_at", "operator": ">", "value": "nope"}])
+ assert response.status_code == 400
+
+ def test_unsupported_column_type_rejected(self):
+ schema = self._create()
+ response = self._patch(schema, [{"column": "geom", "operator": "=", "value": "x"}])
+ assert response.status_code == 400
+
+ def test_row_filters_rejected_for_direct_postgres_source(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.POSTGRES,
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ job_inputs={"host": "h", "port": "5432", "database": "d", "user": "u", "password": "p", "schema": "public"},
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Customers",
+ team=self.team,
+ source=source,
+ sync_type_config={"schema_metadata": self.SCHEMA_METADATA},
+ )
+ response = self._patch(schema, [{"column": "id", "operator": ">", "value": 10}])
+ assert response.status_code == 400
+ assert "not supported for direct Postgres" in str(response.json())
+
+ def test_row_filters_rejected_for_cdc_schema(self):
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.POSTGRES,
+ job_inputs={"host": "h", "port": "5432", "database": "d", "user": "u", "password": "p", "schema": "public"},
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Customers",
+ team=self.team,
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config={"schema_metadata": self.SCHEMA_METADATA},
+ )
+ response = self._patch(schema, [{"column": "id", "operator": ">", "value": 10}])
+ assert response.status_code == 400
+ assert "not supported for CDC" in str(response.json())
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 9416ac0b4b81..5814e20c3b07 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -1582,6 +1582,7 @@ class TestExternalDataSource(APIBaseTest):
"primary_key_columns": None,
"cdc_table_mode": "consolidated",
"enabled_columns": None,
+ "row_filters": None,
"available_columns": [],
"source": None,
}
@@ -2564,6 +2565,61 @@ class TestExternalDataSource(APIBaseTest):
1,
)
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_create_direct_postgres_rejects_row_filters(self, mock_get_source):
+ source_mock = mock_get_source.return_value
+ source_mock.validate_config.return_value = (True, [])
+ parsed_config = Mock()
+ parsed_config.to_dict.return_value = {
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "public",
+ }
+ source_mock.parse_config.return_value = parsed_config
+ source_mock.validate_credentials.return_value = (True, None)
+ source_mock.get_schemas.return_value = [
+ SourceSchema(
+ name="accounts",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ ),
+ ]
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Postgres",
+ "created_via": "web",
+ "access_method": "direct",
+ "prefix": "Primary database",
+ "payload": {
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "public",
+ "schemas": [
+ {
+ "name": "accounts",
+ "should_sync": True,
+ "sync_type": None,
+ "row_filters": [{"column": "id", "operator": ">", "value": 10}],
+ },
+ ],
+ },
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("not supported for direct Postgres", str(response.json()))
+ self.assertFalse(ExternalDataSource.objects.filter(team_id=self.team.pk).exists())
+
@patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
def test_create_direct_postgres_blank_schema_prefixes_table_names_and_preserves_physical_schema(
self, mock_get_source
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 88ddb2c25375..9be8a7828d87 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -36,6 +36,7 @@ import {
IncrementalField,
ManualLinkSourceType,
manualLinkSources,
+ RowFilter,
} from '~/types'
import {
@@ -323,6 +324,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
schema,
enabledColumns,
}),
+ setSchemaRowFilters: (schema: ExternalDataSourceSyncSchema, rowFilters: RowFilter[] | null) => ({
+ schema,
+ rowFilters,
+ }),
updateSchemaSyncType: (
schema: ExternalDataSourceSyncSchema,
syncType: ExternalDataSourceSyncSchema['sync_type'],
@@ -471,6 +476,12 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
enabled_columns: s.table === schema.table ? enabledColumns : s.enabled_columns,
}))
},
+ setSchemaRowFilters: (state, { schema, rowFilters }) => {
+ return state.map((s) => ({
+ ...s,
+ row_filters: s.table === schema.table ? rowFilters : s.row_filters,
+ }))
+ },
updateSchemaSyncType: (
state,
{ schema, syncType, incrementalField, incrementalFieldType, primaryKeyColumns, cdcTableMode }
@@ -1190,6 +1201,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
sync_time_of_day: schema.sync_time_of_day,
primary_key_columns: schema.primary_key_columns,
enabled_columns: schema.enabled_columns ?? null,
+ row_filters: schema.row_filters ?? null,
...(schema.sync_type === 'cdc' && schema.cdc_table_mode
? { cdc_table_mode: schema.cdc_table_mode }
: {}),
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index a4fc736b7fba..cb3af439f954 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -23,7 +23,7 @@ import { newInternalTab } from 'lib/utils/newInternalTab'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { DataWarehouseSyncInterval, ExternalDataSource, ExternalDataSourceSchema } from '~/types'
+import { DataWarehouseSyncInterval, ExternalDataSource, ExternalDataSourceSchema, RowFilter } from '~/types'
import {
SyncMethodForm,
@@ -42,6 +42,8 @@ import {
} from 'products/data_warehouse/frontend/utils'
import { ColumnSelectionPicker } from '../SourceScene/tabs/ColumnSelectionModal'
+import { RowFilterEditor } from '../SourceScene/tabs/RowFilterEditor'
+import { validateRowFilters } from '../SourceScene/tabs/rowFilterUtils'
import { SchemaConfigurationSection, schemaSceneLogic } from './schemaSceneLogic'
// null means "all columns" on either side, so switching to null after a partial list flags
@@ -53,6 +55,14 @@ function getAddedColumns(prev: string[] | null, next: string[] | null, available
return allColumns.filter((c) => nextSet.has(c) && !prevSet.has(c))
}
+// null normalizes to "all columns" so an explicit full list and null compare equal.
+function sameColumns(a: string[] | null, b: string[] | null, available: { name: string }[]): boolean {
+ const allColumns = available.map((c) => c.name)
+ const setA = new Set(a ?? allColumns)
+ const setB = new Set(b ?? allColumns)
+ return setA.size === setB.size && [...setA].every((c) => setB.has(c))
+}
+
export interface ConfigurationTabProps {
sourceId: string
schema: ExternalDataSourceSchema
@@ -92,7 +102,7 @@ export function ConfigurationTab({
return <SyncMethodSection sourceId={sourceId} source={source} schema={schema} />
case 'columns':
return (
- <ColumnsSection
+ <ColumnsAndRowFiltersSection
source={source}
schema={schema}
updateSchema={updateSchema}
@@ -431,7 +441,7 @@ function SyncMethodSection({
)
}
-function ColumnsSection({
+function ColumnsAndRowFiltersSection({
source,
schema,
updateSchema,
@@ -448,28 +458,74 @@ function ColumnsSection({
}): JSX.Element {
const available = schema.available_columns ?? []
const hasAvailableColumns = available.length > 0
- const synced = schema.enabled_columns
+
+ // Plain value, not the render-prop form of SourceEditorAction: a fresh inline render-prop on
+ // every edit would remount the editors and wipe their drafts. See useSourceEditorAccess's docstring.
+ const { disabledReason: editorDisabledReason } = useSourceEditorAccess(source)
+
+ // Both editors run in `hideActions` mode and report edits up here, so one Save commits both.
+ const [draftColumns, setDraftColumns] = useState<string[] | null>(schema.enabled_columns ?? null)
+ const [draftRowFilters, setDraftRowFilters] = useState<RowFilter[] | null>(schema.row_filters ?? null)
+
+ // Reset drafts on schema switch or when server values change (e.g. reload after save).
+ // Keyed on content so unrelated re-renders don't wipe edits.
+ useEffect(() => {
+ setDraftColumns(schema.enabled_columns ?? null)
+ setDraftRowFilters(schema.row_filters ?? null)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [schema.id, JSON.stringify(schema.enabled_columns ?? null), JSON.stringify(schema.row_filters ?? null)])
const alwaysRetained = new Set<string>([
...(schema.primary_key_columns ?? []),
...(schema.incremental_field ? [schema.incremental_field] : []),
])
- const syncedCount = synced ? new Set([...synced, ...alwaysRetained]).size : available.length
- const summaryLine = !synced
+ const syncedCount = draftColumns ? new Set([...draftColumns, ...alwaysRetained]).size : available.length
+ const columnsSummary = !draftColumns
? `Syncing all ${available.length || 'discovered'} columns`
: `Syncing ${syncedCount} of ${available.length} columns`
- const handleSave = (nextSyncedColumns: string[] | null): void => {
+ const filterCount = draftRowFilters?.length ?? 0
+ const rowFiltersSummary =
+ filterCount === 0 ? 'Syncing all rows' : `${filterCount} ${filterCount === 1 ? 'filter' : 'filters'} active`
+
+ const rowFilterErrors = validateRowFilters(draftRowFilters ?? [], { availableColumns: available })
+ const hasRowFilterErrors = Object.keys(rowFilterErrors).length > 0
+
+ const isDirty =
+ !sameColumns(draftColumns, schema.enabled_columns ?? null, available) ||
+ JSON.stringify(draftRowFilters ?? null) !== JSON.stringify(schema.row_filters ?? null)
+
+ const commit = (resyncAfter: boolean): void => {
+ const next = { ...schema, enabled_columns: draftColumns, row_filters: draftRowFilters }
+ if (resyncAfter) {
+ // Bypass the bulk-update debounce so resync reads the new config from the DB, not the
+ // stale one a still-queued PATCH hasn't written yet.
+ void api.externalDataSchemas
+ .update(schema.id, { enabled_columns: draftColumns, row_filters: draftRowFilters })
+ .then(() => {
+ updateSchema(next)
+ resyncSchema(next)
+ lemonToast.success('Saved — full resync queued')
+ })
+ .catch((e: any) => {
+ lemonToast.error(e?.message || "Can't save at this time")
+ })
+ return
+ }
+ updateSchema(next)
+ lemonToast.success('Saved')
+ }
+
+ const handleSave = (): void => {
const syncType = schema.sync_type
- const added = getAddedColumns(schema.enabled_columns ?? null, nextSyncedColumns, available)
+ const added = getAddedColumns(schema.enabled_columns ?? null, draftColumns, available)
const requiresPrompt =
!!schema.last_synced_at &&
(syncType === 'incremental' || syncType === 'append' || syncType === 'cdc') &&
added.length > 0
if (!requiresPrompt) {
- updateSchema({ ...schema, enabled_columns: nextSyncedColumns })
- lemonToast.success('Columns saved')
+ commit(false)
return
}
@@ -487,68 +543,86 @@ function ColumnsSection({
)}
</div>
),
- primaryButton: {
- children: 'Full resync now',
- onClick: () => {
- // Bypass the bulk-update debounce so the Temporal workflow reads the new
- // enabled_columns from the DB; firing resync against the queued (but unsent)
- // PATCH would otherwise re-sync against the old column selection.
- void api.externalDataSchemas
- .update(schema.id, { enabled_columns: nextSyncedColumns })
- .then(() => {
- updateSchema({ ...schema, enabled_columns: nextSyncedColumns })
- resyncSchema({ ...schema, enabled_columns: nextSyncedColumns })
- lemonToast.success('Columns saved — full resync queued')
- })
- .catch((e: any) => {
- lemonToast.error(e?.message || "Can't save columns at this time")
- })
- },
- },
- secondaryButton: {
- children: 'Sync forward only',
- onClick: () => {
- updateSchema({ ...schema, enabled_columns: nextSyncedColumns })
- lemonToast.success('Columns saved')
- },
- },
+ primaryButton: { children: 'Full resync now', onClick: () => commit(true) },
+ secondaryButton: { children: 'Sync forward only', onClick: () => commit(false) },
})
}
return (
- <div>
- <SectionHeader
- title="Columns"
- description="Choose which columns from this table get synced. Primary keys and the active incremental field are always synced."
- />
- <div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">
- {!hasAvailableColumns ? (
- <div className="flex flex-col items-center gap-2 text-center text-muted-alt py-6">
- <span className="text-sm">No columns discovered yet for this schema.</span>
- <SourceEditorAction source={source}>
- <LemonButton
- type="secondary"
- size="small"
- loading={refreshingSchemas}
- onClick={() => refreshSchemas()}
- >
- Pull new schemas
- </LemonButton>
- </SourceEditorAction>
- </div>
- ) : (
- <>
- <span className="text-sm text-secondary">{summaryLine}</span>
- <SourceEditorAction source={source}>
- {({ disabledReason }) => (
- <fieldset disabled={!!disabledReason}>
- <ColumnSelectionPicker schema={schema} onSave={handleSave} />
- </fieldset>
- )}
- </SourceEditorAction>
- </>
- )}
+ <div className="flex flex-col gap-6">
+ <div>
+ <SectionHeader
+ title="Columns"
+ description="Choose which columns from this table get synced. Primary keys and the active incremental field are always synced."
+ />
+ <div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">
+ {!hasAvailableColumns ? (
+ <div className="flex flex-col items-center gap-2 text-center text-muted-alt py-6">
+ <span className="text-sm">No columns discovered yet for this schema.</span>
+ <SourceEditorAction source={source}>
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={refreshingSchemas}
+ onClick={() => refreshSchemas()}
+ >
+ Pull new schemas
+ </LemonButton>
+ </SourceEditorAction>
+ </div>
+ ) : (
+ <>
+ <span className="text-sm text-secondary">{columnsSummary}</span>
+ <fieldset disabled={!!editorDisabledReason}>
+ <ColumnSelectionPicker hideActions schema={schema} onChange={setDraftColumns} />
+ </fieldset>
+ </>
+ )}
+ </div>
</div>
+
+ {source?.access_method !== 'direct' && schema.sync_type !== 'cdc' && (
+ <div>
+ <SectionHeader
+ title="Row filters"
+ description="Sync only rows that match these conditions. Filters are ANDed together and applied on the next sync — they don't remove rows already synced."
+ />
+ <div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">
+ {!hasAvailableColumns ? (
+ <div className="text-sm text-muted-alt py-2 text-center">
+ No columns discovered yet — pull schemas from the Columns section above to add row
+ filters.
+ </div>
+ ) : (
+ <>
+ <span className="text-sm text-secondary">{rowFiltersSummary}</span>
+ <fieldset disabled={!!editorDisabledReason}>
+ <RowFilterEditor hideActions schema={schema} onChange={setDraftRowFilters} />
+ </fieldset>
+ </>
+ )}
+ </div>
+ </div>
+ )}
+
+ {hasAvailableColumns && (
+ <div className="flex justify-end">
+ <LemonButton
+ type="primary"
+ onClick={handleSave}
+ disabledReason={
+ editorDisabledReason ??
+ (hasRowFilterErrors
+ ? 'Fix the highlighted row filters first'
+ : !isDirty
+ ? 'No changes to save'
+ : undefined)
+ }
+ >
+ Save
+ </LemonButton>
+ </div>
+ )}
</div>
)
}
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
index 21a2a8be23e5..3bd951dcbab9 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
@@ -49,6 +49,7 @@ function buildSchemaUpdatePayload(schema: ExternalDataSourceSchema): Partial<Ext
sync_time_of_day: schema.sync_time_of_day,
cdc_table_mode: schema.cdc_table_mode,
enabled_columns: schema.enabled_columns ?? null,
+ row_filters: schema.row_filters ?? null,
}
}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx
index 3fa0e165dfdb..e3ddce948711 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx
@@ -17,9 +17,11 @@ export interface ColumnSelectionTarget {
interface ColumnSelectionPickerProps {
schema: ColumnSelectionTarget | null
- onSave: (enabledColumns: string[] | null) => void
+ onSave?: (enabledColumns: string[] | null) => void
onCancel?: () => void
hideActions?: boolean
+ /** Fires on every edit, so a parent can drive saving with its own button. */
+ onChange?: (enabledColumns: string[] | null) => void
}
interface ColumnSelectionModalProps {
@@ -44,7 +46,10 @@ interface UseColumnSelectionResult {
filteredColumns: { name: string; data_type?: string; is_nullable?: boolean }[]
}
-function useColumnSelection(schema: ColumnSelectionTarget | null): UseColumnSelectionResult {
+function useColumnSelection(
+ schema: ColumnSelectionTarget | null,
+ onChange?: (enabledColumns: string[] | null) => void
+): UseColumnSelectionResult {
const available = schema?.available_columns ?? []
const primaryKeys = useMemo(() => new Set(schema?.primary_key_columns ?? []), [schema?.primary_key_columns])
const incrementalField = schema?.incremental_field
@@ -73,23 +78,40 @@ function useColumnSelection(schema: ColumnSelectionTarget | null): UseColumnSele
return selected.has(name)
}
+ // PKs + incremental are always synced — including them explicitly keeps the persisted
+ // list legible (e.g. ["id"] reads as "PK only" rather than the ambiguous []).
+ const computePersisted = (sel: Set<string> | null): string[] | null => {
+ if (sel === null) {
+ return null
+ }
+ const result = new Set(sel)
+ primaryKeys.forEach((pk) => result.add(pk))
+ if (incrementalField) {
+ result.add(incrementalField)
+ }
+ return Array.from(result)
+ }
+
+ const commit = (next: Set<string> | null): void => {
+ setSelected(next)
+ onChange?.(computePersisted(next))
+ }
+
const toggleColumn = (name: string, checked: boolean): void => {
if (isAlwaysRetained(name)) {
return
}
- setSelected((current) => {
- const baseline = current ?? new Set(available.map((c) => c.name))
- const next = new Set(baseline)
- if (checked) {
- next.add(name)
- } else {
- next.delete(name)
- }
- return next
- })
+ const baseline = selected ?? new Set(available.map((c) => c.name))
+ const next = new Set(baseline)
+ if (checked) {
+ next.add(name)
+ } else {
+ next.delete(name)
+ }
+ commit(next)
}
- const setSyncAll = (): void => setSelected(null)
+ const setSyncAll = (): void => commit(null)
const filteredColumns = useMemo(() => {
const term = filter.trim().toLowerCase()
@@ -99,19 +121,7 @@ function useColumnSelection(schema: ColumnSelectionTarget | null): UseColumnSele
return available.filter((column) => column.name.toLowerCase().includes(term))
}, [available, filter])
- const persistedSelection = (): string[] | null => {
- if (selected === null) {
- return null
- }
- // PKs + incremental are always synced — including them explicitly keeps the persisted
- // list legible (e.g. ["id"] reads as "PK only" rather than the ambiguous []).
- const result = new Set(selected)
- primaryKeys.forEach((pk) => result.add(pk))
- if (incrementalField) {
- result.add(incrementalField)
- }
- return Array.from(result)
- }
+ const persistedSelection = (): string[] | null => computePersisted(selected)
return {
selected,
@@ -134,6 +144,7 @@ export function ColumnSelectionPicker({
onSave,
onCancel,
hideActions,
+ onChange,
}: ColumnSelectionPickerProps): JSX.Element {
const {
filter,
@@ -146,7 +157,7 @@ export function ColumnSelectionPicker({
available,
primaryKeys,
filteredColumns,
- } = useColumnSelection(schema)
+ } = useColumnSelection(schema, onChange)
return (
<div className="flex flex-col gap-2">
@@ -208,7 +219,7 @@ export function ColumnSelectionPicker({
)}
<LemonButton
type="primary"
- onClick={() => onSave(persistedSelection())}
+ onClick={() => onSave?.(persistedSelection())}
disabledReason={available.length === 0 ? 'No columns discovered' : undefined}
>
Save
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/RowFilterEditor.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/RowFilterEditor.tsx
new file mode 100644
index 000000000000..fef76fb0119e
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/RowFilterEditor.tsx
@@ -0,0 +1,281 @@
+import { useEffect, useMemo, useState } from 'react'
+
+import { IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'
+
+import { RowFilter, RowFilterOperator } from '~/types'
+
+import {
+ MAX_ROW_FILTERS,
+ ROW_FILTER_OPERATORS,
+ RowFilterColumnCategory,
+ classifyColumnType,
+ isMultiValueOperator,
+ rowFilterOperatorLabel,
+ validateRowFilters,
+} from './rowFilterUtils'
+
+// Shares the column-source shape with the column picker so the editor works for both the
+// existing-source schema and the wizard's pre-creation sync schema.
+export interface RowFilterTarget {
+ id?: string
+ name?: string
+ row_filters?: RowFilter[] | null
+ available_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]
+}
+
+interface RowFilterEditorProps {
+ schema: RowFilterTarget | null
+ onSave?: (rowFilters: RowFilter[] | null) => void
+ /** Hide the Save/Reset footer (a parent drives saving itself). */
+ hideActions?: boolean
+ /** Fires on every edit, so a parent can drive saving with its own button. */
+ onChange?: (rowFilters: RowFilter[] | null) => void
+}
+
+const DEFAULT_OPERATOR: RowFilterOperator = '='
+
+function defaultValueForCategory(category: RowFilterColumnCategory): string | number | boolean {
+ return category === 'boolean' ? true : ''
+}
+
+export function RowFilterEditor({ schema, onSave, hideActions, onChange }: RowFilterEditorProps): JSX.Element {
+ const available = useMemo(() => schema?.available_columns ?? [], [schema?.available_columns])
+ const [filters, setFilters] = useState<RowFilter[]>([])
+
+ // Key the reset effect on content, not the array ref (which changes on every poll).
+ const rowFiltersKey = JSON.stringify(schema?.row_filters ?? null)
+ useEffect(() => {
+ setFilters(Array.isArray(schema?.row_filters) ? schema!.row_filters!.map((f) => ({ ...f })) : [])
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [schema?.id, rowFiltersKey])
+
+ const errors = useMemo(() => validateRowFilters(filters, { availableColumns: available }), [filters, available])
+
+ const columnOptions = useMemo(
+ () =>
+ available.map((column) => ({
+ value: column.name,
+ label: column.name,
+ labelInMenu: (
+ <div className="flex items-center gap-2">
+ <code>{column.name}</code>
+ {column.data_type && <span className="text-xs text-muted-alt">{column.data_type}</span>}
+ </div>
+ ),
+ })),
+ [available]
+ )
+
+ // Commit a new filter list to local state and report it upward (null when empty).
+ const applyFilters = (next: RowFilter[]): void => {
+ setFilters(next)
+ onChange?.(next.length ? next : null)
+ }
+
+ const categoryFor = (column: string): RowFilterColumnCategory =>
+ classifyColumnType(available.find((c) => c.name === column)?.data_type)
+
+ const addFilter = (): void => {
+ const firstColumn = available[0]?.name ?? ''
+ const category = categoryFor(firstColumn)
+ applyFilters([
+ ...filters,
+ { column: firstColumn, operator: DEFAULT_OPERATOR, value: defaultValueForCategory(category) },
+ ])
+ }
+
+ const removeFilter = (index: number): void => {
+ applyFilters(filters.filter((_, i) => i !== index))
+ }
+
+ const patchFilter = (index: number, patch: Partial<RowFilter>): void => {
+ applyFilters(
+ filters.map((filter, i) => {
+ if (i !== index) {
+ return filter
+ }
+ const merged = { ...filter, ...patch }
+ // On column change, reset the value if the type category changed (don't carry a
+ // date string onto an integer column).
+ if (patch.column && patch.column !== filter.column) {
+ const prevCategory = categoryFor(filter.column)
+ const nextCategory = categoryFor(patch.column)
+ if (prevCategory !== nextCategory) {
+ merged.value = isMultiValueOperator(merged.operator)
+ ? ''
+ : defaultValueForCategory(nextCategory)
+ }
+ }
+ // Scalar <-> multi-value changes the value shape (single vs list), so reset it.
+ if (patch.operator && isMultiValueOperator(patch.operator) !== isMultiValueOperator(filter.operator)) {
+ merged.value = isMultiValueOperator(patch.operator)
+ ? ''
+ : defaultValueForCategory(categoryFor(merged.column))
+ }
+ return merged
+ })
+ )
+ }
+
+ const hasErrors = Object.keys(errors).length > 0
+
+ return (
+ <div className="flex flex-col gap-2">
+ {filters.length === 0 && (
+ <div className="text-sm text-muted-alt">
+ No row filters. All rows sync. Add a filter to sync only matching rows.
+ </div>
+ )}
+ {filters.map((filter, index) => {
+ const category = categoryFor(filter.column)
+ return (
+ <div key={index} className="flex flex-col gap-1">
+ <div className="flex items-center gap-2">
+ <LemonSelect
+ className="flex-1"
+ placeholder="Column"
+ value={filter.column || undefined}
+ onChange={(value) => patchFilter(index, { column: value as string })}
+ options={columnOptions}
+ />
+ <LemonSelect
+ value={filter.operator}
+ onChange={(value) => patchFilter(index, { operator: value as RowFilterOperator })}
+ options={ROW_FILTER_OPERATORS.map((op) => ({
+ value: op,
+ label: op,
+ labelInMenu: rowFilterOperatorLabel(op),
+ }))}
+ />
+ <RowFilterValueInput
+ category={category}
+ multiValue={isMultiValueOperator(filter.operator)}
+ value={filter.value}
+ hasError={!!errors[index]}
+ onChange={(value) => patchFilter(index, { value })}
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ status="danger"
+ onClick={() => removeFilter(index)}
+ tooltip="Remove filter"
+ />
+ </div>
+ {errors[index] && <span className="text-xs text-danger pl-1">{errors[index]}</span>}
+ </div>
+ )
+ })}
+ <div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={addFilter}
+ disabledReason={
+ available.length === 0
+ ? 'No columns discovered'
+ : filters.length >= MAX_ROW_FILTERS
+ ? `At most ${MAX_ROW_FILTERS} filters`
+ : undefined
+ }
+ >
+ Add filter
+ </LemonButton>
+ </div>
+ {!hideActions && (
+ <div className="flex items-center justify-between gap-2 mt-2">
+ <LemonButton
+ type="tertiary"
+ onClick={() => applyFilters([])}
+ disabledReason={filters.length === 0 ? 'No filters to clear' : undefined}
+ >
+ Clear all filters
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => onSave?.(filters.length ? filters : null)}
+ disabledReason={hasErrors ? 'Fix the highlighted filters first' : undefined}
+ >
+ Save
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ )
+}
+
+function RowFilterValueInput({
+ category,
+ multiValue,
+ value,
+ hasError,
+ onChange,
+}: {
+ category: RowFilterColumnCategory
+ multiValue: boolean
+ value: string | number | boolean
+ hasError: boolean
+ onChange: (value: string | number | boolean) => void
+}): JSX.Element {
+ // IN / NOT IN take a comma-separated list, so a single text input regardless of type.
+ if (multiValue) {
+ const example =
+ category === 'string'
+ ? "'a', 'b', 'c'"
+ : category === 'date'
+ ? '2026-01-01, 2026-02-01'
+ : category === 'boolean'
+ ? 'true, false'
+ : '1, 2, 3'
+ return (
+ <LemonInput
+ className="flex-1"
+ type="text"
+ status={hasError ? 'danger' : 'default'}
+ placeholder={`Comma-separated, e.g. ${example}`}
+ value={value === undefined || value === null ? '' : String(value)}
+ onChange={(v) => onChange(v)}
+ />
+ )
+ }
+
+ if (category === 'boolean') {
+ return (
+ <LemonSelect
+ className="flex-1"
+ value={typeof value === 'boolean' ? value : true}
+ onChange={(v) => onChange(!!v)}
+ options={[
+ { value: true, label: 'true' },
+ { value: false, label: 'false' },
+ ]}
+ />
+ )
+ }
+
+ // Everything non-boolean uses a text input (LemonInput's number/date variants break the
+ // onChange union); the backend coerces the string and `validateRowFilters` checks it client-side.
+ const placeholder =
+ category === 'date'
+ ? 'YYYY-MM-DD'
+ : category === 'timestamp'
+ ? 'YYYY-MM-DDTHH:MM:SS'
+ : category === 'integer'
+ ? 'Whole number'
+ : category === 'numeric'
+ ? 'Number'
+ : 'Value'
+
+ return (
+ <LemonInput
+ className="flex-1"
+ type="text"
+ status={hasError ? 'danger' : 'default'}
+ placeholder={placeholder}
+ value={value === undefined || value === null ? '' : String(value)}
+ onChange={(v) => onChange(v)}
+ />
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.test.ts
new file mode 100644
index 000000000000..2fbb3647f05a
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.test.ts
@@ -0,0 +1,78 @@
+import { RowFilter } from '~/types'
+
+import { isMultiValueOperator, parseInList, validateInListValue, validateRowFilters } from './rowFilterUtils'
+
+describe('rowFilterUtils', () => {
+ describe('isMultiValueOperator', () => {
+ it('is true only for IN / NOT IN', () => {
+ expect(isMultiValueOperator('IN')).toBe(true)
+ expect(isMultiValueOperator('NOT IN')).toBe(true)
+ expect(isMultiValueOperator('=')).toBe(false)
+ expect(isMultiValueOperator('>')).toBe(false)
+ })
+ })
+
+ describe('parseInList', () => {
+ it.each([
+ ['1,2,3', ['1', '2', '3']],
+ ['1, 2, 3', ['1', '2', '3']],
+ [' 1 , 2 ,3 ', ['1', '2', '3']],
+ ["'abc','cde'", ['abc', 'cde']],
+ ["'abc', 'cde'", ['abc', 'cde']],
+ ["'a,b','c'", ['a,b', 'c']],
+ ["'o''brien'", ["o'brien"]],
+ ['', []],
+ ])('parses %p', (raw, expected) => {
+ expect(parseInList(raw)).toEqual(expected)
+ })
+
+ it('throws on an unterminated quote', () => {
+ expect(() => parseInList("'abc")).toThrow()
+ })
+ })
+
+ describe('validateInListValue', () => {
+ it('accepts a valid integer list', () => {
+ expect(validateInListValue('integer', '1, 2, 3')).toBeNull()
+ })
+
+ it('accepts a valid string list', () => {
+ expect(validateInListValue('string', "'a','b'")).toBeNull()
+ })
+
+ it('rejects an empty list', () => {
+ expect(validateInListValue('integer', '')).toBe('Enter at least one value')
+ })
+
+ it('rejects a blank element', () => {
+ expect(validateInListValue('integer', '1,,2')).toBe('The list has an empty value')
+ })
+
+ it('rejects a non-integer element', () => {
+ expect(validateInListValue('integer', '1, abc, 3')).toContain('not a whole number')
+ })
+
+ it('rejects an unterminated quote', () => {
+ expect(validateInListValue('string', "'abc")).toBe('Unterminated quote in list')
+ })
+
+ it('validates boolean elements as true/false', () => {
+ expect(validateInListValue('boolean', 'true, false')).toBeNull()
+ expect(validateInListValue('boolean', 'yes, no')).toContain('must be true or false')
+ })
+ })
+
+ describe('validateRowFilters with IN operators', () => {
+ const context = { availableColumns: [{ name: 'id', data_type: 'integer' }] }
+
+ it('passes a valid IN filter', () => {
+ const filters: RowFilter[] = [{ column: 'id', operator: 'IN', value: '1, 2, 3' }]
+ expect(validateRowFilters(filters, context)).toEqual({})
+ })
+
+ it('flags an invalid IN element', () => {
+ const filters: RowFilter[] = [{ column: 'id', operator: 'NOT IN', value: '1, x' }]
+ expect(Object.keys(validateRowFilters(filters, context))).toEqual(['0'])
+ })
+ })
+})
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.ts
new file mode 100644
index 000000000000..576ddcbb9182
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/rowFilterUtils.ts
@@ -0,0 +1,344 @@
+import { RowFilter, RowFilterOperator } from '~/types'
+
+// Client-side mirror of the backend classifier (predicates.py) so the UI can validate before
+// the PATCH. The backend re-validates and is the source of truth.
+
+export type RowFilterColumnCategory = 'integer' | 'numeric' | 'string' | 'boolean' | 'date' | 'timestamp' | 'unknown'
+
+export const ROW_FILTER_OPERATORS: RowFilterOperator[] = ['>', '>=', '<', '<=', '=', '!=', 'IN', 'NOT IN']
+
+// Mirrors `MAX_ROW_FILTERS` in predicates.py so the editor can cap before the PATCH 400s.
+export const MAX_ROW_FILTERS = 20
+
+const OPERATOR_LABELS: Record<RowFilterOperator, string> = {
+ '>': '> greater than',
+ '>=': '≥ greater than or equal',
+ '<': '< less than',
+ '<=': '≤ less than or equal',
+ '=': '= equals',
+ '!=': '≠ not equal',
+ IN: 'IN one of',
+ 'NOT IN': 'NOT IN any of',
+}
+
+export function rowFilterOperatorLabel(operator: RowFilterOperator): string {
+ return OPERATOR_LABELS[operator]
+}
+
+export function isMultiValueOperator(operator: RowFilterOperator): boolean {
+ return operator === 'IN' || operator === 'NOT IN'
+}
+
+const INTEGER_TYPES = new Set([
+ 'int',
+ 'int2',
+ 'int4',
+ 'int8',
+ 'int16',
+ 'int32',
+ 'int64',
+ 'int128',
+ 'int256',
+ 'integer',
+ 'smallint',
+ 'mediumint',
+ 'bigint',
+ 'tinyint',
+ 'byteint',
+ 'serial',
+ 'smallserial',
+ 'bigserial',
+ 'uint8',
+ 'uint16',
+ 'uint32',
+ 'uint64',
+ 'uint128',
+ 'uint256',
+])
+
+const NUMERIC_TYPES = new Set([
+ 'numeric',
+ 'decimal',
+ 'real',
+ 'double',
+ 'double precision',
+ 'float',
+ 'float4',
+ 'float8',
+ 'float32',
+ 'float64',
+ 'number',
+ 'money',
+ 'smallmoney',
+ 'bignumeric',
+ 'dec',
+ 'fixed',
+])
+
+const STRING_TYPES = new Set([
+ 'char',
+ 'character',
+ 'character varying',
+ 'varchar',
+ 'varchar2',
+ 'nchar',
+ 'nvarchar',
+ 'nvarchar2',
+ 'text',
+ 'tinytext',
+ 'mediumtext',
+ 'longtext',
+ 'ntext',
+ 'string',
+ 'fixedstring',
+ 'clob',
+ 'nclob',
+ 'uuid',
+ 'uniqueidentifier',
+ 'name',
+ 'citext',
+ 'enum',
+ // json / jsonb excluded (unfilterable) — mirror of `_STRING_TYPES` in predicates.py.
+])
+
+const BOOLEAN_TYPES = new Set(['bool', 'boolean', 'bit'])
+const DATE_TYPES = new Set(['date', 'date32'])
+const TIMESTAMP_TYPES = new Set([
+ 'timestamp',
+ 'timestamptz',
+ 'timestamp with time zone',
+ 'timestamp without time zone',
+ 'datetime',
+ 'datetime2',
+ 'datetime64',
+ 'smalldatetime',
+ 'datetimeoffset',
+])
+
+function stripNullableWrappers(dataType: string): string {
+ let current = dataType.trim()
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ if (current.startsWith('Nullable(') && current.endsWith(')')) {
+ current = current.slice('Nullable('.length, -1).trim()
+ } else if (current.startsWith('LowCardinality(') && current.endsWith(')')) {
+ current = current.slice('LowCardinality('.length, -1).trim()
+ } else {
+ return current
+ }
+ }
+}
+
+function stripTypeParams(dataType: string): string {
+ const paren = dataType.indexOf('(')
+ return (paren === -1 ? dataType : dataType.slice(0, paren)).trim()
+}
+
+export function classifyColumnType(dataType: string | undefined | null): RowFilterColumnCategory {
+ if (!dataType || !dataType.trim()) {
+ return 'unknown'
+ }
+ const base = stripTypeParams(stripNullableWrappers(dataType)).toLowerCase()
+ if (INTEGER_TYPES.has(base)) {
+ return 'integer'
+ }
+ if (NUMERIC_TYPES.has(base)) {
+ return 'numeric'
+ }
+ if (BOOLEAN_TYPES.has(base)) {
+ return 'boolean'
+ }
+ if (DATE_TYPES.has(base)) {
+ return 'date'
+ }
+ if (STRING_TYPES.has(base)) {
+ return 'string'
+ }
+ if (TIMESTAMP_TYPES.has(base) || base.startsWith('timestamp') || base.startsWith('datetime')) {
+ return 'timestamp'
+ }
+ return 'unknown'
+}
+
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
+const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?(\.\d+)?(Z|[+-]\d{2}:?\d{2})?)?$/
+
+/** Validate a scalar value against the column's type. Returns an error string, or `null` if valid. */
+export function validateRowFilterValue(
+ category: RowFilterColumnCategory,
+ value: string | number | boolean
+): string | null {
+ switch (category) {
+ case 'unknown':
+ return 'This column type is not supported for filtering'
+ case 'boolean':
+ if (typeof value === 'boolean') {
+ return null
+ }
+ return 'Pick true or false'
+ case 'integer': {
+ const raw = String(value).trim()
+ if (raw === '' || !/^[+-]?\d+$/.test(raw)) {
+ return 'Enter a whole number'
+ }
+ return null
+ }
+ case 'numeric': {
+ const raw = String(value).trim()
+ if (raw === '' || !Number.isFinite(Number(raw))) {
+ return 'Enter a number'
+ }
+ return null
+ }
+ case 'string':
+ return typeof value === 'string' ? null : 'Enter a text value'
+ case 'date': {
+ const raw = String(value).trim()
+ if (!ISO_DATE.test(raw) || Number.isNaN(Date.parse(raw))) {
+ return 'Enter a date as YYYY-MM-DD'
+ }
+ return null
+ }
+ case 'timestamp': {
+ const raw = String(value).trim()
+ if (!ISO_DATETIME.test(raw) || Number.isNaN(Date.parse(raw))) {
+ return 'Enter a date or timestamp (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS)'
+ }
+ return null
+ }
+ }
+}
+
+// Split on commas that are not inside single quotes; quote chars stay in each piece.
+// Throws on an unterminated quote (mirrors the backend `_split_top_level_commas`).
+function splitTopLevelCommas(raw: string): string[] {
+ const pieces: string[] = []
+ let buf = ''
+ let inQuote = false
+ for (let i = 0; i < raw.length; i++) {
+ const ch = raw[i]
+ if (ch === "'") {
+ buf += ch
+ if (inQuote && raw[i + 1] === "'") {
+ buf += "'"
+ i++
+ continue
+ }
+ inQuote = !inQuote
+ } else if (ch === ',' && !inQuote) {
+ pieces.push(buf)
+ buf = ''
+ } else {
+ buf += ch
+ }
+ }
+ if (inQuote) {
+ throw new Error('Unterminated quote in list')
+ }
+ pieces.push(buf)
+ return pieces
+}
+
+/**
+ * Parse a comma-separated `IN` / `NOT IN` list into element strings. Mirrors the backend
+ * `_split_in_list`: trims, keeps quoted contents verbatim, unescapes `''`. Throws on an open quote.
+ */
+export function parseInList(raw: string): string[] {
+ if (!raw.trim()) {
+ return []
+ }
+ return splitTopLevelCommas(raw).map((piece) => {
+ const token = piece.trim()
+ if (token.length >= 2 && token.startsWith("'") && token.endsWith("'")) {
+ return token.slice(1, -1).replace(/''/g, "'")
+ }
+ return token
+ })
+}
+
+function validateInElement(category: RowFilterColumnCategory, element: string): string | null {
+ switch (category) {
+ case 'unknown':
+ return 'This column type is not supported for filtering'
+ case 'string':
+ return null
+ case 'integer':
+ return /^[+-]?\d+$/.test(element) ? null : `"${element}" is not a whole number`
+ case 'numeric':
+ return element !== '' && Number.isFinite(Number(element)) ? null : `"${element}" is not a number`
+ case 'boolean':
+ return element === 'true' || element === 'false' ? null : `"${element}" must be true or false`
+ case 'date':
+ return ISO_DATE.test(element) && !Number.isNaN(Date.parse(element))
+ ? null
+ : `"${element}" is not a date (YYYY-MM-DD)`
+ case 'timestamp':
+ return ISO_DATETIME.test(element) && !Number.isNaN(Date.parse(element))
+ ? null
+ : `"${element}" is not a date or timestamp`
+ }
+}
+
+/** Validate an `IN` / `NOT IN` value (comma-separated) against the column type. Error string, or `null`. */
+export function validateInListValue(
+ category: RowFilterColumnCategory,
+ value: string | number | boolean
+): string | null {
+ if (typeof value !== 'string') {
+ return 'Enter a comma-separated list'
+ }
+ let elements: string[]
+ try {
+ elements = parseInList(value)
+ } catch {
+ return 'Unterminated quote in list'
+ }
+ if (elements.length === 0) {
+ return 'Enter at least one value'
+ }
+ for (const element of elements) {
+ if (element === '') {
+ return 'The list has an empty value'
+ }
+ const error = validateInElement(category, element)
+ if (error) {
+ return error
+ }
+ }
+ return null
+}
+
+export interface RowFilterValidationContext {
+ availableColumns: { name: string; data_type?: string }[]
+}
+
+/** Validate every filter. Returns a per-index error map (empty when all valid). */
+export function validateRowFilters(
+ filters: RowFilter[],
+ { availableColumns }: RowFilterValidationContext
+): Record<number, string> {
+ const typeByColumn = new Map(availableColumns.map((c) => [c.name, c.data_type]))
+ const errors: Record<number, string> = {}
+ filters.forEach((filter, index) => {
+ if (!filter.column) {
+ errors[index] = 'Pick a column'
+ return
+ }
+ if (!typeByColumn.has(filter.column)) {
+ errors[index] = `Unknown column "${filter.column}"`
+ return
+ }
+ if (!ROW_FILTER_OPERATORS.includes(filter.operator)) {
+ errors[index] = 'Pick an operator'
+ return
+ }
+ const category = classifyColumnType(typeByColumn.get(filter.column))
+ const valueError = isMultiValueOperator(filter.operator)
+ ? validateInListValue(category, filter.value)
+ : validateRowFilterValue(category, filter.value)
+ if (valueError) {
+ errors[index] = valueError
+ }
+ })
+ return errors
+}
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
index 583c6b6222bb..3c08ebc609e8 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
@@ -22,6 +22,7 @@ import { SyncTypeLabelMap } from 'products/data_warehouse/frontend/utils'
import { sourceWizardLogic } from '../../../scenes/NewSourceScene/sourceWizardLogic'
import { ColumnSelectionPicker } from '../../../scenes/SourceScene/tabs/ColumnSelectionModal'
+import { RowFilterEditor } from '../../../scenes/SourceScene/tabs/RowFilterEditor'
import { splitQualifiedTableName } from './schemaGroupingUtils'
import { SyncMethodForm } from './SyncMethodForm'
@@ -59,6 +60,7 @@ export default function SchemaForm(): JSX.Element {
setExpandedSchemaGroupKeys,
setSchemaNameFilter,
setSchemaSyncedColumns,
+ setSchemaRowFilters,
} = useActions(sourceWizardLogic)
const [columnSelectionSchema, setColumnSelectionSchema] = useState<ExternalDataSourceSyncSchema | null>(null)
const {
@@ -606,40 +608,74 @@ export default function SchemaForm(): JSX.Element {
title={
columnSelectionSchema ? (
<>
- Select columns for <span className="font-mono">{columnSelectionSchema.table}</span>
+ Columns and row filters for <span className="font-mono">{columnSelectionSchema.table}</span>
</>
) : null
}
- description="Primary-key and incremental columns are always synced and cannot be unchecked."
+ description="Choose which columns to sync and add row filters to sync only matching rows. Primary-key and incremental columns are always synced."
isOpen={columnSelectionSchema !== null}
onClose={() => setColumnSelectionSchema(null)}
+ footer={
+ <LemonButton type="primary" onClick={() => setColumnSelectionSchema(null)}>
+ Done
+ </LemonButton>
+ }
>
- <div className="min-w-[420px]">
- <ColumnSelectionPicker
- schema={
- columnSelectionSchema
- ? {
- id: columnSelectionSchema.table,
- name: columnSelectionSchema.table,
- enabled_columns: columnSelectionSchema.enabled_columns,
- primary_key_columns: columnSelectionSchema.primary_key_columns,
- incremental_field: columnSelectionSchema.incremental_field,
- available_columns: columnSelectionSchema.available_columns.map((c) => ({
- name: c.field,
- data_type: c.type,
- is_nullable: c.nullable,
- })),
- }
- : null
- }
- onSave={(enabledColumns) => {
- if (columnSelectionSchema) {
- setSchemaSyncedColumns(columnSelectionSchema, enabledColumns)
+ <div className="min-w-[420px] flex flex-col gap-6">
+ <div className="flex flex-col gap-2">
+ <h4 className="font-semibold mb-0">Columns to sync</h4>
+ <ColumnSelectionPicker
+ hideActions
+ schema={
+ columnSelectionSchema
+ ? {
+ id: columnSelectionSchema.table,
+ name: columnSelectionSchema.table,
+ enabled_columns: columnSelectionSchema.enabled_columns,
+ primary_key_columns: columnSelectionSchema.primary_key_columns,
+ incremental_field: columnSelectionSchema.incremental_field,
+ available_columns: columnSelectionSchema.available_columns.map((c) => ({
+ name: c.field,
+ data_type: c.type,
+ is_nullable: c.nullable,
+ })),
+ }
+ : null
}
- setColumnSelectionSchema(null)
- }}
- onCancel={() => setColumnSelectionSchema(null)}
- />
+ onChange={(enabledColumns) => {
+ if (columnSelectionSchema) {
+ setSchemaSyncedColumns(columnSelectionSchema, enabledColumns)
+ }
+ }}
+ />
+ </div>
+ {columnSelectionSchema?.sync_type !== 'cdc' && (
+ <div className="flex flex-col gap-2">
+ <h4 className="font-semibold mb-0">Row filters</h4>
+ <RowFilterEditor
+ hideActions
+ schema={
+ columnSelectionSchema
+ ? {
+ id: columnSelectionSchema.table,
+ name: columnSelectionSchema.table,
+ row_filters: columnSelectionSchema.row_filters,
+ available_columns: columnSelectionSchema.available_columns.map((c) => ({
+ name: c.field,
+ data_type: c.type,
+ is_nullable: c.nullable,
+ })),
+ }
+ : null
+ }
+ onChange={(rowFilters) => {
+ if (columnSelectionSchema) {
+ setSchemaRowFilters(columnSelectionSchema, rowFilters)
+ }
+ }}
+ />
+ </div>
+ )}
</div>
</LemonModal>
</>
diff --git a/products/warehouse_sources/backend/migrations/0016_externaldataschema_row_filters.py b/products/warehouse_sources/backend/migrations/0016_externaldataschema_row_filters.py
new file mode 100644
index 000000000000..27f6b0f75977
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0016_externaldataschema_row_filters.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0015_alter_externaldatasource_source_type_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="externaldataschema",
+ name="row_filters",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index fb10cee46724..f167d30a11dd 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_alter_externaldatasource_source_type_and_more
+0016_externaldataschema_row_filters
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 8d93edfeafaa..0e202af952ab 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -80,6 +80,8 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
# null = sync all columns (default). Non-empty list = exact column projection.
# PK + active incremental field are always retained server-side regardless of this list.
enabled_columns = models.JSONField(null=True, blank=True, default=None)
+ # null (default) = sync all rows. List of {column, operator, value} predicates ANDed onto the WHERE clause.
+ row_filters = models.JSONField(null=True, blank=True, default=None)
__repr__ = sane_repr("name")
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 4853349fbf5e..b4992d822b01 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -90,6 +90,14 @@ export const CdcTableModeEnumApi = {
*/
export type ExternalDataSchemaApiTable = { [key: string]: unknown } | null
+export type ExternalDataSchemaApiRowFiltersItem = {
+ column: string
+ /** One of: > >= < <= = != IN "NOT IN". */
+ operator: string
+ /** Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`). */
+ value: unknown
+}
+
export type ExternalDataSchemaApiAvailableColumnsItem = {
name: string
data_type?: string
@@ -185,6 +193,11 @@ export interface ExternalDataSchemaApi {
* @nullable
*/
enabled_columns?: string[] | null
+ /**
+ * Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN "NOT IN"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows.
+ * @nullable
+ */
+ row_filters?: ExternalDataSchemaApiRowFiltersItem[] | null
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns: readonly ExternalDataSchemaApiAvailableColumnsItem[]
/**
@@ -208,6 +221,14 @@ export interface PaginatedExternalDataSchemaListApi {
*/
export type PatchedExternalDataSchemaApiTable = { [key: string]: unknown } | null
+export type PatchedExternalDataSchemaApiRowFiltersItem = {
+ column: string
+ /** One of: > >= < <= = != IN "NOT IN". */
+ operator: string
+ /** Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`). */
+ value: unknown
+}
+
export type PatchedExternalDataSchemaApiAvailableColumnsItem = {
name: string
data_type?: string
@@ -303,6 +324,11 @@ export interface PatchedExternalDataSchemaApi {
* @nullable
*/
enabled_columns?: string[] | null
+ /**
+ * Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN "NOT IN"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows.
+ * @nullable
+ */
+ row_filters?: PatchedExternalDataSchemaApiRowFiltersItem[] | null
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns?: readonly PatchedExternalDataSchemaApiAvailableColumnsItem[]
/**
@@ -2374,6 +2400,14 @@ export interface PatchedExternalDataSourceSerializersApi {
readonly supports_column_selection?: boolean
}
+export type ExternalDataSourceBulkUpdateSchemaApiRowFiltersItem = {
+ column: string
+ /** One of: > >= < <= = != IN "NOT IN". */
+ operator: string
+ /** Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`). */
+ value: unknown
+}
+
export interface ExternalDataSourceBulkUpdateSchemaApi {
/** Schema identifier to update. */
id: string
@@ -2418,6 +2452,11 @@ export interface ExternalDataSourceBulkUpdateSchemaApi {
* @nullable
*/
enabled_columns?: string[] | null
+ /**
+ * Row-filter predicates ANDed onto the source query. Null/empty means sync all rows.
+ * @nullable
+ */
+ row_filters?: ExternalDataSourceBulkUpdateSchemaApiRowFiltersItem[] | null
}
export interface PatchedExternalDataSourceBulkUpdateSchemasApi {
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index 1e6e1bc28a8a..8823cd7425dc 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -82,6 +82,22 @@ export const ExternalDataSchemasCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zod.object({
@@ -157,6 +173,22 @@ export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
@@ -232,6 +264,22 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
@@ -307,6 +355,22 @@ export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__PURE__ */ zod.object({
@@ -382,6 +446,22 @@ export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__PURE__ */ zo
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasReloadCreateBody = /* @__PURE__ */ zod.object({
@@ -457,6 +537,22 @@ export const ExternalDataSchemasReloadCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasResyncCreateBody = /* @__PURE__ */ zod.object({
@@ -532,6 +628,22 @@ export const ExternalDataSchemasResyncCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
/**
@@ -1294,6 +1406,20 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = /* @__PURE_
.array(zod.string())
.nullish()
.describe('Columns to sync. Null means sync all columns.'),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe('Row-filter predicates ANDed onto the source query. Null\/empty means sync all rows.'),
})
)
.optional()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b5ef0a3c5b52..53d251c44445 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20296,6 +20296,14 @@ export namespace Schemas {
*/
export type ExternalDataSchemaTable = { [key: string]: unknown } | null;
+ export type ExternalDataSchemaRowFiltersItem = {
+ column: string;
+ /** One of: > >= < <= = != IN "NOT IN". */
+ operator: string;
+ /** Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`). */
+ value: unknown;
+ };
+
export type ExternalDataSchemaAvailableColumnsItem = {
name: string;
data_type?: string;
@@ -20459,6 +20467,11 @@ export namespace Schemas {
* @nullable
*/
enabled_columns?: string[] | null;
+ /**
+ * Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN "NOT IN"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows.
+ * @nullable
+ */
+ row_filters?: ExternalDataSchemaRowFiltersItem[] | null;
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns: readonly ExternalDataSchemaAvailableColumnsItem[];
/**
@@ -20468,6 +20481,14 @@ export namespace Schemas {
readonly source: ExternalDataSchemaSource;
}
+ export type ExternalDataSourceBulkUpdateSchemaRowFiltersItem = {
+ column: string;
+ /** One of: > >= < <= = != IN "NOT IN". */
+ operator: string;
+ /** Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`). */
+ value: unknown;
+ };
+
export interface ExternalDataSourceBulkUpdateSchema {
/** Schema identifier to update. */
id: string;
@@ -20512,6 +20533,11 @@ export namespace Schemas {
* @nullable
*/
enabled_columns?: string[] | null;
+ /**
+ * Row-filter predicates ANDed onto the source query. Null/empty means sync all rows.
+ * @nullable
+ */
+ row_filters?: ExternalDataSourceBulkUpdateSchemaRowFiltersItem[] | null;
}
export interface ExternalDataSourceConnectionOption {
@@ -34199,6 +34225,14 @@ export namespace Schemas {
*/
export type PatchedExternalDataSchemaTable = { [key: string]: unknown } | null;
+ export type PatchedExternalDataSchemaRowFiltersItem = {
+ column: string;
+ /** One of: > >= < <= = != IN "NOT IN". */
+ operator: string;
+ /** Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`). */
+ value: unknown;
+ };
+
export type PatchedExternalDataSchemaAvailableColumnsItem = {
name: string;
data_type?: string;
@@ -34294,6 +34328,11 @@ export namespace Schemas {
* @nullable
*/
enabled_columns?: string[] | null;
+ /**
+ * Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN "NOT IN"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows.
+ * @nullable
+ */
+ row_filters?: PatchedExternalDataSchemaRowFiltersItem[] | null;
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns?: readonly PatchedExternalDataSchemaAvailableColumnsItem[];
/**
diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.ts
index 21c431c34884..c67ea46cbb5c 100644
--- a/services/mcp/src/generated/warehouse_sources/api.ts
+++ b/services/mcp/src/generated/warehouse_sources/api.ts
@@ -113,6 +113,22 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN "NOT IN".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasCancelCreateParams = /* @__PURE__ */ zod.object({
@@ -197,6 +213,22 @@ export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN "NOT IN".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasDeleteDataDestroyParams = /* @__PURE__ */ zod.object({
@@ -290,6 +322,22 @@ export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__PURE__ */ zo
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN "NOT IN".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasReloadCreateParams = /* @__PURE__ */ zod.object({
@@ -374,6 +422,22 @@ export const ExternalDataSchemasReloadCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN "NOT IN".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
export const ExternalDataSchemasResyncCreateParams = /* @__PURE__ */ zod.object({
@@ -458,6 +522,22 @@ export const ExternalDataSchemasResyncCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
),
+ row_filters: zod
+ .array(
+ zod.object({
+ column: zod.string(),
+ operator: zod.string().describe('One of: > >= < <= = != IN "NOT IN".'),
+ value: zod
+ .unknown()
+ .describe(
+ "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.ts
index 21f3b1ad8523..78e8cca54229 100644
--- a/services/mcp/src/tools/generated/warehouse_sources.ts
+++ b/services/mcp/src/tools/generated/warehouse_sources.ts
@@ -155,6 +155,9 @@ const externalDataSchemasCancel = (): ToolBase<typeof ExternalDataSchemasCancelS
if (params.enabled_columns !== undefined) {
body['enabled_columns'] = params.enabled_columns
}
+ if (params.row_filters !== undefined) {
+ body['row_filters'] = params.row_filters
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/cancel/`,
@@ -219,6 +222,9 @@ const externalDataSchemasIncrementalFieldsCreate = (): ToolBase<
if (params.enabled_columns !== undefined) {
body['enabled_columns'] = params.enabled_columns
}
+ if (params.row_filters !== undefined) {
+ body['row_filters'] = params.row_filters
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/incremental_fields/`,
@@ -291,6 +297,9 @@ const externalDataSchemasPartialUpdate = (): ToolBase<
if (params.enabled_columns !== undefined) {
body['enabled_columns'] = params.enabled_columns
}
+ if (params.row_filters !== undefined) {
+ body['row_filters'] = params.row_filters
+ }
const result = await context.api.request<Schemas.ExternalDataSchema>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/`,
@@ -337,6 +346,9 @@ const externalDataSchemasReload = (): ToolBase<typeof ExternalDataSchemasReloadS
if (params.enabled_columns !== undefined) {
body['enabled_columns'] = params.enabled_columns
}
+ if (params.row_filters !== undefined) {
+ body['row_filters'] = params.row_filters
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/reload/`,
@@ -383,6 +395,9 @@ const externalDataSchemasResync = (): ToolBase<typeof ExternalDataSchemasResyncS
if (params.enabled_columns !== undefined) {
body['enabled_columns'] = params.enabled_columns
}
+ if (params.row_filters !== undefined) {
+ body['row_filters'] = params.row_filters
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/resync/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json
index 21fd6ed98783..9ed2f72b630f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json
@@ -70,6 +70,33 @@
],
"description": "Column names for primary key deduplication."
},
+ "row_filters": {
+ "anyOf": [
+ {
+ "items": {
+ "properties": {
+ "column": {
+ "type": "string"
+ },
+ "operator": {
+ "description": "One of: > >= < <= = != IN \"NOT IN\".",
+ "type": "string"
+ },
+ "value": {
+ "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ }
+ },
+ "required": ["column", "operator", "value"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ },
"should_sync": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json
index 21fd6ed98783..9ed2f72b630f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json
@@ -70,6 +70,33 @@
],
"description": "Column names for primary key deduplication."
},
+ "row_filters": {
+ "anyOf": [
+ {
+ "items": {
+ "properties": {
+ "column": {
+ "type": "string"
+ },
+ "operator": {
+ "description": "One of: > >= < <= = != IN \"NOT IN\".",
+ "type": "string"
+ },
+ "value": {
+ "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ }
+ },
+ "required": ["column", "operator", "value"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ },
"should_sync": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json
index 21fd6ed98783..9ed2f72b630f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json
@@ -70,6 +70,33 @@
],
"description": "Column names for primary key deduplication."
},
+ "row_filters": {
+ "anyOf": [
+ {
+ "items": {
+ "properties": {
+ "column": {
+ "type": "string"
+ },
+ "operator": {
+ "description": "One of: > >= < <= = != IN \"NOT IN\".",
+ "type": "string"
+ },
+ "value": {
+ "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ }
+ },
+ "required": ["column", "operator", "value"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ },
"should_sync": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-reload.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-reload.json
index 21fd6ed98783..9ed2f72b630f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-reload.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-reload.json
@@ -70,6 +70,33 @@
],
"description": "Column names for primary key deduplication."
},
+ "row_filters": {
+ "anyOf": [
+ {
+ "items": {
+ "properties": {
+ "column": {
+ "type": "string"
+ },
+ "operator": {
+ "description": "One of: > >= < <= = != IN \"NOT IN\".",
+ "type": "string"
+ },
+ "value": {
+ "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ }
+ },
+ "required": ["column", "operator", "value"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ },
"should_sync": {
"type": "boolean"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-resync.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-resync.json
index 21fd6ed98783..9ed2f72b630f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-resync.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-resync.json
@@ -70,6 +70,33 @@
],
"description": "Column names for primary key deduplication."
},
+ "row_filters": {
+ "anyOf": [
+ {
+ "items": {
+ "properties": {
+ "column": {
+ "type": "string"
+ },
+ "operator": {
+ "description": "One of: > >= < <= = != IN \"NOT IN\".",
+ "type": "string"
+ },
+ "value": {
+ "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
+ }
+ },
+ "required": ["column", "operator", "value"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
+ },
"should_sync": {
"type": "boolean"
},