-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
roundtrip_logical_plan.rs
2091 lines (1852 loc) · 66.5 KB
/
roundtrip_logical_plan.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
use std::vec;
use arrow::array::{ArrayRef, FixedSizeListArray};
use arrow::datatypes::{
DataType, Field, Fields, Int32Type, IntervalDayTimeType, IntervalMonthDayNanoType,
IntervalUnit, Schema, SchemaRef, TimeUnit, UnionFields, UnionMode,
};
use datafusion::datasource::provider::TableProviderFactory;
use datafusion::datasource::TableProvider;
use datafusion::execution::context::SessionState;
use datafusion::execution::runtime_env::{RuntimeConfig, RuntimeEnv};
use datafusion::functions_aggregate::expr_fn::first_value;
use datafusion::prelude::*;
use datafusion::test_util::{TestTableFactory, TestTableProvider};
use datafusion_common::config::{FormatOptions, TableOptions};
use datafusion_common::scalar::ScalarStructBuilder;
use datafusion_common::{
internal_datafusion_err, internal_err, not_impl_err, plan_err, DFSchema, DFSchemaRef,
DataFusionError, FileType, Result, ScalarValue,
};
use datafusion_expr::dml::CopyTo;
use datafusion_expr::expr::{
self, Between, BinaryExpr, Case, Cast, GroupingSet, InList, Like, ScalarFunction,
Sort, Unnest,
};
use datafusion_expr::logical_plan::{Extension, UserDefinedLogicalNodeCore};
use datafusion_expr::{
col, create_udaf, lit, Accumulator, AggregateFunction, ColumnarValue, Expr,
ExprSchemable, LogicalPlan, Operator, PartitionEvaluator, ScalarUDF, ScalarUDFImpl,
Signature, TryCast, Volatility, WindowFrame, WindowFrameBound, WindowFrameUnits,
WindowFunctionDefinition, WindowUDF, WindowUDFImpl,
};
use datafusion_proto::bytes::{
logical_plan_from_bytes, logical_plan_from_bytes_with_extension_codec,
logical_plan_to_bytes, logical_plan_to_bytes_with_extension_codec,
};
use datafusion_proto::logical_plan::to_proto::serialize_expr;
use datafusion_proto::logical_plan::LogicalExtensionCodec;
use datafusion_proto::logical_plan::{from_proto, DefaultLogicalExtensionCodec};
use datafusion_proto::protobuf;
use datafusion::execution::FunctionRegistry;
use prost::Message;
#[cfg(feature = "json")]
fn roundtrip_json_test(proto: &protobuf::LogicalExprNode) {
let string = serde_json::to_string(proto).unwrap();
let back: protobuf::LogicalExprNode = serde_json::from_str(&string).unwrap();
assert_eq!(proto, &back);
}
#[cfg(not(feature = "json"))]
fn roundtrip_json_test(_proto: &protobuf::LogicalExprNode) {}
// Given a DataFusion logical Expr, convert it to protobuf and back, using debug formatting to test
// equality.
fn roundtrip_expr_test(initial_struct: Expr, ctx: SessionContext) {
let extension_codec = DefaultLogicalExtensionCodec {};
let proto: protobuf::LogicalExprNode =
match serialize_expr(&initial_struct, &extension_codec) {
Ok(p) => p,
Err(e) => panic!("Error serializing expression: {:?}", e),
};
let round_trip: Expr =
from_proto::parse_expr(&proto, &ctx, &extension_codec).unwrap();
assert_eq!(format!("{:?}", &initial_struct), format!("{round_trip:?}"));
roundtrip_json_test(&proto);
}
fn new_arc_field(name: &str, dt: DataType, nullable: bool) -> Arc<Field> {
Arc::new(Field::new(name, dt, nullable))
}
#[tokio::test]
async fn roundtrip_logical_plan() -> Result<()> {
let ctx = SessionContext::new();
ctx.register_csv("t1", "tests/testdata/test.csv", CsvReadOptions::default())
.await?;
let scan = ctx.table("t1").await?.into_optimized_plan()?;
let topk_plan = LogicalPlan::Extension(Extension {
node: Arc::new(TopKPlanNode::new(3, scan, col("revenue"))),
});
let extension_codec = TopKExtensionCodec {};
let bytes = logical_plan_to_bytes_with_extension_codec(&topk_plan, &extension_codec)?;
let logical_round_trip =
logical_plan_from_bytes_with_extension_codec(&bytes, &ctx, &extension_codec)?;
assert_eq!(format!("{topk_plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[derive(Clone, PartialEq, Eq, ::prost::Message)]
pub struct TestTableProto {
/// URL of the table root
#[prost(string, tag = "1")]
pub url: String,
}
#[derive(Debug)]
pub struct TestTableProviderCodec {}
impl LogicalExtensionCodec for TestTableProviderCodec {
fn try_decode(
&self,
_buf: &[u8],
_inputs: &[LogicalPlan],
_ctx: &SessionContext,
) -> Result<Extension> {
not_impl_err!("No extension codec provided")
}
fn try_encode(&self, _node: &Extension, _buf: &mut Vec<u8>) -> Result<()> {
not_impl_err!("No extension codec provided")
}
fn try_decode_table_provider(
&self,
buf: &[u8],
schema: SchemaRef,
_ctx: &SessionContext,
) -> Result<Arc<dyn TableProvider>> {
let msg = TestTableProto::decode(buf).map_err(|_| {
DataFusionError::Internal("Error decoding test table".to_string())
})?;
let provider = TestTableProvider {
url: msg.url,
schema,
};
Ok(Arc::new(provider))
}
fn try_encode_table_provider(
&self,
node: Arc<dyn TableProvider>,
buf: &mut Vec<u8>,
) -> Result<()> {
let table = node
.as_ref()
.as_any()
.downcast_ref::<TestTableProvider>()
.expect("Can't encode non-test tables");
let msg = TestTableProto {
url: table.url.clone(),
};
msg.encode(buf).map_err(|_| {
DataFusionError::Internal("Error encoding test table".to_string())
})
}
}
#[tokio::test]
async fn roundtrip_custom_tables() -> Result<()> {
let mut table_factories: HashMap<String, Arc<dyn TableProviderFactory>> =
HashMap::new();
table_factories.insert("TESTTABLE".to_string(), Arc::new(TestTableFactory {}));
let cfg = RuntimeConfig::new();
let env = RuntimeEnv::new(cfg).unwrap();
let ses = SessionConfig::new();
let mut state = SessionState::new_with_config_rt(ses, Arc::new(env));
// replace factories
*state.table_factories_mut() = table_factories;
let ctx = SessionContext::new_with_state(state);
let sql = "CREATE EXTERNAL TABLE t STORED AS testtable LOCATION 's3://bucket/schema/table';";
ctx.sql(sql).await.unwrap();
let codec = TestTableProviderCodec {};
let scan = ctx.table("t").await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes_with_extension_codec(&scan, &codec)?;
let logical_round_trip =
logical_plan_from_bytes_with_extension_codec(&bytes, &ctx, &codec)?;
assert_eq!(format!("{scan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_custom_memory_tables() -> Result<()> {
let ctx = SessionContext::new();
// Make sure during round-trip, constraint information is preserved
let query = "CREATE TABLE sales_global_with_pk (zip_code INT,
country VARCHAR(3),
sn INT,
ts TIMESTAMP,
currency VARCHAR(3),
amount FLOAT,
primary key(sn)
) as VALUES
(0, 'GRC', 0, '2022-01-01 06:00:00'::timestamp, 'EUR', 30.0),
(1, 'FRA', 1, '2022-01-01 08:00:00'::timestamp, 'EUR', 50.0),
(1, 'TUR', 2, '2022-01-01 11:30:00'::timestamp, 'TRY', 75.0),
(1, 'FRA', 3, '2022-01-02 12:00:00'::timestamp, 'EUR', 200.0),
(1, 'TUR', 4, '2022-01-03 10:00:00'::timestamp, 'TRY', 100.0)";
let plan = ctx.sql(query).await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_custom_listing_tables() -> Result<()> {
let ctx = SessionContext::new();
let query = "CREATE EXTERNAL TABLE multiple_ordered_table_with_pk (
a0 INTEGER,
a INTEGER DEFAULT 1*2 + 3,
b INTEGER DEFAULT NULL,
c INTEGER,
d INTEGER,
primary key(c)
)
STORED AS CSV
WITH HEADER ROW
WITH ORDER (a ASC, b ASC)
WITH ORDER (c ASC)
LOCATION '../core/tests/data/window_2.csv';";
let plan = ctx.state().create_logical_plan(query).await?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
// Use exact matching to verify everything. Make sure during round-trip,
// information like constraints, column defaults, and other aspects of the plan are preserved.
assert_eq!(plan, logical_round_trip);
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_aggregation_with_pk() -> Result<()> {
let ctx = SessionContext::new();
ctx.sql(
"CREATE EXTERNAL TABLE multiple_ordered_table_with_pk (
a0 INTEGER,
a INTEGER,
b INTEGER,
c INTEGER,
d INTEGER,
primary key(c)
)
STORED AS CSV
WITH HEADER ROW
WITH ORDER (a ASC, b ASC)
WITH ORDER (c ASC)
LOCATION '../core/tests/data/window_2.csv';",
)
.await?;
let query = "SELECT c, b, SUM(d)
FROM multiple_ordered_table_with_pk
GROUP BY c";
let plan = ctx.sql(query).await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_aggregation() -> Result<()> {
let ctx = SessionContext::new();
let schema = Schema::new(vec![
Field::new("a", DataType::Int64, true),
Field::new("b", DataType::Decimal128(15, 2), true),
]);
ctx.register_csv(
"t1",
"tests/testdata/test.csv",
CsvReadOptions::default().schema(&schema),
)
.await?;
let query = "SELECT a, SUM(b + 1) as b_sum FROM t1 GROUP BY a ORDER BY b_sum DESC";
let plan = ctx.sql(query).await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_copy_to_sql_options() -> Result<()> {
let ctx = SessionContext::new();
let input = create_csv_scan(&ctx).await?;
let mut table_options = ctx.copied_table_options();
table_options.set_file_format(FileType::CSV);
table_options.set("format.delimiter", ";")?;
let plan = LogicalPlan::Copy(CopyTo {
input: Arc::new(input),
output_url: "test.csv".to_string(),
partition_by: vec!["a".to_string(), "b".to_string(), "c".to_string()],
format_options: FormatOptions::CSV(table_options.csv.clone()),
options: Default::default(),
});
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_copy_to_writer_options() -> Result<()> {
let ctx = SessionContext::new();
let input = create_csv_scan(&ctx).await?;
let table_options =
TableOptions::default_from_session_config(ctx.state().config_options());
let mut parquet_format = table_options.parquet;
parquet_format.global.bloom_filter_enabled = true;
parquet_format.global.created_by = "DataFusion Test".to_string();
parquet_format.global.writer_version = "PARQUET_2_0".to_string();
parquet_format.global.write_batch_size = 111;
parquet_format.global.data_pagesize_limit = 222;
parquet_format.global.data_page_row_count_limit = 333;
parquet_format.global.dictionary_page_size_limit = 444;
parquet_format.global.max_row_group_size = 555;
let plan = LogicalPlan::Copy(CopyTo {
input: Arc::new(input),
output_url: "test.parquet".to_string(),
format_options: FormatOptions::PARQUET(parquet_format.clone()),
partition_by: vec!["a".to_string(), "b".to_string(), "c".to_string()],
options: Default::default(),
});
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
match logical_round_trip {
LogicalPlan::Copy(copy_to) => {
assert_eq!("test.parquet", copy_to.output_url);
assert_eq!(vec!["a", "b", "c"], copy_to.partition_by);
assert_eq!(
copy_to.format_options,
FormatOptions::PARQUET(parquet_format)
);
}
_ => panic!(),
}
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_copy_to_arrow() -> Result<()> {
let ctx = SessionContext::new();
let input = create_csv_scan(&ctx).await?;
let plan = LogicalPlan::Copy(CopyTo {
input: Arc::new(input),
output_url: "test.arrow".to_string(),
partition_by: vec!["a".to_string(), "b".to_string(), "c".to_string()],
format_options: FormatOptions::ARROW,
options: Default::default(),
});
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
match logical_round_trip {
LogicalPlan::Copy(copy_to) => {
assert_eq!("test.arrow", copy_to.output_url);
assert_eq!(FormatOptions::ARROW, copy_to.format_options);
assert_eq!(vec!["a", "b", "c"], copy_to.partition_by);
}
_ => panic!(),
}
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_copy_to_csv() -> Result<()> {
let ctx = SessionContext::new();
let input = create_csv_scan(&ctx).await?;
let table_options =
TableOptions::default_from_session_config(ctx.state().config_options());
let mut csv_format = table_options.csv;
csv_format.delimiter = b'*';
csv_format.date_format = Some("dd/MM/yyyy".to_string());
csv_format.datetime_format = Some("dd/MM/yyyy HH:mm:ss".to_string());
csv_format.timestamp_format = Some("HH:mm:ss.SSSSSS".to_string());
csv_format.time_format = Some("HH:mm:ss".to_string());
csv_format.null_value = Some("NIL".to_string());
let plan = LogicalPlan::Copy(CopyTo {
input: Arc::new(input),
output_url: "test.csv".to_string(),
partition_by: vec!["a".to_string(), "b".to_string(), "c".to_string()],
format_options: FormatOptions::CSV(csv_format.clone()),
options: Default::default(),
});
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
match logical_round_trip {
LogicalPlan::Copy(copy_to) => {
assert_eq!("test.csv", copy_to.output_url);
assert_eq!(FormatOptions::CSV(csv_format), copy_to.format_options);
assert_eq!(vec!["a", "b", "c"], copy_to.partition_by);
}
_ => panic!(),
}
Ok(())
}
async fn create_csv_scan(ctx: &SessionContext) -> Result<LogicalPlan, DataFusionError> {
ctx.register_csv("t1", "tests/testdata/test.csv", CsvReadOptions::default())
.await?;
let input = ctx.table("t1").await?.into_optimized_plan()?;
Ok(input)
}
#[tokio::test]
async fn roundtrip_logical_plan_distinct_on() -> Result<()> {
let ctx = SessionContext::new();
let schema = Schema::new(vec![
Field::new("a", DataType::Int64, true),
Field::new("b", DataType::Decimal128(15, 2), true),
]);
ctx.register_csv(
"t1",
"tests/testdata/test.csv",
CsvReadOptions::default().schema(&schema),
)
.await?;
let query = "SELECT DISTINCT ON (a % 2) a, b * 2 FROM t1 ORDER BY a % 2 DESC, b";
let plan = ctx.sql(query).await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_single_count_distinct() -> Result<()> {
let ctx = SessionContext::new();
let schema = Schema::new(vec![
Field::new("a", DataType::Int64, true),
Field::new("b", DataType::Decimal128(15, 2), true),
]);
ctx.register_csv(
"t1",
"tests/testdata/test.csv",
CsvReadOptions::default().schema(&schema),
)
.await?;
let query = "SELECT a, COUNT(DISTINCT b) as b_cd FROM t1 GROUP BY a";
let plan = ctx.sql(query).await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_with_extension() -> Result<()> {
let ctx = SessionContext::new();
ctx.register_csv("t1", "tests/testdata/test.csv", CsvReadOptions::default())
.await?;
let plan = ctx.table("t1").await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_expr_api() -> Result<()> {
let ctx = SessionContext::new();
ctx.register_csv("t1", "tests/testdata/test.csv", CsvReadOptions::default())
.await?;
let table = ctx.table("t1").await?;
let schema = table.schema().clone();
// list of expressions to round trip
let expr_list = vec![
encode(col("a").cast_to(&DataType::Utf8, &schema)?, lit("hex")),
decode(lit("1234"), lit("hex")),
array_to_string(make_array(vec![lit(1), lit(2), lit(3)]), lit(",")),
array_dims(make_array(vec![lit(1), lit(2), lit(3)])),
array_ndims(make_array(vec![lit(1), lit(2), lit(3)])),
cardinality(make_array(vec![lit(1), lit(2), lit(3)])),
string_to_array(lit("abc#def#ghl"), lit("#"), lit(",")),
range(lit(1), lit(10), lit(2)),
gen_series(lit(1), lit(10), lit(2)),
array_append(make_array(vec![lit(1), lit(2), lit(3)]), lit(4)),
array_prepend(lit(1), make_array(vec![lit(2), lit(3), lit(4)])),
array_concat(vec![
make_array(vec![lit(1), lit(2)]),
make_array(vec![lit(3), lit(4)]),
]),
make_array(vec![lit(1), lit(2), lit(3)]),
array_has(make_array(vec![lit(1), lit(2), lit(3)]), lit(1)),
array_has_all(
make_array(vec![lit(1), lit(2), lit(3)]),
make_array(vec![lit(1), lit(2)]),
),
array_has_any(
make_array(vec![lit(1), lit(2), lit(3)]),
make_array(vec![lit(1), lit(4)]),
),
array_empty(make_array(vec![lit(1), lit(2), lit(3)])),
array_length(make_array(vec![lit(1), lit(2), lit(3)])),
array_repeat(lit(1), lit(3)),
flatten(make_array(vec![lit(1), lit(2), lit(3)])),
array_sort(
make_array(vec![lit(3), lit(4), lit(1), lit(2)]),
lit("desc"),
lit("NULLS LAST"),
),
array_distinct(make_array(vec![lit(1), lit(3), lit(3), lit(2), lit(2)])),
array_intersect(
make_array(vec![lit(1), lit(3)]),
make_array(vec![lit(1), lit(4)]),
),
array_union(
make_array(vec![lit(1), lit(3)]),
make_array(vec![lit(1), lit(4)]),
),
array_resize(make_array(vec![lit(1), lit(2), lit(3)]), lit(5), lit(0)),
array_element(make_array(vec![lit(1), lit(2), lit(3)]), lit(2)),
array_slice(
make_array(vec![lit(1), lit(2), lit(3)]),
lit(1),
lit(2),
lit(1),
),
array_pop_front(make_array(vec![lit(1), lit(2), lit(3)])),
array_pop_back(make_array(vec![lit(1), lit(2), lit(3)])),
array_reverse(make_array(vec![lit(1), lit(2), lit(3)])),
array_position(
make_array(vec![lit(1), lit(2), lit(3), lit(4)]),
lit(3),
lit(2),
),
array_positions(make_array(vec![lit(4), lit(3), lit(3), lit(1)]), lit(3)),
array_except(
make_array(vec![lit(1), lit(2), lit(3)]),
make_array(vec![lit(1), lit(2)]),
),
array_remove(make_array(vec![lit(4), lit(3), lit(2), lit(1)]), lit(3)),
array_remove_n(
make_array(vec![lit(1), lit(3), lit(3), lit(3)]),
lit(3),
lit(2),
),
array_remove_all(
make_array(vec![lit(3), lit(3), lit(2), lit(3), lit(1)]),
lit(3),
),
array_replace(make_array(vec![lit(1), lit(2), lit(3)]), lit(2), lit(4)),
array_replace_n(
make_array(vec![lit(1), lit(2), lit(3)]),
lit(2),
lit(4),
lit(1),
),
array_replace_all(make_array(vec![lit(1), lit(2), lit(3)]), lit(2), lit(4)),
first_value(lit(1)),
];
// ensure expressions created with the expr api can be round tripped
let plan = table.select(expr_list)?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
#[tokio::test]
async fn roundtrip_logical_plan_with_view_scan() -> Result<()> {
let ctx = SessionContext::new();
ctx.register_csv("t1", "tests/testdata/test.csv", CsvReadOptions::default())
.await?;
ctx.sql("CREATE VIEW view_t1(a, b) AS SELECT a, b FROM t1")
.await?;
// SELECT
let plan = ctx
.sql("SELECT * FROM view_t1")
.await?
.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
// DROP
let plan = ctx.sql("DROP VIEW view_t1").await?.into_optimized_plan()?;
let bytes = logical_plan_to_bytes(&plan)?;
let logical_round_trip = logical_plan_from_bytes(&bytes, &ctx)?;
assert_eq!(format!("{plan:?}"), format!("{logical_round_trip:?}"));
Ok(())
}
pub mod proto {
#[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<datafusion_proto::protobuf::LogicalExprNode>,
}
#[derive(Clone, PartialEq, Eq, ::prost::Message)]
pub struct TopKExecProto {
#[prost(uint64, tag = "1")]
pub k: u64,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MyRegexUdfNode {
#[prost(string, tag = "1")]
pub pattern: String,
}
}
#[derive(PartialEq, Eq, Hash)]
struct TopKPlanNode {
k: usize,
input: LogicalPlan,
/// The sort expression (this example only supports a single sort
/// expr)
expr: Expr,
}
impl TopKPlanNode {
pub fn new(k: usize, input: LogicalPlan, expr: Expr) -> Self {
Self { k, input, expr }
}
}
impl Debug for TopKPlanNode {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.fmt_for_explain(f)
}
}
impl UserDefinedLogicalNodeCore for TopKPlanNode {
fn name(&self) -> &str {
"TopK"
}
fn inputs(&self) -> Vec<&LogicalPlan> {
vec![&self.input]
}
/// Schema for TopK is the same as the input
fn schema(&self) -> &DFSchemaRef {
self.input.schema()
}
fn expressions(&self) -> Vec<Expr> {
vec![self.expr.clone()]
}
/// For example: `TopK: k=10`
fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "TopK: k={}", self.k)
}
fn from_template(&self, exprs: &[Expr], inputs: &[LogicalPlan]) -> Self {
assert_eq!(inputs.len(), 1, "input size inconsistent");
assert_eq!(exprs.len(), 1, "expression size inconsistent");
Self {
k: self.k,
input: inputs[0].clone(),
expr: exprs[0].clone(),
}
}
}
#[derive(Debug)]
pub struct TopKExtensionCodec {}
impl LogicalExtensionCodec for TopKExtensionCodec {
fn try_decode(
&self,
buf: &[u8],
inputs: &[LogicalPlan],
ctx: &SessionContext,
) -> Result<Extension> {
if let Some((input, _)) = inputs.split_first() {
let proto = proto::TopKPlanProto::decode(buf).map_err(|e| {
DataFusionError::Internal(format!("failed to decode logical plan: {e:?}"))
})?;
if let Some(expr) = proto.expr.as_ref() {
let node = TopKPlanNode::new(
proto.k as usize,
input.clone(),
from_proto::parse_expr(expr, ctx, self)?,
);
Ok(Extension {
node: Arc::new(node),
})
} else {
internal_err!("invalid plan, no expr")
}
} else {
internal_err!("invalid plan, no input")
}
}
fn try_encode(&self, node: &Extension, buf: &mut Vec<u8>) -> Result<()> {
if let Some(exec) = node.node.as_any().downcast_ref::<TopKPlanNode>() {
let proto = proto::TopKPlanProto {
k: exec.k as u64,
expr: Some(serialize_expr(&exec.expr, self)?),
};
proto.encode(buf).map_err(|e| {
DataFusionError::Internal(format!("failed to encode logical plan: {e:?}"))
})?;
Ok(())
} else {
internal_err!("unsupported plan type")
}
}
fn try_decode_table_provider(
&self,
_buf: &[u8],
_schema: SchemaRef,
_ctx: &SessionContext,
) -> Result<Arc<dyn TableProvider>> {
internal_err!("unsupported plan type")
}
fn try_encode_table_provider(
&self,
_node: Arc<dyn TableProvider>,
_buf: &mut Vec<u8>,
) -> Result<()> {
internal_err!("unsupported plan type")
}
}
#[derive(Debug)]
struct MyRegexUdf {
signature: Signature,
// regex as original string
pattern: String,
}
impl MyRegexUdf {
fn new(pattern: String) -> Self {
Self {
signature: Signature::uniform(
1,
vec![DataType::Int32],
Volatility::Immutable,
),
pattern,
}
}
}
/// Implement the ScalarUDFImpl trait for MyRegexUdf
impl ScalarUDFImpl for MyRegexUdf {
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &str {
"regex_udf"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, args: &[DataType]) -> Result<DataType> {
if !matches!(args.first(), Some(&DataType::Utf8)) {
return plan_err!("regex_udf only accepts Utf8 arguments");
}
Ok(DataType::Int32)
}
fn invoke(&self, _args: &[ColumnarValue]) -> Result<ColumnarValue> {
unimplemented!()
}
}
#[derive(Debug)]
pub struct ScalarUDFExtensionCodec {}
impl LogicalExtensionCodec for ScalarUDFExtensionCodec {
fn try_decode(
&self,
_buf: &[u8],
_inputs: &[LogicalPlan],
_ctx: &SessionContext,
) -> Result<Extension> {
not_impl_err!("No extension codec provided")
}
fn try_encode(&self, _node: &Extension, _buf: &mut Vec<u8>) -> Result<()> {
not_impl_err!("No extension codec provided")
}
fn try_decode_table_provider(
&self,
_buf: &[u8],
_schema: SchemaRef,
_ctx: &SessionContext,
) -> Result<Arc<dyn TableProvider>> {
internal_err!("unsupported plan type")
}
fn try_encode_table_provider(
&self,
_node: Arc<dyn TableProvider>,
_buf: &mut Vec<u8>,
) -> Result<()> {
internal_err!("unsupported plan type")
}
fn try_decode_udf(&self, name: &str, buf: &[u8]) -> Result<Arc<ScalarUDF>> {
if name == "regex_udf" {
let proto = proto::MyRegexUdfNode::decode(buf).map_err(|err| {
DataFusionError::Internal(format!("failed to decode regex_udf: {}", err))
})?;
Ok(Arc::new(ScalarUDF::new_from_impl(MyRegexUdf::new(
proto.pattern,
))))
} else {
not_impl_err!("unrecognized scalar UDF implementation, cannot decode")
}
}
fn try_encode_udf(&self, node: &ScalarUDF, buf: &mut Vec<u8>) -> Result<()> {
let binding = node.inner();
let udf = binding.as_any().downcast_ref::<MyRegexUdf>().unwrap();
let proto = proto::MyRegexUdfNode {
pattern: udf.pattern.clone(),
};
proto.encode(buf).map_err(|e| {
DataFusionError::Internal(format!("failed to encode udf: {e:?}"))
})?;
Ok(())
}
}
#[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(ScalarValue::new_list(&[], &DataType::Boolean)),
ScalarValue::LargeList(ScalarValue::new_large_list(&[], &DataType::Boolean)),
ScalarValue::Date32(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::Date32(None),
ScalarValue::Date64(Some(0)),
ScalarValue::Date64(Some(i64::MAX)),
ScalarValue::Date64(None),
ScalarValue::Time32Second(Some(0)),
ScalarValue::Time32Second(Some(i32::MAX)),
ScalarValue::Time32Second(None),
ScalarValue::Time32Millisecond(Some(0)),
ScalarValue::Time32Millisecond(Some(i32::MAX)),
ScalarValue::Time32Millisecond(None),
ScalarValue::Time64Microsecond(Some(0)),
ScalarValue::Time64Microsecond(Some(i64::MAX)),
ScalarValue::Time64Microsecond(None),
ScalarValue::Time64Nanosecond(Some(0)),
ScalarValue::Time64Nanosecond(Some(i64::MAX)),
ScalarValue::Time64Nanosecond(None),
ScalarValue::TimestampNanosecond(Some(0), None),
ScalarValue::TimestampNanosecond(Some(i64::MAX), None),
ScalarValue::TimestampNanosecond(Some(0), Some("UTC".into())),
ScalarValue::TimestampNanosecond(None, None),
ScalarValue::TimestampMicrosecond(Some(0), None),
ScalarValue::TimestampMicrosecond(Some(i64::MAX), None),
ScalarValue::TimestampMicrosecond(Some(0), Some("UTC".into())),
ScalarValue::TimestampMicrosecond(None, None),
ScalarValue::TimestampMillisecond(Some(0), None),
ScalarValue::TimestampMillisecond(Some(i64::MAX), None),
ScalarValue::TimestampMillisecond(Some(0), Some("UTC".into())),
ScalarValue::TimestampMillisecond(None, None),
ScalarValue::TimestampSecond(Some(0), None),
ScalarValue::TimestampSecond(Some(i64::MAX), None),
ScalarValue::TimestampSecond(Some(0), Some("UTC".into())),
ScalarValue::TimestampSecond(None, None),
ScalarValue::IntervalDayTime(Some(IntervalDayTimeType::make_value(0, 0))),
ScalarValue::IntervalDayTime(Some(IntervalDayTimeType::make_value(1, 2))),
ScalarValue::IntervalDayTime(Some(IntervalDayTimeType::make_value(
i32::MAX,
i32::MAX,
))),
ScalarValue::IntervalDayTime(None),
ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNanoType::make_value(
0, 0, 0,