This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new 4e7307bd18 [python] Accept SQL WHERE strings in 
ReadBuilder.with_filter (#10951)
4e7307bd18 is described below

commit 4e7307bd1890d4490744f8c2468d3694b8d6a700
Author: Yujiang Zhong <[email protected]>
AuthorDate: Mon Nov 2 21:51:51 2026 +0800

    [python] Accept SQL WHERE strings in ReadBuilder.with_filter (#10951)
---
 paimon-python/pypaimon/read/read_builder.py        | 19 ++++-
 paimon-python/pypaimon/read/stream_read_builder.py | 14 ++--
 paimon-python/pypaimon/tests/where_parser_test.py  | 98 ++++++++++++++++++++++
 3 files changed, 124 insertions(+), 7 deletions(-)

diff --git a/paimon-python/pypaimon/read/read_builder.py 
b/paimon-python/pypaimon/read/read_builder.py
index 16ab3a3182..74206361e1 100644
--- a/paimon-python/pypaimon/read/read_builder.py
+++ b/paimon-python/pypaimon/read/read_builder.py
@@ -22,6 +22,7 @@ import pyarrow
 
 from pypaimon.common.predicate import Predicate
 from pypaimon.common.predicate_builder import PredicateBuilder
+from pypaimon.common.where_parser import parse_where_clause
 from pypaimon.read.explain import ExplainResult
 from pypaimon.read.push_down_utils import predicate_field_names, 
predicate_matches_physical_names
 from pypaimon.read.table_read import ROW_KIND_COLUMN, TableRead
@@ -83,6 +84,13 @@ def _normalize_sql_literals(expression: str) -> str:
     return ''.join(normalized)
 
 
+def _normalize_filter(predicate: Union[str, Predicate], fields: 
List[DataField]) -> Optional[Predicate]:
+    """Parse a SQL-like WHERE string into a Predicate; pass a Predicate 
through."""
+    if isinstance(predicate, str):
+        return parse_where_clause(predicate, fields)
+    return predicate
+
+
 class _ReadPredicateBuilder(PredicateBuilder):
 
     def __init__(self, fields, unsupported_fields, paths=None):
@@ -116,8 +124,15 @@ class ReadBuilder:
         self._partition_filter: Optional[Predicate] = None
         self._limit: Optional[int] = None
 
-    def with_filter(self, predicate: Predicate) -> 'ReadBuilder':
-        self._predicate = predicate
+    def with_filter(self, predicate: Union[str, Predicate]) -> 'ReadBuilder':
+        """Set the row filter from a Predicate or a SQL-like WHERE string.
+
+        A string is parsed against the table schema. Supported syntax:
+        ``=, !=, <>, <, <=, >, >=, IS [NOT] NULL, [NOT] IN, [NOT] BETWEEN,
+        LIKE`` combined with ``AND``/``OR`` and parentheses; see
+        :mod:`pypaimon.common.where_parser`. An empty string clears the filter.
+        """
+        self._predicate = _normalize_filter(predicate, self.table.fields)
         return self
 
     def with_partition_filter(self, partition_filter: Optional[Predicate]) -> 
'ReadBuilder':
diff --git a/paimon-python/pypaimon/read/stream_read_builder.py 
b/paimon-python/pypaimon/read/stream_read_builder.py
index 912fa4f653..f9a6ebeddf 100644
--- a/paimon-python/pypaimon/read/stream_read_builder.py
+++ b/paimon-python/pypaimon/read/stream_read_builder.py
@@ -26,7 +26,7 @@ from typing import Callable, Dict, List, Optional, Set, 
Union, TYPE_CHECKING
 
 from pypaimon.common.predicate import Predicate
 from pypaimon.common.predicate_builder import PredicateBuilder
-from pypaimon.read.read_builder import ReadBuilder
+from pypaimon.read.read_builder import ReadBuilder, _normalize_filter
 from pypaimon.read.table_read import TableRead
 from pypaimon.schema.data_types import DataField
 
@@ -61,10 +61,14 @@ class StreamReadBuilder:
         self._bucket_filter: Optional[Callable[[int], bool]] = None
         self._consumer_id: Optional[str] = None
 
-    def with_filter(self, predicate: Predicate) -> 'StreamReadBuilder':
-        """Set a filter predicate for the streaming read."""
-        self._predicate = predicate
-        self._read_builder.with_filter(predicate)
+    def with_filter(self, predicate: Union[str, Predicate]) -> 
'StreamReadBuilder':
+        """Set a filter predicate, either a Predicate or a SQL-like WHERE 
string.
+
+        Strings are parsed against the table schema, as in
+        :meth:`pypaimon.read.read_builder.ReadBuilder.with_filter`.
+        """
+        self._predicate = _normalize_filter(predicate, self.table.fields)
+        self._read_builder.with_filter(self._predicate)
         return self
 
     def with_projection(
diff --git a/paimon-python/pypaimon/tests/where_parser_test.py 
b/paimon-python/pypaimon/tests/where_parser_test.py
index 762f4db485..f1d2f5c9ec 100644
--- a/paimon-python/pypaimon/tests/where_parser_test.py
+++ b/paimon-python/pypaimon/tests/where_parser_test.py
@@ -25,6 +25,7 @@ import unittest
 import pyarrow as pa
 
 from pypaimon import CatalogFactory, Schema
+from pypaimon.common.predicate import Predicate
 from pypaimon.common.where_parser import parse_where_clause, _tokenize, 
_cast_literal
 from pypaimon.schema.data_types import ArrayType, AtomicType, DataField
 
@@ -531,5 +532,102 @@ class WhereParserScanTest(unittest.TestCase):
         self.assertEqual(self._scan_ids("t = '12:30:00'"), [1])
 
 
+class ReadBuilderStringFilterTest(unittest.TestCase):
+    """End-to-end: ReadBuilder.with_filter accepts a WHERE string directly."""
+
+    @classmethod
+    def setUpClass(cls):
+        cls.tempdir = tempfile.mkdtemp()
+        cls.catalog = CatalogFactory.create(
+            {'warehouse': os.path.join(cls.tempdir, 'warehouse')})
+        cls.catalog.create_database('default', False)
+        pa_schema = pa.schema([
+            ('id', pa.int32()),
+            ('name', pa.string()),
+            ('age', pa.int32()),
+            ('city', pa.string()),
+        ])
+        cls.catalog.create_table(
+            'default.where_string_filter', 
Schema.from_pyarrow_schema(pa_schema), False)
+        cls.table = cls.catalog.get_table('default.where_string_filter')
+        data = pa.table({
+            'id': pa.array([1, 2, 3, 4], pa.int32()),
+            'name': pa.array(['Alice', 'Bob', None, 'Carol'], pa.string()),
+            'age': pa.array([30, 15, 45, 8], pa.int32()),
+            'city': pa.array(['Beijing', 'Shanghai', 'Beijing', 'Shenzhen'], 
pa.string()),
+        })
+        wb = cls.table.new_batch_write_builder()
+        writer = wb.new_write()
+        commit = wb.new_commit()
+        writer.write_arrow(data)
+        commit.commit(writer.prepare_commit())
+        writer.close()
+        commit.close()
+
+    @classmethod
+    def tearDownClass(cls):
+        shutil.rmtree(cls.tempdir, ignore_errors=True)
+
+    def _scan_ids(self, where, projection=None):
+        read_builder = self.table.new_read_builder().with_filter(where)
+        if projection is not None:
+            read_builder = read_builder.with_projection(projection)
+        splits = read_builder.new_scan().plan().splits()
+        return 
sorted(read_builder.new_read().to_arrow(splits).column('id').to_pylist())
+
+    def test_string_filter_matches_predicate_builder(self):
+        # with_filter("age > 18") must be equivalent to building the same
+        # predicate through new_predicate_builder().
+        read_builder = self.table.new_read_builder()
+        predicate = read_builder.new_predicate_builder().greater_than('age', 
18)
+        splits = read_builder.with_filter(predicate).new_scan().plan().splits()
+        expected = sorted(
+            read_builder.new_read().to_arrow(splits).column('id').to_pylist())
+        self.assertEqual(self._scan_ids("age > 18"), expected)
+        self.assertEqual(expected, [1, 3])
+
+    def test_and_or_combinations(self):
+        self.assertEqual(self._scan_ids("age > 10 AND city = 'Beijing'"), [1, 
3])
+        self.assertEqual(self._scan_ids("age > 40 OR age < 10"), [3, 4])
+        self.assertEqual(
+            self._scan_ids("city = 'Shanghai' OR (age < 10 AND name IS NOT 
NULL)"),
+            [2, 4])
+
+    def test_in_between_like_is_null(self):
+        self.assertEqual(self._scan_ids("name IN ('Alice', 'Carol')"), [1, 4])
+        self.assertEqual(self._scan_ids("age BETWEEN 10 AND 40"), [1, 2])
+        self.assertEqual(self._scan_ids("city LIKE 'Bei%'"), [1, 3])
+        self.assertEqual(self._scan_ids("name IS NULL"), [3])
+
+    def test_filter_on_unprojected_column(self):
+        # Like PyIceberg's row_filter, the string binds to the table schema,
+        # not the projection: 'age' is not projected but still filters. This
+        # holds for both with_filter/with_projection call orders.
+        self.assertEqual(
+            self._scan_ids("age > 18", projection=['id', 'name']), [1, 3])
+        read_builder = self.table.new_read_builder().with_projection(['id', 
'name'])
+        read_builder.with_filter("age < 10")
+        splits = read_builder.new_scan().plan().splits()
+        ids = 
sorted(read_builder.new_read().to_arrow(splits).column('id').to_pylist())
+        self.assertEqual(ids, [4])
+
+    def test_unknown_field_raises_value_error(self):
+        with self.assertRaises(ValueError):
+            self.table.new_read_builder().with_filter("nope > 1")
+
+    def test_empty_string_clears_filter(self):
+        # parse_where_clause returns None for blank input; the CLI relies on
+        # the same behavior to skip filtering.
+        self.assertEqual(self._scan_ids(""), [1, 2, 3, 4])
+        self.assertEqual(self._scan_ids("   "), [1, 2, 3, 4])
+
+    def test_stream_read_builder_normalizes_string(self):
+        # StreamReadBuilder.new_read() passes the stored predicate straight to
+        # TableRead, so a string must be parsed before it is stored.
+        table_read = self.table.new_stream_read_builder() \
+            .with_filter("age > 18").new_read()
+        self.assertIsInstance(table_read.predicate, Predicate)
+
+
 if __name__ == '__main__':
     unittest.main()

Reply via email to