World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#5199] feat(client-python): add sort order serdes (#8459)
George T. C. Laic51b8d59642e
diff --git a/clients/client-python/gravitino/dto/rel/json_serdes/__init__.py b/clients/client-python/gravitino/dto/rel/json_serdes/__init__.pynew file mode 100644index 0000000000..13a83393a9--- /dev/null+++ b/clients/client-python/gravitino/dto/rel/json_serdes/__init__.py@@ -0,0 +1,16 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.diff --git a/clients/client-python/gravitino/dto/rel/json_serdes/sort_order_serdes.py b/clients/client-python/gravitino/dto/rel/json_serdes/sort_order_serdes.pynew file mode 100644index 0000000000..7eadb5416f--- /dev/null+++ b/clients/client-python/gravitino/dto/rel/json_serdes/sort_order_serdes.py@@ -0,0 +1,88 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++from typing import Any, Dict++from gravitino.api.expressions.sorts.null_ordering import NullOrdering+from gravitino.api.expressions.sorts.sort_direction import SortDirection+from gravitino.api.types.json_serdes import JsonSerializable+from gravitino.dto.rel.expressions.json_serdes._helper.serdes_utils import SerdesUtils+from gravitino.dto.rel.sort_order_dto import SortOrderDTO+from gravitino.utils.precondition import Precondition+from gravitino.utils.serdes import SerdesUtilsBase+++class SortOrderSerdes(SerdesUtilsBase, JsonSerializable[SortOrderDTO]):+ """Custom JSON serializer/deserializer for SortOrderDTO objects."""++ @classmethod+ def serialize(cls, data_type: SortOrderDTO) -> dict[str, Any]:+ """+ Serialize the given data into a dictionary.++ Args:+ data_type (SortOrderDTO): The data to be serialized.++ Returns:+ dict[str, Any]: The serialized data.+ """++ return {+ cls.SORT_TERM: SerdesUtils.write_function_arg(data_type.sort_term()),+ cls.DIRECTION: str(data_type.direction()),+ cls.NULL_ORDERING: str(data_type.null_ordering()),+ }++ @classmethod+ def deserialize(cls, data: dict[str, Any]) -> SortOrderDTO:+ """+ Deserialize the given data into a `SortOrderDTO` instance.++ Args:+ data (dict[str, Any]): The data to be deserialized.++ Returns:+ SortOrderDTO: The deserialized `SortOrderDTO` instance.+ """++ Precondition.check_argument(+ isinstance(data, Dict) and len(data) > 0,+ f"Cannot parse sort order from invalid JSON: {data}",+ )+ Precondition.check_argument(+ cls.SORT_TERM in data,+ f"Cannot parse sort order from missing sort term: {data}",+ )+ sort_term_data = data[cls.SORT_TERM]+ Precondition.check_argument(+ sort_term_data is not None, "expression cannot be null"+ )+ direction_data = data.get(cls.DIRECTION)+ null_order_data = data.get(cls.NULL_ORDERING)+ sort_term = SerdesUtils.read_function_arg(data[cls.SORT_TERM])+ direction = (+ SortDirection.from_string(direction_data)+ if direction_data+ else SortDirection.ASCENDING+ )+ null_order = (+ NullOrdering(null_order_data)+ if null_order_data+ else direction.default_null_ordering()+ )++ return SortOrderDTO(sort_term, direction, null_order)diff --git a/clients/client-python/gravitino/dto/rel/sort_order_dto.py b/clients/client-python/gravitino/dto/rel/sort_order_dto.pyindex 3d6fa77a08..53141d1a12 100644--- a/clients/client-python/gravitino/dto/rel/sort_order_dto.py+++ b/clients/client-python/gravitino/dto/rel/sort_order_dto.py@@ -15,7 +15,7 @@# specific language governing permissions and limitations# under the License.-from typing import ClassVar, List+from typing import ClassVarfrom gravitino.api.expressions.expression import Expressionfrom gravitino.api.expressions.sorts.null_ordering import NullOrdering@@ -23,18 +23,17 @@ from gravitino.api.expressions.sorts.sort_direction import SortDirectionfrom gravitino.api.expressions.sorts.sort_order import SortOrderfrom gravitino.dto.rel.column_dto import ColumnDTOfrom gravitino.dto.rel.expressions.function_arg import FunctionArg-from gravitino.utils.precondition import Preconditionclass SortOrderDTO(SortOrder):"""Data Transfer Object for SortOrder.Attributes:- EMPTY_SORT (List[SortOrderDTO]):+ EMPTY_SORT (list[SortOrderDTO]):An empty array of SortOrderDTO."""- EMPTY_SORT: ClassVar[List["SortOrderDTO"]] = []+ EMPTY_SORT: ClassVar[list["SortOrderDTO"]] = []def __init__(self,@@ -42,17 +41,9 @@ class SortOrderDTO(SortOrder):direction: SortDirection,null_ordering: NullOrdering,):- Precondition.check_argument(sort_term is not None, "expression cannot be null")-self._sort_term = sort_term- self._direction = (- direction if direction is not None else SortDirection.ASCENDING- )- self._null_ordering = (- null_ordering- if null_ordering is not None- else direction.default_null_ordering()- )+ self._direction = direction+ self._null_ordering = null_orderingdef sort_term(self) -> FunctionArg:"""Returns the sort term.@@ -71,11 +62,11 @@ class SortOrderDTO(SortOrder):def null_ordering(self):return self._null_ordering- def validate(self, columns: List[ColumnDTO]) -> None:+ def validate(self, columns: list[ColumnDTO]) -> None:"""Validates the sort order.Args:- columns (List[ColumnDTO]):+ columns (list[ColumnDTO]):The column DTOs to validate against.Raises:diff --git a/clients/client-python/tests/unittests/dto/rel/test_sort_order_dto.py b/clients/client-python/tests/unittests/dto/rel/test_sort_order_dto.pyindex e7cdf8950a..68a39e1ab3 100644--- a/clients/client-python/tests/unittests/dto/rel/test_sort_order_dto.py+++ b/clients/client-python/tests/unittests/dto/rel/test_sort_order_dto.py@@ -23,7 +23,6 @@ from gravitino.api.types.types import Typesfrom gravitino.dto.rel.column_dto import ColumnDTOfrom gravitino.dto.rel.expressions.field_reference_dto import FieldReferenceDTOfrom gravitino.dto.rel.sort_order_dto import SortOrderDTO-from gravitino.exceptions.base import IllegalArgumentExceptionclass TestSortOrderDTO(unittest.TestCase):@@ -54,11 +53,6 @@ class TestSortOrderDTO(unittest.TestCase):self.assertEqual(SortOrderDTO.EMPTY_NAMED_REFERENCE, [])def test_sort_order_dto_init(self):- with self.assertRaisesRegex(- IllegalArgumentException, "expression cannot be null"- ):- SortOrderDTO(None, SortDirection.ASCENDING, NullOrdering.NULLS_FIRST)-self.sort_order_dto.validate(self.columns)self.assertTrue(self.sort_order_dto.sort_term() == self.field_ref_dto)self.assertIs(self.sort_order_dto.direction(), SortDirection.ASCENDING)diff --git a/clients/client-python/tests/unittests/dto/rel/test_sort_order_serdes.py b/clients/client-python/tests/unittests/dto/rel/test_sort_order_serdes.pynew file mode 100644index 0000000000..bb2bce511a--- /dev/null+++ b/clients/client-python/tests/unittests/dto/rel/test_sort_order_serdes.py@@ -0,0 +1,158 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.+++import json+import unittest+from dataclasses import dataclass, field+from typing import cast++from dataclasses_json import DataClassJsonMixin, config++from gravitino.api.expressions.sorts.null_ordering import NullOrdering+from gravitino.api.expressions.sorts.sort_direction import SortDirection+from gravitino.api.types.types import Types+from gravitino.dto.rel.expressions.field_reference_dto import FieldReferenceDTO+from gravitino.dto.rel.expressions.func_expression_dto import FuncExpressionDTO+from gravitino.dto.rel.expressions.literal_dto import LiteralDTO+from gravitino.dto.rel.json_serdes.sort_order_serdes import SortOrderSerdes+from gravitino.dto.rel.sort_order_dto import SortOrderDTO+from gravitino.exceptions.base import IllegalArgumentException+++@dataclass+class MockDataClass(DataClassJsonMixin):+ sort_orders: list[SortOrderDTO] = field(+ metadata=config(+ field_name="sortOrders",+ encoder=lambda data: [SortOrderSerdes.serialize(item) for item in data],+ decoder=lambda data: [SortOrderSerdes.deserialize(item) for item in data],+ )+ )+++class TestSortOrderSerdes(unittest.TestCase):+ def test_sort_order_serdes_invalid_json(self):+ json_strings = [+ '{"sortOrders": [{}]}',+ '{"sortOrders": [""]}',+ '{"sortOrders": [null]}',+ ]++ with self.assertRaisesRegex(+ IllegalArgumentException, "Cannot parse sort order from invalid JSON"+ ):+ for json_string in json_strings:+ MockDataClass.from_json(json_string)++ def test_sort_order_serdes_missing_sort_term(self):+ json_string = '{"sortOrders": [{"direction": "asc"}]}'++ with self.assertRaisesRegex(+ IllegalArgumentException, "Cannot parse sort order from missing sort term"+ ):+ MockDataClass.from_json(json_string)++ def test_sort_order_serdes_invalid_sort_term(self):+ json_string = '{"sortOrders": [{"sortTerm": null, "direction": "asc"}]}'++ with self.assertRaisesRegex(+ IllegalArgumentException, "expression cannot be null"+ ):+ MockDataClass.from_json(json_string)++ def test_sort_order_serdes(self):+ json_string = """+ {+ "sortOrders": [+ {+ "sortTerm": {+ "type": "field",+ "fieldName": ["age"]+ },+ "direction": "asc",+ "nullOrdering": "nulls_first"+ }+ ]+ }+ """++ mock_data_class = MockDataClass.from_json(json_string)+ sort_orders = mock_data_class.sort_orders+ self.assertEqual(len(sort_orders), 1)+ self.assertIsInstance(sort_orders[0], SortOrderDTO)+ self.assertEqual(+ cast(FieldReferenceDTO, sort_orders[0].sort_term()).field_name(), ["age"]+ )+ self.assertIs(sort_orders[0].null_ordering(), NullOrdering.NULLS_FIRST)+ self.assertIs(sort_orders[0].direction(), SortDirection.ASCENDING)++ serialized = mock_data_class.to_json()+ self.assertDictEqual(json.loads(json_string), json.loads(serialized))++ def test_sort_order_serdes_function_sort_term(self):+ json_string = """+ {+ "sortOrders": [+ {+ "sortTerm": {+ "type": "function",+ "funcName": "date_trunc",+ "funcArgs": [+ {+ "type": "literal",+ "dataType": "string",+ "value": "year"+ },+ {+ "type": "field",+ "fieldName": ["birthday"]+ }+ ]+ },+ "direction": "desc",+ "nullOrdering": "nulls_last"+ }+ ]+ }+ """++ mock_data_class = MockDataClass.from_json(json_string)+ sort_orders = mock_data_class.sort_orders+ self.assertEqual(len(sort_orders), 1)+ self.assertIsInstance(sort_orders[0], SortOrderDTO)+ deserialized_func_dto = cast(FuncExpressionDTO, sort_orders[0].sort_term())+ expected_func_dto = (+ FuncExpressionDTO.builder()+ .with_function_name("date_trunc")+ .with_function_args(+ [+ LiteralDTO.builder()+ .with_data_type(Types.StringType())+ .with_value("year")+ .build(),+ FieldReferenceDTO.builder().with_field_name(["birthday"]).build(),+ ]+ )+ .build()+ )+ self.assertTrue(deserialized_func_dto == expected_func_dto)+ self.assertIs(sort_orders[0].null_ordering(), NullOrdering.NULLS_LAST)+ self.assertIs(sort_orders[0].direction(), SortDirection.DESCENDING)++ serialized = mock_data_class.to_json()+ self.assertDictEqual(json.loads(json_string), json.loads(serialized))