Skip to content

Apache DataFusion SQL Query Engine

Create a `datafusion-proto` crate for datafusion protobuf serialization (#1887)

Carol (Nichols || Goulding)2549500e327a
diff --git a/Cargo.toml b/Cargo.toml
index 65dd7224b5..f7e9c0330e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,6 +24,7 @@ members = [
"datafusion-physical-expr",
"datafusion-cli",
"datafusion-examples",
+ "datafusion-proto",
"benchmarks",
"ballista/rust/client",
"ballista/rust/core",
diff --git a/ballista/rust/core/Cargo.toml b/ballista/rust/core/Cargo.toml
index 6181d731a0..5054b0f517 100644
--- a/ballista/rust/core/Cargo.toml
+++ b/ballista/rust/core/Cargo.toml
@@ -36,6 +36,7 @@ futures = "0.3"
hashbrown = "0.12"
log = "0.4"
prost = "0.9"
+prost-types = "0.9"
serde = {version = "1", features = ["derive"]}
sqlparser = "0.14"
tokio = "1.0"
@@ -47,6 +48,7 @@ parse_arg = "0.1.3"
arrow-flight = { version = "9.1" }
datafusion = { path = "../../../datafusion", version = "7.0.0" }
+datafusion-proto = { path = "../../../datafusion-proto", version = "7.0.0" }
parking_lot = "0.12"
diff --git a/ballista/rust/core/build.rs b/ballista/rust/core/build.rs
index 6ad153e87c..b5110f8f57 100644
--- a/ballista/rust/core/build.rs
+++ b/ballista/rust/core/build.rs
@@ -20,7 +20,9 @@ fn main() -> Result<(), String> {
println!("cargo:rerun-if-env-changed=FORCE_REBUILD");
println!("cargo:rerun-if-changed=proto/ballista.proto");
+ println!("cargo:rerun-if-changed=proto/datafusion.proto");
tonic_build::configure()
+ .extern_path(".datafusion", "::datafusion_proto::protobuf")
.compile(&["proto/ballista.proto"], &["proto"])
.map_err(|e| format!("protobuf compilation failed: {}", e))
}
diff --git a/ballista/rust/core/proto/ballista.proto b/ballista/rust/core/proto/ballista.proto
index a0925b4443..2733521644 100644
--- a/ballista/rust/core/proto/ballista.proto
+++ b/ballista/rust/core/proto/ballista.proto
@@ -24,230 +24,12 @@ option java_multiple_files = true;
option java_package = "org.ballistacompute.protobuf";
option java_outer_classname = "BallistaProto";
+import "datafusion.proto";
+
///////////////////////////////////////////////////////////////////////////////////////////////////
// Ballista Logical Plan
///////////////////////////////////////////////////////////////////////////////////////////////////
-message ColumnRelation {
- string relation = 1;
-}
-
-message Column {
- string name = 1;
- ColumnRelation relation = 2;
-}
-
-message DfField{
- Field field = 1;
- ColumnRelation qualifier = 2;
-}
-
-message DfSchema {
- repeated DfField columns = 1;
-}
-
-// logical expressions
-message LogicalExprNode {
- oneof ExprType {
- // column references
- Column column = 1;
-
- // alias
- AliasNode alias = 2;
-
- ScalarValue literal = 3;
-
- // binary expressions
- BinaryExprNode binary_expr = 4;
-
- // aggregate expressions
- AggregateExprNode aggregate_expr = 5;
-
- // null checks
- IsNull is_null_expr = 6;
- IsNotNull is_not_null_expr = 7;
- Not not_expr = 8;
-
- BetweenNode between = 9;
- CaseNode case_ = 10;
- CastNode cast = 11;
- SortExprNode sort = 12;
- NegativeNode negative = 13;
- InListNode in_list = 14;
- bool wildcard = 15;
- ScalarFunctionNode scalar_function = 16;
- TryCastNode try_cast = 17;
-
- // window expressions
- WindowExprNode window_expr = 18;
- }
-}
-
-message IsNull {
- LogicalExprNode expr = 1;
-}
-
-message IsNotNull {
- LogicalExprNode expr = 1;
-}
-
-message Not {
- LogicalExprNode expr = 1;
-}
-
-message AliasNode {
- LogicalExprNode expr = 1;
- string alias = 2;
-}
-
-message BinaryExprNode {
- LogicalExprNode l = 1;
- LogicalExprNode r = 2;
- string op = 3;
-}
-
-message NegativeNode {
- LogicalExprNode expr = 1;
-}
-
-message InListNode {
- LogicalExprNode expr = 1;
- repeated LogicalExprNode list = 2;
- bool negated = 3;
-}
-
-enum ScalarFunction {
- SQRT = 0;
- SIN = 1;
- COS = 2;
- TAN = 3;
- ASIN = 4;
- ACOS = 5;
- ATAN = 6;
- EXP = 7;
- LOG = 8;
- LOG2 = 9;
- LOG10 = 10;
- FLOOR = 11;
- CEIL = 12;
- ROUND = 13;
- TRUNC = 14;
- ABS = 15;
- SIGNUM = 16;
- OCTETLENGTH = 17;
- CONCAT = 18;
- LOWER = 19;
- UPPER = 20;
- TRIM = 21;
- LTRIM = 22;
- RTRIM = 23;
- TOTIMESTAMP = 24;
- ARRAY = 25;
- NULLIF = 26;
- DATEPART = 27;
- DATETRUNC = 28;
- MD5 = 29;
- SHA224 = 30;
- SHA256 = 31;
- SHA384 = 32;
- SHA512 = 33;
- LN = 34;
- TOTIMESTAMPMILLIS = 35;
- DIGEST = 36;
-}
-
-message ScalarFunctionNode {
- ScalarFunction fun = 1;
- repeated LogicalExprNode args = 2;
-}
-
-enum AggregateFunction {
- MIN = 0;
- MAX = 1;
- SUM = 2;
- AVG = 3;
- COUNT = 4;
- APPROX_DISTINCT = 5;
- ARRAY_AGG = 6;
- VARIANCE=7;
- VARIANCE_POP=8;
- COVARIANCE=9;
- COVARIANCE_POP=10;
- STDDEV=11;
- STDDEV_POP=12;
- CORRELATION=13;
- APPROX_PERCENTILE_CONT = 14;
- APPROX_MEDIAN=15;
-}
-
-message AggregateExprNode {
- AggregateFunction aggr_function = 1;
- repeated LogicalExprNode expr = 2;
-}
-
-enum BuiltInWindowFunction {
- ROW_NUMBER = 0;
- RANK = 1;
- DENSE_RANK = 2;
- PERCENT_RANK = 3;
- CUME_DIST = 4;
- NTILE = 5;
- LAG = 6;
- LEAD = 7;
- FIRST_VALUE = 8;
- LAST_VALUE = 9;
- NTH_VALUE = 10;
-}
-
-message WindowExprNode {
- oneof window_function {
- AggregateFunction aggr_function = 1;
- BuiltInWindowFunction built_in_function = 2;
- // udaf = 3
- }
- LogicalExprNode expr = 4;
- repeated LogicalExprNode partition_by = 5;
- repeated LogicalExprNode order_by = 6;
- // repeated LogicalExprNode filter = 7;
- oneof window_frame {
- WindowFrame frame = 8;
- }
-}
-
-message BetweenNode {
- LogicalExprNode expr = 1;
- bool negated = 2;
- LogicalExprNode low = 3;
- LogicalExprNode high = 4;
-}
-
-message CaseNode {
- LogicalExprNode expr = 1;
- repeated WhenThen when_then_expr = 2;
- LogicalExprNode else_expr = 3;
-}
-
-message WhenThen {
- LogicalExprNode when_expr = 1;
- LogicalExprNode then_expr = 2;
-}
-
-message CastNode {
- LogicalExprNode expr = 1;
- ArrowType arrow_type = 2;
-}
-
-message TryCastNode {
- LogicalExprNode expr = 1;
- ArrowType arrow_type = 2;
-}
-
-message SortExprNode {
- LogicalExprNode expr = 1;
- bool asc = 2;
- bool nulls_first = 3;
-}
-
// LogicalPlan is a nested type
message LogicalPlanNode {
oneof LogicalPlanType {
@@ -290,7 +72,7 @@ message PartitionedFile {
string path = 1;
uint64 size = 2;
uint64 last_modified_ns = 3;
- repeated ScalarValue partition_values = 4;
+ repeated datafusion.ScalarValue partition_values = 4;
}
message CsvFormat {
@@ -309,8 +91,8 @@ message ListingTableScanNode {
string path = 2;
string file_extension = 3;
ProjectionColumns projection = 4;
- Schema schema = 5;
- repeated LogicalExprNode filters = 6;
+ datafusion.Schema schema = 5;
+ repeated datafusion.LogicalExprNode filters = 6;
repeated string table_partition_cols = 7;
bool collect_stat = 8;
uint32 target_partitions = 9;
@@ -323,7 +105,7 @@ message ListingTableScanNode {
message ProjectionNode {
LogicalPlanNode input = 1;
- repeated LogicalExprNode expr = 2;
+ repeated datafusion.LogicalExprNode expr = 2;
oneof optional_alias {
string alias = 3;
}
@@ -331,12 +113,12 @@ message ProjectionNode {
message SelectionNode {
LogicalPlanNode input = 1;
- LogicalExprNode expr = 2;
+ datafusion.LogicalExprNode expr = 2;
}
message SortNode {
LogicalPlanNode input = 1;
- repeated LogicalExprNode expr = 2;
+ repeated datafusion.LogicalExprNode expr = 2;
}
message RepartitionNode {
@@ -348,7 +130,7 @@ message RepartitionNode {
}
message HashRepartition {
- repeated LogicalExprNode hash_expr = 1;
+ repeated datafusion.LogicalExprNode hash_expr = 1;
uint64 partition_count = 2;
}
@@ -361,14 +143,14 @@ message CreateExternalTableNode {
string location = 2;
FileType file_type = 3;
bool has_header = 4;
- DfSchema schema = 5;
+ datafusion.DfSchema schema = 5;
}
// a node containing data for defining values list. unlike in SQL where it's two dimensional, here
// the list is flattened, and with the field n_cols it can be parsed and partitioned into rows
message ValuesNode {
uint64 n_cols = 1;
- repeated LogicalExprNode values_list = 2;
+ repeated datafusion.LogicalExprNode values_list = 2;
}
enum FileType {
@@ -390,44 +172,13 @@ message ExplainNode{
message AggregateNode {
LogicalPlanNode input = 1;
- repeated LogicalExprNode group_expr = 2;
- repeated LogicalExprNode aggr_expr = 3;
+ repeated datafusion.LogicalExprNode group_expr = 2;
+ repeated datafusion.LogicalExprNode aggr_expr = 3;
}
message WindowNode {
LogicalPlanNode input = 1;
- repeated LogicalExprNode window_expr = 2;
-}
-
-enum WindowFrameUnits {
- ROWS = 0;
- RANGE = 1;
- GROUPS = 2;
-}
-
-message WindowFrame {
- WindowFrameUnits window_frame_units = 1;
- WindowFrameBound start_bound = 2;
- // "optional" keyword is stable in protoc 3.15 but prost is still on 3.14 (see https://github.com/tokio-rs/prost/issues/430 and https://github.com/tokio-rs/prost/pull/455)
- // this syntax is ugly but is binary compatible with the "optional" keyword (see https://stackoverflow.com/questions/42622015/how-to-define-an-optional-field-in-protobuf-3)
- oneof end_bound {
- WindowFrameBound bound = 3;
- }
-}
-
-enum WindowFrameBoundType {
- CURRENT_ROW = 0;
- PRECEDING = 1;
- FOLLOWING = 2;
-}
-
-message WindowFrameBound {
- WindowFrameBoundType window_frame_bound_type = 1;
- // "optional" keyword is stable in protoc 3.15 but prost is still on 3.14 (see https://github.com/tokio-rs/prost/issues/430 and https://github.com/tokio-rs/prost/pull/455)
- // this syntax is ugly but is binary compatible with the "optional" keyword (see https://stackoverflow.com/questions/42622015/how-to-define-an-optional-field-in-protobuf-3)
- oneof bound_value {
- uint64 value = 2;
- }
+ repeated datafusion.LogicalExprNode window_expr = 2;
}
enum JoinType {
@@ -449,8 +200,8 @@ message JoinNode {
LogicalPlanNode right = 2;
JoinType join_type = 3;
JoinConstraint join_constraint = 4;
- repeated Column left_join_column = 5;
- repeated Column right_join_column = 6;
+ repeated datafusion.Column left_join_column = 5;
+ repeated datafusion.Column right_join_column = 6;
bool null_equals_null = 7;
}
@@ -465,7 +216,7 @@ message LimitNode {
}
message SelectionExecNode {
- LogicalExprNode expr = 1;
+ datafusion.LogicalExprNode expr = 1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
@@ -509,7 +260,7 @@ message PhysicalExprNode {
// column references
PhysicalColumn column = 1;
- ScalarValue literal = 2;
+ datafusion.ScalarValue literal = 2;
// binary expressions
PhysicalBinaryExprNode binary_expr = 3;
@@ -536,14 +287,14 @@ message PhysicalExprNode {
}
message PhysicalAggregateExprNode {
- AggregateFunction aggr_function = 1;
+ datafusion.AggregateFunction aggr_function = 1;
PhysicalExprNode expr = 2;
}
message PhysicalWindowExprNode {
oneof window_function {
- AggregateFunction aggr_function = 1;
- BuiltInWindowFunction built_in_function = 2;
+ datafusion.AggregateFunction aggr_function = 1;
+ datafusion.BuiltInWindowFunction built_in_function = 2;
// udaf = 3
}
PhysicalExprNode expr = 4;
@@ -597,19 +348,19 @@ message PhysicalCaseNode {
message PhysicalScalarFunctionNode {
string name = 1;
- ScalarFunction fun = 2;
+ datafusion.ScalarFunction fun = 2;
repeated PhysicalExprNode args = 3;
- ArrowType return_type = 4;
+ datafusion.ArrowType return_type = 4;
}
message PhysicalTryCastNode {
PhysicalExprNode expr = 1;
- ArrowType arrow_type = 2;
+ datafusion.ArrowType arrow_type = 2;
}
message PhysicalCastNode {
PhysicalExprNode expr = 1;
- ArrowType arrow_type = 2;
+ datafusion.ArrowType arrow_type = 2;
}
message PhysicalNegativeNode {
@@ -618,7 +369,7 @@ message PhysicalNegativeNode {
message UnresolvedShuffleExecNode {
uint32 stage_id = 1;
- Schema schema = 2;
+ datafusion.Schema schema = 2;
uint32 input_partition_count = 3;
uint32 output_partition_count = 4;
}
@@ -639,7 +390,7 @@ message ScanLimit {
message FileScanExecConf {
repeated FileGroup file_groups = 1;
- Schema schema = 2;
+ datafusion.Schema schema = 2;
repeated uint32 projection = 4;
ScanLimit limit = 5;
Statistics statistics = 6;
@@ -691,7 +442,7 @@ message JoinOn {
message EmptyExecNode {
bool produce_one_row = 1;
- Schema schema = 2;
+ datafusion.Schema schema = 2;
}
message ProjectionExecNode {
@@ -710,7 +461,7 @@ message WindowAggExecNode {
PhysicalPlanNode input = 1;
repeated PhysicalExprNode window_expr = 2;
repeated string window_expr_name = 3;
- Schema input_schema = 4;
+ datafusion.Schema input_schema = 4;
}
message HashAggregateExecNode {
@@ -721,7 +472,7 @@ message HashAggregateExecNode {
repeated string group_expr_name = 5;
repeated string aggr_expr_name = 6;
// we need the input schema to the partial aggregate to pass to the final aggregate
- Schema input_schema = 7;
+ datafusion.Schema input_schema = 7;
}
message ShuffleWriterExecNode {
@@ -735,7 +486,7 @@ message ShuffleWriterExecNode {
message ShuffleReaderExecNode {
repeated ShuffleReaderPartition partition = 1;
- Schema schema = 2;
+ datafusion.Schema schema = 2;
}
message ShuffleReaderPartition {
@@ -842,8 +593,8 @@ message PartitionStats {
}
message ColumnStats {
- ScalarValue min_value = 1;
- ScalarValue max_value = 2;
+ datafusion.ScalarValue min_value = 1;
+ datafusion.ScalarValue max_value = 2;
uint32 null_count = 3;
uint32 distinct_count = 4;
}
@@ -1045,7 +796,7 @@ message GetFileMetadataParams {
}
message GetFileMetadataResult {
- Schema schema = 1;
+ datafusion.Schema schema = 1;
}
message FilePartitionMetadata {
@@ -1086,225 +837,3 @@ service ExecutorGrpc {
rpc StopExecutor (StopExecutorParams) returns (StopExecutorResult) {}
}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Arrow Data Types
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-message Schema {
- repeated Field columns = 1;
-}
-
-message Field {
- // name of the field
- string name = 1;
- ArrowType arrow_type = 2;
- bool nullable = 3;
- // for complex data types like structs, unions
- repeated Field children = 4;
-}
-
-message FixedSizeBinary{
- int32 length = 1;
-}
-
-message Timestamp{
- TimeUnit time_unit = 1;
- string timezone = 2;
-}
-
-enum DateUnit{
- Day = 0;
- DateMillisecond = 1;
-}
-
-enum TimeUnit{
- Second = 0;
- TimeMillisecond = 1;
- Microsecond = 2;
- Nanosecond = 3;
-}
-
-enum IntervalUnit{
- YearMonth = 0;
- DayTime = 1;
- MonthDayNano = 2;
-}
-
-message Decimal{
- uint64 whole = 1;
- uint64 fractional = 2;
-}
-
-message List{
- Field field_type = 1;
-}
-
-message FixedSizeList{
- Field field_type = 1;
- int32 list_size = 2;
-}
-
-message Dictionary{
- ArrowType key = 1;
- ArrowType value = 2;
-}
-
-message Struct{
- repeated Field sub_field_types = 1;
-}
-
-enum UnionMode{
- sparse = 0;
- dense = 1;
-}
-
-message Union{
- repeated Field union_types = 1;
- UnionMode union_mode = 2;
-}
-
-
-
-message ScalarListValue{
- ScalarType datatype = 1;
- repeated ScalarValue values = 2;
-}
-
-
-
-message ScalarValue{
- oneof value {
- bool bool_value = 1;
- string utf8_value = 2;
- string large_utf8_value = 3;
- int32 int8_value = 4;
- int32 int16_value = 5;
- int32 int32_value = 6;
- int64 int64_value = 7;
- uint32 uint8_value = 8;
- uint32 uint16_value = 9;
- uint32 uint32_value = 10;
- uint64 uint64_value = 11;
- float float32_value = 12;
- double float64_value = 13;
- //Literal Date32 value always has a unit of day
- int32 date_32_value = 14;
- int64 time_microsecond_value = 15;
- int64 time_nanosecond_value = 16;
- ScalarListValue list_value = 17;
- ScalarType null_list_value = 18;
-
- PrimitiveScalarType null_value = 19;
- Decimal128 decimal128_value = 20;
- int64 date_64_value = 21;
- int64 time_second_value = 22;
- int64 time_millisecond_value = 23;
- int32 interval_yearmonth_value = 24;
- int64 interval_daytime_value = 25;
- }
-}
-
-message Decimal128{
- bytes value = 1;
- int64 p = 2;
- int64 s = 3;
-}
-
-// Contains all valid datafusion scalar type except for
-// List
-enum PrimitiveScalarType{
-
- BOOL = 0; // arrow::Type::BOOL
- UINT8 = 1; // arrow::Type::UINT8
- INT8 = 2; // arrow::Type::INT8
- UINT16 = 3; // represents arrow::Type fields in src/arrow/type.h
- INT16 = 4;
- UINT32 = 5;
- INT32 = 6;
- UINT64 = 7;
- INT64 = 8;
- FLOAT32 = 9;
- FLOAT64 = 10;
- UTF8 = 11;
- LARGE_UTF8 = 12;
- DATE32 = 13;
- TIME_MICROSECOND = 14;
- TIME_NANOSECOND = 15;
- NULL = 16;
-
- DECIMAL128 = 17;
- DATE64 = 20;
- TIME_SECOND = 21;
- TIME_MILLISECOND = 22;
- INTERVAL_YEARMONTH = 23;
- INTERVAL_DAYTIME = 24;
-}
-
-message ScalarType{
- oneof datatype{
- PrimitiveScalarType scalar = 1;
- ScalarListType list = 2;
- }
-}
-
-message ScalarListType{
- repeated string field_names = 3;
- PrimitiveScalarType deepest_type = 2;
-}
-
-// Broke out into multiple message types so that type
-// metadata did not need to be in separate message
-//All types that are of the empty message types contain no additional metadata
-// about the type
-message ArrowType{
- oneof arrow_type_enum{
- EmptyMessage NONE = 1; // arrow::Type::NA
- EmptyMessage BOOL = 2; // arrow::Type::BOOL
- EmptyMessage UINT8 = 3; // arrow::Type::UINT8
- EmptyMessage INT8 = 4; // arrow::Type::INT8
- EmptyMessage UINT16 =5; // represents arrow::Type fields in src/arrow/type.h
- EmptyMessage INT16 = 6;
- EmptyMessage UINT32 =7;
- EmptyMessage INT32 = 8;
- EmptyMessage UINT64 =9;
- EmptyMessage INT64 =10 ;
- EmptyMessage FLOAT16 =11 ;
- EmptyMessage FLOAT32 =12 ;
- EmptyMessage FLOAT64 =13 ;
- EmptyMessage UTF8 =14 ;
- EmptyMessage LARGE_UTF8 = 32;
- EmptyMessage BINARY =15 ;
- int32 FIXED_SIZE_BINARY =16 ;
- EmptyMessage LARGE_BINARY = 31;
- EmptyMessage DATE32 =17 ;
- EmptyMessage DATE64 =18 ;
- TimeUnit DURATION = 19;
- Timestamp TIMESTAMP =20 ;
- TimeUnit TIME32 =21 ;
- TimeUnit TIME64 =22 ;
- IntervalUnit INTERVAL =23 ;
- Decimal DECIMAL =24 ;
- List LIST =25;
- List LARGE_LIST = 26;
- FixedSizeList FIXED_SIZE_LIST = 27;
- Struct STRUCT =28;
- Union UNION =29;
- Dictionary DICTIONARY =30;
- }
-}
-
-
-
-
-
-//Useful for representing an empty enum variant in rust
-// E.G. enum example{One, Two(i32)}
-// maps to
-// message example{
-// oneof{
-// EmptyMessage One = 1;
-// i32 Two = 2;
-// }
-//}
-message EmptyMessage{}
diff --git a/ballista/rust/core/proto/datafusion.proto b/ballista/rust/core/proto/datafusion.proto
new file mode 100644
index 0000000000..f1a0730644
--- /dev/null
+++ b/ballista/rust/core/proto/datafusion.proto
@@ -0,0 +1,490 @@
+/*
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ */
+
+syntax = "proto3";
+
+package datafusion;
+
+option java_multiple_files = true;
+option java_package = "org.datafusioncompute.protobuf";
+option java_outer_classname = "DatafusionProto";
+
+message ColumnRelation {
+ string relation = 1;
+}
+
+message Column {
+ string name = 1;
+ ColumnRelation relation = 2;
+}
+
+message DfField{
+ Field field = 1;
+ ColumnRelation qualifier = 2;
+}
+
+message DfSchema {
+ repeated DfField columns = 1;
+}
+
+// logical expressions
+message LogicalExprNode {
+ oneof ExprType {
+ // column references
+ Column column = 1;
+
+ // alias
+ AliasNode alias = 2;
+
+ ScalarValue literal = 3;
+
+ // binary expressions
+ BinaryExprNode binary_expr = 4;
+
+ // aggregate expressions
+ AggregateExprNode aggregate_expr = 5;
+
+ // null checks
+ IsNull is_null_expr = 6;
+ IsNotNull is_not_null_expr = 7;
+ Not not_expr = 8;
+
+ BetweenNode between = 9;
+ CaseNode case_ = 10;
+ CastNode cast = 11;
+ SortExprNode sort = 12;
+ NegativeNode negative = 13;
+ InListNode in_list = 14;
+ bool wildcard = 15;
+ ScalarFunctionNode scalar_function = 16;
+ TryCastNode try_cast = 17;
+
+ // window expressions
+ WindowExprNode window_expr = 18;
+ }
+}
+
+message IsNull {
+ LogicalExprNode expr = 1;
+}
+
+message IsNotNull {
+ LogicalExprNode expr = 1;
+}
+
+message Not {
+ LogicalExprNode expr = 1;
+}
+
+message AliasNode {
+ LogicalExprNode expr = 1;
+ string alias = 2;
+}
+
+message BinaryExprNode {
+ LogicalExprNode l = 1;
+ LogicalExprNode r = 2;
+ string op = 3;
+}
+
+message NegativeNode {
+ LogicalExprNode expr = 1;
+}
+
+message InListNode {
+ LogicalExprNode expr = 1;
+ repeated LogicalExprNode list = 2;
+ bool negated = 3;
+}
+
+enum ScalarFunction {
+ SQRT = 0;
+ SIN = 1;
+ COS = 2;
+ TAN = 3;
+ ASIN = 4;
+ ACOS = 5;
+ ATAN = 6;
+ EXP = 7;
+ LOG = 8;
+ LOG2 = 9;
+ LOG10 = 10;
+ FLOOR = 11;
+ CEIL = 12;
+ ROUND = 13;
+ TRUNC = 14;
+ ABS = 15;
+ SIGNUM = 16;
+ OCTETLENGTH = 17;
+ CONCAT = 18;
+ LOWER = 19;
+ UPPER = 20;
+ TRIM = 21;
+ LTRIM = 22;
+ RTRIM = 23;
+ TOTIMESTAMP = 24;
+ ARRAY = 25;
+ NULLIF = 26;
+ DATEPART = 27;
+ DATETRUNC = 28;
+ MD5 = 29;
+ SHA224 = 30;
+ SHA256 = 31;
+ SHA384 = 32;
+ SHA512 = 33;
+ LN = 34;
+ TOTIMESTAMPMILLIS = 35;
+ DIGEST = 36;
+}
+
+message ScalarFunctionNode {
+ ScalarFunction fun = 1;
+ repeated LogicalExprNode args = 2;
+}
+
+enum AggregateFunction {
+ MIN = 0;
+ MAX = 1;
+ SUM = 2;
+ AVG = 3;
+ COUNT = 4;
+ APPROX_DISTINCT = 5;
+ ARRAY_AGG = 6;
+ VARIANCE=7;
+ VARIANCE_POP=8;
+ COVARIANCE=9;
+ COVARIANCE_POP=10;
+ STDDEV=11;
+ STDDEV_POP=12;
+ CORRELATION=13;
+ APPROX_PERCENTILE_CONT = 14;
+ APPROX_MEDIAN=15;
+}
+
+message AggregateExprNode {
+ AggregateFunction aggr_function = 1;
+ repeated LogicalExprNode expr = 2;
+}
+
+enum BuiltInWindowFunction {
+ ROW_NUMBER = 0;
+ RANK = 1;
+ DENSE_RANK = 2;
+ PERCENT_RANK = 3;
+ CUME_DIST = 4;
+ NTILE = 5;
+ LAG = 6;
+ LEAD = 7;
+ FIRST_VALUE = 8;
+ LAST_VALUE = 9;
+ NTH_VALUE = 10;
+}
+
+message WindowExprNode {
+ oneof window_function {
+ AggregateFunction aggr_function = 1;
+ BuiltInWindowFunction built_in_function = 2;
+ // udaf = 3
+ }
+ LogicalExprNode expr = 4;
+ repeated LogicalExprNode partition_by = 5;
+ repeated LogicalExprNode order_by = 6;
+ // repeated LogicalExprNode filter = 7;
+ oneof window_frame {
+ WindowFrame frame = 8;
+ }
+}
+
+message BetweenNode {
+ LogicalExprNode expr = 1;
+ bool negated = 2;
+ LogicalExprNode low = 3;
+ LogicalExprNode high = 4;
+}
+
+message CaseNode {
+ LogicalExprNode expr = 1;
+ repeated WhenThen when_then_expr = 2;
+ LogicalExprNode else_expr = 3;
+}
+
+message WhenThen {
+ LogicalExprNode when_expr = 1;
+ LogicalExprNode then_expr = 2;
+}
+
+message CastNode {
+ LogicalExprNode expr = 1;
+ ArrowType arrow_type = 2;
+}
+
+message TryCastNode {
+ LogicalExprNode expr = 1;
+ ArrowType arrow_type = 2;
+}
+
+message SortExprNode {
+ LogicalExprNode expr = 1;
+ bool asc = 2;
+ bool nulls_first = 3;
+}
+
+enum WindowFrameUnits {
+ ROWS = 0;
+ RANGE = 1;
+ GROUPS = 2;
+}
+
+message WindowFrame {
+ WindowFrameUnits window_frame_units = 1;
+ WindowFrameBound start_bound = 2;
+ // "optional" keyword is stable in protoc 3.15 but prost is still on 3.14 (see https://github.com/tokio-rs/prost/issues/430 and https://github.com/tokio-rs/prost/pull/455)
+ // this syntax is ugly but is binary compatible with the "optional" keyword (see https://stackoverflow.com/questions/42622015/how-to-define-an-optional-field-in-protobuf-3)
+ oneof end_bound {
+ WindowFrameBound bound = 3;
+ }
+}
+
+enum WindowFrameBoundType {
+ CURRENT_ROW = 0;
+ PRECEDING = 1;
+ FOLLOWING = 2;
+}
+
+message WindowFrameBound {
+ WindowFrameBoundType window_frame_bound_type = 1;
+ // "optional" keyword is stable in protoc 3.15 but prost is still on 3.14 (see https://github.com/tokio-rs/prost/issues/430 and https://github.com/tokio-rs/prost/pull/455)
+ // this syntax is ugly but is binary compatible with the "optional" keyword (see https://stackoverflow.com/questions/42622015/how-to-define-an-optional-field-in-protobuf-3)
+ oneof bound_value {
+ uint64 value = 2;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Arrow Data Types
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+message Schema {
+ repeated datafusion.Field columns = 1;
+}
+
+message Field {
+ // name of the field
+ string name = 1;
+ ArrowType arrow_type = 2;
+ bool nullable = 3;
+ // for complex data types like structs, unions
+ repeated Field children = 4;
+}
+
+message FixedSizeBinary{
+ int32 length = 1;
+}
+
+message Timestamp{
+ TimeUnit time_unit = 1;
+ string timezone = 2;
+}
+
+enum DateUnit{
+ Day = 0;
+ DateMillisecond = 1;
+}
+
+enum TimeUnit{
+ Second = 0;
+ TimeMillisecond = 1;
+ Microsecond = 2;
+ Nanosecond = 3;
+}
+
+enum IntervalUnit{
+ YearMonth = 0;
+ DayTime = 1;
+ MonthDayNano = 2;
+}
+
+message Decimal{
+ uint64 whole = 1;
+ uint64 fractional = 2;
+}
+
+message List{
+ Field field_type = 1;
+}
+
+message FixedSizeList{
+ Field field_type = 1;
+ int32 list_size = 2;
+}
+
+message Dictionary{
+ ArrowType key = 1;
+ ArrowType value = 2;
+}
+
+message Struct{
+ repeated Field sub_field_types = 1;
+}
+
+enum UnionMode{
+ sparse = 0;
+ dense = 1;
+}
+
+message Union{
+ repeated Field union_types = 1;
+ UnionMode union_mode = 2;
+}
+
+message ScalarListValue{
+ ScalarType datatype = 1;
+ repeated ScalarValue values = 2;
+}
+
+message ScalarValue{
+ oneof value {
+ bool bool_value = 1;
+ string utf8_value = 2;
+ string large_utf8_value = 3;
+ int32 int8_value = 4;
+ int32 int16_value = 5;
+ int32 int32_value = 6;
+ int64 int64_value = 7;
+ uint32 uint8_value = 8;
+ uint32 uint16_value = 9;
+ uint32 uint32_value = 10;
+ uint64 uint64_value = 11;
+ float float32_value = 12;
+ double float64_value = 13;
+ //Literal Date32 value always has a unit of day
+ int32 date_32_value = 14;
+ int64 time_microsecond_value = 15;
+ int64 time_nanosecond_value = 16;
+ ScalarListValue list_value = 17;
+ ScalarType null_list_value = 18;
+
+ PrimitiveScalarType null_value = 19;
+ Decimal128 decimal128_value = 20;
+ int64 date_64_value = 21;
+ int64 time_second_value = 22;
+ int64 time_millisecond_value = 23;
+ int32 interval_yearmonth_value = 24;
+ int64 interval_daytime_value = 25;
+ }
+}
+
+message Decimal128{
+ bytes value = 1;
+ int64 p = 2;
+ int64 s = 3;
+}
+
+// Contains all valid datafusion scalar type except for
+// List
+enum PrimitiveScalarType{
+
+ BOOL = 0; // arrow::Type::BOOL
+ UINT8 = 1; // arrow::Type::UINT8
+ INT8 = 2; // arrow::Type::INT8
+ UINT16 = 3; // represents arrow::Type fields in src/arrow/type.h
+ INT16 = 4;
+ UINT32 = 5;
+ INT32 = 6;
+ UINT64 = 7;
+ INT64 = 8;
+ FLOAT32 = 9;
+ FLOAT64 = 10;
+ UTF8 = 11;
+ LARGE_UTF8 = 12;
+ DATE32 = 13;
+ TIME_MICROSECOND = 14;
+ TIME_NANOSECOND = 15;
+ NULL = 16;
+
+ DECIMAL128 = 17;
+ DATE64 = 20;
+ TIME_SECOND = 21;
+ TIME_MILLISECOND = 22;
+ INTERVAL_YEARMONTH = 23;
+ INTERVAL_DAYTIME = 24;
+}
+
+message ScalarType{
+ oneof datatype{
+ PrimitiveScalarType scalar = 1;
+ ScalarListType list = 2;
+ }
+}
+
+message ScalarListType{
+ repeated string field_names = 3;
+ PrimitiveScalarType deepest_type = 2;
+}
+
+// Broke out into multiple message types so that type
+// metadata did not need to be in separate message
+//All types that are of the empty message types contain no additional metadata
+// about the type
+message ArrowType{
+ oneof arrow_type_enum{
+ EmptyMessage NONE = 1; // arrow::Type::NA
+ EmptyMessage BOOL = 2; // arrow::Type::BOOL
+ EmptyMessage UINT8 = 3; // arrow::Type::UINT8
+ EmptyMessage INT8 = 4; // arrow::Type::INT8
+ EmptyMessage UINT16 =5; // represents arrow::Type fields in src/arrow/type.h
+ EmptyMessage INT16 = 6;
+ EmptyMessage UINT32 =7;
+ EmptyMessage INT32 = 8;
+ EmptyMessage UINT64 =9;
+ EmptyMessage INT64 =10 ;
+ EmptyMessage FLOAT16 =11 ;
+ EmptyMessage FLOAT32 =12 ;
+ EmptyMessage FLOAT64 =13 ;
+ EmptyMessage UTF8 =14 ;
+ EmptyMessage LARGE_UTF8 = 32;
+ EmptyMessage BINARY =15 ;
+ int32 FIXED_SIZE_BINARY =16 ;
+ EmptyMessage LARGE_BINARY = 31;
+ EmptyMessage DATE32 =17 ;
+ EmptyMessage DATE64 =18 ;
+ TimeUnit DURATION = 19;
+ Timestamp TIMESTAMP =20 ;
+ TimeUnit TIME32 =21 ;
+ TimeUnit TIME64 =22 ;
+ IntervalUnit INTERVAL =23 ;
+ Decimal DECIMAL =24 ;
+ List LIST =25;
+ List LARGE_LIST = 26;
+ FixedSizeList FIXED_SIZE_LIST = 27;
+ Struct STRUCT =28;
+ Union UNION =29;
+ Dictionary DICTIONARY =30;
+ }
+}
+
+//Useful for representing an empty enum variant in rust
+// E.G. enum example{One, Two(i32)}
+// maps to
+// message example{
+// oneof{
+// EmptyMessage One = 1;
+// i32 Two = 2;
+// }
+//}
+message EmptyMessage{}
diff --git a/ballista/rust/core/src/error.rs b/ballista/rust/core/src/error.rs
index e9ffcd8180..64b20e37bb 100644
--- a/ballista/rust/core/src/error.rs
+++ b/ballista/rust/core/src/error.rs
@@ -138,6 +138,18 @@ impl From<tokio::task::JoinError> for BallistaError {
}
}
+impl From<datafusion_proto::from_proto::Error> for BallistaError {
+ fn from(e: datafusion_proto::from_proto::Error) -> Self {
+ BallistaError::General(e.to_string())
+ }
+}
+
+impl From<datafusion_proto::to_proto::Error> for BallistaError {
+ fn from(e: datafusion_proto::to_proto::Error) -> Self {
+ BallistaError::General(e.to_string())
+ }
+}
+
impl Display for BallistaError {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
diff --git a/ballista/rust/core/src/serde/logical_plan/from_proto.rs b/ballista/rust/core/src/serde/logical_plan/from_proto.rs
index 068f1ef0fa..afd9b268d2 100644
--- a/ballista/rust/core/src/serde/logical_plan/from_proto.rs
+++ b/ballista/rust/core/src/serde/logical_plan/from_proto.rs
@@ -17,949 +17,8 @@
//! Serde code to convert from protocol buffers to Rust data structures.
-use crate::convert_required;
use crate::error::BallistaError;
-use crate::serde::{from_proto_binary_op, proto_error, protobuf, vec_to_array};
-use datafusion::arrow::datatypes::{DataType, Field, Schema};
-
-use datafusion::logical_plan::window_frames::{
- WindowFrame, WindowFrameBound, WindowFrameUnits,
-};
-use datafusion::logical_plan::{
- abs, atan, ceil, cos, digest, exp, floor, ln, log10, log2, round, signum, sin, sqrt,
- tan, trunc, Column, DFField, DFSchema, Expr,
-};
-use datafusion::physical_plan::aggregates::AggregateFunction;
-use datafusion::physical_plan::window_functions::BuiltInWindowFunction;
-use datafusion::prelude::*;
-use datafusion::scalar::ScalarValue;
-
-use std::{
- convert::{From, TryInto},
- sync::Arc,
-};
-
-impl From<&protobuf::Column> for Column {
- fn from(c: &protobuf::Column) -> Column {
- let c = c.clone();
- Column {
- relation: c.relation.map(|r| r.relation),
- name: c.name,
- }
- }
-}
-
-impl TryInto<DFSchema> for &protobuf::DfSchema {
- type Error = BallistaError;
-
- fn try_into(self) -> Result<DFSchema, BallistaError> {
- let fields = self
- .columns
- .iter()
- .map(|c| c.try_into())
- .collect::<Result<Vec<DFField>, _>>()?;
- Ok(DFSchema::new(fields)?)
- }
-}
-
-impl TryInto<datafusion::logical_plan::DFSchemaRef> for protobuf::DfSchema {
- type Error = BallistaError;
-
- fn try_into(self) -> Result<datafusion::logical_plan::DFSchemaRef, Self::Error> {
- let dfschema: DFSchema = (&self).try_into()?;
- Ok(Arc::new(dfschema))
- }
-}
-
-impl TryInto<DFField> for &protobuf::DfField {
- type Error = BallistaError;
-
- fn try_into(self) -> Result<DFField, Self::Error> {
- let field: Field = convert_required!(self.field)?;
-
- Ok(match &self.qualifier {
- Some(q) => DFField::from_qualified(&q.relation, field),
- None => DFField::from(field),
- })
- }
-}
-
-impl TryInto<DataType> for &protobuf::scalar_type::Datatype {
- type Error = BallistaError;
- fn try_into(self) -> Result<DataType, Self::Error> {
- use protobuf::scalar_type::Datatype;
- Ok(match self {
- Datatype::Scalar(scalar_type) => {
- let pb_scalar_enum = protobuf::PrimitiveScalarType::from_i32(*scalar_type).ok_or_else(|| {
- proto_error(format!(
- "Protobuf deserialization error, scalar_type::Datatype missing was provided invalid enum variant: {}",
- *scalar_type
- ))
- })?;
- pb_scalar_enum.into()
- }
- Datatype::List(protobuf::ScalarListType {
- deepest_type,
- field_names,
- }) => {
- if field_names.is_empty() {
- return Err(proto_error(
- "Protobuf deserialization error: found no field names in ScalarListType message which requires at least one",
- ));
- }
- let pb_scalar_type = protobuf::PrimitiveScalarType::from_i32(
- *deepest_type,
- )
- .ok_or_else(|| {
- proto_error(format!(
- "Protobuf deserialization error: invalid i32 for scalar enum: {}",
- *deepest_type
- ))
- })?;
- //Because length is checked above it is safe to unwrap .last()
- let mut scalar_type = DataType::List(Box::new(Field::new(
- field_names.last().unwrap().as_str(),
- pb_scalar_type.into(),
- true,
- )));
- //Iterate over field names in reverse order except for the last item in the vector
- for name in field_names.iter().rev().skip(1) {
- let new_datatype = DataType::List(Box::new(Field::new(
- name.as_str(),
- scalar_type,
- true,
- )));
- scalar_type = new_datatype;
- }
- scalar_type
- }
- })
- }
-}
-
-//Does not typecheck lists
-fn typechecked_scalar_value_conversion(
- tested_type: &protobuf::scalar_value::Value,
- required_type: protobuf::PrimitiveScalarType,
-) -> Result<datafusion::scalar::ScalarValue, BallistaError> {
- use protobuf::scalar_value::Value;
- use protobuf::PrimitiveScalarType;
- Ok(match (tested_type, &required_type) {
- (Value::BoolValue(v), PrimitiveScalarType::Bool) => {
- ScalarValue::Boolean(Some(*v))
- }
- (Value::Int8Value(v), PrimitiveScalarType::Int8) => {
- ScalarValue::Int8(Some(*v as i8))
- }
- (Value::Int16Value(v), PrimitiveScalarType::Int16) => {
- ScalarValue::Int16(Some(*v as i16))
- }
- (Value::Int32Value(v), PrimitiveScalarType::Int32) => {
- ScalarValue::Int32(Some(*v))
- }
- (Value::Int64Value(v), PrimitiveScalarType::Int64) => {
- ScalarValue::Int64(Some(*v))
- }
- (Value::Uint8Value(v), PrimitiveScalarType::Uint8) => {
- ScalarValue::UInt8(Some(*v as u8))
- }
- (Value::Uint16Value(v), PrimitiveScalarType::Uint16) => {
- ScalarValue::UInt16(Some(*v as u16))
- }
- (Value::Uint32Value(v), PrimitiveScalarType::Uint32) => {
- ScalarValue::UInt32(Some(*v))
- }
- (Value::Uint64Value(v), PrimitiveScalarType::Uint64) => {
- ScalarValue::UInt64(Some(*v))
- }
- (Value::Float32Value(v), PrimitiveScalarType::Float32) => {
- ScalarValue::Float32(Some(*v))
- }
- (Value::Float64Value(v), PrimitiveScalarType::Float64) => {
- ScalarValue::Float64(Some(*v))
- }
- (Value::Date32Value(v), PrimitiveScalarType::Date32) => {
- ScalarValue::Date32(Some(*v))
- }
- (Value::TimeMicrosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {
- ScalarValue::TimestampMicrosecond(Some(*v), None)
- }
- (Value::TimeNanosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {
- ScalarValue::TimestampNanosecond(Some(*v), None)
- }
- (Value::Utf8Value(v), PrimitiveScalarType::Utf8) => {
- ScalarValue::Utf8(Some(v.to_owned()))
- }
- (Value::LargeUtf8Value(v), PrimitiveScalarType::LargeUtf8) => {
- ScalarValue::LargeUtf8(Some(v.to_owned()))
- }
-
- (Value::NullValue(i32_enum), required_scalar_type) => {
- if *i32_enum == *required_scalar_type as i32 {
- let pb_scalar_type = PrimitiveScalarType::from_i32(*i32_enum).ok_or_else(|| {
- BallistaError::General(format!(
- "Invalid i32_enum={} when converting with PrimitiveScalarType::from_i32()",
- *i32_enum
- ))
- })?;
- let scalar_value: ScalarValue = match pb_scalar_type {
- PrimitiveScalarType::Bool => ScalarValue::Boolean(None),
- PrimitiveScalarType::Uint8 => ScalarValue::UInt8(None),
- PrimitiveScalarType::Int8 => ScalarValue::Int8(None),
- PrimitiveScalarType::Uint16 => ScalarValue::UInt16(None),
- PrimitiveScalarType::Int16 => ScalarValue::Int16(None),
- PrimitiveScalarType::Uint32 => ScalarValue::UInt32(None),
- PrimitiveScalarType::Int32 => ScalarValue::Int32(None),
- PrimitiveScalarType::Uint64 => ScalarValue::UInt64(None),
- PrimitiveScalarType::Int64 => ScalarValue::Int64(None),
- PrimitiveScalarType::Float32 => ScalarValue::Float32(None),
- PrimitiveScalarType::Float64 => ScalarValue::Float64(None),
- PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),
- PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),
- PrimitiveScalarType::Date32 => ScalarValue::Date32(None),
- PrimitiveScalarType::TimeMicrosecond => {
- ScalarValue::TimestampMicrosecond(None, None)
- }
- PrimitiveScalarType::TimeNanosecond => {
- ScalarValue::TimestampNanosecond(None, None)
- }
- PrimitiveScalarType::Null => {
- return Err(proto_error(
- "Untyped scalar null is not a valid scalar value",
- ))
- }
- PrimitiveScalarType::Decimal128 => {
- ScalarValue::Decimal128(None, 0, 0)
- }
- PrimitiveScalarType::Date64 => ScalarValue::Date64(None),
- PrimitiveScalarType::TimeSecond => {
- ScalarValue::TimestampSecond(None, None)
- }
- PrimitiveScalarType::TimeMillisecond => {
- ScalarValue::TimestampMillisecond(None, None)
- }
- PrimitiveScalarType::IntervalYearmonth => {
- ScalarValue::IntervalYearMonth(None)
- }
- PrimitiveScalarType::IntervalDaytime => {
- ScalarValue::IntervalDayTime(None)
- }
- };
- scalar_value
- } else {
- return Err(proto_error("Could not convert to the proper type"));
- }
- }
- (Value::Decimal128Value(val), PrimitiveScalarType::Decimal128) => {
- let array = vec_to_array(val.value.clone());
- ScalarValue::Decimal128(
- Some(i128::from_be_bytes(array)),
- val.p as usize,
- val.s as usize,
- )
- }
- (Value::Date64Value(v), PrimitiveScalarType::Date64) => {
- ScalarValue::Date64(Some(*v))
- }
- (Value::TimeSecondValue(v), PrimitiveScalarType::TimeSecond) => {
- ScalarValue::TimestampSecond(Some(*v), None)
- }
- (Value::TimeMillisecondValue(v), PrimitiveScalarType::TimeMillisecond) => {
- ScalarValue::TimestampMillisecond(Some(*v), None)
- }
- (Value::IntervalYearmonthValue(v), PrimitiveScalarType::IntervalYearmonth) => {
- ScalarValue::IntervalYearMonth(Some(*v))
- }
- (Value::IntervalDaytimeValue(v), PrimitiveScalarType::IntervalDaytime) => {
- ScalarValue::IntervalDayTime(Some(*v))
- }
- _ => return Err(proto_error("Could not convert to the proper type")),
- })
-}
-
-impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::scalar_value::Value {
- type Error = BallistaError;
- fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
- use protobuf::PrimitiveScalarType;
- let scalar = match self {
- protobuf::scalar_value::Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),
- protobuf::scalar_value::Value::Utf8Value(v) => {
- ScalarValue::Utf8(Some(v.to_owned()))
- }
- protobuf::scalar_value::Value::LargeUtf8Value(v) => {
- ScalarValue::LargeUtf8(Some(v.to_owned()))
- }
- protobuf::scalar_value::Value::Int8Value(v) => {
- ScalarValue::Int8(Some(*v as i8))
- }
- protobuf::scalar_value::Value::Int16Value(v) => {
- ScalarValue::Int16(Some(*v as i16))
- }
- protobuf::scalar_value::Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),
- protobuf::scalar_value::Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),
- protobuf::scalar_value::Value::Uint8Value(v) => {
- ScalarValue::UInt8(Some(*v as u8))
- }
- protobuf::scalar_value::Value::Uint16Value(v) => {
- ScalarValue::UInt16(Some(*v as u16))
- }
- protobuf::scalar_value::Value::Uint32Value(v) => {
- ScalarValue::UInt32(Some(*v))
- }
- protobuf::scalar_value::Value::Uint64Value(v) => {
- ScalarValue::UInt64(Some(*v))
- }
- protobuf::scalar_value::Value::Float32Value(v) => {
- ScalarValue::Float32(Some(*v))
- }
- protobuf::scalar_value::Value::Float64Value(v) => {
- ScalarValue::Float64(Some(*v))
- }
- protobuf::scalar_value::Value::Date32Value(v) => {
- ScalarValue::Date32(Some(*v))
- }
- protobuf::scalar_value::Value::TimeMicrosecondValue(v) => {
- ScalarValue::TimestampMicrosecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::TimeNanosecondValue(v) => {
- ScalarValue::TimestampNanosecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::ListValue(v) => v.try_into()?,
- protobuf::scalar_value::Value::NullListValue(v) => {
- ScalarValue::List(None, Box::new(v.try_into()?))
- }
- protobuf::scalar_value::Value::NullValue(null_enum) => {
- PrimitiveScalarType::from_i32(*null_enum)
- .ok_or_else(|| proto_error("Invalid scalar type"))?
- .try_into()?
- }
- protobuf::scalar_value::Value::Decimal128Value(val) => {
- let array = vec_to_array(val.value.clone());
- ScalarValue::Decimal128(
- Some(i128::from_be_bytes(array)),
- val.p as usize,
- val.s as usize,
- )
- }
- protobuf::scalar_value::Value::Date64Value(v) => {
- ScalarValue::Date64(Some(*v))
- }
- protobuf::scalar_value::Value::TimeSecondValue(v) => {
- ScalarValue::TimestampSecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::TimeMillisecondValue(v) => {
- ScalarValue::TimestampMillisecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::IntervalYearmonthValue(v) => {
- ScalarValue::IntervalYearMonth(Some(*v))
- }
- protobuf::scalar_value::Value::IntervalDaytimeValue(v) => {
- ScalarValue::IntervalDayTime(Some(*v))
- }
- };
- Ok(scalar)
- }
-}
-
-impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarListValue {
- type Error = BallistaError;
- fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
- use protobuf::scalar_type::Datatype;
- use protobuf::PrimitiveScalarType;
- let protobuf::ScalarListValue { datatype, values } = self;
- let pb_scalar_type = datatype
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: ScalarListValue messsage missing required field 'datatype'"))?;
- let scalar_type = pb_scalar_type
- .datatype
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: ScalarListValue.Datatype messsage missing required field 'datatype'"))?;
- let scalar_values = match scalar_type {
- Datatype::Scalar(scalar_type_i32) => {
- let leaf_scalar_type =
- protobuf::PrimitiveScalarType::from_i32(*scalar_type_i32)
- .ok_or_else(|| {
- proto_error("Error converting i32 to basic scalar type")
- })?;
- let typechecked_values: Vec<datafusion::scalar::ScalarValue> = values
- .iter()
- .map(|protobuf::ScalarValue { value: opt_value }| {
- let value = opt_value.as_ref().ok_or_else(|| {
- proto_error(
- "Protobuf deserialization error: missing required field 'value'",
- )
- })?;
- typechecked_scalar_value_conversion(value, leaf_scalar_type)
- })
- .collect::<Result<Vec<_>, _>>()?;
- datafusion::scalar::ScalarValue::List(
- Some(Box::new(typechecked_values)),
- Box::new(leaf_scalar_type.into()),
- )
- }
- Datatype::List(list_type) => {
- let protobuf::ScalarListType {
- deepest_type,
- field_names,
- } = &list_type;
- let leaf_type =
- PrimitiveScalarType::from_i32(*deepest_type).ok_or_else(|| {
- proto_error("Error converting i32 to basic scalar type")
- })?;
- let depth = field_names.len();
-
- let typechecked_values: Vec<datafusion::scalar::ScalarValue> = if depth
- == 0
- {
- return Err(proto_error(
- "Protobuf deserialization error, ScalarListType had no field names, requires at least one",
- ));
- } else if depth == 1 {
- values
- .iter()
- .map(|protobuf::ScalarValue { value: opt_value }| {
- let value = opt_value
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: missing required field 'value'"))?;
- typechecked_scalar_value_conversion(value, leaf_type)
- })
- .collect::<Result<Vec<_>, _>>()?
- } else {
- values
- .iter()
- .map(|protobuf::ScalarValue { value: opt_value }| {
- let value = opt_value
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: missing required field 'value'"))?;
- value.try_into()
- })
- .collect::<Result<Vec<_>, _>>()?
- };
- datafusion::scalar::ScalarValue::List(
- match typechecked_values.len() {
- 0 => None,
- _ => Some(Box::new(typechecked_values)),
- },
- Box::new(list_type.try_into()?),
- )
- }
- };
- Ok(scalar_values)
- }
-}
-
-impl TryInto<DataType> for &protobuf::ScalarListType {
- type Error = BallistaError;
- fn try_into(self) -> Result<DataType, Self::Error> {
- use protobuf::PrimitiveScalarType;
- let protobuf::ScalarListType {
- deepest_type,
- field_names,
- } = self;
-
- let depth = field_names.len();
- if depth == 0 {
- return Err(proto_error(
- "Protobuf deserialization error: Found a ScalarListType message with no field names, at least one is required",
- ));
- }
-
- let mut curr_type = DataType::List(Box::new(Field::new(
- //Since checked vector is not empty above this is safe to unwrap
- field_names.last().unwrap(),
- PrimitiveScalarType::from_i32(*deepest_type)
- .ok_or_else(|| {
- proto_error("Could not convert to datafusion scalar type")
- })?
- .into(),
- true,
- )));
- //Iterates over field names in reverse order except for the last item in the vector
- for name in field_names.iter().rev().skip(1) {
- let temp_curr_type =
- DataType::List(Box::new(Field::new(name, curr_type, true)));
- curr_type = temp_curr_type;
- }
- Ok(curr_type)
- }
-}
-
-impl TryInto<datafusion::scalar::ScalarValue> for protobuf::PrimitiveScalarType {
- type Error = BallistaError;
- fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
- Ok(match self {
- protobuf::PrimitiveScalarType::Null => {
- return Err(proto_error("Untyped null is an invalid scalar value"))
- }
- protobuf::PrimitiveScalarType::Bool => ScalarValue::Boolean(None),
- protobuf::PrimitiveScalarType::Uint8 => ScalarValue::UInt8(None),
- protobuf::PrimitiveScalarType::Int8 => ScalarValue::Int8(None),
- protobuf::PrimitiveScalarType::Uint16 => ScalarValue::UInt16(None),
- protobuf::PrimitiveScalarType::Int16 => ScalarValue::Int16(None),
- protobuf::PrimitiveScalarType::Uint32 => ScalarValue::UInt32(None),
- protobuf::PrimitiveScalarType::Int32 => ScalarValue::Int32(None),
- protobuf::PrimitiveScalarType::Uint64 => ScalarValue::UInt64(None),
- protobuf::PrimitiveScalarType::Int64 => ScalarValue::Int64(None),
- protobuf::PrimitiveScalarType::Float32 => ScalarValue::Float32(None),
- protobuf::PrimitiveScalarType::Float64 => ScalarValue::Float64(None),
- protobuf::PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),
- protobuf::PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),
- protobuf::PrimitiveScalarType::Date32 => ScalarValue::Date32(None),
- protobuf::PrimitiveScalarType::TimeMicrosecond => {
- ScalarValue::TimestampMicrosecond(None, None)
- }
- protobuf::PrimitiveScalarType::TimeNanosecond => {
- ScalarValue::TimestampNanosecond(None, None)
- }
- protobuf::PrimitiveScalarType::Decimal128 => {
- ScalarValue::Decimal128(None, 0, 0)
- }
- protobuf::PrimitiveScalarType::Date64 => ScalarValue::Date64(None),
- protobuf::PrimitiveScalarType::TimeSecond => {
- ScalarValue::TimestampSecond(None, None)
- }
- protobuf::PrimitiveScalarType::TimeMillisecond => {
- ScalarValue::TimestampMillisecond(None, None)
- }
- protobuf::PrimitiveScalarType::IntervalYearmonth => {
- ScalarValue::IntervalYearMonth(None)
- }
- protobuf::PrimitiveScalarType::IntervalDaytime => {
- ScalarValue::IntervalDayTime(None)
- }
- })
- }
-}
-
-impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarValue {
- type Error = BallistaError;
- fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
- let value = self.value.as_ref().ok_or_else(|| {
- proto_error("Protobuf deserialization error: missing required field 'value'")
- })?;
- Ok(match value {
- protobuf::scalar_value::Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),
- protobuf::scalar_value::Value::Utf8Value(v) => {
- ScalarValue::Utf8(Some(v.to_owned()))
- }
- protobuf::scalar_value::Value::LargeUtf8Value(v) => {
- ScalarValue::LargeUtf8(Some(v.to_owned()))
- }
- protobuf::scalar_value::Value::Int8Value(v) => {
- ScalarValue::Int8(Some(*v as i8))
- }
- protobuf::scalar_value::Value::Int16Value(v) => {
- ScalarValue::Int16(Some(*v as i16))
- }
- protobuf::scalar_value::Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),
- protobuf::scalar_value::Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),
- protobuf::scalar_value::Value::Uint8Value(v) => {
- ScalarValue::UInt8(Some(*v as u8))
- }
- protobuf::scalar_value::Value::Uint16Value(v) => {
- ScalarValue::UInt16(Some(*v as u16))
- }
- protobuf::scalar_value::Value::Uint32Value(v) => {
- ScalarValue::UInt32(Some(*v))
- }
- protobuf::scalar_value::Value::Uint64Value(v) => {
- ScalarValue::UInt64(Some(*v))
- }
- protobuf::scalar_value::Value::Float32Value(v) => {
- ScalarValue::Float32(Some(*v))
- }
- protobuf::scalar_value::Value::Float64Value(v) => {
- ScalarValue::Float64(Some(*v))
- }
- protobuf::scalar_value::Value::Date32Value(v) => {
- ScalarValue::Date32(Some(*v))
- }
- protobuf::scalar_value::Value::TimeMicrosecondValue(v) => {
- ScalarValue::TimestampMicrosecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::TimeNanosecondValue(v) => {
- ScalarValue::TimestampNanosecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::ListValue(scalar_list) => {
- let protobuf::ScalarListValue {
- values,
- datatype: opt_scalar_type,
- } = &scalar_list;
- let pb_scalar_type = opt_scalar_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization err: ScalaListValue missing required field 'datatype'"))?;
- let typechecked_values: Vec<ScalarValue> = values
- .iter()
- .map(|val| val.try_into())
- .collect::<Result<Vec<_>, _>>()?;
- let scalar_type: DataType = pb_scalar_type.try_into()?;
- let scalar_type = Box::new(scalar_type);
- ScalarValue::List(Some(Box::new(typechecked_values)), scalar_type)
- }
- protobuf::scalar_value::Value::NullListValue(v) => {
- let pb_datatype = v
- .datatype
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: NullListValue message missing required field 'datatyp'"))?;
- let pb_datatype = Box::new(pb_datatype.try_into()?);
- ScalarValue::List(None, pb_datatype)
- }
- protobuf::scalar_value::Value::NullValue(v) => {
- let null_type_enum = protobuf::PrimitiveScalarType::from_i32(*v)
- .ok_or_else(|| proto_error("Protobuf deserialization error found invalid enum variant for DatafusionScalar"))?;
- null_type_enum.try_into()?
- }
- protobuf::scalar_value::Value::Decimal128Value(val) => {
- let array = vec_to_array(val.value.clone());
- ScalarValue::Decimal128(
- Some(i128::from_be_bytes(array)),
- val.p as usize,
- val.s as usize,
- )
- }
- protobuf::scalar_value::Value::Date64Value(v) => {
- ScalarValue::Date64(Some(*v))
- }
- protobuf::scalar_value::Value::TimeSecondValue(v) => {
- ScalarValue::TimestampSecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::TimeMillisecondValue(v) => {
- ScalarValue::TimestampMillisecond(Some(*v), None)
- }
- protobuf::scalar_value::Value::IntervalYearmonthValue(v) => {
- ScalarValue::IntervalYearMonth(Some(*v))
- }
- protobuf::scalar_value::Value::IntervalDaytimeValue(v) => {
- ScalarValue::IntervalDayTime(Some(*v))
- }
- })
- }
-}
-
-impl TryInto<Expr> for &protobuf::LogicalExprNode {
- type Error = BallistaError;
-
- fn try_into(self) -> Result<Expr, Self::Error> {
- use datafusion::physical_plan::window_functions;
- use protobuf::logical_expr_node::ExprType;
- use protobuf::window_expr_node;
-
- let expr_type = self
- .expr_type
- .as_ref()
- .ok_or_else(|| proto_error("Unexpected empty logical expression"))?;
- match expr_type {
- ExprType::BinaryExpr(binary_expr) => Ok(Expr::BinaryExpr {
- left: Box::new(parse_required_expr(&binary_expr.l)?),
- op: from_proto_binary_op(&binary_expr.op)?,
- right: Box::new(parse_required_expr(&binary_expr.r)?),
- }),
- ExprType::Column(column) => Ok(Expr::Column(column.into())),
- ExprType::Literal(literal) => {
- let scalar_value: datafusion::scalar::ScalarValue = literal.try_into()?;
- Ok(Expr::Literal(scalar_value))
- }
- ExprType::WindowExpr(expr) => {
- let window_function = expr
- .window_function
- .as_ref()
- .ok_or_else(|| proto_error("Received empty window function"))?;
- let partition_by = expr
- .partition_by
- .iter()
- .map(|e| e.try_into())
- .collect::<Result<Vec<_>, _>>()?;
- let order_by = expr
- .order_by
- .iter()
- .map(|e| e.try_into())
- .collect::<Result<Vec<_>, _>>()?;
- let window_frame = expr
- .window_frame
- .as_ref()
- .map::<Result<WindowFrame, _>, _>(|e| match e {
- window_expr_node::WindowFrame::Frame(frame) => {
- let window_frame: WindowFrame = frame.clone().try_into()?;
- if WindowFrameUnits::Range == window_frame.units
- && order_by.len() != 1
- {
- Err(proto_error("With window frame of type RANGE, the order by expression must be of length 1"))
- } else {
- Ok(window_frame)
- }
- }
- })
- .transpose()?;
-
- match window_function {
- window_expr_node::WindowFunction::AggrFunction(i) => {
- let aggr_function = protobuf::AggregateFunction::from_i32(*i)
- .ok_or_else(|| {
- proto_error(format!(
- "Received an unknown aggregate window function: {}",
- i
- ))
- })?;
-
- Ok(Expr::WindowFunction {
- fun: window_functions::WindowFunction::AggregateFunction(
- AggregateFunction::from(aggr_function),
- ),
- args: vec![parse_required_expr(&expr.expr)?],
- partition_by,
- order_by,
- window_frame,
- })
- }
- window_expr_node::WindowFunction::BuiltInFunction(i) => {
- let built_in_function =
- protobuf::BuiltInWindowFunction::from_i32(*i).ok_or_else(
- || {
- proto_error(format!(
- "Received an unknown built-in window function: {}",
- i
- ))
- },
- )?;
-
- Ok(Expr::WindowFunction {
- fun: window_functions::WindowFunction::BuiltInWindowFunction(
- BuiltInWindowFunction::from(built_in_function),
- ),
- args: vec![parse_required_expr(&expr.expr)?],
- partition_by,
- order_by,
- window_frame,
- })
- }
- }
- }
- ExprType::AggregateExpr(expr) => {
- let aggr_function =
- protobuf::AggregateFunction::from_i32(expr.aggr_function)
- .ok_or_else(|| {
- proto_error(format!(
- "Received an unknown aggregate function: {}",
- expr.aggr_function
- ))
- })?;
- let fun = AggregateFunction::from(aggr_function);
-
- Ok(Expr::AggregateFunction {
- fun,
- args: expr
- .expr
- .iter()
- .map(|e| e.try_into())
- .collect::<Result<Vec<_>, _>>()?,
- distinct: false, //TODO
- })
- }
- ExprType::Alias(alias) => Ok(Expr::Alias(
- Box::new(parse_required_expr(&alias.expr)?),
- alias.alias.clone(),
- )),
- ExprType::IsNullExpr(is_null) => {
- Ok(Expr::IsNull(Box::new(parse_required_expr(&is_null.expr)?)))
- }
- ExprType::IsNotNullExpr(is_not_null) => Ok(Expr::IsNotNull(Box::new(
- parse_required_expr(&is_not_null.expr)?,
- ))),
- ExprType::NotExpr(not) => {
- Ok(Expr::Not(Box::new(parse_required_expr(&not.expr)?)))
- }
- ExprType::Between(between) => Ok(Expr::Between {
- expr: Box::new(parse_required_expr(&between.expr)?),
- negated: between.negated,
- low: Box::new(parse_required_expr(&between.low)?),
- high: Box::new(parse_required_expr(&between.high)?),
- }),
- ExprType::Case(case) => {
- let when_then_expr = case
- .when_then_expr
- .iter()
- .map(|e| {
- Ok((
- Box::new(match &e.when_expr {
- Some(e) => e.try_into(),
- None => Err(proto_error("Missing required expression")),
- }?),
- Box::new(match &e.then_expr {
- Some(e) => e.try_into(),
- None => Err(proto_error("Missing required expression")),
- }?),
- ))
- })
- .collect::<Result<Vec<(Box<Expr>, Box<Expr>)>, BallistaError>>()?;
- Ok(Expr::Case {
- expr: parse_optional_expr(&case.expr)?.map(Box::new),
- when_then_expr,
- else_expr: parse_optional_expr(&case.else_expr)?.map(Box::new),
- })
- }
- ExprType::Cast(cast) => {
- let expr = Box::new(parse_required_expr(&cast.expr)?);
- let arrow_type: &protobuf::ArrowType = cast
- .arrow_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: CastNode message missing required field 'arrow_type'"))?;
- let data_type = arrow_type.try_into()?;
- Ok(Expr::Cast { expr, data_type })
- }
- ExprType::TryCast(cast) => {
- let expr = Box::new(parse_required_expr(&cast.expr)?);
- let arrow_type: &protobuf::ArrowType = cast
- .arrow_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: CastNode message missing required field 'arrow_type'"))?;
- let data_type = arrow_type.try_into()?;
- Ok(Expr::TryCast { expr, data_type })
- }
- ExprType::Sort(sort) => Ok(Expr::Sort {
- expr: Box::new(parse_required_expr(&sort.expr)?),
- asc: sort.asc,
- nulls_first: sort.nulls_first,
- }),
- ExprType::Negative(negative) => Ok(Expr::Negative(Box::new(
- parse_required_expr(&negative.expr)?,
- ))),
- ExprType::InList(in_list) => Ok(Expr::InList {
- expr: Box::new(parse_required_expr(&in_list.expr)?),
- list: in_list
- .list
- .iter()
- .map(|expr| expr.try_into())
- .collect::<Result<Vec<_>, _>>()?,
- negated: in_list.negated,
- }),
- ExprType::Wildcard(_) => Ok(Expr::Wildcard),
- ExprType::ScalarFunction(expr) => {
- let scalar_function = protobuf::ScalarFunction::from_i32(expr.fun)
- .ok_or_else(|| {
- proto_error(format!(
- "Received an unknown scalar function: {}",
- expr.fun
- ))
- })?;
- let args = &expr.args;
-
- match scalar_function {
- protobuf::ScalarFunction::Sqrt => Ok(sqrt((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Sin => Ok(sin((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Cos => Ok(cos((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Tan => Ok(tan((&args[0]).try_into()?)),
- // protobuf::ScalarFunction::Asin => Ok(asin(&args[0]).try_into()?)),
- // protobuf::ScalarFunction::Acos => Ok(acos(&args[0]).try_into()?)),
- protobuf::ScalarFunction::Atan => Ok(atan((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Exp => Ok(exp((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Log2 => Ok(log2((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Ln => Ok(ln((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Log10 => Ok(log10((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Floor => Ok(floor((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Ceil => Ok(ceil((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Round => Ok(round((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Trunc => Ok(trunc((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Abs => Ok(abs((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Signum => {
- Ok(signum((&args[0]).try_into()?))
- }
- protobuf::ScalarFunction::Octetlength => {
- Ok(octet_length((&args[0]).try_into()?))
- }
- // // protobuf::ScalarFunction::Concat => Ok(concat((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Lower => Ok(lower((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Upper => Ok(upper((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Trim => Ok(trim((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Ltrim => Ok(ltrim((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Rtrim => Ok(rtrim((&args[0]).try_into()?)),
- // protobuf::ScalarFunction::Totimestamp => Ok(to_timestamp((&args[0]).try_into()?)),
- // protobuf::ScalarFunction::Array => Ok(array((&args[0]).try_into()?)),
- // // protobuf::ScalarFunction::Nullif => Ok(nulli((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Datepart => {
- Ok(date_part((&args[0]).try_into()?, (&args[1]).try_into()?))
- }
- protobuf::ScalarFunction::Datetrunc => {
- Ok(date_trunc((&args[0]).try_into()?, (&args[1]).try_into()?))
- }
- // protobuf::ScalarFunction::Md5 => Ok(md5((&args[0]).try_into()?)),
- protobuf::ScalarFunction::Sha224 => {
- Ok(sha224((&args[0]).try_into()?))
- }
- protobuf::ScalarFunction::Sha256 => {
- Ok(sha256((&args[0]).try_into()?))
- }
- protobuf::ScalarFunction::Sha384 => {
- Ok(sha384((&args[0]).try_into()?))
- }
- protobuf::ScalarFunction::Sha512 => {
- Ok(sha512((&args[0]).try_into()?))
- }
- protobuf::ScalarFunction::Digest => {
- Ok(digest((&args[0]).try_into()?, (&args[1]).try_into()?))
- }
- _ => Err(proto_error(
- "Protobuf deserialization error: Unsupported scalar function",
- )),
- }
- }
- }
- }
-}
-
-impl TryInto<DataType> for &protobuf::ScalarType {
- type Error = BallistaError;
- fn try_into(self) -> Result<DataType, Self::Error> {
- let pb_scalartype = self.datatype.as_ref().ok_or_else(|| {
- proto_error("ScalarType message missing required field 'datatype'")
- })?;
- pb_scalartype.try_into()
- }
-}
-
-impl TryInto<Schema> for &protobuf::Schema {
- type Error = BallistaError;
-
- fn try_into(self) -> Result<Schema, BallistaError> {
- let fields = self
- .columns
- .iter()
- .map(|c| {
- let pb_arrow_type_res = c
- .arrow_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: Field message was missing required field 'arrow_type'"));
- let pb_arrow_type: &protobuf::ArrowType = match pb_arrow_type_res {
- Ok(res) => res,
- Err(e) => return Err(e),
- };
- Ok(Field::new(&c.name, pb_arrow_type.try_into()?, c.nullable))
- })
- .collect::<Result<Vec<_>, _>>()?;
- Ok(Schema::new(fields))
- }
-}
-
-impl TryInto<Field> for &protobuf::Field {
- type Error = BallistaError;
- fn try_into(self) -> Result<Field, Self::Error> {
- let pb_datatype = self.arrow_type.as_ref().ok_or_else(|| {
- proto_error(
- "Protobuf deserialization error: Field message missing required field 'arrow_type'",
- )
- })?;
-
- Ok(Field::new(
- self.name.as_str(),
- pb_datatype.as_ref().try_into()?,
- self.nullable,
- ))
- }
-}
-
-use datafusion::prelude::{
- date_part, date_trunc, lower, ltrim, rtrim, sha224, sha256, sha384, sha512, trim,
- upper,
-};
+use crate::serde::protobuf;
use std::convert::TryFrom;
impl TryFrom<i32> for protobuf::FileType {
@@ -991,96 +50,3 @@ impl Into<datafusion::sql::parser::FileType> for protobuf::FileType {
}
}
}
-
-fn parse_required_expr(
- p: &Option<Box<protobuf::LogicalExprNode>>,
-) -> Result<Expr, BallistaError> {
- match p {
- Some(expr) => expr.as_ref().try_into(),
- None => Err(proto_error("Missing required expression")),
- }
-}
-
-fn parse_optional_expr(
- p: &Option<Box<protobuf::LogicalExprNode>>,
-) -> Result<Option<Expr>, BallistaError> {
- match p {
- Some(expr) => expr.as_ref().try_into().map(Some),
- None => Ok(None),
- }
-}
-
-impl From<protobuf::WindowFrameUnits> for WindowFrameUnits {
- fn from(units: protobuf::WindowFrameUnits) -> Self {
- match units {
- protobuf::WindowFrameUnits::Rows => WindowFrameUnits::Rows,
- protobuf::WindowFrameUnits::Range => WindowFrameUnits::Range,
- protobuf::WindowFrameUnits::Groups => WindowFrameUnits::Groups,
- }
- }
-}
-
-impl TryFrom<protobuf::WindowFrameBound> for WindowFrameBound {
- type Error = BallistaError;
-
- fn try_from(bound: protobuf::WindowFrameBound) -> Result<Self, Self::Error> {
- let bound_type = protobuf::WindowFrameBoundType::from_i32(bound.window_frame_bound_type).ok_or_else(|| {
- proto_error(format!(
- "Received a WindowFrameBound message with unknown WindowFrameBoundType {}",
- bound.window_frame_bound_type
- ))
- })?;
- match bound_type {
- protobuf::WindowFrameBoundType::CurrentRow => {
- Ok(WindowFrameBound::CurrentRow)
- }
- protobuf::WindowFrameBoundType::Preceding => {
- // FIXME implement bound value parsing
- // https://github.com/apache/arrow-datafusion/issues/361
- Ok(WindowFrameBound::Preceding(Some(1)))
- }
- protobuf::WindowFrameBoundType::Following => {
- // FIXME implement bound value parsing
- // https://github.com/apache/arrow-datafusion/issues/361
- Ok(WindowFrameBound::Following(Some(1)))
- }
- }
- }
-}
-
-impl TryFrom<protobuf::WindowFrame> for WindowFrame {
- type Error = BallistaError;
-
- fn try_from(window: protobuf::WindowFrame) -> Result<Self, Self::Error> {
- let units = protobuf::WindowFrameUnits::from_i32(window.window_frame_units)
- .ok_or_else(|| {
- proto_error(format!(
- "Received a WindowFrame message with unknown WindowFrameUnits {}",
- window.window_frame_units
- ))
- })?
- .into();
- let start_bound = window
- .start_bound
- .ok_or_else(|| {
- proto_error(
- "Received a WindowFrame message with no start_bound".to_owned(),
- )
- })?
- .try_into()?;
- let end_bound = window
- .end_bound
- .map(|end_bound| match end_bound {
- protobuf::window_frame::EndBound::Bound(end_bound) => {
- end_bound.try_into()
- }
- })
- .transpose()?
- .unwrap_or(WindowFrameBound::CurrentRow);
- Ok(WindowFrame {
- units,
- start_bound,
- end_bound,
- })
- }
-}
diff --git a/ballista/rust/core/src/serde/logical_plan/mod.rs b/ballista/rust/core/src/serde/logical_plan/mod.rs
index f6e4627ab2..4970cd600a 100644
--- a/ballista/rust/core/src/serde/logical_plan/mod.rs
+++ b/ballista/rust/core/src/serde/logical_plan/mod.rs
@@ -47,7 +47,6 @@ use std::convert::TryInto;
use std::sync::Arc;
pub mod from_proto;
-pub mod to_proto;
impl AsLogicalPlan for LogicalPlanNode {
fn try_decode(buf: &[u8]) -> Result<Self, BallistaError>
@@ -96,11 +95,13 @@ impl AsLogicalPlan for LogicalPlanNode {
.values_list
.chunks_exact(n_cols)
.map(|r| {
- r.iter()
- .map(|v| v.try_into())
- .collect::<Result<Vec<_>, _>>()
+ r.iter().map(|v| v.try_into()).collect::<Result<
+ Vec<_>,
+ datafusion_proto::from_proto::Error,
+ >>()
})
.collect::<Result<Vec<_>, _>>()
+ .map_err(|e| e.into())
}?;
LogicalPlanBuilder::values(values)?
.build()
@@ -458,9 +459,9 @@ impl AsLogicalPlan for LogicalPlanNode {
})
}
};
- let schema: protobuf::Schema = schema.as_ref().into();
+ let schema: datafusion_proto::protobuf::Schema = schema.as_ref().into();
- let filters: Vec<protobuf::LogicalExprNode> = filters
+ let filters: Vec<datafusion_proto::protobuf::LogicalExprNode> = filters
.iter()
.map(|filter| filter.try_into())
.collect::<Result<Vec<_>, _>>()?;
@@ -531,7 +532,7 @@ impl AsLogicalPlan for LogicalPlanNode {
)),
expr: expr.iter().map(|expr| expr.try_into()).collect::<Result<
Vec<_>,
- BallistaError,
+ datafusion_proto::to_proto::Error,
>>(
)?,
optional_alias: alias
@@ -661,10 +662,10 @@ impl AsLogicalPlan for LogicalPlanNode {
input.as_ref(),
extension_codec,
)?;
- let selection_expr: Vec<protobuf::LogicalExprNode> = expr
- .iter()
- .map(|expr| expr.try_into())
- .collect::<Result<Vec<_>, BallistaError>>()?;
+ let selection_expr: Vec<datafusion_proto::protobuf::LogicalExprNode> =
+ expr.iter()
+ .map(|expr| expr.try_into())
+ .collect::<Result<Vec<_>, datafusion_proto::to_proto::Error>>()?;
Ok(protobuf::LogicalPlanNode {
logical_plan_type: Some(LogicalPlanType::Sort(Box::new(
protobuf::SortNode {
@@ -689,20 +690,24 @@ impl AsLogicalPlan for LogicalPlanNode {
//Used u64 to avoid any nastyness involving large values, most data clusters are probably uniformly 64 bits any ways
use protobuf::repartition_node::PartitionMethod;
- let pb_partition_method = match partitioning_scheme {
- Partitioning::Hash(exprs, partition_count) => {
- PartitionMethod::Hash(protobuf::HashRepartition {
- hash_expr: exprs
- .iter()
- .map(|expr| expr.try_into())
- .collect::<Result<Vec<_>, BallistaError>>()?,
- partition_count: *partition_count as u64,
- })
- }
- Partitioning::RoundRobinBatch(partition_count) => {
- PartitionMethod::RoundRobin(*partition_count as u64)
- }
- };
+ let pb_partition_method =
+ match partitioning_scheme {
+ Partitioning::Hash(exprs, partition_count) => {
+ PartitionMethod::Hash(protobuf::HashRepartition {
+ hash_expr: exprs
+ .iter()
+ .map(|expr| expr.try_into())
+ .collect::<Result<
+ Vec<_>,
+ datafusion_proto::to_proto::Error,
+ >>()?,
+ partition_count: *partition_count as u64,
+ })
+ }
+ Partitioning::RoundRobinBatch(partition_count) => {
+ PartitionMethod::RoundRobin(*partition_count as u64)
+ }
+ };
Ok(protobuf::LogicalPlanNode {
logical_plan_type: Some(LogicalPlanType::Repartition(Box::new(
@@ -854,19 +859,16 @@ mod roundtrip_tests {
};
use datafusion::error::DataFusionError;
use datafusion::{
- arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit, UnionMode},
+ arrow::datatypes::{DataType, Field, Schema},
datasource::object_store::local::LocalFileSystem,
logical_plan::{
col, CreateExternalTable, Expr, LogicalPlan, LogicalPlanBuilder, Repartition,
ToDFSchema,
},
- physical_plan::{aggregates, functions::BuiltinScalarFunction::Sqrt},
prelude::*,
- scalar::ScalarValue,
sql::parser::FileType,
};
-
- use std::{convert::TryInto, sync::Arc};
+ use std::sync::Arc;
#[derive(Debug)]
struct TestObjectStore {}
@@ -1020,532 +1022,6 @@ mod roundtrip_tests {
Ok(())
}
- fn new_box_field(name: &str, dt: DataType, nullable: bool) -> Box<Field> {
- Box::new(Field::new(name, dt, nullable))
- }
-
- #[test]
- fn scalar_values_error_serialization() -> Result<()> {
- let should_fail_on_seralize: Vec<ScalarValue> = vec![
- //Should fail due to inconsistent types
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::Int16(None),
- ScalarValue::Float32(Some(32.0)),
- ])),
- Box::new(DataType::List(new_box_field("item", DataType::Int16, true))),
- ),
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::Float32(None),
- ScalarValue::Float32(Some(32.0)),
- ])),
- Box::new(DataType::List(new_box_field("item", DataType::Int16, true))),
- ),
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::List(
- None,
- Box::new(DataType::List(new_box_field(
- "level2",
- DataType::Float32,
- true,
- ))),
- ),
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::Float32(Some(-213.1)),
- ScalarValue::Float32(None),
- ScalarValue::Float32(Some(5.5)),
- ScalarValue::Float32(Some(2.0)),
- ScalarValue::Float32(Some(1.0)),
- ])),
- Box::new(DataType::List(new_box_field(
- "level2",
- DataType::Float32,
- true,
- ))),
- ),
- ScalarValue::List(
- None,
- Box::new(DataType::List(new_box_field(
- "lists are typed inconsistently",
- DataType::Int16,
- true,
- ))),
- ),
- ])),
- Box::new(DataType::List(new_box_field(
- "level1",
- DataType::List(new_box_field("level2", DataType::Float32, true)),
- true,
- ))),
- ),
- ];
-
- for test_case in should_fail_on_seralize.into_iter() {
- let res: Result<protobuf::ScalarValue> = (&test_case).try_into();
- if let Ok(val) = res {
- return Err(BallistaError::General(format!(
- "The value {:?} should not have been able to serialize. Serialized to :{:?}",
- test_case, val
- )));
- }
- }
- Ok(())
- }
-
- #[test]
- fn round_trip_scalar_values() -> Result<()> {
- let should_pass: Vec<ScalarValue> = vec![
- ScalarValue::Boolean(None),
- ScalarValue::Float32(None),
- ScalarValue::Float64(None),
- ScalarValue::Int8(None),
- ScalarValue::Int16(None),
- ScalarValue::Int32(None),
- ScalarValue::Int64(None),
- ScalarValue::UInt8(None),
- ScalarValue::UInt16(None),
- ScalarValue::UInt32(None),
- ScalarValue::UInt64(None),
- ScalarValue::Utf8(None),
- ScalarValue::LargeUtf8(None),
- ScalarValue::List(None, Box::new(DataType::Boolean)),
- ScalarValue::Date32(None),
- ScalarValue::TimestampMicrosecond(None, None),
- ScalarValue::TimestampNanosecond(None, None),
- ScalarValue::Boolean(Some(true)),
- ScalarValue::Boolean(Some(false)),
- ScalarValue::Float32(Some(1.0)),
- ScalarValue::Float32(Some(f32::MAX)),
- ScalarValue::Float32(Some(f32::MIN)),
- ScalarValue::Float32(Some(-2000.0)),
- ScalarValue::Float64(Some(1.0)),
- ScalarValue::Float64(Some(f64::MAX)),
- ScalarValue::Float64(Some(f64::MIN)),
- ScalarValue::Float64(Some(-2000.0)),
- ScalarValue::Int8(Some(i8::MIN)),
- ScalarValue::Int8(Some(i8::MAX)),
- ScalarValue::Int8(Some(0)),
- ScalarValue::Int8(Some(-15)),
- ScalarValue::Int16(Some(i16::MIN)),
- ScalarValue::Int16(Some(i16::MAX)),
- ScalarValue::Int16(Some(0)),
- ScalarValue::Int16(Some(-15)),
- ScalarValue::Int32(Some(i32::MIN)),
- ScalarValue::Int32(Some(i32::MAX)),
- ScalarValue::Int32(Some(0)),
- ScalarValue::Int32(Some(-15)),
- ScalarValue::Int64(Some(i64::MIN)),
- ScalarValue::Int64(Some(i64::MAX)),
- ScalarValue::Int64(Some(0)),
- ScalarValue::Int64(Some(-15)),
- ScalarValue::UInt8(Some(u8::MAX)),
- ScalarValue::UInt8(Some(0)),
- ScalarValue::UInt16(Some(u16::MAX)),
- ScalarValue::UInt16(Some(0)),
- ScalarValue::UInt32(Some(u32::MAX)),
- ScalarValue::UInt32(Some(0)),
- ScalarValue::UInt64(Some(u64::MAX)),
- ScalarValue::UInt64(Some(0)),
- ScalarValue::Utf8(Some(String::from("Test string "))),
- ScalarValue::LargeUtf8(Some(String::from("Test Large utf8"))),
- ScalarValue::Date32(Some(0)),
- ScalarValue::Date32(Some(i32::MAX)),
- ScalarValue::TimestampNanosecond(Some(0), None),
- ScalarValue::TimestampNanosecond(Some(i64::MAX), None),
- ScalarValue::TimestampMicrosecond(Some(0), None),
- ScalarValue::TimestampMicrosecond(Some(i64::MAX), None),
- ScalarValue::TimestampMicrosecond(None, None),
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::Float32(Some(-213.1)),
- ScalarValue::Float32(None),
- ScalarValue::Float32(Some(5.5)),
- ScalarValue::Float32(Some(2.0)),
- ScalarValue::Float32(Some(1.0)),
- ])),
- Box::new(DataType::List(new_box_field(
- "level1",
- DataType::Float32,
- true,
- ))),
- ),
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::List(
- None,
- Box::new(DataType::List(new_box_field(
- "level2",
- DataType::Float32,
- true,
- ))),
- ),
- ScalarValue::List(
- Some(Box::new(vec![
- ScalarValue::Float32(Some(-213.1)),
- ScalarValue::Float32(None),
- ScalarValue::Float32(Some(5.5)),
- ScalarValue::Float32(Some(2.0)),
- ScalarValue::Float32(Some(1.0)),
- ])),
- Box::new(DataType::List(new_box_field(
- "level2",
- DataType::Float32,
- true,
- ))),
- ),
- ])),
- Box::new(DataType::List(new_box_field(
- "level1",
- DataType::List(new_box_field("level2", DataType::Float32, true)),
- true,
- ))),
- ),
- ];
-
- for test_case in should_pass.into_iter() {
- let proto: protobuf::ScalarValue = (&test_case).try_into()?;
- let _roundtrip: ScalarValue = (&proto).try_into()?;
- }
-
- Ok(())
- }
-
- #[test]
- fn round_trip_scalar_types() -> Result<()> {
- let should_pass: Vec<DataType> = vec![
- DataType::Boolean,
- DataType::Int8,
- DataType::Int16,
- DataType::Int32,
- DataType::Int64,
- DataType::UInt8,
- DataType::UInt16,
- DataType::UInt32,
- DataType::UInt64,
- DataType::Float32,
- DataType::Float64,
- DataType::Date32,
- DataType::Time64(TimeUnit::Microsecond),
- DataType::Time64(TimeUnit::Nanosecond),
- DataType::Utf8,
- DataType::LargeUtf8,
- //Recursive list tests
- DataType::List(new_box_field("Level1", DataType::Boolean, true)),
- DataType::List(new_box_field(
- "Level1",
- DataType::List(new_box_field("Level2", DataType::Date32, true)),
- true,
- )),
- ];
-
- let should_fail: Vec<DataType> = vec![
- DataType::Null,
- DataType::Float16,
- //Add more timestamp tests
- DataType::Timestamp(TimeUnit::Millisecond, None),
- DataType::Date64,
- DataType::Time32(TimeUnit::Second),
- DataType::Time32(TimeUnit::Millisecond),
- DataType::Time32(TimeUnit::Microsecond),
- DataType::Time32(TimeUnit::Nanosecond),
- DataType::Time64(TimeUnit::Second),
- DataType::Time64(TimeUnit::Millisecond),
- DataType::Duration(TimeUnit::Second),
- DataType::Duration(TimeUnit::Millisecond),
- DataType::Duration(TimeUnit::Microsecond),
- DataType::Duration(TimeUnit::Nanosecond),
- DataType::Interval(IntervalUnit::YearMonth),
- DataType::Interval(IntervalUnit::DayTime),
- DataType::Binary,
- DataType::FixedSizeBinary(0),
- DataType::FixedSizeBinary(1234),
- DataType::FixedSizeBinary(-432),
- DataType::LargeBinary,
- DataType::Decimal(1345, 5431),
- //Recursive list tests
- DataType::List(new_box_field("Level1", DataType::Binary, true)),
- DataType::List(new_box_field(
- "Level1",
- DataType::List(new_box_field(
- "Level2",
- DataType::FixedSizeBinary(53),
- false,
- )),
- true,
- )),
- //Fixed size lists
- DataType::FixedSizeList(new_box_field("Level1", DataType::Binary, true), 4),
- DataType::FixedSizeList(
- new_box_field(
- "Level1",
- DataType::List(new_box_field(
- "Level2",
- DataType::FixedSizeBinary(53),
- false,
- )),
- true,
- ),
- 41,
- ),
- //Struct Testing
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ]),
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- Field::new(
- "nested_struct",
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ]),
- true,
- ),
- ]),
- DataType::Union(
- vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ],
- UnionMode::Dense,
- ),
- DataType::Union(
- vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- Field::new(
- "nested_struct",
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ]),
- true,
- ),
- ],
- UnionMode::Sparse,
- ),
- DataType::Dictionary(
- Box::new(DataType::Utf8),
- Box::new(DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ])),
- ),
- DataType::Dictionary(
- Box::new(DataType::Decimal(10, 50)),
- Box::new(DataType::FixedSizeList(
- new_box_field("Level1", DataType::Binary, true),
- 4,
- )),
- ),
- ];
-
- for test_case in should_pass.into_iter() {
- let proto: protobuf::ScalarType = (&test_case).try_into()?;
- let roundtrip: DataType = (&proto).try_into()?;
- assert_eq!(format!("{:?}", test_case), format!("{:?}", roundtrip));
- }
-
- let mut success: Vec<DataType> = Vec::new();
- for test_case in should_fail.into_iter() {
- let proto: Result<protobuf::ScalarType> = (&test_case).try_into();
- if proto.is_ok() {
- success.push(test_case)
- }
- }
- if !success.is_empty() {
- return Err(BallistaError::General(format!(
- "The following items which should have ressulted in an error completed successfully: {:?}",
- success
- )));
- }
- Ok(())
- }
-
- #[test]
- fn round_trip_datatype() -> Result<()> {
- let test_cases: Vec<DataType> = vec![
- DataType::Null,
- DataType::Boolean,
- DataType::Int8,
- DataType::Int16,
- DataType::Int32,
- DataType::Int64,
- DataType::UInt8,
- DataType::UInt16,
- DataType::UInt32,
- DataType::UInt64,
- DataType::Float16,
- DataType::Float32,
- DataType::Float64,
- //Add more timestamp tests
- DataType::Timestamp(TimeUnit::Millisecond, None),
- DataType::Date32,
- DataType::Date64,
- DataType::Time32(TimeUnit::Second),
- DataType::Time32(TimeUnit::Millisecond),
- DataType::Time32(TimeUnit::Microsecond),
- DataType::Time32(TimeUnit::Nanosecond),
- DataType::Time64(TimeUnit::Second),
- DataType::Time64(TimeUnit::Millisecond),
- DataType::Time64(TimeUnit::Microsecond),
- DataType::Time64(TimeUnit::Nanosecond),
- DataType::Duration(TimeUnit::Second),
- DataType::Duration(TimeUnit::Millisecond),
- DataType::Duration(TimeUnit::Microsecond),
- DataType::Duration(TimeUnit::Nanosecond),
- DataType::Interval(IntervalUnit::YearMonth),
- DataType::Interval(IntervalUnit::DayTime),
- DataType::Binary,
- DataType::FixedSizeBinary(0),
- DataType::FixedSizeBinary(1234),
- DataType::FixedSizeBinary(-432),
- DataType::LargeBinary,
- DataType::Utf8,
- DataType::LargeUtf8,
- DataType::Decimal(1345, 5431),
- //Recursive list tests
- DataType::List(new_box_field("Level1", DataType::Binary, true)),
- DataType::List(new_box_field(
- "Level1",
- DataType::List(new_box_field(
- "Level2",
- DataType::FixedSizeBinary(53),
- false,
- )),
- true,
- )),
- //Fixed size lists
- DataType::FixedSizeList(new_box_field("Level1", DataType::Binary, true), 4),
- DataType::FixedSizeList(
- new_box_field(
- "Level1",
- DataType::List(new_box_field(
- "Level2",
- DataType::FixedSizeBinary(53),
- false,
- )),
- true,
- ),
- 41,
- ),
- //Struct Testing
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ]),
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- Field::new(
- "nested_struct",
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ]),
- true,
- ),
- ]),
- DataType::Union(
- vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ],
- UnionMode::Sparse,
- ),
- DataType::Union(
- vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- Field::new(
- "nested_struct",
- DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ]),
- true,
- ),
- ],
- UnionMode::Dense,
- ),
- DataType::Dictionary(
- Box::new(DataType::Utf8),
- Box::new(DataType::Struct(vec![
- Field::new("nullable", DataType::Boolean, false),
- Field::new("name", DataType::Utf8, false),
- Field::new("datatype", DataType::Binary, false),
- ])),
- ),
- DataType::Dictionary(
- Box::new(DataType::Decimal(10, 50)),
- Box::new(DataType::FixedSizeList(
- new_box_field("Level1", DataType::Binary, true),
- 4,
- )),
- ),
- ];
-
- for test_case in test_cases.into_iter() {
- let proto: protobuf::ArrowType = (&test_case).into();
- let roundtrip: DataType = (&proto).try_into()?;
- assert_eq!(format!("{:?}", test_case), format!("{:?}", roundtrip));
- }
- Ok(())
- }
-
- #[test]
- fn roundtrip_null_scalar_values() -> Result<()> {
- let test_types = vec![
- ScalarValue::Boolean(None),
- ScalarValue::Float32(None),
- ScalarValue::Float64(None),
- ScalarValue::Int8(None),
- ScalarValue::Int16(None),
- ScalarValue::Int32(None),
- ScalarValue::Int64(None),
- ScalarValue::UInt8(None),
- ScalarValue::UInt16(None),
- ScalarValue::UInt32(None),
- ScalarValue::UInt64(None),
- ScalarValue::Utf8(None),
- ScalarValue::LargeUtf8(None),
- ScalarValue::Date32(None),
- ScalarValue::TimestampMicrosecond(None, None),
- ScalarValue::TimestampNanosecond(None, None),
- //ScalarValue::List(None, DataType::Boolean)
- ];
-
- for test_case in test_types.into_iter() {
- let proto_scalar: protobuf::ScalarValue = (&test_case).try_into()?;
- let returned_scalar: datafusion::scalar::ScalarValue =
- (&proto_scalar).try_into()?;
- assert_eq!(
- format!("{:?}", &test_case),
- format!("{:?}", returned_scalar)
- );
- }
-
- Ok(())
- }
-
#[test]
fn roundtrip_create_external_table() -> Result<()> {
let schema = Schema::new(vec![
@@ -1833,141 +1309,4 @@ mod roundtrip_tests {
Ok(())
}
-
- #[test]
- fn roundtrip_not() -> Result<()> {
- let test_expr = Expr::Not(Box::new(Expr::Literal((1.0).into())));
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_is_null() -> Result<()> {
- let test_expr = Expr::IsNull(Box::new(col("id")));
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_is_not_null() -> Result<()> {
- let test_expr = Expr::IsNotNull(Box::new(col("id")));
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_between() -> Result<()> {
- let test_expr = Expr::Between {
- expr: Box::new(Expr::Literal((1.0).into())),
- negated: true,
- low: Box::new(Expr::Literal((2.0).into())),
- high: Box::new(Expr::Literal((3.0).into())),
- };
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_case() -> Result<()> {
- let test_expr = Expr::Case {
- expr: Some(Box::new(Expr::Literal((1.0).into()))),
- when_then_expr: vec![(
- Box::new(Expr::Literal((2.0).into())),
- Box::new(Expr::Literal((3.0).into())),
- )],
- else_expr: Some(Box::new(Expr::Literal((4.0).into()))),
- };
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_cast() -> Result<()> {
- let test_expr = Expr::Cast {
- expr: Box::new(Expr::Literal((1.0).into())),
- data_type: DataType::Boolean,
- };
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_sort_expr() -> Result<()> {
- let test_expr = Expr::Sort {
- expr: Box::new(Expr::Literal((1.0).into())),
- asc: true,
- nulls_first: true,
- };
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_negative() -> Result<()> {
- let test_expr = Expr::Negative(Box::new(Expr::Literal((1.0).into())));
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_inlist() -> Result<()> {
- let test_expr = Expr::InList {
- expr: Box::new(Expr::Literal((1.0).into())),
- list: vec![Expr::Literal((2.0).into())],
- negated: true,
- };
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_wildcard() -> Result<()> {
- let test_expr = Expr::Wildcard;
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_sqrt() -> Result<()> {
- let test_expr = Expr::ScalarFunction {
- fun: Sqrt,
- args: vec![col("col")],
- };
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
-
- #[test]
- fn roundtrip_approx_percentile_cont() -> Result<()> {
- let test_expr = Expr::AggregateFunction {
- fun: aggregates::AggregateFunction::ApproxPercentileCont,
- args: vec![col("bananas"), lit(0.42)],
- distinct: false,
- };
-
- roundtrip_test!(test_expr, protobuf::LogicalExprNode, Expr);
-
- Ok(())
- }
}
diff --git a/ballista/rust/core/src/serde/mod.rs b/ballista/rust/core/src/serde/mod.rs
index 25a8b2879b..b85a957d43 100644
--- a/ballista/rust/core/src/serde/mod.rs
+++ b/ballista/rust/core/src/serde/mod.rs
@@ -24,10 +24,7 @@ use std::marker::PhantomData;
use std::sync::Arc;
use std::{convert::TryInto, io::Cursor};
-use datafusion::arrow::datatypes::{IntervalUnit, UnionMode};
use datafusion::logical_plan::{JoinConstraint, JoinType, LogicalPlan, Operator};
-use datafusion::physical_plan::aggregates::AggregateFunction;
-use datafusion::physical_plan::window_functions::BuiltInWindowFunction;
use crate::{error::BallistaError, serde::scheduler::Action as BallistaAction};
@@ -231,7 +228,7 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> BallistaCodec<T,
macro_rules! convert_required {
($PB:expr) => {{
if let Some(field) = $PB.as_ref() {
- field.try_into()
+ Ok(field.try_into()?)
} else {
Err(proto_error("Missing required field in protobuf"))
}
@@ -284,235 +281,6 @@ pub(crate) fn from_proto_binary_op(op: &str) -> Result<Operator, BallistaError>
}
}
-impl From<protobuf::AggregateFunction> for AggregateFunction {
- fn from(agg_fun: protobuf::AggregateFunction) -> AggregateFunction {
- match agg_fun {
- protobuf::AggregateFunction::Min => AggregateFunction::Min,
- protobuf::AggregateFunction::Max => AggregateFunction::Max,
- protobuf::AggregateFunction::Sum => AggregateFunction::Sum,
- protobuf::AggregateFunction::Avg => AggregateFunction::Avg,
- protobuf::AggregateFunction::Count => AggregateFunction::Count,
- protobuf::AggregateFunction::ApproxDistinct => {
- AggregateFunction::ApproxDistinct
- }
- protobuf::AggregateFunction::ArrayAgg => AggregateFunction::ArrayAgg,
- protobuf::AggregateFunction::Variance => AggregateFunction::Variance,
- protobuf::AggregateFunction::VariancePop => AggregateFunction::VariancePop,
- protobuf::AggregateFunction::Covariance => AggregateFunction::Covariance,
- protobuf::AggregateFunction::CovariancePop => {
- AggregateFunction::CovariancePop
- }
- protobuf::AggregateFunction::Stddev => AggregateFunction::Stddev,
- protobuf::AggregateFunction::StddevPop => AggregateFunction::StddevPop,
- protobuf::AggregateFunction::Correlation => AggregateFunction::Correlation,
- protobuf::AggregateFunction::ApproxPercentileCont => {
- AggregateFunction::ApproxPercentileCont
- }
- protobuf::AggregateFunction::ApproxMedian => AggregateFunction::ApproxMedian,
- }
- }
-}
-
-impl From<protobuf::BuiltInWindowFunction> for BuiltInWindowFunction {
- fn from(built_in_function: protobuf::BuiltInWindowFunction) -> Self {
- match built_in_function {
- protobuf::BuiltInWindowFunction::RowNumber => {
- BuiltInWindowFunction::RowNumber
- }
- protobuf::BuiltInWindowFunction::Rank => BuiltInWindowFunction::Rank,
- protobuf::BuiltInWindowFunction::PercentRank => {
- BuiltInWindowFunction::PercentRank
- }
- protobuf::BuiltInWindowFunction::DenseRank => {
- BuiltInWindowFunction::DenseRank
- }
- protobuf::BuiltInWindowFunction::Lag => BuiltInWindowFunction::Lag,
- protobuf::BuiltInWindowFunction::Lead => BuiltInWindowFunction::Lead,
- protobuf::BuiltInWindowFunction::FirstValue => {
- BuiltInWindowFunction::FirstValue
- }
- protobuf::BuiltInWindowFunction::CumeDist => BuiltInWindowFunction::CumeDist,
- protobuf::BuiltInWindowFunction::Ntile => BuiltInWindowFunction::Ntile,
- protobuf::BuiltInWindowFunction::NthValue => BuiltInWindowFunction::NthValue,
- protobuf::BuiltInWindowFunction::LastValue => {
- BuiltInWindowFunction::LastValue
- }
- }
- }
-}
-
-impl TryInto<datafusion::arrow::datatypes::DataType>
- for &protobuf::arrow_type::ArrowTypeEnum
-{
- type Error = BallistaError;
- fn try_into(self) -> Result<datafusion::arrow::datatypes::DataType, Self::Error> {
- use datafusion::arrow::datatypes::DataType;
- use protobuf::arrow_type;
- Ok(match self {
- arrow_type::ArrowTypeEnum::None(_) => DataType::Null,
- arrow_type::ArrowTypeEnum::Bool(_) => DataType::Boolean,
- arrow_type::ArrowTypeEnum::Uint8(_) => DataType::UInt8,
- arrow_type::ArrowTypeEnum::Int8(_) => DataType::Int8,
- arrow_type::ArrowTypeEnum::Uint16(_) => DataType::UInt16,
- arrow_type::ArrowTypeEnum::Int16(_) => DataType::Int16,
- arrow_type::ArrowTypeEnum::Uint32(_) => DataType::UInt32,
- arrow_type::ArrowTypeEnum::Int32(_) => DataType::Int32,
- arrow_type::ArrowTypeEnum::Uint64(_) => DataType::UInt64,
- arrow_type::ArrowTypeEnum::Int64(_) => DataType::Int64,
- arrow_type::ArrowTypeEnum::Float16(_) => DataType::Float16,
- arrow_type::ArrowTypeEnum::Float32(_) => DataType::Float32,
- arrow_type::ArrowTypeEnum::Float64(_) => DataType::Float64,
- arrow_type::ArrowTypeEnum::Utf8(_) => DataType::Utf8,
- arrow_type::ArrowTypeEnum::LargeUtf8(_) => DataType::LargeUtf8,
- arrow_type::ArrowTypeEnum::Binary(_) => DataType::Binary,
- arrow_type::ArrowTypeEnum::FixedSizeBinary(size) => {
- DataType::FixedSizeBinary(*size)
- }
- arrow_type::ArrowTypeEnum::LargeBinary(_) => DataType::LargeBinary,
- arrow_type::ArrowTypeEnum::Date32(_) => DataType::Date32,
- arrow_type::ArrowTypeEnum::Date64(_) => DataType::Date64,
- arrow_type::ArrowTypeEnum::Duration(time_unit) => {
- DataType::Duration(protobuf::TimeUnit::from_i32_to_arrow(*time_unit)?)
- }
- arrow_type::ArrowTypeEnum::Timestamp(protobuf::Timestamp {
- time_unit,
- timezone,
- }) => DataType::Timestamp(
- protobuf::TimeUnit::from_i32_to_arrow(*time_unit)?,
- match timezone.len() {
- 0 => None,
- _ => Some(timezone.to_owned()),
- },
- ),
- arrow_type::ArrowTypeEnum::Time32(time_unit) => {
- DataType::Time32(protobuf::TimeUnit::from_i32_to_arrow(*time_unit)?)
- }
- arrow_type::ArrowTypeEnum::Time64(time_unit) => {
- DataType::Time64(protobuf::TimeUnit::from_i32_to_arrow(*time_unit)?)
- }
- arrow_type::ArrowTypeEnum::Interval(interval_unit) => DataType::Interval(
- protobuf::IntervalUnit::from_i32_to_arrow(*interval_unit)?,
- ),
- arrow_type::ArrowTypeEnum::Decimal(protobuf::Decimal {
- whole,
- fractional,
- }) => DataType::Decimal(*whole as usize, *fractional as usize),
- arrow_type::ArrowTypeEnum::List(list) => {
- let list_type: &protobuf::Field = list
- .as_ref()
- .field_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: List message missing required field 'field_type'"))?
- .as_ref();
- DataType::List(Box::new(list_type.try_into()?))
- }
- arrow_type::ArrowTypeEnum::LargeList(list) => {
- let list_type: &protobuf::Field = list
- .as_ref()
- .field_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: List message missing required field 'field_type'"))?
- .as_ref();
- DataType::LargeList(Box::new(list_type.try_into()?))
- }
- arrow_type::ArrowTypeEnum::FixedSizeList(list) => {
- let list_type: &protobuf::Field = list
- .as_ref()
- .field_type
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: List message missing required field 'field_type'"))?
- .as_ref();
- let list_size = list.list_size;
- DataType::FixedSizeList(Box::new(list_type.try_into()?), list_size)
- }
- arrow_type::ArrowTypeEnum::Struct(strct) => DataType::Struct(
- strct
- .sub_field_types
- .iter()
- .map(|field| field.try_into())
- .collect::<Result<Vec<_>, _>>()?,
- ),
- arrow_type::ArrowTypeEnum::Union(union) => {
- let union_mode = protobuf::UnionMode::from_i32(union.union_mode)
- .ok_or_else(|| {
- proto_error(
- "Protobuf deserialization error: Unknown union mode type",
- )
- })?;
- let union_mode = match union_mode {
- protobuf::UnionMode::Dense => UnionMode::Dense,
- protobuf::UnionMode::Sparse => UnionMode::Sparse,
- };
- let union_types = union
- .union_types
- .iter()
- .map(|field| field.try_into())
- .collect::<Result<Vec<_>, _>>()?;
- DataType::Union(union_types, union_mode)
- }
- arrow_type::ArrowTypeEnum::Dictionary(dict) => {
- let pb_key_datatype = dict
- .as_ref()
- .key
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: Dictionary message missing required field 'key'"))?;
- let pb_value_datatype = dict
- .as_ref()
- .value
- .as_ref()
- .ok_or_else(|| proto_error("Protobuf deserialization error: Dictionary message missing required field 'key'"))?;
- let key_datatype: DataType = pb_key_datatype.as_ref().try_into()?;
- let value_datatype: DataType = pb_value_datatype.as_ref().try_into()?;
- DataType::Dictionary(Box::new(key_datatype), Box::new(value_datatype))
- }
- })
- }
-}
-
-#[allow(clippy::from_over_into)]
-impl Into<datafusion::arrow::datatypes::DataType> for protobuf::PrimitiveScalarType {
- fn into(self) -> datafusion::arrow::datatypes::DataType {
- use datafusion::arrow::datatypes::{DataType, TimeUnit};
- match self {
- protobuf::PrimitiveScalarType::Bool => DataType::Boolean,
- protobuf::PrimitiveScalarType::Uint8 => DataType::UInt8,
- protobuf::PrimitiveScalarType::Int8 => DataType::Int8,
- protobuf::PrimitiveScalarType::Uint16 => DataType::UInt16,
- protobuf::PrimitiveScalarType::Int16 => DataType::Int16,
- protobuf::PrimitiveScalarType::Uint32 => DataType::UInt32,
- protobuf::PrimitiveScalarType::Int32 => DataType::Int32,
- protobuf::PrimitiveScalarType::Uint64 => DataType::UInt64,
- protobuf::PrimitiveScalarType::Int64 => DataType::Int64,
- protobuf::PrimitiveScalarType::Float32 => DataType::Float32,
- protobuf::PrimitiveScalarType::Float64 => DataType::Float64,
- protobuf::PrimitiveScalarType::Utf8 => DataType::Utf8,
- protobuf::PrimitiveScalarType::LargeUtf8 => DataType::LargeUtf8,
- protobuf::PrimitiveScalarType::Date32 => DataType::Date32,
- protobuf::PrimitiveScalarType::TimeMicrosecond => {
- DataType::Time64(TimeUnit::Microsecond)
- }
- protobuf::PrimitiveScalarType::TimeNanosecond => {
- DataType::Time64(TimeUnit::Nanosecond)
- }
- protobuf::PrimitiveScalarType::Null => DataType::Null,
- protobuf::PrimitiveScalarType::Decimal128 => DataType::Decimal(0, 0),
- protobuf::PrimitiveScalarType::Date64 => DataType::Date64,
- protobuf::PrimitiveScalarType::TimeSecond => {
- DataType::Timestamp(TimeUnit::Second, None)
- }
- protobuf::PrimitiveScalarType::TimeMillisecond => {
- DataType::Timestamp(TimeUnit::Millisecond, None)
- }
- protobuf::PrimitiveScalarType::IntervalYearmonth => {
- DataType::Interval(IntervalUnit::YearMonth)
- }
- protobuf::PrimitiveScalarType::IntervalDaytime => {
- DataType::Interval(IntervalUnit::DayTime)
- }
- }
- }
-}
-
impl From<protobuf::JoinType> for JoinType {
fn from(t: protobuf::JoinType) -> Self {
match t {
@@ -571,12 +339,6 @@ fn str_to_byte(s: &str) -> Result<u8, BallistaError> {
Ok(s.as_bytes()[0])
}
-fn vec_to_array<T, const N: usize>(v: Vec<T>) -> [T; N] {
- v.try_into().unwrap_or_else(|v: Vec<T>| {
- panic!("Expected a Vec of length {} but it was {}", N, v.len())
- })
-}
-
#[cfg(test)]
mod tests {
use async_trait::async_trait;
@@ -605,15 +367,13 @@ mod tests {
use std::sync::Arc;
pub mod proto {
- use crate::serde::protobuf;
-
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TopKPlanProto {
#[prost(uint64, tag = "1")]
pub k: u64,
#[prost(message, optional, tag = "2")]
- pub expr: ::core::option::Option<protobuf::LogicalExprNode>,
+ pub expr: ::core::option::Option<datafusion_proto::protobuf::LogicalExprNode>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
diff --git a/ballista/rust/core/src/serde/physical_plan/from_proto.rs b/ballista/rust/core/src/serde/physical_plan/from_proto.rs
index 9356e4bd70..8daefc904b 100644
--- a/ballista/rust/core/src/serde/physical_plan/from_proto.rs
+++ b/ballista/rust/core/src/serde/physical_plan/from_proto.rs
@@ -44,7 +44,7 @@ use datafusion::physical_plan::{
BinaryExpr, CaseExpr, CastExpr, Column, InListExpr, IsNotNullExpr, IsNullExpr,
Literal, NegativeExpr, NotExpr, TryCastExpr, DEFAULT_DATAFUSION_CAST_OPTIONS,
},
- functions::{self, BuiltinScalarFunction, ScalarFunctionExpr},
+ functions::{self, ScalarFunctionExpr},
Partitioning,
};
use datafusion::physical_plan::{ColumnStatistics, PhysicalExpr, Statistics};
@@ -57,51 +57,6 @@ impl From<&protobuf::PhysicalColumn> for Column {
}
}
-impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction {
- fn from(f: &protobuf::ScalarFunction) -> BuiltinScalarFunction {
- use protobuf::ScalarFunction;
- match f {
- ScalarFunction::Sqrt => BuiltinScalarFunction::Sqrt,
- ScalarFunction::Sin => BuiltinScalarFunction::Sin,
- ScalarFunction::Cos => BuiltinScalarFunction::Cos,
- ScalarFunction::Tan => BuiltinScalarFunction::Tan,
- ScalarFunction::Asin => BuiltinScalarFunction::Asin,
- ScalarFunction::Acos => BuiltinScalarFunction::Acos,
- ScalarFunction::Atan => BuiltinScalarFunction::Atan,
- ScalarFunction::Exp => BuiltinScalarFunction::Exp,
- ScalarFunction::Log => BuiltinScalarFunction::Log,
- ScalarFunction::Log2 => BuiltinScalarFunction::Log2,
- ScalarFunction::Log10 => BuiltinScalarFunction::Log10,
- ScalarFunction::Floor => BuiltinScalarFunction::Floor,
- ScalarFunction::Ceil => BuiltinScalarFunction::Ceil,
- ScalarFunction::Round => BuiltinScalarFunction::Round,
- ScalarFunction::Trunc => BuiltinScalarFunction::Trunc,
- ScalarFunction::Abs => BuiltinScalarFunction::Abs,
- ScalarFunction::Signum => BuiltinScalarFunction::Signum,
- ScalarFunction::Octetlength => BuiltinScalarFunction::OctetLength,
- ScalarFunction::Concat => BuiltinScalarFunction::Concat,
- ScalarFunction::Lower => BuiltinScalarFunction::Lower,
- ScalarFunction::Upper => BuiltinScalarFunction::Upper,
- ScalarFunction::Trim => BuiltinScalarFunction::Trim,
- ScalarFunction::Ltrim => BuiltinScalarFunction::Ltrim,
- ScalarFunction::Rtrim => BuiltinScalarFunction::Rtrim,
- ScalarFunction::Totimestamp => BuiltinScalarFunction::ToTimestamp,
- ScalarFunction::Array => BuiltinScalarFunction::Array,
- ScalarFunction::Nullif => BuiltinScalarFunction::NullIf,
- ScalarFunction::Datepart => BuiltinScalarFunction::DatePart,
- ScalarFunction::Datetrunc => BuiltinScalarFunction::DateTrunc,
- ScalarFunction::Md5 => BuiltinScalarFunction::MD5,
- ScalarFunction::Sha224 => BuiltinScalarFunction::SHA224,
- ScalarFunction::Sha256 => BuiltinScalarFunction::SHA256,
- ScalarFunction::Sha384 => BuiltinScalarFunction::SHA384,
- ScalarFunction::Sha512 => BuiltinScalarFunction::SHA512,
- ScalarFunction::Digest => BuiltinScalarFunction::Digest,
- ScalarFunction::Ln => BuiltinScalarFunction::Ln,
- ScalarFunction::Totimestampmillis => BuiltinScalarFunction::ToTimestampMillis,
- }
- }
-}
-
impl TryFrom<&protobuf::PhysicalExprNode> for Arc<dyn PhysicalExpr> {
type Error = BallistaError;
@@ -187,13 +142,14 @@ impl TryFrom<&protobuf::PhysicalExprNode> for Arc<dyn PhysicalExpr> {
convert_required!(e.arrow_type)?,
)),
ExprType::ScalarFunction(e) => {
- let scalar_function = protobuf::ScalarFunction::from_i32(e.fun)
- .ok_or_else(|| {
- proto_error(format!(
- "Received an unknown scalar function: {}",
- e.fun,
- ))
- })?;
+ let scalar_function =
+ datafusion_proto::protobuf::ScalarFunction::from_i32(e.fun)
+ .ok_or_else(|| {
+ proto_error(format!(
+ "Received an unknown scalar function: {}",
+ e.fun,
+ ))
+ })?;
let args = e
.args
@@ -240,24 +196,25 @@ impl TryFrom<&protobuf::physical_window_expr_node::WindowFunction> for WindowFun
) -> Result<Self, Self::Error> {
match expr {
protobuf::physical_window_expr_node::WindowFunction::AggrFunction(n) => {
- let f = protobuf::AggregateFunction::from_i32(*n).ok_or_else(|| {
- proto_error(format!(
- "Received an unknown window aggregate function: {}",
- n
- ))
- })?;
-
- Ok(WindowFunction::AggregateFunction(f.into()))
- }
- protobuf::physical_window_expr_node::WindowFunction::BuiltInFunction(n) => {
- let f =
- protobuf::BuiltInWindowFunction::from_i32(*n).ok_or_else(|| {
+ let f = datafusion_proto::protobuf::AggregateFunction::from_i32(*n)
+ .ok_or_else(|| {
proto_error(format!(
- "Received an unknown window builtin function: {}",
+ "Received an unknown window aggregate function: {}",
n
))
})?;
+ Ok(WindowFunction::AggregateFunction(f.into()))
+ }
+ protobuf::physical_window_expr_node::WindowFunction::BuiltInFunction(n) => {
+ let f = datafusion_proto::protobuf::BuiltInWindowFunction::from_i32(*n)
+ .ok_or_else(|| {
+ proto_error(format!(
+ "Received an unknown window builtin function: {}",
+ n
+ ))
+ })?;
+
Ok(WindowFunction::BuiltInWindowFunction(f.into()))
}
}
diff --git a/ballista/rust/core/src/serde/physical_plan/mod.rs b/ballista/rust/core/src/serde/physical_plan/mod.rs
index 5ef699215f..c84c92f252 100644
--- a/ballista/rust/core/src/serde/physical_plan/mod.rs
+++ b/ballista/rust/core/src/serde/physical_plan/mod.rs
@@ -298,7 +298,7 @@ impl AsExecutionPlan for PhysicalPlanNode {
match expr_type {
ExprType::AggregateExpr(agg_node) => {
let aggr_function =
- protobuf::AggregateFunction::from_i32(
+ datafusion_proto::protobuf::AggregateFunction::from_i32(
agg_node.aggr_function,
)
.ok_or_else(
diff --git a/ballista/rust/core/src/serde/physical_plan/to_proto.rs b/ballista/rust/core/src/serde/physical_plan/to_proto.rs
index e3b60e03c3..c6cfb1ec84 100644
--- a/ballista/rust/core/src/serde/physical_plan/to_proto.rs
+++ b/ballista/rust/core/src/serde/physical_plan/to_proto.rs
@@ -51,16 +51,17 @@ impl TryInto<protobuf::PhysicalExprNode> for Arc<dyn AggregateExpr> {
type Error = BallistaError;
fn try_into(self) -> Result<protobuf::PhysicalExprNode, Self::Error> {
+ use datafusion_proto::protobuf::AggregateFunction;
let aggr_function = if self.as_any().downcast_ref::<Avg>().is_some() {
- Ok(protobuf::AggregateFunction::Avg.into())
+ Ok(AggregateFunction::Avg.into())
} else if self.as_any().downcast_ref::<Sum>().is_some() {
- Ok(protobuf::AggregateFunction::Sum.into())
+ Ok(AggregateFunction::Sum.into())
} else if self.as_any().downcast_ref::<Count>().is_some() {
- Ok(protobuf::AggregateFunction::Count.into())
+ Ok(AggregateFunction::Count.into())
} else if self.as_any().downcast_ref::<Min>().is_some() {
- Ok(protobuf::AggregateFunction::Min.into())
+ Ok(AggregateFunction::Min.into())
} else if self.as_any().downcast_ref::<Max>().is_some() {
- Ok(protobuf::AggregateFunction::Max.into())
+ Ok(AggregateFunction::Max.into())
} else {
Err(BallistaError::NotImplemented(format!(
"Aggregate function not supported: {:?}",
@@ -220,7 +221,7 @@ impl TryFrom<Arc<dyn PhysicalExpr>> for protobuf::PhysicalExprNode {
} else if let Some(expr) = expr.downcast_ref::<ScalarFunctionExpr>() {
let fun: BuiltinScalarFunction =
BuiltinScalarFunction::from_str(expr.name())?;
- let fun: protobuf::ScalarFunction = (&fun).try_into()?;
+ let fun: datafusion_proto::protobuf::ScalarFunction = (&fun).try_into()?;
let args: Vec<protobuf::PhysicalExprNode> = expr
.args()
.iter()
diff --git a/datafusion-proto/Cargo.toml b/datafusion-proto/Cargo.toml
new file mode 100644
index 0000000000..b71e434531
--- /dev/null
+++ b/datafusion-proto/Cargo.toml
@@ -0,0 +1,42 @@
+# 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.
+
+[package]
+name = "datafusion-proto"
+description = "Protobuf serialization of DataFusion logical plan expressions"
+version = "7.0.0"
+homepage = "https://github.com/apache/arrow-datafusion"
+repository = "https://github.com/apache/arrow-datafusion"
+readme = "../README.md"
+authors = ["Apache Arrow <[email protected]>"]
+license = "Apache-2.0"
+keywords = [ "arrow", "query", "sql" ]
+edition = "2021"
+rust-version = "1.58"
+
+[lib]
+name = "datafusion_proto"
+path = "src/lib.rs"
+
+[features]
+
+[dependencies]
+datafusion = { path = "../datafusion", version = "7.0.0" }
+prost = "0.9"
+
+[build-dependencies]
+tonic-build = { version = "0.6" }
diff --git a/datafusion-proto/build.rs b/datafusion-proto/build.rs
new file mode 100644
index 0000000000..414593eeef
--- /dev/null
+++ b/datafusion-proto/build.rs
@@ -0,0 +1,26 @@
+// 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.
+
+fn main() -> Result<(), String> {
+ // for use in docker build where file changes can be wonky
+ println!("cargo:rerun-if-env-changed=FORCE_REBUILD");
+
+ println!("cargo:rerun-if-changed=proto/datafusion.proto");
+ tonic_build::configure()
+ .compile(&["proto/datafusion.proto"], &["proto"])
+ .map_err(|e| format!("protobuf compilation failed: {}", e))
+}
diff --git a/datafusion-proto/proto/datafusion.proto b/datafusion-proto/proto/datafusion.proto
new file mode 100644
index 0000000000..f1a0730644
--- /dev/null
+++ b/datafusion-proto/proto/datafusion.proto
@@ -0,0 +1,490 @@
+/*
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ */
+
+syntax = "proto3";
+
+package datafusion;
+
+option java_multiple_files = true;
+option java_package = "org.datafusioncompute.protobuf";
+option java_outer_classname = "DatafusionProto";
+
+message ColumnRelation {
+ string relation = 1;
+}
+
+message Column {
+ string name = 1;
+ ColumnRelation relation = 2;
+}
+
+message DfField{
+ Field field = 1;
+ ColumnRelation qualifier = 2;
+}
+
+message DfSchema {
+ repeated DfField columns = 1;
+}
+
+// logical expressions
+message LogicalExprNode {
+ oneof ExprType {
+ // column references
+ Column column = 1;
+
+ // alias
+ AliasNode alias = 2;
+
+ ScalarValue literal = 3;
+
+ // binary expressions
+ BinaryExprNode binary_expr = 4;
+
+ // aggregate expressions
+ AggregateExprNode aggregate_expr = 5;
+
+ // null checks
+ IsNull is_null_expr = 6;
+ IsNotNull is_not_null_expr = 7;
+ Not not_expr = 8;
+
+ BetweenNode between = 9;
+ CaseNode case_ = 10;
+ CastNode cast = 11;
+ SortExprNode sort = 12;
+ NegativeNode negative = 13;
+ InListNode in_list = 14;
+ bool wildcard = 15;
+ ScalarFunctionNode scalar_function = 16;
+ TryCastNode try_cast = 17;
+
+ // window expressions
+ WindowExprNode window_expr = 18;
+ }
+}
+
+message IsNull {
+ LogicalExprNode expr = 1;
+}
+
+message IsNotNull {
+ LogicalExprNode expr = 1;
+}
+
+message Not {
+ LogicalExprNode expr = 1;
+}
+
+message AliasNode {
+ LogicalExprNode expr = 1;
+ string alias = 2;
+}
+
+message BinaryExprNode {
+ LogicalExprNode l = 1;
+ LogicalExprNode r = 2;
+ string op = 3;
+}
+
+message NegativeNode {
+ LogicalExprNode expr = 1;
+}
+
+message InListNode {
+ LogicalExprNode expr = 1;
+ repeated LogicalExprNode list = 2;
+ bool negated = 3;
+}
+
+enum ScalarFunction {
+ SQRT = 0;
+ SIN = 1;
+ COS = 2;
+ TAN = 3;
+ ASIN = 4;
+ ACOS = 5;
+ ATAN = 6;
+ EXP = 7;
+ LOG = 8;
+ LOG2 = 9;
+ LOG10 = 10;
+ FLOOR = 11;
+ CEIL = 12;
+ ROUND = 13;
+ TRUNC = 14;
+ ABS = 15;
+ SIGNUM = 16;
+ OCTETLENGTH = 17;
+ CONCAT = 18;
+ LOWER = 19;
+ UPPER = 20;
+ TRIM = 21;
+ LTRIM = 22;
+ RTRIM = 23;
+ TOTIMESTAMP = 24;
+ ARRAY = 25;
+ NULLIF = 26;
+ DATEPART = 27;
+ DATETRUNC = 28;
+ MD5 = 29;
+ SHA224 = 30;
+ SHA256 = 31;
+ SHA384 = 32;
+ SHA512 = 33;
+ LN = 34;
+ TOTIMESTAMPMILLIS = 35;
+ DIGEST = 36;
+}
+
+message ScalarFunctionNode {
+ ScalarFunction fun = 1;
+ repeated LogicalExprNode args = 2;
+}
+
+enum AggregateFunction {
+ MIN = 0;
+ MAX = 1;
+ SUM = 2;
+ AVG = 3;
+ COUNT = 4;
+ APPROX_DISTINCT = 5;
+ ARRAY_AGG = 6;
+ VARIANCE=7;
+ VARIANCE_POP=8;
+ COVARIANCE=9;
+ COVARIANCE_POP=10;
+ STDDEV=11;
+ STDDEV_POP=12;
+ CORRELATION=13;
+ APPROX_PERCENTILE_CONT = 14;
+ APPROX_MEDIAN=15;
+}
+
+message AggregateExprNode {
+ AggregateFunction aggr_function = 1;
+ repeated LogicalExprNode expr = 2;
+}
+
+enum BuiltInWindowFunction {
+ ROW_NUMBER = 0;
+ RANK = 1;
+ DENSE_RANK = 2;
+ PERCENT_RANK = 3;
+ CUME_DIST = 4;
+ NTILE = 5;
+ LAG = 6;
+ LEAD = 7;
+ FIRST_VALUE = 8;
+ LAST_VALUE = 9;
+ NTH_VALUE = 10;
+}
+
+message WindowExprNode {
+ oneof window_function {
+ AggregateFunction aggr_function = 1;
+ BuiltInWindowFunction built_in_function = 2;
+ // udaf = 3
+ }
+ LogicalExprNode expr = 4;
+ repeated LogicalExprNode partition_by = 5;
+ repeated LogicalExprNode order_by = 6;
+ // repeated LogicalExprNode filter = 7;
+ oneof window_frame {
+ WindowFrame frame = 8;
+ }
+}
+
+message BetweenNode {
+ LogicalExprNode expr = 1;
+ bool negated = 2;
+ LogicalExprNode low = 3;
+ LogicalExprNode high = 4;
+}
+
+message CaseNode {
+ LogicalExprNode expr = 1;
+ repeated WhenThen when_then_expr = 2;
+ LogicalExprNode else_expr = 3;
+}
+
+message WhenThen {
+ LogicalExprNode when_expr = 1;
+ LogicalExprNode then_expr = 2;
+}
+
+message CastNode {
+ LogicalExprNode expr = 1;
+ ArrowType arrow_type = 2;
+}
+
+message TryCastNode {
+ LogicalExprNode expr = 1;
+ ArrowType arrow_type = 2;
+}
+
+message SortExprNode {
+ LogicalExprNode expr = 1;
+ bool asc = 2;
+ bool nulls_first = 3;
+}
+
+enum WindowFrameUnits {
+ ROWS = 0;
+ RANGE = 1;
+ GROUPS = 2;
+}
+
+message WindowFrame {
+ WindowFrameUnits window_frame_units = 1;
+ WindowFrameBound start_bound = 2;
+ // "optional" keyword is stable in protoc 3.15 but prost is still on 3.14 (see https://github.com/tokio-rs/prost/issues/430 and https://github.com/tokio-rs/prost/pull/455)
+ // this syntax is ugly but is binary compatible with the "optional" keyword (see https://stackoverflow.com/questions/42622015/how-to-define-an-optional-field-in-protobuf-3)
+ oneof end_bound {
+ WindowFrameBound bound = 3;
+ }
+}
+
+enum WindowFrameBoundType {
+ CURRENT_ROW = 0;
+ PRECEDING = 1;
+ FOLLOWING = 2;
+}
+
+message WindowFrameBound {
+ WindowFrameBoundType window_frame_bound_type = 1;
+ // "optional" keyword is stable in protoc 3.15 but prost is still on 3.14 (see https://github.com/tokio-rs/prost/issues/430 and https://github.com/tokio-rs/prost/pull/455)
+ // this syntax is ugly but is binary compatible with the "optional" keyword (see https://stackoverflow.com/questions/42622015/how-to-define-an-optional-field-in-protobuf-3)
+ oneof bound_value {
+ uint64 value = 2;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Arrow Data Types
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+message Schema {
+ repeated datafusion.Field columns = 1;
+}
+
+message Field {
+ // name of the field
+ string name = 1;
+ ArrowType arrow_type = 2;
+ bool nullable = 3;
+ // for complex data types like structs, unions
+ repeated Field children = 4;
+}
+
+message FixedSizeBinary{
+ int32 length = 1;
+}
+
+message Timestamp{
+ TimeUnit time_unit = 1;
+ string timezone = 2;
+}
+
+enum DateUnit{
+ Day = 0;
+ DateMillisecond = 1;
+}
+
+enum TimeUnit{
+ Second = 0;
+ TimeMillisecond = 1;
+ Microsecond = 2;
+ Nanosecond = 3;
+}
+
+enum IntervalUnit{
+ YearMonth = 0;
+ DayTime = 1;
+ MonthDayNano = 2;
+}
+
+message Decimal{
+ uint64 whole = 1;
+ uint64 fractional = 2;
+}
+
+message List{
+ Field field_type = 1;
+}
+
+message FixedSizeList{
+ Field field_type = 1;
+ int32 list_size = 2;
+}
+
+message Dictionary{
+ ArrowType key = 1;
+ ArrowType value = 2;
+}
+
+message Struct{
+ repeated Field sub_field_types = 1;
+}
+
+enum UnionMode{
+ sparse = 0;
+ dense = 1;
+}
+
+message Union{
+ repeated Field union_types = 1;
+ UnionMode union_mode = 2;
+}
+
+message ScalarListValue{
+ ScalarType datatype = 1;
+ repeated ScalarValue values = 2;
+}
+
+message ScalarValue{
+ oneof value {
+ bool bool_value = 1;
+ string utf8_value = 2;
+ string large_utf8_value = 3;
+ int32 int8_value = 4;
+ int32 int16_value = 5;
+ int32 int32_value = 6;
+ int64 int64_value = 7;
+ uint32 uint8_value = 8;
+ uint32 uint16_value = 9;
+ uint32 uint32_value = 10;
+ uint64 uint64_value = 11;
+ float float32_value = 12;
+ double float64_value = 13;
+ //Literal Date32 value always has a unit of day
+ int32 date_32_value = 14;
+ int64 time_microsecond_value = 15;
+ int64 time_nanosecond_value = 16;
+ ScalarListValue list_value = 17;
+ ScalarType null_list_value = 18;
+
+ PrimitiveScalarType null_value = 19;
+ Decimal128 decimal128_value = 20;
+ int64 date_64_value = 21;
+ int64 time_second_value = 22;
+ int64 time_millisecond_value = 23;
+ int32 interval_yearmonth_value = 24;
+ int64 interval_daytime_value = 25;
+ }
+}
+
+message Decimal128{
+ bytes value = 1;
+ int64 p = 2;
+ int64 s = 3;
+}
+
+// Contains all valid datafusion scalar type except for
+// List
+enum PrimitiveScalarType{
+
+ BOOL = 0; // arrow::Type::BOOL
+ UINT8 = 1; // arrow::Type::UINT8
+ INT8 = 2; // arrow::Type::INT8
+ UINT16 = 3; // represents arrow::Type fields in src/arrow/type.h
+ INT16 = 4;
+ UINT32 = 5;
+ INT32 = 6;
+ UINT64 = 7;
+ INT64 = 8;
+ FLOAT32 = 9;
+ FLOAT64 = 10;
+ UTF8 = 11;
+ LARGE_UTF8 = 12;
+ DATE32 = 13;
+ TIME_MICROSECOND = 14;
+ TIME_NANOSECOND = 15;
+ NULL = 16;
+
+ DECIMAL128 = 17;
+ DATE64 = 20;
+ TIME_SECOND = 21;
+ TIME_MILLISECOND = 22;
+ INTERVAL_YEARMONTH = 23;
+ INTERVAL_DAYTIME = 24;
+}
+
+message ScalarType{
+ oneof datatype{
+ PrimitiveScalarType scalar = 1;
+ ScalarListType list = 2;
+ }
+}
+
+message ScalarListType{
+ repeated string field_names = 3;
+ PrimitiveScalarType deepest_type = 2;
+}
+
+// Broke out into multiple message types so that type
+// metadata did not need to be in separate message
+//All types that are of the empty message types contain no additional metadata
+// about the type
+message ArrowType{
+ oneof arrow_type_enum{
+ EmptyMessage NONE = 1; // arrow::Type::NA
+ EmptyMessage BOOL = 2; // arrow::Type::BOOL
+ EmptyMessage UINT8 = 3; // arrow::Type::UINT8
+ EmptyMessage INT8 = 4; // arrow::Type::INT8
+ EmptyMessage UINT16 =5; // represents arrow::Type fields in src/arrow/type.h
+ EmptyMessage INT16 = 6;
+ EmptyMessage UINT32 =7;
+ EmptyMessage INT32 = 8;
+ EmptyMessage UINT64 =9;
+ EmptyMessage INT64 =10 ;
+ EmptyMessage FLOAT16 =11 ;
+ EmptyMessage FLOAT32 =12 ;
+ EmptyMessage FLOAT64 =13 ;
+ EmptyMessage UTF8 =14 ;
+ EmptyMessage LARGE_UTF8 = 32;
+ EmptyMessage BINARY =15 ;
+ int32 FIXED_SIZE_BINARY =16 ;
+ EmptyMessage LARGE_BINARY = 31;
+ EmptyMessage DATE32 =17 ;
+ EmptyMessage DATE64 =18 ;
+ TimeUnit DURATION = 19;
+ Timestamp TIMESTAMP =20 ;
+ TimeUnit TIME32 =21 ;
+ TimeUnit TIME64 =22 ;
+ IntervalUnit INTERVAL =23 ;
+ Decimal DECIMAL =24 ;
+ List LIST =25;
+ List LARGE_LIST = 26;
+ FixedSizeList FIXED_SIZE_LIST = 27;
+ Struct STRUCT =28;
+ Union UNION =29;
+ Dictionary DICTIONARY =30;
+ }
+}
+
+//Useful for representing an empty enum variant in rust
+// E.G. enum example{One, Two(i32)}
+// maps to
+// message example{
+// oneof{
+// EmptyMessage One = 1;
+// i32 Two = 2;
+// }
+//}
+message EmptyMessage{}
diff --git a/datafusion-proto/src/from_proto.rs b/datafusion-proto/src/from_proto.rs
new file mode 100644
index 0000000000..d589ef388c
--- /dev/null
+++ b/datafusion-proto/src/from_proto.rs
@@ -0,0 +1,1302 @@
+// 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.
+
+use crate::protobuf;
+use datafusion::{
+ arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit, UnionMode},
+ error::DataFusionError,
+ logical_plan::{
+ abs, atan, ceil, cos, digest, exp, floor, ln, log10, log2, round, signum, sin,
+ sqrt, tan, trunc,
+ window_frames::{WindowFrame, WindowFrameBound, WindowFrameUnits},
+ Column, DFField, DFSchema, DFSchemaRef, Expr, Operator,
+ },
+ physical_plan::{
+ aggregates::AggregateFunction, functions::BuiltinScalarFunction,
+ window_functions::BuiltInWindowFunction,
+ },
+ prelude::{
+ date_part, date_trunc, lower, ltrim, octet_length, rtrim, sha224, sha256, sha384,
+ sha512, trim, upper,
+ },
+ scalar::ScalarValue,
+};
+use std::sync::Arc;
+
+#[derive(Debug)]
+pub enum Error {
+ General(String),
+
+ DataFusionError(DataFusionError),
+
+ MissingRequiredField(String),
+
+ AtLeastOneValue(String),
+
+ UnknownEnumVariant { name: String, value: i32 },
+}
+
+impl std::fmt::Display for Error {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ match self {
+ Self::General(desc) => write!(f, "General error: {}", desc),
+
+ Self::DataFusionError(desc) => {
+ write!(f, "DataFusion error: {:?}", desc)
+ }
+
+ Self::MissingRequiredField(name) => {
+ write!(f, "Missing required field {}", name)
+ }
+ Self::AtLeastOneValue(name) => {
+ write!(f, "Must have at least one {}, found 0", name)
+ }
+ Self::UnknownEnumVariant { name, value } => {
+ write!(f, "Unknown i32 value for {} enum: {}", name, value)
+ }
+ }
+ }
+}
+
+impl std::error::Error for Error {}
+
+impl From<DataFusionError> for Error {
+ fn from(e: DataFusionError) -> Self {
+ Error::DataFusionError(e)
+ }
+}
+
+impl Error {
+ fn required(field: impl Into<String>) -> Error {
+ Error::MissingRequiredField(field.into())
+ }
+
+ fn at_least_one(field: impl Into<String>) -> Error {
+ Error::AtLeastOneValue(field.into())
+ }
+
+ fn unknown(name: impl Into<String>, value: i32) -> Error {
+ Error::UnknownEnumVariant {
+ name: name.into(),
+ value,
+ }
+ }
+}
+
+/// An extension trait that adds the methods `optional` and `required` to any
+/// Option containing a type implementing `TryInto<U, Error = Error>`
+pub trait FromOptionalField<T> {
+ /// Converts an optional protobuf field to an option of a different type
+ ///
+ /// Returns None if the option is None, otherwise calls [`FromField::field`]
+ /// on the contained data, returning any error encountered
+ fn optional(self) -> Result<Option<T>, Error>;
+
+ /// Converts an optional protobuf field to a different type, returning an error if None
+ ///
+ /// Returns `Error::MissingRequiredField` if None, otherwise calls [`FromField::field`]
+ /// on the contained data, returning any error encountered
+ fn required(self, field: impl Into<String>) -> Result<T, Error>;
+}
+
+impl<T, U> FromOptionalField<U> for Option<T>
+where
+ T: TryInto<U, Error = Error>,
+{
+ fn optional(self) -> Result<Option<U>, Error> {
+ self.map(|t| t.try_into()).transpose()
+ }
+
+ fn required(self, field: impl Into<String>) -> Result<U, Error> {
+ match self {
+ None => Err(Error::required(field)),
+ Some(t) => t.try_into(),
+ }
+ }
+}
+
+impl From<protobuf::Column> for Column {
+ fn from(c: protobuf::Column) -> Self {
+ let protobuf::Column { relation, name } = c;
+
+ Self {
+ relation: relation.map(|r| r.relation),
+ name,
+ }
+ }
+}
+
+impl From<&protobuf::Column> for Column {
+ fn from(c: &protobuf::Column) -> Self {
+ c.clone().into()
+ }
+}
+
+impl TryFrom<&protobuf::DfSchema> for DFSchema {
+ type Error = Error;
+
+ fn try_from(df_schema: &protobuf::DfSchema) -> Result<Self, Self::Error> {
+ let fields = df_schema
+ .columns
+ .iter()
+ .map(|c| c.try_into())
+ .collect::<Result<Vec<DFField>, _>>()?;
+ Ok(DFSchema::new(fields)?)
+ }
+}
+
+impl TryFrom<protobuf::DfSchema> for DFSchemaRef {
+ type Error = Error;
+
+ fn try_from(df_schema: protobuf::DfSchema) -> Result<Self, Self::Error> {
+ let dfschema: DFSchema = (&df_schema).try_into()?;
+ Ok(Arc::new(dfschema))
+ }
+}
+
+impl TryFrom<&protobuf::DfField> for DFField {
+ type Error = Error;
+
+ fn try_from(df_field: &protobuf::DfField) -> Result<Self, Self::Error> {
+ let field = df_field.field.as_ref().required("field")?;
+
+ Ok(match &df_field.qualifier {
+ Some(q) => DFField::from_qualified(&q.relation, field),
+ None => DFField::from(field),
+ })
+ }
+}
+
+impl From<protobuf::WindowFrameUnits> for WindowFrameUnits {
+ fn from(units: protobuf::WindowFrameUnits) -> Self {
+ match units {
+ protobuf::WindowFrameUnits::Rows => Self::Rows,
+ protobuf::WindowFrameUnits::Range => Self::Range,
+ protobuf::WindowFrameUnits::Groups => Self::Groups,
+ }
+ }
+}
+
+impl From<protobuf::PrimitiveScalarType> for DataType {
+ fn from(scalar: protobuf::PrimitiveScalarType) -> Self {
+ match scalar {
+ protobuf::PrimitiveScalarType::Bool => DataType::Boolean,
+ protobuf::PrimitiveScalarType::Uint8 => DataType::UInt8,
+ protobuf::PrimitiveScalarType::Int8 => DataType::Int8,
+ protobuf::PrimitiveScalarType::Uint16 => DataType::UInt16,
+ protobuf::PrimitiveScalarType::Int16 => DataType::Int16,
+ protobuf::PrimitiveScalarType::Uint32 => DataType::UInt32,
+ protobuf::PrimitiveScalarType::Int32 => DataType::Int32,
+ protobuf::PrimitiveScalarType::Uint64 => DataType::UInt64,
+ protobuf::PrimitiveScalarType::Int64 => DataType::Int64,
+ protobuf::PrimitiveScalarType::Float32 => DataType::Float32,
+ protobuf::PrimitiveScalarType::Float64 => DataType::Float64,
+ protobuf::PrimitiveScalarType::Utf8 => DataType::Utf8,
+ protobuf::PrimitiveScalarType::LargeUtf8 => DataType::LargeUtf8,
+ protobuf::PrimitiveScalarType::Date32 => DataType::Date32,
+ protobuf::PrimitiveScalarType::TimeMicrosecond => {
+ DataType::Time64(TimeUnit::Microsecond)
+ }
+ protobuf::PrimitiveScalarType::TimeNanosecond => {
+ DataType::Time64(TimeUnit::Nanosecond)
+ }
+ protobuf::PrimitiveScalarType::Null => DataType::Null,
+ protobuf::PrimitiveScalarType::Decimal128 => DataType::Decimal(0, 0),
+ protobuf::PrimitiveScalarType::Date64 => DataType::Date64,
+ protobuf::PrimitiveScalarType::TimeSecond => {
+ DataType::Timestamp(TimeUnit::Second, None)
+ }
+ protobuf::PrimitiveScalarType::TimeMillisecond => {
+ DataType::Timestamp(TimeUnit::Millisecond, None)
+ }
+ protobuf::PrimitiveScalarType::IntervalYearmonth => {
+ DataType::Interval(IntervalUnit::YearMonth)
+ }
+ protobuf::PrimitiveScalarType::IntervalDaytime => {
+ DataType::Interval(IntervalUnit::DayTime)
+ }
+ }
+ }
+}
+
+impl TryFrom<&protobuf::ArrowType> for DataType {
+ type Error = Error;
+
+ fn try_from(arrow_type: &protobuf::ArrowType) -> Result<Self, Self::Error> {
+ arrow_type
+ .arrow_type_enum
+ .as_ref()
+ .required("arrow_type_enum")
+ }
+}
+
+impl TryFrom<&protobuf::arrow_type::ArrowTypeEnum> for DataType {
+ type Error = Error;
+ fn try_from(
+ arrow_type_enum: &protobuf::arrow_type::ArrowTypeEnum,
+ ) -> Result<Self, Self::Error> {
+ use protobuf::arrow_type;
+ Ok(match arrow_type_enum {
+ arrow_type::ArrowTypeEnum::None(_) => DataType::Null,
+ arrow_type::ArrowTypeEnum::Bool(_) => DataType::Boolean,
+ arrow_type::ArrowTypeEnum::Uint8(_) => DataType::UInt8,
+ arrow_type::ArrowTypeEnum::Int8(_) => DataType::Int8,
+ arrow_type::ArrowTypeEnum::Uint16(_) => DataType::UInt16,
+ arrow_type::ArrowTypeEnum::Int16(_) => DataType::Int16,
+ arrow_type::ArrowTypeEnum::Uint32(_) => DataType::UInt32,
+ arrow_type::ArrowTypeEnum::Int32(_) => DataType::Int32,
+ arrow_type::ArrowTypeEnum::Uint64(_) => DataType::UInt64,
+ arrow_type::ArrowTypeEnum::Int64(_) => DataType::Int64,
+ arrow_type::ArrowTypeEnum::Float16(_) => DataType::Float16,
+ arrow_type::ArrowTypeEnum::Float32(_) => DataType::Float32,
+ arrow_type::ArrowTypeEnum::Float64(_) => DataType::Float64,
+ arrow_type::ArrowTypeEnum::Utf8(_) => DataType::Utf8,
+ arrow_type::ArrowTypeEnum::LargeUtf8(_) => DataType::LargeUtf8,
+ arrow_type::ArrowTypeEnum::Binary(_) => DataType::Binary,
+ arrow_type::ArrowTypeEnum::FixedSizeBinary(size) => {
+ DataType::FixedSizeBinary(*size)
+ }
+ arrow_type::ArrowTypeEnum::LargeBinary(_) => DataType::LargeBinary,
+ arrow_type::ArrowTypeEnum::Date32(_) => DataType::Date32,
+ arrow_type::ArrowTypeEnum::Date64(_) => DataType::Date64,
+ arrow_type::ArrowTypeEnum::Duration(time_unit) => {
+ DataType::Duration(protobuf::TimeUnit::try_from(time_unit)?.into())
+ }
+ arrow_type::ArrowTypeEnum::Timestamp(protobuf::Timestamp {
+ time_unit,
+ timezone,
+ }) => DataType::Timestamp(
+ protobuf::TimeUnit::try_from(time_unit)?.into(),
+ match timezone.len() {
+ 0 => None,
+ _ => Some(timezone.to_owned()),
+ },
+ ),
+ arrow_type::ArrowTypeEnum::Time32(time_unit) => {
+ DataType::Time32(protobuf::TimeUnit::try_from(time_unit)?.into())
+ }
+ arrow_type::ArrowTypeEnum::Time64(time_unit) => {
+ DataType::Time64(protobuf::TimeUnit::try_from(time_unit)?.into())
+ }
+ arrow_type::ArrowTypeEnum::Interval(interval_unit) => DataType::Interval(
+ protobuf::IntervalUnit::try_from(interval_unit)?.into(),
+ ),
+ arrow_type::ArrowTypeEnum::Decimal(protobuf::Decimal {
+ whole,
+ fractional,
+ }) => DataType::Decimal(*whole as usize, *fractional as usize),
+ arrow_type::ArrowTypeEnum::List(list) => {
+ let list_type =
+ list.as_ref().field_type.as_deref().required("field_type")?;
+ DataType::List(Box::new(list_type))
+ }
+ arrow_type::ArrowTypeEnum::LargeList(list) => {
+ let list_type =
+ list.as_ref().field_type.as_deref().required("field_type")?;
+ DataType::LargeList(Box::new(list_type))
+ }
+ arrow_type::ArrowTypeEnum::FixedSizeList(list) => {
+ let list_type =
+ list.as_ref().field_type.as_deref().required("field_type")?;
+ let list_size = list.list_size;
+ DataType::FixedSizeList(Box::new(list_type), list_size)
+ }
+ arrow_type::ArrowTypeEnum::Struct(strct) => DataType::Struct(
+ strct
+ .sub_field_types
+ .iter()
+ .map(|field| field.try_into())
+ .collect::<Result<Vec<_>, _>>()?,
+ ),
+ arrow_type::ArrowTypeEnum::Union(union) => {
+ let union_mode = protobuf::UnionMode::from_i32(union.union_mode)
+ .ok_or_else(|| Error::unknown("UnionMode", union.union_mode))?;
+ let union_mode = match union_mode {
+ protobuf::UnionMode::Dense => UnionMode::Dense,
+ protobuf::UnionMode::Sparse => UnionMode::Sparse,
+ };
+ let union_types = union
+ .union_types
+ .iter()
+ .map(|field| field.try_into())
+ .collect::<Result<Vec<_>, _>>()?;
+ DataType::Union(union_types, union_mode)
+ }
+ arrow_type::ArrowTypeEnum::Dictionary(dict) => {
+ let key_datatype = dict.as_ref().key.as_deref().required("key")?;
+ let value_datatype = dict.as_ref().value.as_deref().required("value")?;
+ DataType::Dictionary(Box::new(key_datatype), Box::new(value_datatype))
+ }
+ })
+ }
+}
+
+impl TryFrom<&protobuf::Field> for Field {
+ type Error = Error;
+ fn try_from(field: &protobuf::Field) -> Result<Self, Self::Error> {
+ let datatype = field.arrow_type.as_deref().required("arrow_type")?;
+
+ Ok(Self::new(field.name.as_str(), datatype, field.nullable))
+ }
+}
+
+impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction {
+ fn from(f: &protobuf::ScalarFunction) -> Self {
+ use protobuf::ScalarFunction;
+ match f {
+ ScalarFunction::Sqrt => Self::Sqrt,
+ ScalarFunction::Sin => Self::Sin,
+ ScalarFunction::Cos => Self::Cos,
+ ScalarFunction::Tan => Self::Tan,
+ ScalarFunction::Asin => Self::Asin,
+ ScalarFunction::Acos => Self::Acos,
+ ScalarFunction::Atan => Self::Atan,
+ ScalarFunction::Exp => Self::Exp,
+ ScalarFunction::Log => Self::Log,
+ ScalarFunction::Log2 => Self::Log2,
+ ScalarFunction::Log10 => Self::Log10,
+ ScalarFunction::Floor => Self::Floor,
+ ScalarFunction::Ceil => Self::Ceil,
+ ScalarFunction::Round => Self::Round,
+ ScalarFunction::Trunc => Self::Trunc,
+ ScalarFunction::Abs => Self::Abs,
+ ScalarFunction::Signum => Self::Signum,
+ ScalarFunction::Octetlength => Self::OctetLength,
+ ScalarFunction::Concat => Self::Concat,
+ ScalarFunction::Lower => Self::Lower,
+ ScalarFunction::Upper => Self::Upper,
+ ScalarFunction::Trim => Self::Trim,
+ ScalarFunction::Ltrim => Self::Ltrim,
+ ScalarFunction::Rtrim => Self::Rtrim,
+ ScalarFunction::Totimestamp => Self::ToTimestamp,
+ ScalarFunction::Array => Self::Array,
+ ScalarFunction::Nullif => Self::NullIf,
+ ScalarFunction::Datepart => Self::DatePart,
+ ScalarFunction::Datetrunc => Self::DateTrunc,
+ ScalarFunction::Md5 => Self::MD5,
+ ScalarFunction::Sha224 => Self::SHA224,
+ ScalarFunction::Sha256 => Self::SHA256,
+ ScalarFunction::Sha384 => Self::SHA384,
+ ScalarFunction::Sha512 => Self::SHA512,
+ ScalarFunction::Digest => Self::Digest,
+ ScalarFunction::Ln => Self::Ln,
+ ScalarFunction::Totimestampmillis => Self::ToTimestampMillis,
+ }
+ }
+}
+
+impl From<protobuf::AggregateFunction> for AggregateFunction {
+ fn from(agg_fun: protobuf::AggregateFunction) -> Self {
+ match agg_fun {
+ protobuf::AggregateFunction::Min => Self::Min,
+ protobuf::AggregateFunction::Max => Self::Max,
+ protobuf::AggregateFunction::Sum => Self::Sum,
+ protobuf::AggregateFunction::Avg => Self::Avg,
+ protobuf::AggregateFunction::Count => Self::Count,
+ protobuf::AggregateFunction::ApproxDistinct => Self::ApproxDistinct,
+ protobuf::AggregateFunction::ArrayAgg => Self::ArrayAgg,
+ protobuf::AggregateFunction::Variance => Self::Variance,
+ protobuf::AggregateFunction::VariancePop => Self::VariancePop,
+ protobuf::AggregateFunction::Covariance => Self::Covariance,
+ protobuf::AggregateFunction::CovariancePop => Self::CovariancePop,
+ protobuf::AggregateFunction::Stddev => Self::Stddev,
+ protobuf::AggregateFunction::StddevPop => Self::StddevPop,
+ protobuf::AggregateFunction::Correlation => Self::Correlation,
+ protobuf::AggregateFunction::ApproxPercentileCont => {
+ Self::ApproxPercentileCont
+ }
+ protobuf::AggregateFunction::ApproxMedian => Self::ApproxMedian,
+ }
+ }
+}
+
+impl From<protobuf::BuiltInWindowFunction> for BuiltInWindowFunction {
+ fn from(built_in_function: protobuf::BuiltInWindowFunction) -> Self {
+ match built_in_function {
+ protobuf::BuiltInWindowFunction::RowNumber => Self::RowNumber,
+ protobuf::BuiltInWindowFunction::Rank => Self::Rank,
+ protobuf::BuiltInWindowFunction::PercentRank => Self::PercentRank,
+ protobuf::BuiltInWindowFunction::DenseRank => Self::DenseRank,
+ protobuf::BuiltInWindowFunction::Lag => Self::Lag,
+ protobuf::BuiltInWindowFunction::Lead => Self::Lead,
+ protobuf::BuiltInWindowFunction::FirstValue => Self::FirstValue,
+ protobuf::BuiltInWindowFunction::CumeDist => Self::CumeDist,
+ protobuf::BuiltInWindowFunction::Ntile => Self::Ntile,
+ protobuf::BuiltInWindowFunction::NthValue => Self::NthValue,
+ protobuf::BuiltInWindowFunction::LastValue => Self::LastValue,
+ }
+ }
+}
+
+impl TryFrom<&i32> for protobuf::PrimitiveScalarType {
+ type Error = Error;
+
+ fn try_from(value: &i32) -> Result<Self, Self::Error> {
+ protobuf::PrimitiveScalarType::from_i32(*value)
+ .ok_or_else(|| Error::unknown("PrimitiveScalarType", *value))
+ }
+}
+
+impl TryFrom<&i32> for protobuf::AggregateFunction {
+ type Error = Error;
+
+ fn try_from(value: &i32) -> Result<Self, Self::Error> {
+ protobuf::AggregateFunction::from_i32(*value)
+ .ok_or_else(|| Error::unknown("AggregateFunction", *value))
+ }
+}
+
+impl TryFrom<&protobuf::scalar_type::Datatype> for DataType {
+ type Error = Error;
+
+ fn try_from(
+ scalar_type: &protobuf::scalar_type::Datatype,
+ ) -> Result<Self, Self::Error> {
+ use protobuf::scalar_type::Datatype;
+
+ Ok(match scalar_type {
+ Datatype::Scalar(scalar_type) => {
+ protobuf::PrimitiveScalarType::try_from(scalar_type)?.into()
+ }
+ Datatype::List(protobuf::ScalarListType {
+ deepest_type,
+ field_names,
+ }) => {
+ if field_names.is_empty() {
+ return Err(Error::at_least_one("field_names"));
+ }
+ let field_type =
+ protobuf::PrimitiveScalarType::try_from(deepest_type)?.into();
+ //Because length is checked above it is safe to unwrap .last()
+ let mut scalar_type = DataType::List(Box::new(Field::new(
+ field_names.last().unwrap().as_str(),
+ field_type,
+ true,
+ )));
+ //Iterate over field names in reverse order except for the last item in the vector
+ for name in field_names.iter().rev().skip(1) {
+ let new_datatype = DataType::List(Box::new(Field::new(
+ name.as_str(),
+ scalar_type,
+ true,
+ )));
+ scalar_type = new_datatype;
+ }
+ scalar_type
+ }
+ })
+ }
+}
+
+impl TryFrom<&protobuf::scalar_value::Value> for ScalarValue {
+ type Error = Error;
+
+ fn try_from(scalar: &protobuf::scalar_value::Value) -> Result<Self, Self::Error> {
+ use protobuf::{scalar_value::Value, PrimitiveScalarType};
+
+ let scalar = match scalar {
+ Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),
+ Value::Utf8Value(v) => ScalarValue::Utf8(Some(v.to_owned())),
+ Value::LargeUtf8Value(v) => ScalarValue::LargeUtf8(Some(v.to_owned())),
+ Value::Int8Value(v) => ScalarValue::Int8(Some(*v as i8)),
+ Value::Int16Value(v) => ScalarValue::Int16(Some(*v as i16)),
+ Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),
+ Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),
+ Value::Uint8Value(v) => ScalarValue::UInt8(Some(*v as u8)),
+ Value::Uint16Value(v) => ScalarValue::UInt16(Some(*v as u16)),
+ Value::Uint32Value(v) => ScalarValue::UInt32(Some(*v)),
+ Value::Uint64Value(v) => ScalarValue::UInt64(Some(*v)),
+ Value::Float32Value(v) => ScalarValue::Float32(Some(*v)),
+ Value::Float64Value(v) => ScalarValue::Float64(Some(*v)),
+ Value::Date32Value(v) => ScalarValue::Date32(Some(*v)),
+ Value::TimeMicrosecondValue(v) => {
+ ScalarValue::TimestampMicrosecond(Some(*v), None)
+ }
+ Value::TimeNanosecondValue(v) => {
+ ScalarValue::TimestampNanosecond(Some(*v), None)
+ }
+ Value::ListValue(v) => v.try_into()?,
+ Value::NullListValue(v) => ScalarValue::List(None, Box::new(v.try_into()?)),
+ Value::NullValue(null_enum) => {
+ let primitive = PrimitiveScalarType::try_from(null_enum)?;
+ (&primitive).try_into()?
+ }
+ Value::Decimal128Value(val) => {
+ let array = vec_to_array(val.value.clone());
+ ScalarValue::Decimal128(
+ Some(i128::from_be_bytes(array)),
+ val.p as usize,
+ val.s as usize,
+ )
+ }
+ Value::Date64Value(v) => ScalarValue::Date64(Some(*v)),
+ Value::TimeSecondValue(v) => ScalarValue::TimestampSecond(Some(*v), None),
+ Value::TimeMillisecondValue(v) => {
+ ScalarValue::TimestampMillisecond(Some(*v), None)
+ }
+ Value::IntervalYearmonthValue(v) => ScalarValue::IntervalYearMonth(Some(*v)),
+ Value::IntervalDaytimeValue(v) => ScalarValue::IntervalDayTime(Some(*v)),
+ };
+ Ok(scalar)
+ }
+}
+
+impl TryFrom<&protobuf::ScalarListValue> for ScalarValue {
+ type Error = Error;
+
+ fn try_from(
+ scalar_list_value: &protobuf::ScalarListValue,
+ ) -> Result<Self, Self::Error> {
+ use protobuf::{scalar_type::Datatype, PrimitiveScalarType};
+
+ let protobuf::ScalarListValue { datatype, values } = scalar_list_value;
+ let pb_scalar_type = datatype
+ .as_ref()
+ .ok_or_else(|| Error::required("datatype"))?;
+
+ let scalar_type = pb_scalar_type
+ .datatype
+ .as_ref()
+ .ok_or_else(|| Error::required("datatype"))?;
+ let scalar_values = match scalar_type {
+ Datatype::Scalar(scalar_type_i32) => {
+ let leaf_scalar_type =
+ protobuf::PrimitiveScalarType::try_from(scalar_type_i32)?;
+ let typechecked_values: Vec<datafusion::scalar::ScalarValue> = values
+ .iter()
+ .map(|protobuf::ScalarValue { value: opt_value }| {
+ let value =
+ opt_value.as_ref().ok_or_else(|| Error::required("value"))?;
+ typechecked_scalar_value_conversion(value, leaf_scalar_type)
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ ScalarValue::List(
+ Some(Box::new(typechecked_values)),
+ Box::new(leaf_scalar_type.into()),
+ )
+ }
+ Datatype::List(list_type) => {
+ let protobuf::ScalarListType {
+ deepest_type,
+ field_names,
+ } = &list_type;
+ let leaf_type = PrimitiveScalarType::try_from(deepest_type)?;
+ let depth = field_names.len();
+
+ let typechecked_values: Vec<ScalarValue> = if depth == 0 {
+ return Err(Error::at_least_one("field_names"));
+ } else if depth == 1 {
+ values
+ .iter()
+ .map(|protobuf::ScalarValue { value: opt_value }| {
+ let value = opt_value
+ .as_ref()
+ .ok_or_else(|| Error::required("value"))?;
+ typechecked_scalar_value_conversion(value, leaf_type)
+ })
+ .collect::<Result<Vec<_>, _>>()?
+ } else {
+ values
+ .iter()
+ .map(|protobuf::ScalarValue { value: opt_value }| {
+ opt_value.as_ref().required("value")
+ })
+ .collect::<Result<Vec<_>, _>>()?
+ };
+ ScalarValue::List(
+ match typechecked_values.len() {
+ 0 => None,
+ _ => Some(Box::new(typechecked_values)),
+ },
+ Box::new((list_type).try_into()?),
+ )
+ }
+ };
+ Ok(scalar_values)
+ }
+}
+
+impl TryFrom<&protobuf::ScalarType> for DataType {
+ type Error = Error;
+
+ fn try_from(scalar: &protobuf::ScalarType) -> Result<Self, Self::Error> {
+ scalar.datatype.as_ref().required("datatype")
+ }
+}
+
+impl TryFrom<&protobuf::Schema> for Schema {
+ type Error = Error;
+
+ fn try_from(schema: &protobuf::Schema) -> Result<Self, Self::Error> {
+ let fields = schema
+ .columns
+ .iter()
+ .map(|c| {
+ let pb_arrow_type_res = c
+ .arrow_type
+ .as_ref()
+ .ok_or_else(|| proto_error("Protobuf deserialization error: Field message was missing required field 'arrow_type'"));
+ let pb_arrow_type: &protobuf::ArrowType = match pb_arrow_type_res {
+ Ok(res) => res,
+ Err(e) => return Err(e),
+ };
+ Ok(Field::new(&c.name, pb_arrow_type.try_into()?, c.nullable))
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(Self::new(fields))
+ }
+}
+
+impl TryFrom<&protobuf::PrimitiveScalarType> for ScalarValue {
+ type Error = Error;
+
+ fn try_from(scalar: &protobuf::PrimitiveScalarType) -> Result<Self, Self::Error> {
+ use protobuf::PrimitiveScalarType;
+
+ Ok(match scalar {
+ PrimitiveScalarType::Null => {
+ return Err(proto_error("Untyped null is an invalid scalar value"))
+ }
+ PrimitiveScalarType::Bool => Self::Boolean(None),
+ PrimitiveScalarType::Uint8 => Self::UInt8(None),
+ PrimitiveScalarType::Int8 => Self::Int8(None),
+ PrimitiveScalarType::Uint16 => Self::UInt16(None),
+ PrimitiveScalarType::Int16 => Self::Int16(None),
+ PrimitiveScalarType::Uint32 => Self::UInt32(None),
+ PrimitiveScalarType::Int32 => Self::Int32(None),
+ PrimitiveScalarType::Uint64 => Self::UInt64(None),
+ PrimitiveScalarType::Int64 => Self::Int64(None),
+ PrimitiveScalarType::Float32 => Self::Float32(None),
+ PrimitiveScalarType::Float64 => Self::Float64(None),
+ PrimitiveScalarType::Utf8 => Self::Utf8(None),
+ PrimitiveScalarType::LargeUtf8 => Self::LargeUtf8(None),
+ PrimitiveScalarType::Date32 => Self::Date32(None),
+ PrimitiveScalarType::TimeMicrosecond => {
+ Self::TimestampMicrosecond(None, None)
+ }
+ PrimitiveScalarType::TimeNanosecond => Self::TimestampNanosecond(None, None),
+ PrimitiveScalarType::Decimal128 => Self::Decimal128(None, 0, 0),
+ PrimitiveScalarType::Date64 => Self::Date64(None),
+ PrimitiveScalarType::TimeSecond => Self::TimestampSecond(None, None),
+ PrimitiveScalarType::TimeMillisecond => {
+ Self::TimestampMillisecond(None, None)
+ }
+ PrimitiveScalarType::IntervalYearmonth => Self::IntervalYearMonth(None),
+ PrimitiveScalarType::IntervalDaytime => Self::IntervalDayTime(None),
+ })
+ }
+}
+
+impl TryFrom<&protobuf::ScalarListType> for DataType {
+ type Error = Error;
+ fn try_from(scalar: &protobuf::ScalarListType) -> Result<Self, Self::Error> {
+ use protobuf::PrimitiveScalarType;
+
+ let protobuf::ScalarListType {
+ deepest_type,
+ field_names,
+ } = scalar;
+
+ let depth = field_names.len();
+ if depth == 0 {
+ return Err(Error::at_least_one("field_names"));
+ }
+
+ let mut curr_type = Self::List(Box::new(Field::new(
+ //Since checked vector is not empty above this is safe to unwrap
+ field_names.last().unwrap(),
+ PrimitiveScalarType::try_from(deepest_type)?.into(),
+ true,
+ )));
+ //Iterates over field names in reverse order except for the last item in the vector
+ for name in field_names.iter().rev().skip(1) {
+ let temp_curr_type = Self::List(Box::new(Field::new(name, curr_type, true)));
+ curr_type = temp_curr_type;
+ }
+ Ok(curr_type)
+ }
+}
+
+impl TryFrom<&protobuf::ScalarValue> for ScalarValue {
+ type Error = Error;
+
+ fn try_from(scalar: &protobuf::ScalarValue) -> Result<Self, Self::Error> {
+ use protobuf::scalar_value::Value;
+
+ let value = scalar
+ .value
+ .as_ref()
+ .ok_or_else(|| Error::required("value"))?;
+
+ Ok(match value {
+ Value::BoolValue(v) => Self::Boolean(Some(*v)),
+ Value::Utf8Value(v) => Self::Utf8(Some(v.to_owned())),
+ Value::LargeUtf8Value(v) => Self::LargeUtf8(Some(v.to_owned())),
+ Value::Int8Value(v) => Self::Int8(Some(*v as i8)),
+ Value::Int16Value(v) => Self::Int16(Some(*v as i16)),
+ Value::Int32Value(v) => Self::Int32(Some(*v)),
+ Value::Int64Value(v) => Self::Int64(Some(*v)),
+ Value::Uint8Value(v) => Self::UInt8(Some(*v as u8)),
+ Value::Uint16Value(v) => Self::UInt16(Some(*v as u16)),
+ Value::Uint32Value(v) => Self::UInt32(Some(*v)),
+ Value::Uint64Value(v) => Self::UInt64(Some(*v)),
+ Value::Float32Value(v) => Self::Float32(Some(*v)),
+ Value::Float64Value(v) => Self::Float64(Some(*v)),
+ Value::Date32Value(v) => Self::Date32(Some(*v)),
+ Value::TimeMicrosecondValue(v) => Self::TimestampMicrosecond(Some(*v), None),
+ Value::TimeNanosecondValue(v) => Self::TimestampNanosecond(Some(*v), None),
+ Value::ListValue(scalar_list) => {
+ let protobuf::ScalarListValue {
+ values,
+ datatype: opt_scalar_type,
+ } = &scalar_list;
+
+ let scalar_type = opt_scalar_type.as_ref().required("datatype")?;
+ let scalar_type = Box::new(scalar_type);
+
+ let typechecked_values: Vec<ScalarValue> = values
+ .iter()
+ .map(|val| val.try_into())
+ .collect::<Result<Vec<_>, _>>()?;
+
+ Self::List(Some(Box::new(typechecked_values)), scalar_type)
+ }
+ Value::NullListValue(v) => {
+ let datatype = v.datatype.as_ref().required("datatype")?;
+ Self::List(None, Box::new(datatype))
+ }
+ Value::NullValue(v) => {
+ let null_type_enum = protobuf::PrimitiveScalarType::try_from(v)?;
+ (&null_type_enum).try_into()?
+ }
+ Value::Decimal128Value(val) => {
+ let array = vec_to_array(val.value.clone());
+ Self::Decimal128(
+ Some(i128::from_be_bytes(array)),
+ val.p as usize,
+ val.s as usize,
+ )
+ }
+ Value::Date64Value(v) => Self::Date64(Some(*v)),
+ Value::TimeSecondValue(v) => Self::TimestampSecond(Some(*v), None),
+ Value::TimeMillisecondValue(v) => Self::TimestampMillisecond(Some(*v), None),
+ Value::IntervalYearmonthValue(v) => Self::IntervalYearMonth(Some(*v)),
+ Value::IntervalDaytimeValue(v) => Self::IntervalDayTime(Some(*v)),
+ })
+ }
+}
+
+impl TryFrom<&protobuf::LogicalExprNode> for Expr {
+ type Error = Error;
+
+ fn try_from(expr: &protobuf::LogicalExprNode) -> Result<Self, Self::Error> {
+ use datafusion::physical_plan::window_functions;
+ use protobuf::{logical_expr_node::ExprType, window_expr_node, ScalarFunction};
+
+ let expr_type = expr
+ .expr_type
+ .as_ref()
+ .ok_or_else(|| Error::required("expr_type"))?;
+
+ match expr_type {
+ ExprType::BinaryExpr(binary_expr) => Ok(Self::BinaryExpr {
+ left: Box::new(binary_expr.l.as_deref().required("l")?),
+ op: from_proto_binary_op(&binary_expr.op)?,
+ right: Box::new(binary_expr.r.as_deref().required("r")?),
+ }),
+ ExprType::Column(column) => Ok(Self::Column(column.into())),
+ ExprType::Literal(literal) => {
+ let scalar_value: ScalarValue = literal.try_into()?;
+ Ok(Self::Literal(scalar_value))
+ }
+ ExprType::WindowExpr(expr) => {
+ let window_function = expr
+ .window_function
+ .as_ref()
+ .ok_or_else(|| Error::required("window_function"))?;
+ let partition_by = expr
+ .partition_by
+ .iter()
+ .map(|e| e.try_into())
+ .collect::<Result<Vec<_>, _>>()?;
+ let order_by = expr
+ .order_by
+ .iter()
+ .map(|e| e.try_into())
+ .collect::<Result<Vec<_>, _>>()?;
+ let window_frame = expr
+ .window_frame
+ .as_ref()
+ .map::<Result<WindowFrame, _>, _>(|e| match e {
+ window_expr_node::WindowFrame::Frame(frame) => {
+ let window_frame: WindowFrame = frame.clone().try_into()?;
+ if WindowFrameUnits::Range == window_frame.units
+ && order_by.len() != 1
+ {
+ Err(proto_error("With window frame of type RANGE, the order by expression must be of length 1"))
+ } else {
+ Ok(window_frame)
+ }
+ }
+ })
+ .transpose()?;
+
+ match window_function {
+ window_expr_node::WindowFunction::AggrFunction(i) => {
+ let aggr_function =
+ protobuf::AggregateFunction::try_from(i)?.into();
+
+ Ok(Self::WindowFunction {
+ fun: window_functions::WindowFunction::AggregateFunction(
+ aggr_function,
+ ),
+ args: vec![expr.expr.as_deref().required("expr")?],
+ partition_by,
+ order_by,
+ window_frame,
+ })
+ }
+ window_expr_node::WindowFunction::BuiltInFunction(i) => {
+ let built_in_function =
+ protobuf::BuiltInWindowFunction::from_i32(*i)
+ .ok_or_else(|| {
+ Error::unknown("BuiltInWindowFunction", *i)
+ })?
+ .into();
+
+ Ok(Self::WindowFunction {
+ fun: window_functions::WindowFunction::BuiltInWindowFunction(
+ built_in_function,
+ ),
+ args: vec![expr.expr.as_deref().required("expr")?],
+ partition_by,
+ order_by,
+ window_frame,
+ })
+ }
+ }
+ }
+ ExprType::AggregateExpr(expr) => {
+ let fun =
+ protobuf::AggregateFunction::try_from(&expr.aggr_function)?.into();
+
+ Ok(Self::AggregateFunction {
+ fun,
+ args: expr
+ .expr
+ .iter()
+ .map(|e| e.try_into())
+ .collect::<Result<Vec<_>, _>>()?,
+ distinct: false, //TODO
+ })
+ }
+ ExprType::Alias(alias) => Ok(Self::Alias(
+ Box::new(alias.expr.as_deref().required("expr")?),
+ alias.alias.clone(),
+ )),
+ ExprType::IsNullExpr(is_null) => Ok(Self::IsNull(Box::new(
+ is_null.expr.as_deref().required("expr")?,
+ ))),
+ ExprType::IsNotNullExpr(is_not_null) => Ok(Self::IsNotNull(Box::new(
+ is_not_null.expr.as_deref().required("expr")?,
+ ))),
+ ExprType::NotExpr(not) => {
+ Ok(Self::Not(Box::new(not.expr.as_deref().required("expr")?)))
+ }
+ ExprType::Between(between) => Ok(Self::Between {
+ expr: Box::new(between.expr.as_deref().required("expr")?),
+ negated: between.negated,
+ low: Box::new(between.low.as_deref().required("low")?),
+ high: Box::new(between.high.as_deref().required("high")?),
+ }),
+ ExprType::Case(case) => {
+ let when_then_expr = case
+ .when_then_expr
+ .iter()
+ .map(|e| {
+ let when_expr = e.when_expr.as_ref().required("when_expr")?;
+ let then_expr = e.then_expr.as_ref().required("then_expr")?;
+ Ok((Box::new(when_expr), Box::new(then_expr)))
+ })
+ .collect::<Result<Vec<(Box<Expr>, Box<Expr>)>, Error>>()?;
+ Ok(Self::Case {
+ expr: parse_optional_expr(&case.expr)?.map(Box::new),
+ when_then_expr,
+ else_expr: parse_optional_expr(&case.else_expr)?.map(Box::new),
+ })
+ }
+ ExprType::Cast(cast) => {
+ let expr = Box::new(cast.expr.as_deref().required("expr")?);
+ let data_type = cast.arrow_type.as_ref().required("arrow_type")?;
+ Ok(Self::Cast { expr, data_type })
+ }
+ ExprType::TryCast(cast) => {
+ let expr = Box::new(cast.expr.as_deref().required("expr")?);
+ let data_type = cast.arrow_type.as_ref().required("arrow_type")?;
+ Ok(Self::TryCast { expr, data_type })
+ }
+ ExprType::Sort(sort) => Ok(Self::Sort {
+ expr: Box::new(sort.expr.as_deref().required("expr")?),
+ asc: sort.asc,
+ nulls_first: sort.nulls_first,
+ }),
+ ExprType::Negative(negative) => Ok(Self::Negative(Box::new(
+ negative.expr.as_deref().required("expr")?,
+ ))),
+ ExprType::InList(in_list) => Ok(Self::InList {
+ expr: Box::new(in_list.expr.as_deref().required("expr")?),
+ list: in_list
+ .list
+ .iter()
+ .map(|expr| expr.try_into())
+ .collect::<Result<Vec<_>, _>>()?,
+ negated: in_list.negated,
+ }),
+ ExprType::Wildcard(_) => Ok(Self::Wildcard),
+ ExprType::ScalarFunction(expr) => {
+ let scalar_function = protobuf::ScalarFunction::from_i32(expr.fun)
+ .ok_or_else(|| Error::unknown("ScalarFunction", expr.fun))?;
+ let args = &expr.args;
+
+ match scalar_function {
+ ScalarFunction::Sqrt => Ok(sqrt((&args[0]).try_into()?)),
+ ScalarFunction::Sin => Ok(sin((&args[0]).try_into()?)),
+ ScalarFunction::Cos => Ok(cos((&args[0]).try_into()?)),
+ ScalarFunction::Tan => Ok(tan((&args[0]).try_into()?)),
+ // ScalarFunction::Asin => Ok(asin(&args[0]).try_into()?)),
+ // ScalarFunction::Acos => Ok(acos(&args[0]).try_into()?)),
+ ScalarFunction::Atan => Ok(atan((&args[0]).try_into()?)),
+ ScalarFunction::Exp => Ok(exp((&args[0]).try_into()?)),
+ ScalarFunction::Log2 => Ok(log2((&args[0]).try_into()?)),
+ ScalarFunction::Ln => Ok(ln((&args[0]).try_into()?)),
+ ScalarFunction::Log10 => Ok(log10((&args[0]).try_into()?)),
+ ScalarFunction::Floor => Ok(floor((&args[0]).try_into()?)),
+ ScalarFunction::Ceil => Ok(ceil((&args[0]).try_into()?)),
+ ScalarFunction::Round => Ok(round((&args[0]).try_into()?)),
+ ScalarFunction::Trunc => Ok(trunc((&args[0]).try_into()?)),
+ ScalarFunction::Abs => Ok(abs((&args[0]).try_into()?)),
+ ScalarFunction::Signum => Ok(signum((&args[0]).try_into()?)),
+ ScalarFunction::Octetlength => {
+ Ok(octet_length((&args[0]).try_into()?))
+ }
+ // // ScalarFunction::Concat => Ok(concat((&args[0]).try_into()?)),
+ ScalarFunction::Lower => Ok(lower((&args[0]).try_into()?)),
+ ScalarFunction::Upper => Ok(upper((&args[0]).try_into()?)),
+ ScalarFunction::Trim => Ok(trim((&args[0]).try_into()?)),
+ ScalarFunction::Ltrim => Ok(ltrim((&args[0]).try_into()?)),
+ ScalarFunction::Rtrim => Ok(rtrim((&args[0]).try_into()?)),
+ // ScalarFunction::Totimestamp => Ok(to_timestamp((&args[0]).try_into()?)),
+ // ScalarFunction::Array => Ok(array((&args[0]).try_into()?)),
+ // // ScalarFunction::Nullif => Ok(nulli((&args[0]).try_into()?)),
+ ScalarFunction::Datepart => {
+ Ok(date_part((&args[0]).try_into()?, (&args[1]).try_into()?))
+ }
+ ScalarFunction::Datetrunc => {
+ Ok(date_trunc((&args[0]).try_into()?, (&args[1]).try_into()?))
+ }
+ // ScalarFunction::Md5 => Ok(md5((&args[0]).try_into()?)),
+ ScalarFunction::Sha224 => Ok(sha224((&args[0]).try_into()?)),
+ ScalarFunction::Sha256 => Ok(sha256((&args[0]).try_into()?)),
+ ScalarFunction::Sha384 => Ok(sha384((&args[0]).try_into()?)),
+ ScalarFunction::Sha512 => Ok(sha512((&args[0]).try_into()?)),
+ ScalarFunction::Digest => {
+ Ok(digest((&args[0]).try_into()?, (&args[1]).try_into()?))
+ }
+ _ => Err(proto_error(
+ "Protobuf deserialization error: Unsupported scalar function",
+ )),
+ }
+ }
+ }
+ }
+}
+
+impl TryFrom<protobuf::WindowFrame> for WindowFrame {
+ type Error = Error;
+
+ fn try_from(window: protobuf::WindowFrame) -> Result<Self, Self::Error> {
+ let units = protobuf::WindowFrameUnits::from_i32(window.window_frame_units)
+ .ok_or_else(|| Error::unknown("WindowFrameUnits", window.window_frame_units))?
+ .into();
+ let start_bound = window.start_bound.required("start_bound")?;
+ let end_bound = window
+ .end_bound
+ .map(|end_bound| match end_bound {
+ protobuf::window_frame::EndBound::Bound(end_bound) => {
+ end_bound.try_into()
+ }
+ })
+ .transpose()?
+ .unwrap_or(WindowFrameBound::CurrentRow);
+ Ok(Self {
+ units,
+ start_bound,
+ end_bound,
+ })
+ }
+}
+
+impl TryFrom<protobuf::WindowFrameBound> for WindowFrameBound {
+ type Error = Error;
+
+ fn try_from(bound: protobuf::WindowFrameBound) -> Result<Self, Self::Error> {
+ let bound_type =
+ protobuf::WindowFrameBoundType::from_i32(bound.window_frame_bound_type)
+ .ok_or_else(|| {
+ Error::unknown("WindowFrameBoundType", bound.window_frame_bound_type)
+ })?;
+ match bound_type {
+ protobuf::WindowFrameBoundType::CurrentRow => Ok(Self::CurrentRow),
+ protobuf::WindowFrameBoundType::Preceding => {
+ // FIXME implement bound value parsing
+ // https://github.com/apache/arrow-datafusion/issues/361
+ Ok(Self::Preceding(Some(1)))
+ }
+ protobuf::WindowFrameBoundType::Following => {
+ // FIXME implement bound value parsing
+ // https://github.com/apache/arrow-datafusion/issues/361
+ Ok(Self::Following(Some(1)))
+ }
+ }
+ }
+}
+
+impl TryFrom<&Box<protobuf::List>> for DataType {
+ type Error = Error;
+ fn try_from(list: &Box<protobuf::List>) -> Result<Self, Self::Error> {
+ Ok(Self::List(Box::new(
+ list.as_ref().field_type.as_deref().required("field_type")?,
+ )))
+ }
+}
+
+impl TryFrom<&i32> for protobuf::TimeUnit {
+ type Error = Error;
+
+ fn try_from(value: &i32) -> Result<Self, Self::Error> {
+ protobuf::TimeUnit::from_i32(*value)
+ .ok_or_else(|| Error::unknown("TimeUnit", *value))
+ }
+}
+
+impl From<protobuf::TimeUnit> for TimeUnit {
+ fn from(time_unit: protobuf::TimeUnit) -> Self {
+ match time_unit {
+ protobuf::TimeUnit::Second => TimeUnit::Second,
+ protobuf::TimeUnit::TimeMillisecond => TimeUnit::Millisecond,
+ protobuf::TimeUnit::Microsecond => TimeUnit::Microsecond,
+ protobuf::TimeUnit::Nanosecond => TimeUnit::Nanosecond,
+ }
+ }
+}
+
+impl TryFrom<&i32> for protobuf::IntervalUnit {
+ type Error = Error;
+
+ fn try_from(value: &i32) -> Result<Self, Self::Error> {
+ protobuf::IntervalUnit::from_i32(*value)
+ .ok_or_else(|| Error::unknown("IntervalUnit", *value))
+ }
+}
+
+impl From<protobuf::IntervalUnit> for IntervalUnit {
+ fn from(interval_unit: protobuf::IntervalUnit) -> Self {
+ match interval_unit {
+ protobuf::IntervalUnit::YearMonth => IntervalUnit::YearMonth,
+ protobuf::IntervalUnit::DayTime => IntervalUnit::DayTime,
+ protobuf::IntervalUnit::MonthDayNano => IntervalUnit::MonthDayNano,
+ }
+ }
+}
+
+fn vec_to_array<T, const N: usize>(v: Vec<T>) -> [T; N] {
+ v.try_into().unwrap_or_else(|v: Vec<T>| {
+ panic!("Expected a Vec of length {} but it was {}", N, v.len())
+ })
+}
+
+//Does not typecheck lists
+fn typechecked_scalar_value_conversion(
+ tested_type: &protobuf::scalar_value::Value,
+ required_type: protobuf::PrimitiveScalarType,
+) -> Result<ScalarValue, Error> {
+ use protobuf::{scalar_value::Value, PrimitiveScalarType};
+
+ Ok(match (tested_type, &required_type) {
+ (Value::BoolValue(v), PrimitiveScalarType::Bool) => {
+ ScalarValue::Boolean(Some(*v))
+ }
+ (Value::Int8Value(v), PrimitiveScalarType::Int8) => {
+ ScalarValue::Int8(Some(*v as i8))
+ }
+ (Value::Int16Value(v), PrimitiveScalarType::Int16) => {
+ ScalarValue::Int16(Some(*v as i16))
+ }
+ (Value::Int32Value(v), PrimitiveScalarType::Int32) => {
+ ScalarValue::Int32(Some(*v))
+ }
+ (Value::Int64Value(v), PrimitiveScalarType::Int64) => {
+ ScalarValue::Int64(Some(*v))
+ }
+ (Value::Uint8Value(v), PrimitiveScalarType::Uint8) => {
+ ScalarValue::UInt8(Some(*v as u8))
+ }
+ (Value::Uint16Value(v), PrimitiveScalarType::Uint16) => {
+ ScalarValue::UInt16(Some(*v as u16))
+ }
+ (Value::Uint32Value(v), PrimitiveScalarType::Uint32) => {
+ ScalarValue::UInt32(Some(*v))
+ }
+ (Value::Uint64Value(v), PrimitiveScalarType::Uint64) => {
+ ScalarValue::UInt64(Some(*v))
+ }
+ (Value::Float32Value(v), PrimitiveScalarType::Float32) => {
+ ScalarValue::Float32(Some(*v))
+ }
+ (Value::Float64Value(v), PrimitiveScalarType::Float64) => {
+ ScalarValue::Float64(Some(*v))
+ }
+ (Value::Date32Value(v), PrimitiveScalarType::Date32) => {
+ ScalarValue::Date32(Some(*v))
+ }
+ (Value::TimeMicrosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {
+ ScalarValue::TimestampMicrosecond(Some(*v), None)
+ }
+ (Value::TimeNanosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {
+ ScalarValue::TimestampNanosecond(Some(*v), None)
+ }
+ (Value::Utf8Value(v), PrimitiveScalarType::Utf8) => {
+ ScalarValue::Utf8(Some(v.to_owned()))
+ }
+ (Value::LargeUtf8Value(v), PrimitiveScalarType::LargeUtf8) => {
+ ScalarValue::LargeUtf8(Some(v.to_owned()))
+ }
+
+ (Value::NullValue(i32_enum), required_scalar_type) => {
+ if *i32_enum == *required_scalar_type as i32 {
+ let pb_scalar_type = PrimitiveScalarType::try_from(i32_enum)?;
+ let scalar_value: ScalarValue = match pb_scalar_type {
+ PrimitiveScalarType::Bool => ScalarValue::Boolean(None),
+ PrimitiveScalarType::Uint8 => ScalarValue::UInt8(None),
+ PrimitiveScalarType::Int8 => ScalarValue::Int8(None),
+ PrimitiveScalarType::Uint16 => ScalarValue::UInt16(None),
+ PrimitiveScalarType::Int16 => ScalarValue::Int16(None),
+ PrimitiveScalarType::Uint32 => ScalarValue::UInt32(None),
+ PrimitiveScalarType::Int32 => ScalarValue::Int32(None),
+ PrimitiveScalarType::Uint64 => ScalarValue::UInt64(None),
+ PrimitiveScalarType::Int64 => ScalarValue::Int64(None),
+ PrimitiveScalarType::Float32 => ScalarValue::Float32(None),
+ PrimitiveScalarType::Float64 => ScalarValue::Float64(None),
+ PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),
+ PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),
+ PrimitiveScalarType::Date32 => ScalarValue::Date32(None),
+ PrimitiveScalarType::TimeMicrosecond => {
+ ScalarValue::TimestampMicrosecond(None, None)
+ }
+ PrimitiveScalarType::TimeNanosecond => {
+ ScalarValue::TimestampNanosecond(None, None)
+ }
+ PrimitiveScalarType::Null => {
+ return Err(proto_error(
+ "Untyped scalar null is not a valid scalar value",
+ ))
+ }
+ PrimitiveScalarType::Decimal128 => {
+ ScalarValue::Decimal128(None, 0, 0)
+ }
+ PrimitiveScalarType::Date64 => ScalarValue::Date64(None),
+ PrimitiveScalarType::TimeSecond => {
+ ScalarValue::TimestampSecond(None, None)
+ }
+ PrimitiveScalarType::TimeMillisecond => {
+ ScalarValue::TimestampMillisecond(None, None)
+ }
+ PrimitiveScalarType::IntervalYearmonth => {
+ ScalarValue::IntervalYearMonth(None)
+ }
+ PrimitiveScalarType::IntervalDaytime => {
+ ScalarValue::IntervalDayTime(None)
+ }
+ };
+ scalar_value
+ } else {
+ return Err(proto_error("Could not convert to the proper type"));
+ }
+ }
+ (Value::Decimal128Value(val), PrimitiveScalarType::Decimal128) => {
+ let array = vec_to_array(val.value.clone());
+ ScalarValue::Decimal128(
+ Some(i128::from_be_bytes(array)),
+ val.p as usize,
+ val.s as usize,
+ )
+ }
+ (Value::Date64Value(v), PrimitiveScalarType::Date64) => {
+ ScalarValue::Date64(Some(*v))
+ }
+ (Value::TimeSecondValue(v), PrimitiveScalarType::TimeSecond) => {
+ ScalarValue::TimestampSecond(Some(*v), None)
+ }
+ (Value::TimeMillisecondValue(v), PrimitiveScalarType::TimeMillisecond) => {
+ ScalarValue::TimestampMillisecond(Some(*v), None)
+ }
+ (Value::IntervalYearmonthValue(v), PrimitiveScalarType::IntervalYearmonth) => {
+ ScalarValue::IntervalYearMonth(Some(*v))
+ }
+ (Value::IntervalDaytimeValue(v), PrimitiveScalarType::IntervalDaytime) => {
+ ScalarValue::IntervalDayTime(Some(*v))
+ }
+ _ => return Err(proto_error("Could not convert to the proper type")),
+ })
+}
+
+fn from_proto_binary_op(op: &str) -> Result<Operator, Error> {
+ match op {
+ "And" => Ok(Operator::And),
+ "Or" => Ok(Operator::Or),
+ "Eq" => Ok(Operator::Eq),
+ "NotEq" => Ok(Operator::NotEq),
+ "LtEq" => Ok(Operator::LtEq),
+ "Lt" => Ok(Operator::Lt),
+ "Gt" => Ok(Operator::Gt),
+ "GtEq" => Ok(Operator::GtEq),
+ "Plus" => Ok(Operator::Plus),
+ "Minus" => Ok(Operator::Minus),
+ "Multiply" => Ok(Operator::Multiply),
+ "Divide" => Ok(Operator::Divide),
+ "Modulo" => Ok(Operator::Modulo),
+ "Like" => Ok(Operator::Like),
+ "NotLike" => Ok(Operator::NotLike),
+ other => Err(proto_error(format!(
+ "Unsupported binary operator '{:?}'",
+ other
+ ))),
+ }
+}
+
+fn parse_optional_expr(
+ p: &Option<Box<protobuf::LogicalExprNode>>,
+) -> Result<Option<Expr>, Error> {
+ match p {
+ Some(expr) => expr.as_ref().try_into().map(Some),
+ None => Ok(None),
+ }
+}
+
+fn proto_error<S: Into<String>>(message: S) -> Error {
+ Error::General(message.into())
+}
diff --git a/datafusion-proto/src/lib.rs b/datafusion-proto/src/lib.rs
new file mode 100644
index 0000000000..b880f8ee47
--- /dev/null
+++ b/datafusion-proto/src/lib.rs
@@ -0,0 +1,688 @@
+// 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.
+
+// include the generated protobuf source as a submodule
+#[allow(clippy::all)]
+pub mod protobuf {
+ include!(concat!(env!("OUT_DIR"), "/datafusion.rs"));
+}
+
+pub mod from_proto;
+pub mod to_proto;
+
+#[cfg(test)]
+mod roundtrip_tests {
+ use datafusion::{
+ arrow::datatypes::{DataType, Field, IntervalUnit, TimeUnit, UnionMode},
+ logical_plan::{col, Expr},
+ physical_plan::{aggregates, functions::BuiltinScalarFunction::Sqrt},
+ prelude::*,
+ scalar::ScalarValue,
+ };
+
+ // Given a DataFusion type, convert it to protobuf and back, using debug formatting to test
+ // equality.
+ macro_rules! roundtrip_test {
+ ($initial_struct:ident, $proto_type:ty, $struct_type:ty) => {
+ let proto: $proto_type = (&$initial_struct).try_into().unwrap();
+
+ let round_trip: $struct_type = (&proto).try_into().unwrap();
+
+ assert_eq!(
+ format!("{:?}", $initial_struct),
+ format!("{:?}", round_trip)
+ );
+ };
+ }
+
+ fn new_box_field(name: &str, dt: DataType, nullable: bool) -> Box<Field> {
+ Box::new(Field::new(name, dt, nullable))
+ }
+
+ #[test]
+ fn scalar_values_error_serialization() {
+ let should_fail_on_seralize: Vec<ScalarValue> = vec![
+ //Should fail due to inconsistent types
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::Int16(None),
+ ScalarValue::Float32(Some(32.0)),
+ ])),
+ Box::new(DataType::List(new_box_field("item", DataType::Int16, true))),
+ ),
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::Float32(None),
+ ScalarValue::Float32(Some(32.0)),
+ ])),
+ Box::new(DataType::List(new_box_field("item", DataType::Int16, true))),
+ ),
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::List(
+ None,
+ Box::new(DataType::List(new_box_field(
+ "level2",
+ DataType::Float32,
+ true,
+ ))),
+ ),
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::Float32(Some(-213.1)),
+ ScalarValue::Float32(None),
+ ScalarValue::Float32(Some(5.5)),
+ ScalarValue::Float32(Some(2.0)),
+ ScalarValue::Float32(Some(1.0)),
+ ])),
+ Box::new(DataType::List(new_box_field(
+ "level2",
+ DataType::Float32,
+ true,
+ ))),
+ ),
+ ScalarValue::List(
+ None,
+ Box::new(DataType::List(new_box_field(
+ "lists are typed inconsistently",
+ DataType::Int16,
+ true,
+ ))),
+ ),
+ ])),
+ Box::new(DataType::List(new_box_field(
+ "level1",
+ DataType::List(new_box_field("level2", DataType::Float32, true)),
+ true,
+ ))),
+ ),
+ ];
+
+ for test_case in should_fail_on_seralize.into_iter() {
+ let res: std::result::Result<
+ super::protobuf::ScalarValue,
+ super::to_proto::Error,
+ > = (&test_case).try_into();
+ assert!(
+ res.is_err(),
+ "The value {:?} should not have been able to serialize. Serialized to :{:?}",
+ test_case, res
+ );
+ }
+ }
+
+ #[test]
+ fn round_trip_scalar_values() {
+ let should_pass: Vec<ScalarValue> = vec![
+ ScalarValue::Boolean(None),
+ ScalarValue::Float32(None),
+ ScalarValue::Float64(None),
+ ScalarValue::Int8(None),
+ ScalarValue::Int16(None),
+ ScalarValue::Int32(None),
+ ScalarValue::Int64(None),
+ ScalarValue::UInt8(None),
+ ScalarValue::UInt16(None),
+ ScalarValue::UInt32(None),
+ ScalarValue::UInt64(None),
+ ScalarValue::Utf8(None),
+ ScalarValue::LargeUtf8(None),
+ ScalarValue::List(None, Box::new(DataType::Boolean)),
+ ScalarValue::Date32(None),
+ ScalarValue::TimestampMicrosecond(None, None),
+ ScalarValue::TimestampNanosecond(None, None),
+ ScalarValue::Boolean(Some(true)),
+ ScalarValue::Boolean(Some(false)),
+ ScalarValue::Float32(Some(1.0)),
+ ScalarValue::Float32(Some(f32::MAX)),
+ ScalarValue::Float32(Some(f32::MIN)),
+ ScalarValue::Float32(Some(-2000.0)),
+ ScalarValue::Float64(Some(1.0)),
+ ScalarValue::Float64(Some(f64::MAX)),
+ ScalarValue::Float64(Some(f64::MIN)),
+ ScalarValue::Float64(Some(-2000.0)),
+ ScalarValue::Int8(Some(i8::MIN)),
+ ScalarValue::Int8(Some(i8::MAX)),
+ ScalarValue::Int8(Some(0)),
+ ScalarValue::Int8(Some(-15)),
+ ScalarValue::Int16(Some(i16::MIN)),
+ ScalarValue::Int16(Some(i16::MAX)),
+ ScalarValue::Int16(Some(0)),
+ ScalarValue::Int16(Some(-15)),
+ ScalarValue::Int32(Some(i32::MIN)),
+ ScalarValue::Int32(Some(i32::MAX)),
+ ScalarValue::Int32(Some(0)),
+ ScalarValue::Int32(Some(-15)),
+ ScalarValue::Int64(Some(i64::MIN)),
+ ScalarValue::Int64(Some(i64::MAX)),
+ ScalarValue::Int64(Some(0)),
+ ScalarValue::Int64(Some(-15)),
+ ScalarValue::UInt8(Some(u8::MAX)),
+ ScalarValue::UInt8(Some(0)),
+ ScalarValue::UInt16(Some(u16::MAX)),
+ ScalarValue::UInt16(Some(0)),
+ ScalarValue::UInt32(Some(u32::MAX)),
+ ScalarValue::UInt32(Some(0)),
+ ScalarValue::UInt64(Some(u64::MAX)),
+ ScalarValue::UInt64(Some(0)),
+ ScalarValue::Utf8(Some(String::from("Test string "))),
+ ScalarValue::LargeUtf8(Some(String::from("Test Large utf8"))),
+ ScalarValue::Date32(Some(0)),
+ ScalarValue::Date32(Some(i32::MAX)),
+ ScalarValue::TimestampNanosecond(Some(0), None),
+ ScalarValue::TimestampNanosecond(Some(i64::MAX), None),
+ ScalarValue::TimestampMicrosecond(Some(0), None),
+ ScalarValue::TimestampMicrosecond(Some(i64::MAX), None),
+ ScalarValue::TimestampMicrosecond(None, None),
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::Float32(Some(-213.1)),
+ ScalarValue::Float32(None),
+ ScalarValue::Float32(Some(5.5)),
+ ScalarValue::Float32(Some(2.0)),
+ ScalarValue::Float32(Some(1.0)),
+ ])),
+ Box::new(DataType::List(new_box_field(
+ "level1",
+ DataType::Float32,
+ true,
+ ))),
+ ),
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::List(
+ None,
+ Box::new(DataType::List(new_box_field(
+ "level2",
+ DataType::Float32,
+ true,
+ ))),
+ ),
+ ScalarValue::List(
+ Some(Box::new(vec![
+ ScalarValue::Float32(Some(-213.1)),
+ ScalarValue::Float32(None),
+ ScalarValue::Float32(Some(5.5)),
+ ScalarValue::Float32(Some(2.0)),
+ ScalarValue::Float32(Some(1.0)),
+ ])),
+ Box::new(DataType::List(new_box_field(
+ "level2",
+ DataType::Float32,
+ true,
+ ))),
+ ),
+ ])),
+ Box::new(DataType::List(new_box_field(
+ "level1",
+ DataType::List(new_box_field("level2", DataType::Float32, true)),
+ true,
+ ))),
+ ),
+ ];
+
+ for test_case in should_pass.into_iter() {
+ let proto: super::protobuf::ScalarValue = (&test_case).try_into().unwrap();
+ let _roundtrip: ScalarValue = (&proto).try_into().unwrap();
+ }
+ }
+
+ #[test]
+ fn round_trip_scalar_types() {
+ let should_pass: Vec<DataType> = vec![
+ DataType::Boolean,
+ DataType::Int8,
+ DataType::Int16,
+ DataType::Int32,
+ DataType::Int64,
+ DataType::UInt8,
+ DataType::UInt16,
+ DataType::UInt32,
+ DataType::UInt64,
+ DataType::Float32,
+ DataType::Float64,
+ DataType::Date32,
+ DataType::Time64(TimeUnit::Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond),
+ DataType::Utf8,
+ DataType::LargeUtf8,
+ //Recursive list tests
+ DataType::List(new_box_field("Level1", DataType::Boolean, true)),
+ DataType::List(new_box_field(
+ "Level1",
+ DataType::List(new_box_field("Level2", DataType::Date32, true)),
+ true,
+ )),
+ ];
+
+ let should_fail: Vec<DataType> = vec![
+ DataType::Null,
+ DataType::Float16,
+ //Add more timestamp tests
+ DataType::Timestamp(TimeUnit::Millisecond, None),
+ DataType::Date64,
+ DataType::Time32(TimeUnit::Second),
+ DataType::Time32(TimeUnit::Millisecond),
+ DataType::Time32(TimeUnit::Microsecond),
+ DataType::Time32(TimeUnit::Nanosecond),
+ DataType::Time64(TimeUnit::Second),
+ DataType::Time64(TimeUnit::Millisecond),
+ DataType::Duration(TimeUnit::Second),
+ DataType::Duration(TimeUnit::Millisecond),
+ DataType::Duration(TimeUnit::Microsecond),
+ DataType::Duration(TimeUnit::Nanosecond),
+ DataType::Interval(IntervalUnit::YearMonth),
+ DataType::Interval(IntervalUnit::DayTime),
+ DataType::Binary,
+ DataType::FixedSizeBinary(0),
+ DataType::FixedSizeBinary(1234),
+ DataType::FixedSizeBinary(-432),
+ DataType::LargeBinary,
+ DataType::Decimal(1345, 5431),
+ //Recursive list tests
+ DataType::List(new_box_field("Level1", DataType::Binary, true)),
+ DataType::List(new_box_field(
+ "Level1",
+ DataType::List(new_box_field(
+ "Level2",
+ DataType::FixedSizeBinary(53),
+ false,
+ )),
+ true,
+ )),
+ //Fixed size lists
+ DataType::FixedSizeList(new_box_field("Level1", DataType::Binary, true), 4),
+ DataType::FixedSizeList(
+ new_box_field(
+ "Level1",
+ DataType::List(new_box_field(
+ "Level2",
+ DataType::FixedSizeBinary(53),
+ false,
+ )),
+ true,
+ ),
+ 41,
+ ),
+ //Struct Testing
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ]),
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ Field::new(
+ "nested_struct",
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ]),
+ true,
+ ),
+ ]),
+ DataType::Union(
+ vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ],
+ UnionMode::Dense,
+ ),
+ DataType::Union(
+ vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ Field::new(
+ "nested_struct",
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ]),
+ true,
+ ),
+ ],
+ UnionMode::Sparse,
+ ),
+ DataType::Dictionary(
+ Box::new(DataType::Utf8),
+ Box::new(DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ])),
+ ),
+ DataType::Dictionary(
+ Box::new(DataType::Decimal(10, 50)),
+ Box::new(DataType::FixedSizeList(
+ new_box_field("Level1", DataType::Binary, true),
+ 4,
+ )),
+ ),
+ ];
+
+ for test_case in should_pass.into_iter() {
+ let proto: super::protobuf::ScalarType = (&test_case).try_into().unwrap();
+ let roundtrip: DataType = (&proto).try_into().unwrap();
+ assert_eq!(format!("{:?}", test_case), format!("{:?}", roundtrip));
+ }
+
+ let mut success: Vec<DataType> = Vec::new();
+ for test_case in should_fail.into_iter() {
+ let proto: std::result::Result<
+ super::protobuf::ScalarType,
+ super::to_proto::Error,
+ > = (&test_case).try_into();
+ if proto.is_ok() {
+ success.push(test_case)
+ }
+ }
+ assert!(
+ success.is_empty(),
+ "These should have resulted in an error but completed successfully: {:?}",
+ success
+ );
+ }
+
+ #[test]
+ fn round_trip_datatype() {
+ let test_cases: Vec<DataType> = vec![
+ DataType::Null,
+ DataType::Boolean,
+ DataType::Int8,
+ DataType::Int16,
+ DataType::Int32,
+ DataType::Int64,
+ DataType::UInt8,
+ DataType::UInt16,
+ DataType::UInt32,
+ DataType::UInt64,
+ DataType::Float16,
+ DataType::Float32,
+ DataType::Float64,
+ //Add more timestamp tests
+ DataType::Timestamp(TimeUnit::Millisecond, None),
+ DataType::Date32,
+ DataType::Date64,
+ DataType::Time32(TimeUnit::Second),
+ DataType::Time32(TimeUnit::Millisecond),
+ DataType::Time32(TimeUnit::Microsecond),
+ DataType::Time32(TimeUnit::Nanosecond),
+ DataType::Time64(TimeUnit::Second),
+ DataType::Time64(TimeUnit::Millisecond),
+ DataType::Time64(TimeUnit::Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond),
+ DataType::Duration(TimeUnit::Second),
+ DataType::Duration(TimeUnit::Millisecond),
+ DataType::Duration(TimeUnit::Microsecond),
+ DataType::Duration(TimeUnit::Nanosecond),
+ DataType::Interval(IntervalUnit::YearMonth),
+ DataType::Interval(IntervalUnit::DayTime),
+ DataType::Binary,
+ DataType::FixedSizeBinary(0),
+ DataType::FixedSizeBinary(1234),
+ DataType::FixedSizeBinary(-432),
+ DataType::LargeBinary,
+ DataType::Utf8,
+ DataType::LargeUtf8,
+ DataType::Decimal(1345, 5431),
+ //Recursive list tests
+ DataType::List(new_box_field("Level1", DataType::Binary, true)),
+ DataType::List(new_box_field(
+ "Level1",
+ DataType::List(new_box_field(
+ "Level2",
+ DataType::FixedSizeBinary(53),
+ false,
+ )),
+ true,
+ )),
+ //Fixed size lists
+ DataType::FixedSizeList(new_box_field("Level1", DataType::Binary, true), 4),
+ DataType::FixedSizeList(
+ new_box_field(
+ "Level1",
+ DataType::List(new_box_field(
+ "Level2",
+ DataType::FixedSizeBinary(53),
+ false,
+ )),
+ true,
+ ),
+ 41,
+ ),
+ //Struct Testing
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ]),
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ Field::new(
+ "nested_struct",
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ]),
+ true,
+ ),
+ ]),
+ DataType::Union(
+ vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ],
+ UnionMode::Sparse,
+ ),
+ DataType::Union(
+ vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ Field::new(
+ "nested_struct",
+ DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ]),
+ true,
+ ),
+ ],
+ UnionMode::Dense,
+ ),
+ DataType::Dictionary(
+ Box::new(DataType::Utf8),
+ Box::new(DataType::Struct(vec![
+ Field::new("nullable", DataType::Boolean, false),
+ Field::new("name", DataType::Utf8, false),
+ Field::new("datatype", DataType::Binary, false),
+ ])),
+ ),
+ DataType::Dictionary(
+ Box::new(DataType::Decimal(10, 50)),
+ Box::new(DataType::FixedSizeList(
+ new_box_field("Level1", DataType::Binary, true),
+ 4,
+ )),
+ ),
+ ];
+
+ for test_case in test_cases.into_iter() {
+ let proto: super::protobuf::ArrowType = (&test_case).into();
+ let roundtrip: DataType = (&proto).try_into().unwrap();
+ assert_eq!(format!("{:?}", test_case), format!("{:?}", roundtrip));
+ }
+ }
+
+ #[test]
+ fn roundtrip_null_scalar_values() {
+ let test_types = vec![
+ ScalarValue::Boolean(None),
+ ScalarValue::Float32(None),
+ ScalarValue::Float64(None),
+ ScalarValue::Int8(None),
+ ScalarValue::Int16(None),
+ ScalarValue::Int32(None),
+ ScalarValue::Int64(None),
+ ScalarValue::UInt8(None),
+ ScalarValue::UInt16(None),
+ ScalarValue::UInt32(None),
+ ScalarValue::UInt64(None),
+ ScalarValue::Utf8(None),
+ ScalarValue::LargeUtf8(None),
+ ScalarValue::Date32(None),
+ ScalarValue::TimestampMicrosecond(None, None),
+ ScalarValue::TimestampNanosecond(None, None),
+ //ScalarValue::List(None, DataType::Boolean)
+ ];
+
+ for test_case in test_types.into_iter() {
+ let proto_scalar: super::protobuf::ScalarValue =
+ (&test_case).try_into().unwrap();
+ let returned_scalar: datafusion::scalar::ScalarValue =
+ (&proto_scalar).try_into().unwrap();
+ assert_eq!(
+ format!("{:?}", &test_case),
+ format!("{:?}", returned_scalar)
+ );
+ }
+ }
+
+ #[test]
+ fn roundtrip_not() {
+ let test_expr = Expr::Not(Box::new(Expr::Literal((1.0).into())));
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_is_null() {
+ let test_expr = Expr::IsNull(Box::new(col("id")));
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_is_not_null() {
+ let test_expr = Expr::IsNotNull(Box::new(col("id")));
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_between() {
+ let test_expr = Expr::Between {
+ expr: Box::new(Expr::Literal((1.0).into())),
+ negated: true,
+ low: Box::new(Expr::Literal((2.0).into())),
+ high: Box::new(Expr::Literal((3.0).into())),
+ };
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_case() {
+ let test_expr = Expr::Case {
+ expr: Some(Box::new(Expr::Literal((1.0).into()))),
+ when_then_expr: vec![(
+ Box::new(Expr::Literal((2.0).into())),
+ Box::new(Expr::Literal((3.0).into())),
+ )],
+ else_expr: Some(Box::new(Expr::Literal((4.0).into()))),
+ };
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_cast() {
+ let test_expr = Expr::Cast {
+ expr: Box::new(Expr::Literal((1.0).into())),
+ data_type: DataType::Boolean,
+ };
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_sort_expr() {
+ let test_expr = Expr::Sort {
+ expr: Box::new(Expr::Literal((1.0).into())),
+ asc: true,
+ nulls_first: true,
+ };
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_negative() {
+ let test_expr = Expr::Negative(Box::new(Expr::Literal((1.0).into())));
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_inlist() {
+ let test_expr = Expr::InList {
+ expr: Box::new(Expr::Literal((1.0).into())),
+ list: vec![Expr::Literal((2.0).into())],
+ negated: true,
+ };
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_wildcard() {
+ let test_expr = Expr::Wildcard;
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_sqrt() {
+ let test_expr = Expr::ScalarFunction {
+ fun: Sqrt,
+ args: vec![col("col")],
+ };
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+
+ #[test]
+ fn roundtrip_approx_percentile_cont() {
+ let test_expr = Expr::AggregateFunction {
+ fun: aggregates::AggregateFunction::ApproxPercentileCont,
+ args: vec![col("bananas"), lit(0.42)],
+ distinct: false,
+ };
+
+ roundtrip_test!(test_expr, super::protobuf::LogicalExprNode, Expr);
+ }
+}
diff --git a/ballista/rust/core/src/serde/logical_plan/to_proto.rs b/datafusion-proto/src/to_proto.rs
similarity index 57%
rename from ballista/rust/core/src/serde/logical_plan/to_proto.rs
rename to datafusion-proto/src/to_proto.rs
index 99a5488261..ade41d2ad7 100644
--- a/ballista/rust/core/src/serde/logical_plan/to_proto.rs
+++ b/datafusion-proto/src/to_proto.rs
@@ -15,105 +15,119 @@
// specific language governing permissions and limitations
// under the License.
-//! Serde code to convert Arrow schemas and DataFusion logical plans to Ballista protocol
-//! buffer format, allowing DataFusion logical plans to be serialized and transmitted between
+//! Code to convert Arrow schemas and DataFusion logical plans to protocol buffer format, allowing
+//! DataFusion logical plans to be serialized and transmitted between
//! processes.
-use super::super::proto_error;
-use crate::serde::{protobuf, BallistaError};
-use datafusion::arrow::datatypes::{
- DataType, Field, IntervalUnit, Schema, SchemaRef, TimeUnit, UnionMode,
+use crate::protobuf;
+use datafusion::{
+ arrow::datatypes::{
+ DataType, Field, IntervalUnit, Schema, SchemaRef, TimeUnit, UnionMode,
+ },
+ logical_plan::{
+ window_frames::{WindowFrame, WindowFrameBound, WindowFrameUnits},
+ Column, DFField, DFSchemaRef, Expr,
+ },
+ physical_plan::{
+ aggregates::AggregateFunction,
+ functions::BuiltinScalarFunction,
+ window_functions::{BuiltInWindowFunction, WindowFunction},
+ },
+ scalar::ScalarValue,
};
-use datafusion::logical_plan::{
- window_frames::{WindowFrame, WindowFrameBound, WindowFrameUnits},
- Column, Expr,
-};
-use datafusion::physical_plan::aggregates::AggregateFunction;
-use datafusion::physical_plan::functions::BuiltinScalarFunction;
-use datafusion::physical_plan::window_functions::{
- BuiltInWindowFunction, WindowFunction,
-};
+#[derive(Debug)]
+pub enum Error {
+ General(String),
-use protobuf::{logical_expr_node::ExprType, scalar_type};
-use std::convert::{TryFrom, TryInto};
+ InconsistentListTyping(DataType, DataType),
-impl protobuf::IntervalUnit {
- pub fn from_arrow_interval_unit(interval_unit: &IntervalUnit) -> Self {
- match interval_unit {
- IntervalUnit::YearMonth => protobuf::IntervalUnit::YearMonth,
- IntervalUnit::DayTime => protobuf::IntervalUnit::DayTime,
- IntervalUnit::MonthDayNano => protobuf::IntervalUnit::MonthDayNano,
- }
- }
+ InconsistentListDesignated {
+ value: ScalarValue,
+ designated: DataType,
+ },
- pub fn from_i32_to_arrow(
- interval_unit_i32: i32,
- ) -> Result<IntervalUnit, BallistaError> {
- let pb_interval_unit = protobuf::IntervalUnit::from_i32(interval_unit_i32);
- match pb_interval_unit {
- Some(interval_unit) => Ok(match interval_unit {
- protobuf::IntervalUnit::YearMonth => IntervalUnit::YearMonth,
- protobuf::IntervalUnit::DayTime => IntervalUnit::DayTime,
- protobuf::IntervalUnit::MonthDayNano => IntervalUnit::MonthDayNano,
- }),
- None => Err(proto_error(
- "Error converting i32 to DateUnit: Passed invalid variant",
- )),
+ InvalidScalarValue(ScalarValue),
+
+ InvalidScalarType(DataType),
+
+ InvalidTimeUnit(TimeUnit),
+
+ UnsupportedScalarFunction(BuiltinScalarFunction),
+}
+
+impl std::error::Error for Error {}
+
+impl std::fmt::Display for Error {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ match self {
+ Self::General(desc) => write!(f, "General error: {}", desc),
+ Self::InconsistentListTyping(type1, type2) => {
+ write!(
+ f,
+ "Lists with inconsistent typing; {:?} and {:?} found within list",
+ type1, type2,
+ )
+ }
+ Self::InconsistentListDesignated { value, designated } => {
+ write!(
+ f,
+ "Value {:?} was inconsistent with designated type {:?}",
+ value, designated
+ )
+ }
+ Self::InvalidScalarValue(value) => {
+ write!(f, "{:?} is invalid as a DataFusion scalar value", value)
+ }
+ Self::InvalidScalarType(data_type) => {
+ write!(f, "{:?} is invalid as a DataFusion scalar type", data_type)
+ }
+ Self::InvalidTimeUnit(time_unit) => {
+ write!(
+ f,
+ "Only TimeUnit::Microsecond and TimeUnit::Nanosecond are valid time units, found: {:?}",
+ time_unit
+ )
+ }
+ Self::UnsupportedScalarFunction(function) => {
+ write!(f, "Unsupported scalar function {:?}", function)
+ }
}
}
}
-/* Arrow changed dates to no longer have date unit
-impl protobuf::DateUnit {
- pub fn from_arrow_date_unit(val: &DateUnit) -> Self {
- match val {
- DateUnit::Day => protobuf::DateUnit::Day,
- DateUnit::Millisecond => protobuf::DateUnit::DateMillisecond,
- }
+impl Error {
+ fn inconsistent_list_typing(type1: &DataType, type2: &DataType) -> Self {
+ Self::InconsistentListTyping(type1.to_owned(), type2.to_owned())
}
- pub fn from_i32_to_arrow(date_unit_i32: i32) -> Result<DateUnit, BallistaError> {
- let pb_date_unit = protobuf::DateUnit::from_i32(date_unit_i32);
- use datafusion::DateUnit;
- match pb_date_unit {
- Some(date_unit) => Ok(match date_unit {
- protobuf::DateUnit::Day => DateUnit::Day,
- protobuf::DateUnit::DateMillisecond => DateUnit::Millisecond,
- }),
- None => Err(proto_error("Error converting i32 to DateUnit: Passed invalid variant")),
+
+ fn inconsistent_list_designated(value: &ScalarValue, designated: &DataType) -> Self {
+ Self::InconsistentListDesignated {
+ value: value.to_owned(),
+ designated: designated.to_owned(),
}
}
-}*/
+ fn invalid_scalar_value(value: &ScalarValue) -> Self {
+ Self::InvalidScalarValue(value.to_owned())
+ }
-impl protobuf::TimeUnit {
- pub fn from_arrow_time_unit(val: &TimeUnit) -> Self {
- match val {
- TimeUnit::Second => protobuf::TimeUnit::Second,
- TimeUnit::Millisecond => protobuf::TimeUnit::TimeMillisecond,
- TimeUnit::Microsecond => protobuf::TimeUnit::Microsecond,
- TimeUnit::Nanosecond => protobuf::TimeUnit::Nanosecond,
- }
+ fn invalid_scalar_type(data_type: &DataType) -> Self {
+ Self::InvalidScalarType(data_type.to_owned())
}
- pub fn from_i32_to_arrow(time_unit_i32: i32) -> Result<TimeUnit, BallistaError> {
- let pb_time_unit = protobuf::TimeUnit::from_i32(time_unit_i32);
- match pb_time_unit {
- Some(time_unit) => Ok(match time_unit {
- protobuf::TimeUnit::Second => TimeUnit::Second,
- protobuf::TimeUnit::TimeMillisecond => TimeUnit::Millisecond,
- protobuf::TimeUnit::Microsecond => TimeUnit::Microsecond,
- protobuf::TimeUnit::Nanosecond => TimeUnit::Nanosecond,
- }),
- None => Err(proto_error(
- "Error converting i32 to TimeUnit: Passed invalid variant",
- )),
- }
+
+ fn invalid_time_unit(time_unit: &TimeUnit) -> Self {
+ Self::InvalidTimeUnit(time_unit.to_owned())
+ }
+
+ fn unsupported_scalar_function(function: &BuiltinScalarFunction) -> Self {
+ Self::UnsupportedScalarFunction(function.to_owned())
}
}
impl From<&Field> for protobuf::Field {
fn from(field: &Field) -> Self {
- protobuf::Field {
+ Self {
name: field.name().to_owned(),
arrow_type: Some(Box::new(field.data_type().into())),
nullable: field.is_nullable(),
@@ -123,101 +137,69 @@ impl From<&Field> for protobuf::Field {
}
impl From<&DataType> for protobuf::ArrowType {
- fn from(val: &DataType) -> protobuf::ArrowType {
- protobuf::ArrowType {
+ fn from(val: &DataType) -> Self {
+ Self {
arrow_type_enum: Some(val.into()),
}
}
}
-impl TryInto<DataType> for &protobuf::ArrowType {
- type Error = BallistaError;
- fn try_into(self) -> Result<DataType, Self::Error> {
- let pb_arrow_type = self.arrow_type_enum.as_ref().ok_or_else(|| {
- proto_error(
- "Protobuf deserialization error: ArrowType missing required field 'data_type'",
- )
- })?;
- pb_arrow_type.try_into()
- }
-}
-
-impl TryInto<DataType> for &Box<protobuf::List> {
- type Error = BallistaError;
- fn try_into(self) -> Result<DataType, Self::Error> {
- let list_ref = self.as_ref();
- match &list_ref.field_type {
- Some(pb_field) => {
- let pb_field_ref = pb_field.as_ref();
- let arrow_field: Field = pb_field_ref.try_into()?;
- Ok(DataType::List(Box::new(arrow_field)))
- }
- None => Err(proto_error(
- "List message missing required field 'field_type'",
- )),
- }
- }
-}
-
impl From<&DataType> for protobuf::arrow_type::ArrowTypeEnum {
- fn from(val: &DataType) -> protobuf::arrow_type::ArrowTypeEnum {
- use protobuf::arrow_type::ArrowTypeEnum;
-
+ fn from(val: &DataType) -> Self {
use protobuf::EmptyMessage;
+
match val {
- DataType::Null => ArrowTypeEnum::None(EmptyMessage {}),
- DataType::Boolean => ArrowTypeEnum::Bool(EmptyMessage {}),
- DataType::Int8 => ArrowTypeEnum::Int8(EmptyMessage {}),
- DataType::Int16 => ArrowTypeEnum::Int16(EmptyMessage {}),
- DataType::Int32 => ArrowTypeEnum::Int32(EmptyMessage {}),
- DataType::Int64 => ArrowTypeEnum::Int64(EmptyMessage {}),
- DataType::UInt8 => ArrowTypeEnum::Uint8(EmptyMessage {}),
- DataType::UInt16 => ArrowTypeEnum::Uint16(EmptyMessage {}),
- DataType::UInt32 => ArrowTypeEnum::Uint32(EmptyMessage {}),
- DataType::UInt64 => ArrowTypeEnum::Uint64(EmptyMessage {}),
- DataType::Float16 => ArrowTypeEnum::Float16(EmptyMessage {}),
- DataType::Float32 => ArrowTypeEnum::Float32(EmptyMessage {}),
- DataType::Float64 => ArrowTypeEnum::Float64(EmptyMessage {}),
+ DataType::Null => Self::None(EmptyMessage {}),
+ DataType::Boolean => Self::Bool(EmptyMessage {}),
+ DataType::Int8 => Self::Int8(EmptyMessage {}),
+ DataType::Int16 => Self::Int16(EmptyMessage {}),
+ DataType::Int32 => Self::Int32(EmptyMessage {}),
+ DataType::Int64 => Self::Int64(EmptyMessage {}),
+ DataType::UInt8 => Self::Uint8(EmptyMessage {}),
+ DataType::UInt16 => Self::Uint16(EmptyMessage {}),
+ DataType::UInt32 => Self::Uint32(EmptyMessage {}),
+ DataType::UInt64 => Self::Uint64(EmptyMessage {}),
+ DataType::Float16 => Self::Float16(EmptyMessage {}),
+ DataType::Float32 => Self::Float32(EmptyMessage {}),
+ DataType::Float64 => Self::Float64(EmptyMessage {}),
DataType::Timestamp(time_unit, timezone) => {
- ArrowTypeEnum::Timestamp(protobuf::Timestamp {
- time_unit: protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,
+ Self::Timestamp(protobuf::Timestamp {
+ time_unit: protobuf::TimeUnit::from(time_unit) as i32,
timezone: timezone.to_owned().unwrap_or_default(),
})
}
- DataType::Date32 => ArrowTypeEnum::Date32(EmptyMessage {}),
- DataType::Date64 => ArrowTypeEnum::Date64(EmptyMessage {}),
- DataType::Time32(time_unit) => ArrowTypeEnum::Time32(
- protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,
- ),
- DataType::Time64(time_unit) => ArrowTypeEnum::Time64(
- protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,
- ),
- DataType::Duration(time_unit) => ArrowTypeEnum::Duration(
- protobuf::TimeUnit::from_arrow_time_unit(time_unit) as i32,
- ),
- DataType::Interval(interval_unit) => ArrowTypeEnum::Interval(
- protobuf::IntervalUnit::from_arrow_interval_unit(interval_unit) as i32,
- ),
- DataType::Binary => ArrowTypeEnum::Binary(EmptyMessage {}),
- DataType::FixedSizeBinary(size) => ArrowTypeEnum::FixedSizeBinary(*size),
- DataType::LargeBinary => ArrowTypeEnum::LargeBinary(EmptyMessage {}),
- DataType::Utf8 => ArrowTypeEnum::Utf8(EmptyMessage {}),
- DataType::LargeUtf8 => ArrowTypeEnum::LargeUtf8(EmptyMessage {}),
- DataType::List(item_type) => ArrowTypeEnum::List(Box::new(protobuf::List {
+ DataType::Date32 => Self::Date32(EmptyMessage {}),
+ DataType::Date64 => Self::Date64(EmptyMessage {}),
+ DataType::Time32(time_unit) => {
+ Self::Time32(protobuf::TimeUnit::from(time_unit) as i32)
+ }
+ DataType::Time64(time_unit) => {
+ Self::Time64(protobuf::TimeUnit::from(time_unit) as i32)
+ }
+ DataType::Duration(time_unit) => {
+ Self::Duration(protobuf::TimeUnit::from(time_unit) as i32)
+ }
+ DataType::Interval(interval_unit) => {
+ Self::Interval(protobuf::IntervalUnit::from(interval_unit) as i32)
+ }
+ DataType::Binary => Self::Binary(EmptyMessage {}),
+ DataType::FixedSizeBinary(size) => Self::FixedSizeBinary(*size),
+ DataType::LargeBinary => Self::LargeBinary(EmptyMessage {}),
+ DataType::Utf8 => Self::Utf8(EmptyMessage {}),
+ DataType::LargeUtf8 => Self::LargeUtf8(EmptyMessage {}),
+ DataType::List(item_type) => Self::List(Box::new(protobuf::List {
field_type: Some(Box::new(item_type.as_ref().into())),
})),
DataType::FixedSizeList(item_type, size) => {
- ArrowTypeEnum::FixedSizeList(Box::new(protobuf::FixedSizeList {
+ Self::FixedSizeList(Box::new(protobuf::FixedSizeList {
field_type: Some(Box::new(item_type.as_ref().into())),
list_size: *size,
}))
}
- DataType::LargeList(item_type) => {
- ArrowTypeEnum::LargeList(Box::new(protobuf::List {
- field_type: Some(Box::new(item_type.as_ref().into())),
- }))
- }
- DataType::Struct(struct_fields) => ArrowTypeEnum::Struct(protobuf::Struct {
+ DataType::LargeList(item_type) => Self::LargeList(Box::new(protobuf::List {
+ field_type: Some(Box::new(item_type.as_ref().into())),
+ })),
+ DataType::Struct(struct_fields) => Self::Struct(protobuf::Struct {
sub_field_types: struct_fields
.iter()
.map(|field| field.into())
@@ -228,7 +210,7 @@ impl From<&DataType> for protobuf::arrow_type::ArrowTypeEnum {
UnionMode::Sparse => protobuf::UnionMode::Sparse,
UnionMode::Dense => protobuf::UnionMode::Dense,
};
- ArrowTypeEnum::Union(protobuf::Union {
+ Self::Union(protobuf::Union {
union_types: union_types
.iter()
.map(|field| field.into())
@@ -237,409 +219,188 @@ impl From<&DataType> for protobuf::arrow_type::ArrowTypeEnum {
})
}
DataType::Dictionary(key_type, value_type) => {
- ArrowTypeEnum::Dictionary(Box::new(protobuf::Dictionary {
+ Self::Dictionary(Box::new(protobuf::Dictionary {
key: Some(Box::new(key_type.as_ref().into())),
value: Some(Box::new(value_type.as_ref().into())),
}))
}
- DataType::Decimal(whole, fractional) => {
- ArrowTypeEnum::Decimal(protobuf::Decimal {
- whole: *whole as u64,
- fractional: *fractional as u64,
- })
- }
+ DataType::Decimal(whole, fractional) => Self::Decimal(protobuf::Decimal {
+ whole: *whole as u64,
+ fractional: *fractional as u64,
+ }),
DataType::Map(_, _) => {
- unimplemented!("Ballista does not yet support Map data type")
+ unimplemented!("The Map data type is not yet supported")
}
}
}
}
-//Does not check if list subtypes are valid
-fn is_valid_scalar_type_no_list_check(datatype: &DataType) -> bool {
- match datatype {
- DataType::Boolean
- | DataType::Int8
- | DataType::Int16
- | DataType::Int32
- | DataType::Int64
- | DataType::UInt8
- | DataType::UInt16
- | DataType::UInt32
- | DataType::UInt64
- | DataType::Float32
- | DataType::Float64
- | DataType::LargeUtf8
- | DataType::Utf8
- | DataType::Date32 => true,
- DataType::Time64(time_unit) => {
- matches!(time_unit, TimeUnit::Microsecond | TimeUnit::Nanosecond)
+impl From<Column> for protobuf::Column {
+ fn from(c: Column) -> Self {
+ Self {
+ relation: c
+ .relation
+ .map(|relation| protobuf::ColumnRelation { relation }),
+ name: c.name,
}
+ }
+}
- DataType::List(_) => true,
- _ => false,
+impl From<&Column> for protobuf::Column {
+ fn from(c: &Column) -> Self {
+ c.clone().into()
}
}
-impl TryFrom<&DataType> for protobuf::scalar_type::Datatype {
- type Error = BallistaError;
- fn try_from(val: &DataType) -> Result<Self, Self::Error> {
- use protobuf::PrimitiveScalarType;
- let scalar_value = match val {
- DataType::Boolean => scalar_type::Datatype::Scalar(PrimitiveScalarType::Bool as i32),
- DataType::Int8 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Int8 as i32),
- DataType::Int16 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Int16 as i32),
- DataType::Int32 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Int32 as i32),
- DataType::Int64 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Int64 as i32),
- DataType::UInt8 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Uint8 as i32),
- DataType::UInt16 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Uint16 as i32),
- DataType::UInt32 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Uint32 as i32),
- DataType::UInt64 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Uint64 as i32),
- DataType::Float32 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Float32 as i32),
- DataType::Float64 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Float64 as i32),
- DataType::Date32 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Date32 as i32),
- DataType::Time64(time_unit) => match time_unit {
- TimeUnit::Microsecond => scalar_type::Datatype::Scalar(PrimitiveScalarType::TimeMicrosecond as i32),
- TimeUnit::Nanosecond => scalar_type::Datatype::Scalar(PrimitiveScalarType::TimeNanosecond as i32),
- _ => {
- return Err(proto_error(format!(
- "Found invalid time unit for scalar value, only TimeUnit::Microsecond and TimeUnit::Nanosecond are valid time units: {:?}",
- time_unit
- )))
- }
- },
- DataType::Utf8 => scalar_type::Datatype::Scalar(PrimitiveScalarType::Utf8 as i32),
- DataType::LargeUtf8 => scalar_type::Datatype::Scalar(PrimitiveScalarType::LargeUtf8 as i32),
- DataType::List(field_type) => {
- let mut field_names: Vec<String> = Vec::new();
- let mut curr_field = field_type.as_ref();
- field_names.push(curr_field.name().to_owned());
- //For each nested field check nested datatype, since datafusion scalars only support recursive lists with a leaf scalar type
- // any other compound types are errors.
+impl From<&Schema> for protobuf::Schema {
+ fn from(schema: &Schema) -> Self {
+ Self {
+ columns: schema
+ .fields()
+ .iter()
+ .map(protobuf::Field::from)
+ .collect::<Vec<_>>(),
+ }
+ }
+}
- while let DataType::List(nested_field_type) = curr_field.data_type() {
- curr_field = nested_field_type.as_ref();
- field_names.push(curr_field.name().to_owned());
- if !is_valid_scalar_type_no_list_check(curr_field.data_type()) {
- return Err(proto_error(format!("{:?} is an invalid scalar type", curr_field)));
- }
- }
- let deepest_datatype = curr_field.data_type();
- if !is_valid_scalar_type_no_list_check(deepest_datatype) {
- return Err(proto_error(format!("The list nested type {:?} is an invalid scalar type", curr_field)));
- }
- let pb_deepest_type: PrimitiveScalarType = match deepest_datatype {
- DataType::Boolean => PrimitiveScalarType::Bool,
- DataType::Int8 => PrimitiveScalarType::Int8,
- DataType::Int16 => PrimitiveScalarType::Int16,
- DataType::Int32 => PrimitiveScalarType::Int32,
- DataType::Int64 => PrimitiveScalarType::Int64,
- DataType::UInt8 => PrimitiveScalarType::Uint8,
- DataType::UInt16 => PrimitiveScalarType::Uint16,
- DataType::UInt32 => PrimitiveScalarType::Uint32,
- DataType::UInt64 => PrimitiveScalarType::Uint64,
- DataType::Float32 => PrimitiveScalarType::Float32,
- DataType::Float64 => PrimitiveScalarType::Float64,
- DataType::Date32 => PrimitiveScalarType::Date32,
- DataType::Time64(time_unit) => match time_unit {
- TimeUnit::Microsecond => PrimitiveScalarType::TimeMicrosecond,
- TimeUnit::Nanosecond => PrimitiveScalarType::TimeNanosecond,
- _ => {
- return Err(proto_error(format!(
- "Found invalid time unit for scalar value, only TimeUnit::Microsecond and TimeUnit::Nanosecond are valid time units: {:?}",
- time_unit
- )))
- }
- },
+impl From<SchemaRef> for protobuf::Schema {
+ fn from(schema: SchemaRef) -> Self {
+ Self {
+ columns: schema
+ .fields()
+ .iter()
+ .map(protobuf::Field::from)
+ .collect::<Vec<_>>(),
+ }
+ }
+}
- DataType::Utf8 => PrimitiveScalarType::Utf8,
- DataType::LargeUtf8 => PrimitiveScalarType::LargeUtf8,
- _ => {
- return Err(proto_error(format!(
- "Error converting to Datatype to scalar type, {:?} is invalid as a datafusion scalar.",
- val
- )))
- }
- };
- protobuf::scalar_type::Datatype::List(protobuf::ScalarListType {
- field_names,
- deepest_type: pb_deepest_type as i32,
- })
- }
- DataType::Null
- | DataType::Float16
- | DataType::Timestamp(_, _)
- | DataType::Date64
- | DataType::Time32(_)
- | DataType::Duration(_)
- | DataType::Interval(_)
- | DataType::Binary
- | DataType::FixedSizeBinary(_)
- | DataType::LargeBinary
- | DataType::FixedSizeList(_, _)
- | DataType::LargeList(_)
- | DataType::Struct(_)
- | DataType::Union(_, _)
- | DataType::Dictionary(_, _)
- | DataType::Map(_, _)
- | DataType::Decimal(_, _) => {
- return Err(proto_error(format!(
- "Error converting to Datatype to scalar type, {:?} is invalid as a datafusion scalar.",
- val
- )))
- }
- };
- Ok(scalar_value)
+impl From<&DFField> for protobuf::DfField {
+ fn from(f: &DFField) -> protobuf::DfField {
+ protobuf::DfField {
+ field: Some(f.field().into()),
+ qualifier: f.qualifier().map(|r| protobuf::ColumnRelation {
+ relation: r.to_string(),
+ }),
+ }
}
}
-impl TryFrom<&datafusion::scalar::ScalarValue> for protobuf::ScalarValue {
- type Error = BallistaError;
- fn try_from(
- val: &datafusion::scalar::ScalarValue,
- ) -> Result<protobuf::ScalarValue, Self::Error> {
- use datafusion::scalar;
- use protobuf::scalar_value::Value;
- use protobuf::PrimitiveScalarType;
- let scalar_val = match val {
- scalar::ScalarValue::Boolean(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Bool, |s| Value::BoolValue(*s))
- }
- scalar::ScalarValue::Float32(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Float32, |s| {
- Value::Float32Value(*s)
- })
- }
- scalar::ScalarValue::Float64(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Float64, |s| {
- Value::Float64Value(*s)
- })
- }
- scalar::ScalarValue::Int8(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Int8, |s| {
- Value::Int8Value(*s as i32)
- })
- }
- scalar::ScalarValue::Int16(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Int16, |s| {
- Value::Int16Value(*s as i32)
- })
- }
- scalar::ScalarValue::Int32(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Int32, |s| Value::Int32Value(*s))
- }
- scalar::ScalarValue::Int64(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Int64, |s| Value::Int64Value(*s))
- }
- scalar::ScalarValue::UInt8(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Uint8, |s| {
- Value::Uint8Value(*s as u32)
- })
- }
- scalar::ScalarValue::UInt16(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Uint16, |s| {
- Value::Uint16Value(*s as u32)
- })
- }
- scalar::ScalarValue::UInt32(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Uint32, |s| Value::Uint32Value(*s))
- }
- scalar::ScalarValue::UInt64(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Uint64, |s| Value::Uint64Value(*s))
- }
- scalar::ScalarValue::Utf8(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Utf8, |s| {
- Value::Utf8Value(s.to_owned())
- })
- }
- scalar::ScalarValue::LargeUtf8(val) => {
- create_proto_scalar(val, PrimitiveScalarType::LargeUtf8, |s| {
- Value::LargeUtf8Value(s.to_owned())
- })
- }
- scalar::ScalarValue::List(value, datatype) => {
- println!("Current datatype of list: {:?}", datatype);
- match value {
- Some(values) => {
- if values.is_empty() {
- protobuf::ScalarValue {
- value: Some(protobuf::scalar_value::Value::ListValue(
- protobuf::ScalarListValue {
- datatype: Some(datatype.as_ref().try_into()?),
- values: Vec::new(),
- },
- )),
- }
- } else {
- let scalar_type = match datatype.as_ref() {
- DataType::List(field) => field.as_ref().data_type(),
- _ => todo!("Proper error handling"),
- };
- println!("Current scalar type for list: {:?}", scalar_type);
- let type_checked_values: Vec<protobuf::ScalarValue> = values
- .iter()
- .map(|scalar| match (scalar, scalar_type) {
- (scalar::ScalarValue::List(_, list_type), DataType::List(field)) => {
- if let DataType::List(list_field) = list_type.as_ref() {
- let scalar_datatype = field.data_type();
- let list_datatype = list_field.data_type();
- if std::mem::discriminant(list_datatype) != std::mem::discriminant(scalar_datatype) {
- return Err(proto_error(format!(
- "Protobuf serialization error: Lists with inconsistent typing {:?} and {:?} found within list",
- list_datatype, scalar_datatype
- )));
- }
- scalar.try_into()
- } else {
- Err(proto_error(format!(
- "Protobuf serialization error, {:?} was inconsistent with designated type {:?}",
- scalar, datatype
- )))
- }
- }
- (scalar::ScalarValue::Boolean(_), DataType::Boolean) => scalar.try_into(),
- (scalar::ScalarValue::Float32(_), DataType::Float32) => scalar.try_into(),
- (scalar::ScalarValue::Float64(_), DataType::Float64) => scalar.try_into(),
- (scalar::ScalarValue::Int8(_), DataType::Int8) => scalar.try_into(),
- (scalar::ScalarValue::Int16(_), DataType::Int16) => scalar.try_into(),
- (scalar::ScalarValue::Int32(_), DataType::Int32) => scalar.try_into(),
- (scalar::ScalarValue::Int64(_), DataType::Int64) => scalar.try_into(),
- (scalar::ScalarValue::UInt8(_), DataType::UInt8) => scalar.try_into(),
- (scalar::ScalarValue::UInt16(_), DataType::UInt16) => scalar.try_into(),
- (scalar::ScalarValue::UInt32(_), DataType::UInt32) => scalar.try_into(),
- (scalar::ScalarValue::UInt64(_), DataType::UInt64) => scalar.try_into(),
- (scalar::ScalarValue::Utf8(_), DataType::Utf8) => scalar.try_into(),
- (scalar::ScalarValue::LargeUtf8(_), DataType::LargeUtf8) => scalar.try_into(),
- _ => Err(proto_error(format!(
- "Protobuf serialization error, {:?} was inconsistent with designated type {:?}",
- scalar, datatype
- ))),
- })
- .collect::<Result<Vec<_>, _>>()?;
- protobuf::ScalarValue {
- value: Some(protobuf::scalar_value::Value::ListValue(
- protobuf::ScalarListValue {
- datatype: Some(datatype.as_ref().try_into()?),
- values: type_checked_values,
- },
- )),
- }
- }
- }
- None => protobuf::ScalarValue {
- value: Some(protobuf::scalar_value::Value::NullListValue(
- datatype.as_ref().try_into()?,
- )),
- },
- }
- }
- datafusion::scalar::ScalarValue::Date32(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Date32, |s| Value::Date32Value(*s))
- }
- datafusion::scalar::ScalarValue::TimestampMicrosecond(val, _) => {
- create_proto_scalar(val, PrimitiveScalarType::TimeMicrosecond, |s| {
- Value::TimeMicrosecondValue(*s)
- })
- }
- datafusion::scalar::ScalarValue::TimestampNanosecond(val, _) => {
- create_proto_scalar(val, PrimitiveScalarType::TimeNanosecond, |s| {
- Value::TimeNanosecondValue(*s)
- })
- }
- datafusion::scalar::ScalarValue::Decimal128(val, p, s) => {
- match *val {
- Some(v) => {
- let array = v.to_be_bytes();
- let vec_val: Vec<u8> = array.to_vec();
- protobuf::ScalarValue {
- value: Some(Value::Decimal128Value(protobuf::Decimal128 {
- value: vec_val,
- p: *p as i64,
- s: *s as i64,
- })),
- }
- }
- None => {
- protobuf::ScalarValue {
- value: Some(protobuf::scalar_value::Value::NullValue(PrimitiveScalarType::Decimal128 as i32))
- }
- }
- }
- }
- datafusion::scalar::ScalarValue::Date64(val) => {
- create_proto_scalar(val, PrimitiveScalarType::Date64, |s| {
- Value::Date64Value(*s)
- })
- }
- datafusion::scalar::ScalarValue::TimestampSecond(val, _) => {
- create_proto_scalar(val, PrimitiveScalarType::TimeSecond, |s| {
- Value::TimeSecondValue(*s)
- })
- }
- datafusion::scalar::ScalarValue::TimestampMillisecond(val, _) => {
- create_proto_scalar(val, PrimitiveScalarType::TimeMillisecond, |s| {
- Value::TimeMillisecondValue(*s)
- })
- }
- datafusion::scalar::ScalarValue::IntervalYearMonth(val) => {
- create_proto_scalar(val, PrimitiveScalarType::IntervalYearmonth, |s| {
- Value::IntervalYearmonthValue(*s)
- })
- }
- datafusion::scalar::ScalarValue::IntervalDayTime(val) => {
- create_proto_scalar(val, PrimitiveScalarType::IntervalDaytime, |s| {
- Value::IntervalDaytimeValue(*s)
- })
- }
- _ => {
- return Err(proto_error(format!(
- "Error converting to Datatype to scalar type, {:?} is invalid as a datafusion scalar.",
- val
- )))
- }
- };
- Ok(scalar_val)
+impl From<&DFSchemaRef> for protobuf::DfSchema {
+ fn from(s: &DFSchemaRef) -> protobuf::DfSchema {
+ let columns = s.fields().iter().map(|f| f.into()).collect::<Vec<_>>();
+ protobuf::DfSchema { columns }
}
}
-fn create_proto_scalar<I, T: FnOnce(&I) -> protobuf::scalar_value::Value>(
- v: &Option<I>,
- null_arrow_type: protobuf::PrimitiveScalarType,
- constructor: T,
-) -> protobuf::ScalarValue {
- protobuf::ScalarValue {
- value: Some(v.as_ref().map(constructor).unwrap_or(
- protobuf::scalar_value::Value::NullValue(null_arrow_type as i32),
- )),
+impl From<&AggregateFunction> for protobuf::AggregateFunction {
+ fn from(value: &AggregateFunction) -> Self {
+ match value {
+ AggregateFunction::Min => Self::Min,
+ AggregateFunction::Max => Self::Max,
+ AggregateFunction::Sum => Self::Sum,
+ AggregateFunction::Avg => Self::Avg,
+ AggregateFunction::Count => Self::Count,
+ AggregateFunction::ApproxDistinct => Self::ApproxDistinct,
+ AggregateFunction::ArrayAgg => Self::ArrayAgg,
+ AggregateFunction::Variance => Self::Variance,
+ AggregateFunction::VariancePop => Self::VariancePop,
+ AggregateFunction::Covariance => Self::Covariance,
+ AggregateFunction::CovariancePop => Self::CovariancePop,
+ AggregateFunction::Stddev => Self::Stddev,
+ AggregateFunction::StddevPop => Self::StddevPop,
+ AggregateFunction::Correlation => Self::Correlation,
+ AggregateFunction::ApproxPercentileCont => Self::ApproxPercentileCont,
+ AggregateFunction::ApproxMedian => Self::ApproxMedian,
+ }
}
}
-impl TryInto<protobuf::LogicalExprNode> for &Expr {
- type Error = BallistaError;
+impl From<&BuiltInWindowFunction> for protobuf::BuiltInWindowFunction {
+ fn from(value: &BuiltInWindowFunction) -> Self {
+ match value {
+ BuiltInWindowFunction::FirstValue => Self::FirstValue,
+ BuiltInWindowFunction::LastValue => Self::LastValue,
+ BuiltInWindowFunction::NthValue => Self::NthValue,
+ BuiltInWindowFunction::Ntile => Self::Ntile,
+ BuiltInWindowFunction::CumeDist => Self::CumeDist,
+ BuiltInWindowFunction::PercentRank => Self::PercentRank,
+ BuiltInWindowFunction::RowNumber => Self::RowNumber,
+ BuiltInWindowFunction::Rank => Self::Rank,
+ BuiltInWindowFunction::Lag => Self::Lag,
+ BuiltInWindowFunction::Lead => Self::Lead,
+ BuiltInWindowFunction::DenseRank => Self::DenseRank,
+ }
+ }
+}
- fn try_into(self) -> Result<protobuf::LogicalExprNode, Self::Error> {
- match self {
- Expr::Column(c) => {
- let expr = protobuf::LogicalExprNode {
- expr_type: Some(ExprType::Column(c.into())),
- };
- Ok(expr)
- }
+impl From<WindowFrameUnits> for protobuf::WindowFrameUnits {
+ fn from(units: WindowFrameUnits) -> Self {
+ match units {
+ WindowFrameUnits::Rows => Self::Rows,
+ WindowFrameUnits::Range => Self::Range,
+ WindowFrameUnits::Groups => Self::Groups,
+ }
+ }
+}
+
+impl From<WindowFrameBound> for protobuf::WindowFrameBound {
+ fn from(bound: WindowFrameBound) -> Self {
+ match bound {
+ WindowFrameBound::CurrentRow => Self {
+ window_frame_bound_type: protobuf::WindowFrameBoundType::CurrentRow
+ .into(),
+ bound_value: None,
+ },
+ WindowFrameBound::Preceding(v) => Self {
+ window_frame_bound_type: protobuf::WindowFrameBoundType::Preceding.into(),
+ bound_value: v.map(protobuf::window_frame_bound::BoundValue::Value),
+ },
+ WindowFrameBound::Following(v) => Self {
+ window_frame_bound_type: protobuf::WindowFrameBoundType::Following.into(),
+ bound_value: v.map(protobuf::window_frame_bound::BoundValue::Value),
+ },
+ }
+ }
+}
+
+impl From<WindowFrame> for protobuf::WindowFrame {
+ fn from(window: WindowFrame) -> Self {
+ Self {
+ window_frame_units: protobuf::WindowFrameUnits::from(window.units).into(),
+ start_bound: Some(window.start_bound.into()),
+ end_bound: Some(protobuf::window_frame::EndBound::Bound(
+ window.end_bound.into(),
+ )),
+ }
+ }
+}
+
+impl TryFrom<&Expr> for protobuf::LogicalExprNode {
+ type Error = Error;
+
+ fn try_from(expr: &Expr) -> Result<Self, Self::Error> {
+ use protobuf::logical_expr_node::ExprType;
+
+ let expr_node = match expr {
+ Expr::Column(c) => Self {
+ expr_type: Some(ExprType::Column(c.into())),
+ },
Expr::Alias(expr, alias) => {
let alias = Box::new(protobuf::AliasNode {
expr: Some(Box::new(expr.as_ref().try_into()?)),
alias: alias.to_owned(),
});
- let expr = protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::Alias(alias)),
- };
- Ok(expr)
+ }
}
Expr::Literal(value) => {
let pb_value: protobuf::ScalarValue = value.try_into()?;
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::Literal(pb_value)),
- })
+ }
}
Expr::BinaryExpr { left, op, right } => {
let binary_expr = Box::new(protobuf::BinaryExprNode {
@@ -647,9 +408,9 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
r: Some(Box::new(right.as_ref().try_into()?)),
op: format!("{:?}", op),
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::BinaryExpr(binary_expr)),
- })
+ }
}
Expr::WindowFunction {
ref fun,
@@ -670,8 +431,7 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
)
}
};
- let arg_expr: Option<Box<protobuf::LogicalExprNode>> = if !args.is_empty()
- {
+ let arg_expr: Option<Box<Self>> = if !args.is_empty() {
let arg = &args[0];
Some(Box::new(arg.try_into()?))
} else {
@@ -695,9 +455,9 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
order_by,
window_frame,
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::WindowExpr(window_expr)),
- })
+ }
}
Expr::AggregateFunction {
ref fun, ref args, ..
@@ -744,27 +504,25 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
.map(|v| v.try_into())
.collect::<Result<Vec<_>, _>>()?,
};
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::AggregateExpr(aggregate_expr)),
- })
+ }
}
Expr::ScalarVariable(_) => unimplemented!(),
Expr::ScalarFunction { ref fun, ref args } => {
let fun: protobuf::ScalarFunction = fun.try_into()?;
- let args: Vec<protobuf::LogicalExprNode> = args
+ let args: Vec<Self> = args
.iter()
.map(|e| e.try_into())
- .collect::<Result<Vec<protobuf::LogicalExprNode>, BallistaError>>()?;
- Ok(protobuf::LogicalExprNode {
- expr_type: Some(
- protobuf::logical_expr_node::ExprType::ScalarFunction(
- protobuf::ScalarFunctionNode {
- fun: fun.into(),
- args,
- },
- ),
- ),
- })
+ .collect::<Result<Vec<Self>, Error>>()?;
+ Self {
+ expr_type: Some(ExprType::ScalarFunction(
+ protobuf::ScalarFunctionNode {
+ fun: fun.into(),
+ args,
+ },
+ )),
+ }
}
Expr::ScalarUDF { .. } => unimplemented!(),
Expr::AggregateUDF { .. } => unimplemented!(),
@@ -772,25 +530,25 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
let expr = Box::new(protobuf::Not {
expr: Some(Box::new(expr.as_ref().try_into()?)),
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::NotExpr(expr)),
- })
+ }
}
Expr::IsNull(expr) => {
let expr = Box::new(protobuf::IsNull {
expr: Some(Box::new(expr.as_ref().try_into()?)),
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::IsNullExpr(expr)),
- })
+ }
}
Expr::IsNotNull(expr) => {
let expr = Box::new(protobuf::IsNotNull {
expr: Some(Box::new(expr.as_ref().try_into()?)),
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::IsNotNullExpr(expr)),
- })
+ }
}
Expr::Between {
expr,
@@ -804,9 +562,9 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
low: Some(Box::new(low.as_ref().try_into()?)),
high: Some(Box::new(high.as_ref().try_into()?)),
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::Between(expr)),
- })
+ }
}
Expr::Case {
expr,
@@ -821,7 +579,7 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
then_expr: Some(t.as_ref().try_into()?),
})
})
- .collect::<Result<Vec<protobuf::WhenThen>, BallistaError>>()?;
+ .collect::<Result<Vec<protobuf::WhenThen>, Error>>()?;
let expr = Box::new(protobuf::CaseNode {
expr: match expr {
Some(e) => Some(Box::new(e.as_ref().try_into()?)),
@@ -833,18 +591,18 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
None => None,
},
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::Case(expr)),
- })
+ }
}
Expr::Cast { expr, data_type } => {
let expr = Box::new(protobuf::CastNode {
expr: Some(Box::new(expr.as_ref().try_into()?)),
arrow_type: Some(data_type.into()),
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::Cast(expr)),
- })
+ }
}
Expr::Sort {
expr,
@@ -856,19 +614,17 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
asc: *asc,
nulls_first: *nulls_first,
});
- Ok(protobuf::LogicalExprNode {
+ Self {
expr_type: Some(ExprType::Sort(expr)),
- })
+ }
}
Expr::Negative(expr) => {
let expr = Box::new(protobuf::NegativeNode {
expr: Some(Box::new(expr.as_ref().try_into()?)),
});
- Ok(protobuf::LogicalExprNode {
- expr_type: Some(protobuf::logical_expr_node::ExprType::Negative(
- expr,
- )),
- })
+ Self {
+ expr_type: Some(ExprType::Negative(expr)),
+ }
}
Expr::InList {
expr,
@@ -877,228 +633,503 @@ impl TryInto<protobuf::LogicalExprNode> for &Expr {
} => {
let expr = Box::new(protobuf::InListNode {
expr: Some(Box::new(expr.as_ref().try_into()?)),
- list: list.iter().map(|expr| expr.try_into()).collect::<Result<
- Vec<_>,
- BallistaError,
- >>(
- )?,
+ list: list
+ .iter()
+ .map(|expr| expr.try_into())
+ .collect::<Result<Vec<_>, Error>>()?,
negated: *negated,
});
- Ok(protobuf::LogicalExprNode {
- expr_type: Some(protobuf::logical_expr_node::ExprType::InList(expr)),
- })
+ Self {
+ expr_type: Some(ExprType::InList(expr)),
+ }
}
- Expr::Wildcard => Ok(protobuf::LogicalExprNode {
- expr_type: Some(protobuf::logical_expr_node::ExprType::Wildcard(true)),
- }),
+ Expr::Wildcard => Self {
+ expr_type: Some(ExprType::Wildcard(true)),
+ },
_ => unimplemented!(),
- }
- }
-}
-
-impl From<Column> for protobuf::Column {
- fn from(c: Column) -> protobuf::Column {
- protobuf::Column {
- relation: c
- .relation
- .map(|relation| protobuf::ColumnRelation { relation }),
- name: c.name,
- }
- }
-}
-
-impl From<&Column> for protobuf::Column {
- fn from(c: &Column) -> protobuf::Column {
- c.clone().into()
- }
-}
-
-#[allow(clippy::from_over_into)]
-impl Into<protobuf::Schema> for &Schema {
- fn into(self) -> protobuf::Schema {
- protobuf::Schema {
- columns: self
- .fields()
- .iter()
- .map(protobuf::Field::from)
- .collect::<Vec<_>>(),
- }
- }
-}
+ };
-#[allow(clippy::from_over_into)]
-impl Into<protobuf::Schema> for SchemaRef {
- fn into(self) -> protobuf::Schema {
- protobuf::Schema {
- columns: self
- .fields()
- .iter()
- .map(protobuf::Field::from)
- .collect::<Vec<_>>(),
- }
+ Ok(expr_node)
}
}
-impl From<&datafusion::logical_plan::DFField> for protobuf::DfField {
- fn from(f: &datafusion::logical_plan::DFField) -> protobuf::DfField {
- protobuf::DfField {
- field: Some(f.field().into()),
- qualifier: f.qualifier().map(|r| protobuf::ColumnRelation {
- relation: r.to_string(),
- }),
- }
- }
-}
+impl TryFrom<&ScalarValue> for protobuf::ScalarValue {
+ type Error = Error;
-impl From<&datafusion::logical_plan::DFSchemaRef> for protobuf::DfSchema {
- fn from(s: &datafusion::logical_plan::DFSchemaRef) -> protobuf::DfSchema {
- let columns = s.fields().iter().map(|f| f.into()).collect::<Vec<_>>();
- protobuf::DfSchema { columns }
- }
-}
+ fn try_from(val: &ScalarValue) -> Result<Self, Self::Error> {
+ use datafusion::scalar;
+ use protobuf::{scalar_value::Value, PrimitiveScalarType};
-impl From<&AggregateFunction> for protobuf::AggregateFunction {
- fn from(value: &AggregateFunction) -> Self {
- match value {
- AggregateFunction::Min => Self::Min,
- AggregateFunction::Max => Self::Max,
- AggregateFunction::Sum => Self::Sum,
- AggregateFunction::Avg => Self::Avg,
- AggregateFunction::Count => Self::Count,
- AggregateFunction::ApproxDistinct => Self::ApproxDistinct,
- AggregateFunction::ArrayAgg => Self::ArrayAgg,
- AggregateFunction::Variance => Self::Variance,
- AggregateFunction::VariancePop => Self::VariancePop,
- AggregateFunction::Covariance => Self::Covariance,
- AggregateFunction::CovariancePop => Self::CovariancePop,
- AggregateFunction::Stddev => Self::Stddev,
- AggregateFunction::StddevPop => Self::StddevPop,
- AggregateFunction::Correlation => Self::Correlation,
- AggregateFunction::ApproxPercentileCont => Self::ApproxPercentileCont,
- AggregateFunction::ApproxMedian => Self::ApproxMedian,
- }
+ let scalar_val = match val {
+ scalar::ScalarValue::Boolean(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Bool, |s| {
+ Value::BoolValue(*s)
+ })
+ }
+ scalar::ScalarValue::Float32(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Float32, |s| {
+ Value::Float32Value(*s)
+ })
+ }
+ scalar::ScalarValue::Float64(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Float64, |s| {
+ Value::Float64Value(*s)
+ })
+ }
+ scalar::ScalarValue::Int8(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Int8, |s| {
+ Value::Int8Value(*s as i32)
+ })
+ }
+ scalar::ScalarValue::Int16(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Int16, |s| {
+ Value::Int16Value(*s as i32)
+ })
+ }
+ scalar::ScalarValue::Int32(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Int32, |s| {
+ Value::Int32Value(*s)
+ })
+ }
+ scalar::ScalarValue::Int64(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Int64, |s| {
+ Value::Int64Value(*s)
+ })
+ }
+ scalar::ScalarValue::UInt8(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Uint8, |s| {
+ Value::Uint8Value(*s as u32)
+ })
+ }
+ scalar::ScalarValue::UInt16(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Uint16, |s| {
+ Value::Uint16Value(*s as u32)
+ })
+ }
+ scalar::ScalarValue::UInt32(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Uint32, |s| {
+ Value::Uint32Value(*s)
+ })
+ }
+ scalar::ScalarValue::UInt64(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Uint64, |s| {
+ Value::Uint64Value(*s)
+ })
+ }
+ scalar::ScalarValue::Utf8(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Utf8, |s| {
+ Value::Utf8Value(s.to_owned())
+ })
+ }
+ scalar::ScalarValue::LargeUtf8(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::LargeUtf8, |s| {
+ Value::LargeUtf8Value(s.to_owned())
+ })
+ }
+ scalar::ScalarValue::List(value, datatype) => {
+ println!("Current datatype of list: {:?}", datatype);
+ match value {
+ Some(values) => {
+ if values.is_empty() {
+ protobuf::ScalarValue {
+ value: Some(protobuf::scalar_value::Value::ListValue(
+ protobuf::ScalarListValue {
+ datatype: Some(datatype.as_ref().try_into()?),
+ values: Vec::new(),
+ },
+ )),
+ }
+ } else {
+ let scalar_type = match datatype.as_ref() {
+ DataType::List(field) => field.as_ref().data_type(),
+ _ => todo!("Proper error handling"),
+ };
+ println!("Current scalar type for list: {:?}", scalar_type);
+ let type_checked_values: Vec<protobuf::ScalarValue> = values
+ .iter()
+ .map(|scalar| match (scalar, scalar_type) {
+ (
+ scalar::ScalarValue::List(_, list_type),
+ DataType::List(field),
+ ) => {
+ if let DataType::List(list_field) =
+ list_type.as_ref()
+ {
+ let scalar_datatype = field.data_type();
+ let list_datatype = list_field.data_type();
+ if std::mem::discriminant(list_datatype)
+ != std::mem::discriminant(scalar_datatype)
+ {
+ return Err(
+ Error::inconsistent_list_typing(
+ list_datatype,
+ scalar_datatype,
+ ),
+ );
+ }
+ scalar.try_into()
+ } else {
+ Err(Error::inconsistent_list_designated(
+ scalar, datatype,
+ ))
+ }
+ }
+ (
+ scalar::ScalarValue::Boolean(_),
+ DataType::Boolean,
+ ) => scalar.try_into(),
+ (
+ scalar::ScalarValue::Float32(_),
+ DataType::Float32,
+ ) => scalar.try_into(),
+ (
+ scalar::ScalarValue::Float64(_),
+ DataType::Float64,
+ ) => scalar.try_into(),
+ (scalar::ScalarValue::Int8(_), DataType::Int8) => {
+ scalar.try_into()
+ }
+ (scalar::ScalarValue::Int16(_), DataType::Int16) => {
+ scalar.try_into()
+ }
+ (scalar::ScalarValue::Int32(_), DataType::Int32) => {
+ scalar.try_into()
+ }
+ (scalar::ScalarValue::Int64(_), DataType::Int64) => {
+ scalar.try_into()
+ }
+ (scalar::ScalarValue::UInt8(_), DataType::UInt8) => {
+ scalar.try_into()
+ }
+ (
+ scalar::ScalarValue::UInt16(_),
+ DataType::UInt16,
+ ) => scalar.try_into(),
+ (
+ scalar::ScalarValue::UInt32(_),
+ DataType::UInt32,
+ ) => scalar.try_into(),
+ (
+ scalar::ScalarValue::UInt64(_),
+ DataType::UInt64,
+ ) => scalar.try_into(),
+ (scalar::ScalarValue::Utf8(_), DataType::Utf8) => {
+ scalar.try_into()
+ }
+ (
+ scalar::ScalarValue::LargeUtf8(_),
+ DataType::LargeUtf8,
+ ) => scalar.try_into(),
+ _ => Err(Error::inconsistent_list_designated(
+ scalar, datatype,
+ )),
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ protobuf::ScalarValue {
+ value: Some(protobuf::scalar_value::Value::ListValue(
+ protobuf::ScalarListValue {
+ datatype: Some(datatype.as_ref().try_into()?),
+ values: type_checked_values,
+ },
+ )),
+ }
+ }
+ }
+ None => protobuf::ScalarValue {
+ value: Some(protobuf::scalar_value::Value::NullListValue(
+ datatype.as_ref().try_into()?,
+ )),
+ },
+ }
+ }
+ datafusion::scalar::ScalarValue::Date32(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Date32, |s| {
+ Value::Date32Value(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::TimestampMicrosecond(val, _) => {
+ create_proto_scalar(val, PrimitiveScalarType::TimeMicrosecond, |s| {
+ Value::TimeMicrosecondValue(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::TimestampNanosecond(val, _) => {
+ create_proto_scalar(val, PrimitiveScalarType::TimeNanosecond, |s| {
+ Value::TimeNanosecondValue(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::Decimal128(val, p, s) => match *val {
+ Some(v) => {
+ let array = v.to_be_bytes();
+ let vec_val: Vec<u8> = array.to_vec();
+ protobuf::ScalarValue {
+ value: Some(Value::Decimal128Value(protobuf::Decimal128 {
+ value: vec_val,
+ p: *p as i64,
+ s: *s as i64,
+ })),
+ }
+ }
+ None => protobuf::ScalarValue {
+ value: Some(protobuf::scalar_value::Value::NullValue(
+ PrimitiveScalarType::Decimal128 as i32,
+ )),
+ },
+ },
+ datafusion::scalar::ScalarValue::Date64(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::Date64, |s| {
+ Value::Date64Value(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::TimestampSecond(val, _) => {
+ create_proto_scalar(val, PrimitiveScalarType::TimeSecond, |s| {
+ Value::TimeSecondValue(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::TimestampMillisecond(val, _) => {
+ create_proto_scalar(val, PrimitiveScalarType::TimeMillisecond, |s| {
+ Value::TimeMillisecondValue(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::IntervalYearMonth(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::IntervalYearmonth, |s| {
+ Value::IntervalYearmonthValue(*s)
+ })
+ }
+ datafusion::scalar::ScalarValue::IntervalDayTime(val) => {
+ create_proto_scalar(val, PrimitiveScalarType::IntervalDaytime, |s| {
+ Value::IntervalDaytimeValue(*s)
+ })
+ }
+ _ => {
+ return Err(Error::invalid_scalar_value(val));
+ }
+ };
+
+ Ok(scalar_val)
}
}
-impl From<&BuiltInWindowFunction> for protobuf::BuiltInWindowFunction {
- fn from(value: &BuiltInWindowFunction) -> Self {
- match value {
- BuiltInWindowFunction::FirstValue => Self::FirstValue,
- BuiltInWindowFunction::LastValue => Self::LastValue,
- BuiltInWindowFunction::NthValue => Self::NthValue,
- BuiltInWindowFunction::Ntile => Self::Ntile,
- BuiltInWindowFunction::CumeDist => Self::CumeDist,
- BuiltInWindowFunction::PercentRank => Self::PercentRank,
- BuiltInWindowFunction::RowNumber => Self::RowNumber,
- BuiltInWindowFunction::Rank => Self::Rank,
- BuiltInWindowFunction::Lag => Self::Lag,
- BuiltInWindowFunction::Lead => Self::Lead,
- BuiltInWindowFunction::DenseRank => Self::DenseRank,
- }
+impl TryFrom<&BuiltinScalarFunction> for protobuf::ScalarFunction {
+ type Error = Error;
+
+ fn try_from(scalar: &BuiltinScalarFunction) -> Result<Self, Self::Error> {
+ let scalar_function = match scalar {
+ BuiltinScalarFunction::Sqrt => Self::Sqrt,
+ BuiltinScalarFunction::Sin => Self::Sin,
+ BuiltinScalarFunction::Cos => Self::Cos,
+ BuiltinScalarFunction::Tan => Self::Tan,
+ BuiltinScalarFunction::Asin => Self::Asin,
+ BuiltinScalarFunction::Acos => Self::Acos,
+ BuiltinScalarFunction::Atan => Self::Atan,
+ BuiltinScalarFunction::Exp => Self::Exp,
+ BuiltinScalarFunction::Log => Self::Log,
+ BuiltinScalarFunction::Ln => Self::Ln,
+ BuiltinScalarFunction::Log10 => Self::Log10,
+ BuiltinScalarFunction::Floor => Self::Floor,
+ BuiltinScalarFunction::Ceil => Self::Ceil,
+ BuiltinScalarFunction::Round => Self::Round,
+ BuiltinScalarFunction::Trunc => Self::Trunc,
+ BuiltinScalarFunction::Abs => Self::Abs,
+ BuiltinScalarFunction::OctetLength => Self::Octetlength,
+ BuiltinScalarFunction::Concat => Self::Concat,
+ BuiltinScalarFunction::Lower => Self::Lower,
+ BuiltinScalarFunction::Upper => Self::Upper,
+ BuiltinScalarFunction::Trim => Self::Trim,
+ BuiltinScalarFunction::Ltrim => Self::Ltrim,
+ BuiltinScalarFunction::Rtrim => Self::Rtrim,
+ BuiltinScalarFunction::ToTimestamp => Self::Totimestamp,
+ BuiltinScalarFunction::Array => Self::Array,
+ BuiltinScalarFunction::NullIf => Self::Nullif,
+ BuiltinScalarFunction::DatePart => Self::Datepart,
+ BuiltinScalarFunction::DateTrunc => Self::Datetrunc,
+ BuiltinScalarFunction::MD5 => Self::Md5,
+ BuiltinScalarFunction::SHA224 => Self::Sha224,
+ BuiltinScalarFunction::SHA256 => Self::Sha256,
+ BuiltinScalarFunction::SHA384 => Self::Sha384,
+ BuiltinScalarFunction::SHA512 => Self::Sha512,
+ BuiltinScalarFunction::Digest => Self::Digest,
+ BuiltinScalarFunction::ToTimestampMillis => Self::Totimestampmillis,
+ _ => return Err(Error::unsupported_scalar_function(scalar)),
+ };
+
+ Ok(scalar_function)
}
}
-impl From<WindowFrameUnits> for protobuf::WindowFrameUnits {
- fn from(units: WindowFrameUnits) -> Self {
- match units {
- WindowFrameUnits::Rows => protobuf::WindowFrameUnits::Rows,
- WindowFrameUnits::Range => protobuf::WindowFrameUnits::Range,
- WindowFrameUnits::Groups => protobuf::WindowFrameUnits::Groups,
- }
+impl TryFrom<&DataType> for protobuf::ScalarType {
+ type Error = Error;
+
+ fn try_from(value: &DataType) -> Result<Self, Self::Error> {
+ let datatype = protobuf::scalar_type::Datatype::try_from(value)?;
+ Ok(Self {
+ datatype: Some(datatype),
+ })
}
}
-impl From<WindowFrameBound> for protobuf::WindowFrameBound {
- fn from(bound: WindowFrameBound) -> Self {
- match bound {
- WindowFrameBound::CurrentRow => protobuf::WindowFrameBound {
- window_frame_bound_type: protobuf::WindowFrameBoundType::CurrentRow
- .into(),
- bound_value: None,
- },
- WindowFrameBound::Preceding(v) => protobuf::WindowFrameBound {
- window_frame_bound_type: protobuf::WindowFrameBoundType::Preceding.into(),
- bound_value: v.map(protobuf::window_frame_bound::BoundValue::Value),
- },
- WindowFrameBound::Following(v) => protobuf::WindowFrameBound {
- window_frame_bound_type: protobuf::WindowFrameBoundType::Following.into(),
- bound_value: v.map(protobuf::window_frame_bound::BoundValue::Value),
+impl TryFrom<&DataType> for protobuf::scalar_type::Datatype {
+ type Error = Error;
+
+ fn try_from(val: &DataType) -> Result<Self, Self::Error> {
+ use protobuf::PrimitiveScalarType;
+
+ let scalar_value = match val {
+ DataType::Boolean => Self::Scalar(PrimitiveScalarType::Bool as i32),
+ DataType::Int8 => Self::Scalar(PrimitiveScalarType::Int8 as i32),
+ DataType::Int16 => Self::Scalar(PrimitiveScalarType::Int16 as i32),
+ DataType::Int32 => Self::Scalar(PrimitiveScalarType::Int32 as i32),
+ DataType::Int64 => Self::Scalar(PrimitiveScalarType::Int64 as i32),
+ DataType::UInt8 => Self::Scalar(PrimitiveScalarType::Uint8 as i32),
+ DataType::UInt16 => Self::Scalar(PrimitiveScalarType::Uint16 as i32),
+ DataType::UInt32 => Self::Scalar(PrimitiveScalarType::Uint32 as i32),
+ DataType::UInt64 => Self::Scalar(PrimitiveScalarType::Uint64 as i32),
+ DataType::Float32 => Self::Scalar(PrimitiveScalarType::Float32 as i32),
+ DataType::Float64 => Self::Scalar(PrimitiveScalarType::Float64 as i32),
+ DataType::Date32 => Self::Scalar(PrimitiveScalarType::Date32 as i32),
+ DataType::Time64(time_unit) => match time_unit {
+ TimeUnit::Microsecond => {
+ Self::Scalar(PrimitiveScalarType::TimeMicrosecond as i32)
+ }
+ TimeUnit::Nanosecond => {
+ Self::Scalar(PrimitiveScalarType::TimeNanosecond as i32)
+ }
+ _ => {
+ return Err(Error::invalid_time_unit(time_unit));
+ }
},
+ DataType::Utf8 => Self::Scalar(PrimitiveScalarType::Utf8 as i32),
+ DataType::LargeUtf8 => Self::Scalar(PrimitiveScalarType::LargeUtf8 as i32),
+ DataType::List(field_type) => {
+ let mut field_names: Vec<String> = Vec::new();
+ let mut curr_field = field_type.as_ref();
+ field_names.push(curr_field.name().to_owned());
+ // For each nested field check nested datatype, since datafusion scalars only
+ // support recursive lists with a leaf scalar type
+ // any other compound types are errors.
+
+ while let DataType::List(nested_field_type) = curr_field.data_type() {
+ curr_field = nested_field_type.as_ref();
+ field_names.push(curr_field.name().to_owned());
+ if !is_valid_scalar_type_no_list_check(curr_field.data_type()) {
+ return Err(Error::invalid_scalar_type(curr_field.data_type()));
+ }
+ }
+ let deepest_datatype = curr_field.data_type();
+ if !is_valid_scalar_type_no_list_check(deepest_datatype) {
+ return Err(Error::invalid_scalar_type(deepest_datatype));
+ }
+ let pb_deepest_type: PrimitiveScalarType = match deepest_datatype {
+ DataType::Boolean => PrimitiveScalarType::Bool,
+ DataType::Int8 => PrimitiveScalarType::Int8,
+ DataType::Int16 => PrimitiveScalarType::Int16,
+ DataType::Int32 => PrimitiveScalarType::Int32,
+ DataType::Int64 => PrimitiveScalarType::Int64,
+ DataType::UInt8 => PrimitiveScalarType::Uint8,
+ DataType::UInt16 => PrimitiveScalarType::Uint16,
+ DataType::UInt32 => PrimitiveScalarType::Uint32,
+ DataType::UInt64 => PrimitiveScalarType::Uint64,
+ DataType::Float32 => PrimitiveScalarType::Float32,
+ DataType::Float64 => PrimitiveScalarType::Float64,
+ DataType::Date32 => PrimitiveScalarType::Date32,
+ DataType::Time64(time_unit) => match time_unit {
+ TimeUnit::Microsecond => PrimitiveScalarType::TimeMicrosecond,
+ TimeUnit::Nanosecond => PrimitiveScalarType::TimeNanosecond,
+ _ => {
+ return Err(Error::invalid_time_unit(time_unit));
+ }
+ },
+
+ DataType::Utf8 => PrimitiveScalarType::Utf8,
+ DataType::LargeUtf8 => PrimitiveScalarType::LargeUtf8,
+ _ => {
+ return Err(Error::invalid_scalar_type(val));
+ }
+ };
+ Self::List(protobuf::ScalarListType {
+ field_names,
+ deepest_type: pb_deepest_type as i32,
+ })
+ }
+ DataType::Null
+ | DataType::Float16
+ | DataType::Timestamp(_, _)
+ | DataType::Date64
+ | DataType::Time32(_)
+ | DataType::Duration(_)
+ | DataType::Interval(_)
+ | DataType::Binary
+ | DataType::FixedSizeBinary(_)
+ | DataType::LargeBinary
+ | DataType::FixedSizeList(_, _)
+ | DataType::LargeList(_)
+ | DataType::Struct(_)
+ | DataType::Union(_, _)
+ | DataType::Dictionary(_, _)
+ | DataType::Map(_, _)
+ | DataType::Decimal(_, _) => {
+ return Err(Error::invalid_scalar_type(val));
+ }
+ };
+
+ Ok(scalar_value)
+ }
+}
+
+impl From<&TimeUnit> for protobuf::TimeUnit {
+ fn from(val: &TimeUnit) -> Self {
+ match val {
+ TimeUnit::Second => protobuf::TimeUnit::Second,
+ TimeUnit::Millisecond => protobuf::TimeUnit::TimeMillisecond,
+ TimeUnit::Microsecond => protobuf::TimeUnit::Microsecond,
+ TimeUnit::Nanosecond => protobuf::TimeUnit::Nanosecond,
}
}
}
-impl From<WindowFrame> for protobuf::WindowFrame {
- fn from(window: WindowFrame) -> Self {
- protobuf::WindowFrame {
- window_frame_units: protobuf::WindowFrameUnits::from(window.units).into(),
- start_bound: Some(window.start_bound.into()),
- end_bound: Some(protobuf::window_frame::EndBound::Bound(
- window.end_bound.into(),
- )),
+impl From<&IntervalUnit> for protobuf::IntervalUnit {
+ fn from(interval_unit: &IntervalUnit) -> Self {
+ match interval_unit {
+ IntervalUnit::YearMonth => protobuf::IntervalUnit::YearMonth,
+ IntervalUnit::DayTime => protobuf::IntervalUnit::DayTime,
+ IntervalUnit::MonthDayNano => protobuf::IntervalUnit::MonthDayNano,
}
}
}
-impl TryFrom<&DataType> for protobuf::ScalarType {
- type Error = BallistaError;
- fn try_from(value: &DataType) -> Result<Self, Self::Error> {
- let datatype = protobuf::scalar_type::Datatype::try_from(value)?;
- Ok(protobuf::ScalarType {
- datatype: Some(datatype),
- })
+fn create_proto_scalar<I, T: FnOnce(&I) -> protobuf::scalar_value::Value>(
+ v: &Option<I>,
+ null_arrow_type: protobuf::PrimitiveScalarType,
+ constructor: T,
+) -> protobuf::ScalarValue {
+ protobuf::ScalarValue {
+ value: Some(v.as_ref().map(constructor).unwrap_or(
+ protobuf::scalar_value::Value::NullValue(null_arrow_type as i32),
+ )),
}
}
-impl TryInto<protobuf::ScalarFunction> for &BuiltinScalarFunction {
- type Error = BallistaError;
- fn try_into(self) -> Result<protobuf::ScalarFunction, Self::Error> {
- match self {
- BuiltinScalarFunction::Sqrt => Ok(protobuf::ScalarFunction::Sqrt),
- BuiltinScalarFunction::Sin => Ok(protobuf::ScalarFunction::Sin),
- BuiltinScalarFunction::Cos => Ok(protobuf::ScalarFunction::Cos),
- BuiltinScalarFunction::Tan => Ok(protobuf::ScalarFunction::Tan),
- BuiltinScalarFunction::Asin => Ok(protobuf::ScalarFunction::Asin),
- BuiltinScalarFunction::Acos => Ok(protobuf::ScalarFunction::Acos),
- BuiltinScalarFunction::Atan => Ok(protobuf::ScalarFunction::Atan),
- BuiltinScalarFunction::Exp => Ok(protobuf::ScalarFunction::Exp),
- BuiltinScalarFunction::Log => Ok(protobuf::ScalarFunction::Log),
- BuiltinScalarFunction::Ln => Ok(protobuf::ScalarFunction::Ln),
- BuiltinScalarFunction::Log10 => Ok(protobuf::ScalarFunction::Log10),
- BuiltinScalarFunction::Floor => Ok(protobuf::ScalarFunction::Floor),
- BuiltinScalarFunction::Ceil => Ok(protobuf::ScalarFunction::Ceil),
- BuiltinScalarFunction::Round => Ok(protobuf::ScalarFunction::Round),
- BuiltinScalarFunction::Trunc => Ok(protobuf::ScalarFunction::Trunc),
- BuiltinScalarFunction::Abs => Ok(protobuf::ScalarFunction::Abs),
- BuiltinScalarFunction::OctetLength => {
- Ok(protobuf::ScalarFunction::Octetlength)
- }
- BuiltinScalarFunction::Concat => Ok(protobuf::ScalarFunction::Concat),
- BuiltinScalarFunction::Lower => Ok(protobuf::ScalarFunction::Lower),
- BuiltinScalarFunction::Upper => Ok(protobuf::ScalarFunction::Upper),
- BuiltinScalarFunction::Trim => Ok(protobuf::ScalarFunction::Trim),
- BuiltinScalarFunction::Ltrim => Ok(protobuf::ScalarFunction::Ltrim),
- BuiltinScalarFunction::Rtrim => Ok(protobuf::ScalarFunction::Rtrim),
- BuiltinScalarFunction::ToTimestamp => {
- Ok(protobuf::ScalarFunction::Totimestamp)
- }
- BuiltinScalarFunction::Array => Ok(protobuf::ScalarFunction::Array),
- BuiltinScalarFunction::NullIf => Ok(protobuf::ScalarFunction::Nullif),
- BuiltinScalarFunction::DatePart => Ok(protobuf::ScalarFunction::Datepart),
- BuiltinScalarFunction::DateTrunc => Ok(protobuf::ScalarFunction::Datetrunc),
- BuiltinScalarFunction::MD5 => Ok(protobuf::ScalarFunction::Md5),
- BuiltinScalarFunction::SHA224 => Ok(protobuf::ScalarFunction::Sha224),
- BuiltinScalarFunction::SHA256 => Ok(protobuf::ScalarFunction::Sha256),
- BuiltinScalarFunction::SHA384 => Ok(protobuf::ScalarFunction::Sha384),
- BuiltinScalarFunction::SHA512 => Ok(protobuf::ScalarFunction::Sha512),
- BuiltinScalarFunction::Digest => Ok(protobuf::ScalarFunction::Digest),
- BuiltinScalarFunction::ToTimestampMillis => {
- Ok(protobuf::ScalarFunction::Totimestampmillis)
- }
- _ => Err(BallistaError::General(format!(
- "logical_plan::to_proto() unsupported scalar function {:?}",
- self
- ))),
+// Does not check if list subtypes are valid
+fn is_valid_scalar_type_no_list_check(datatype: &DataType) -> bool {
+ match datatype {
+ DataType::Boolean
+ | DataType::Int8
+ | DataType::Int16
+ | DataType::Int32
+ | DataType::Int64
+ | DataType::UInt8
+ | DataType::UInt16
+ | DataType::UInt32
+ | DataType::UInt64
+ | DataType::Float32
+ | DataType::Float64
+ | DataType::LargeUtf8
+ | DataType::Utf8
+ | DataType::Date32 => true,
+ DataType::Time64(time_unit) => {
+ matches!(time_unit, TimeUnit::Microsecond | TimeUnit::Nanosecond)
}
+
+ DataType::List(_) => true,
+ _ => false,
}
}