-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
sql.rs
5068 lines (4611 loc) · 180 KB
/
sql.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.
//! This module contains end to end tests of running SQL queries using
//! DataFusion
use std::convert::TryFrom;
use std::sync::Arc;
use chrono::prelude::*;
use chrono::Duration;
extern crate arrow;
extern crate datafusion;
use arrow::{
array::*, datatypes::*, record_batch::RecordBatch,
util::display::array_value_to_string,
};
use datafusion::assert_batches_eq;
use datafusion::assert_batches_sorted_eq;
use datafusion::logical_plan::LogicalPlan;
#[cfg(feature = "avro")]
use datafusion::physical_plan::avro::AvroReadOptions;
use datafusion::physical_plan::metrics::MetricValue;
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_plan::ExecutionPlanVisitor;
use datafusion::prelude::*;
use datafusion::{
datasource::{csv::CsvReadOptions, MemTable},
physical_plan::collect,
};
use datafusion::{
error::{DataFusionError, Result},
physical_plan::ColumnarValue,
};
use datafusion::{execution::context::ExecutionContext, physical_plan::displayable};
/// A macro to assert that one string is contained within another with
/// a nice error message if they are not.
///
/// Usage: `assert_contains!(actual, expected)`
///
/// Is a macro so test error
/// messages are on the same line as the failure;
///
/// Both arguments must be convertable into Strings (Into<String>)
macro_rules! assert_contains {
($ACTUAL: expr, $EXPECTED: expr) => {
let actual_value: String = $ACTUAL.into();
let expected_value: String = $EXPECTED.into();
assert!(
actual_value.contains(&expected_value),
"Can not find expected in actual.\n\nExpected:\n{}\n\nActual:\n{}",
expected_value,
actual_value
);
};
}
/// A macro to assert that one string is NOT contained within another with
/// a nice error message if they are are.
///
/// Usage: `assert_not_contains!(actual, unexpected)`
///
/// Is a macro so test error
/// messages are on the same line as the failure;
///
/// Both arguments must be convertable into Strings (Into<String>)
macro_rules! assert_not_contains {
($ACTUAL: expr, $UNEXPECTED: expr) => {
let actual_value: String = $ACTUAL.into();
let unexpected_value: String = $UNEXPECTED.into();
assert!(
!actual_value.contains(&unexpected_value),
"Found unexpected in actual.\n\nUnexpected:\n{}\n\nActual:\n{}",
unexpected_value,
actual_value
);
};
}
#[tokio::test]
async fn nyc() -> Result<()> {
// schema for nyxtaxi csv files
let schema = Schema::new(vec![
Field::new("VendorID", DataType::Utf8, true),
Field::new("tpep_pickup_datetime", DataType::Utf8, true),
Field::new("tpep_dropoff_datetime", DataType::Utf8, true),
Field::new("passenger_count", DataType::Utf8, true),
Field::new("trip_distance", DataType::Float64, true),
Field::new("RatecodeID", DataType::Utf8, true),
Field::new("store_and_fwd_flag", DataType::Utf8, true),
Field::new("PULocationID", DataType::Utf8, true),
Field::new("DOLocationID", DataType::Utf8, true),
Field::new("payment_type", DataType::Utf8, true),
Field::new("fare_amount", DataType::Float64, true),
Field::new("extra", DataType::Float64, true),
Field::new("mta_tax", DataType::Float64, true),
Field::new("tip_amount", DataType::Float64, true),
Field::new("tolls_amount", DataType::Float64, true),
Field::new("improvement_surcharge", DataType::Float64, true),
Field::new("total_amount", DataType::Float64, true),
]);
let mut ctx = ExecutionContext::new();
ctx.register_csv(
"tripdata",
"file.csv",
CsvReadOptions::new().schema(&schema),
)?;
let logical_plan = ctx.create_logical_plan(
"SELECT passenger_count, MIN(fare_amount), MAX(fare_amount) \
FROM tripdata GROUP BY passenger_count",
)?;
let optimized_plan = ctx.optimize(&logical_plan)?;
match &optimized_plan {
LogicalPlan::Projection { input, .. } => match input.as_ref() {
LogicalPlan::Aggregate { input, .. } => match input.as_ref() {
LogicalPlan::TableScan {
ref projected_schema,
..
} => {
assert_eq!(2, projected_schema.fields().len());
assert_eq!(projected_schema.field(0).name(), "passenger_count");
assert_eq!(projected_schema.field(1).name(), "fare_amount");
}
_ => unreachable!(),
},
_ => unreachable!(),
},
_ => unreachable!(false),
}
Ok(())
}
#[tokio::test]
async fn parquet_query() {
let mut ctx = ExecutionContext::new();
register_alltypes_parquet(&mut ctx);
// NOTE that string_col is actually a binary column and does not have the UTF8 logical type
// so we need an explicit cast
let sql = "SELECT id, CAST(string_col AS varchar) FROM alltypes_plain";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+-----------------------------------------+",
"| id | CAST(alltypes_plain.string_col AS Utf8) |",
"+----+-----------------------------------------+",
"| 4 | 0 |",
"| 5 | 1 |",
"| 6 | 0 |",
"| 7 | 1 |",
"| 2 | 0 |",
"| 3 | 1 |",
"| 0 | 0 |",
"| 1 | 1 |",
"+----+-----------------------------------------+",
];
assert_batches_eq!(expected, &actual);
}
#[tokio::test]
async fn parquet_single_nan_schema() {
let mut ctx = ExecutionContext::new();
let testdata = datafusion::test_util::parquet_test_data();
ctx.register_parquet("single_nan", &format!("{}/single_nan.parquet", testdata))
.unwrap();
let sql = "SELECT mycol FROM single_nan";
let plan = ctx.create_logical_plan(sql).unwrap();
let plan = ctx.optimize(&plan).unwrap();
let plan = ctx.create_physical_plan(&plan).await.unwrap();
let results = collect(plan).await.unwrap();
for batch in results {
assert_eq!(1, batch.num_rows());
assert_eq!(1, batch.num_columns());
}
}
#[tokio::test]
#[ignore = "Test ignored, will be enabled as part of the nested Parquet reader"]
async fn parquet_list_columns() {
let mut ctx = ExecutionContext::new();
let testdata = datafusion::test_util::parquet_test_data();
ctx.register_parquet(
"list_columns",
&format!("{}/list_columns.parquet", testdata),
)
.unwrap();
let schema = Arc::new(Schema::new(vec![
Field::new(
"int64_list",
DataType::List(Box::new(Field::new("item", DataType::Int64, true))),
true,
),
Field::new(
"utf8_list",
DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
true,
),
]));
let sql = "SELECT int64_list, utf8_list FROM list_columns";
let plan = ctx.create_logical_plan(sql).unwrap();
let plan = ctx.optimize(&plan).unwrap();
let plan = ctx.create_physical_plan(&plan).await.unwrap();
let results = collect(plan).await.unwrap();
// int64_list utf8_list
// 0 [1, 2, 3] [abc, efg, hij]
// 1 [None, 1] None
// 2 [4] [efg, None, hij, xyz]
assert_eq!(1, results.len());
let batch = &results[0];
assert_eq!(3, batch.num_rows());
assert_eq!(2, batch.num_columns());
assert_eq!(schema, batch.schema());
let int_list_array = batch
.column(0)
.as_any()
.downcast_ref::<ListArray>()
.unwrap();
let utf8_list_array = batch
.column(1)
.as_any()
.downcast_ref::<ListArray>()
.unwrap();
assert_eq!(
int_list_array
.value(0)
.as_any()
.downcast_ref::<PrimitiveArray<Int64Type>>()
.unwrap(),
&PrimitiveArray::<Int64Type>::from(vec![Some(1), Some(2), Some(3),])
);
assert_eq!(
utf8_list_array
.value(0)
.as_any()
.downcast_ref::<StringArray>()
.unwrap(),
&StringArray::try_from(vec![Some("abc"), Some("efg"), Some("hij"),]).unwrap()
);
assert_eq!(
int_list_array
.value(1)
.as_any()
.downcast_ref::<PrimitiveArray<Int64Type>>()
.unwrap(),
&PrimitiveArray::<Int64Type>::from(vec![None, Some(1),])
);
assert!(utf8_list_array.is_null(1));
assert_eq!(
int_list_array
.value(2)
.as_any()
.downcast_ref::<PrimitiveArray<Int64Type>>()
.unwrap(),
&PrimitiveArray::<Int64Type>::from(vec![Some(4),])
);
let result = utf8_list_array.value(2);
let result = result.as_any().downcast_ref::<StringArray>().unwrap();
assert_eq!(result.value(0), "efg");
assert!(result.is_null(1));
assert_eq!(result.value(2), "hij");
assert_eq!(result.value(3), "xyz");
}
#[tokio::test]
async fn csv_select_nested() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT o1, o2, c3
FROM (
SELECT c1 AS o1, c2 + 1 AS o2, c3
FROM (
SELECT c1, c2, c3, c4
FROM aggregate_test_100
WHERE c1 = 'a' AND c2 >= 4
ORDER BY c2 ASC, c3 ASC
)
)";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+----+------+",
"| o1 | o2 | c3 |",
"+----+----+------+",
"| a | 5 | -101 |",
"| a | 5 | -54 |",
"| a | 5 | -38 |",
"| a | 5 | 65 |",
"| a | 6 | -101 |",
"| a | 6 | -31 |",
"| a | 6 | 36 |",
"+----+----+------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_count_star() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(*), COUNT(1) AS c, COUNT(c1) FROM aggregate_test_100";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----------------+-----+------------------------------+",
"| COUNT(UInt8(1)) | c | COUNT(aggregate_test_100.c1) |",
"+-----------------+-----+------------------------------+",
"| 100 | 100 | 100 |",
"+-----------------+-----+------------------------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_with_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, c12 FROM aggregate_test_100 WHERE c12 > 0.376 AND c12 < 0.4";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+---------------------+",
"| c1 | c12 |",
"+----+---------------------+",
"| e | 0.39144436569161134 |",
"| d | 0.38870280983958583 |",
"+----+---------------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_with_negative_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, c4 FROM aggregate_test_100 WHERE c3 < -55 AND -c4 > 30000";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+--------+",
"| c1 | c4 |",
"+----+--------+",
"| e | -31500 |",
"| c | -30187 |",
"+----+--------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_with_negated_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE NOT(c1 != 'a')";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----------------+",
"| COUNT(UInt8(1)) |",
"+-----------------+",
"| 21 |",
"+-----------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_with_is_not_null_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE c1 IS NOT NULL";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----------------+",
"| COUNT(UInt8(1)) |",
"+-----------------+",
"| 100 |",
"+-----------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_with_is_null_predicate() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT COUNT(1) FROM aggregate_test_100 WHERE c1 IS NULL";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----------------+",
"| COUNT(UInt8(1)) |",
"+-----------------+",
"| 0 |",
"+-----------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_int_min_max() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c2, MIN(c12), MAX(c12) FROM aggregate_test_100 GROUP BY c2";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+-----------------------------+-----------------------------+",
"| c2 | MIN(aggregate_test_100.c12) | MAX(aggregate_test_100.c12) |",
"+----+-----------------------------+-----------------------------+",
"| 1 | 0.05636955101974106 | 0.9965400387585364 |",
"| 2 | 0.16301110515739792 | 0.991517828651004 |",
"| 3 | 0.047343434291126085 | 0.9293883502480845 |",
"| 4 | 0.02182578039211991 | 0.9237877978193884 |",
"| 5 | 0.01479305307777301 | 0.9723580396501548 |",
"+----+-----------------------------+-----------------------------+",
];
assert_batches_sorted_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_float32() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx)?;
let sql =
"SELECT COUNT(*) as cnt, c1 FROM aggregate_simple GROUP BY c1 ORDER BY cnt DESC";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----+---------+",
"| cnt | c1 |",
"+-----+---------+",
"| 5 | 0.00005 |",
"| 4 | 0.00004 |",
"| 3 | 0.00003 |",
"| 2 | 0.00002 |",
"| 1 | 0.00001 |",
"+-----+---------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn select_all() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx)?;
let sql = "SELECT c1 FROM aggregate_simple order by c1";
let actual_no_all = execute(&mut ctx, sql).await;
let sql_all = "SELECT ALL c1 FROM aggregate_simple order by c1";
let actual_all = execute(&mut ctx, sql_all).await;
assert_eq!(actual_no_all, actual_all);
Ok(())
}
#[tokio::test]
async fn select_distinct() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx)?;
let sql = "SELECT DISTINCT * FROM aggregate_simple";
let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let mut dedup = actual.clone();
dedup.dedup();
assert_eq!(actual, dedup);
Ok(())
}
#[tokio::test]
async fn select_distinct_simple_1() {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx).unwrap();
let sql = "SELECT DISTINCT c1 FROM aggregate_simple order by c1";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+---------+",
"| c1 |",
"+---------+",
"| 0.00001 |",
"| 0.00002 |",
"| 0.00003 |",
"| 0.00004 |",
"| 0.00005 |",
"+---------+",
];
assert_batches_eq!(expected, &actual);
}
#[tokio::test]
async fn select_distinct_simple_2() {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx).unwrap();
let sql = "SELECT DISTINCT c1, c2 FROM aggregate_simple order by c1";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+---------+----------------+",
"| c1 | c2 |",
"+---------+----------------+",
"| 0.00001 | 0.000000000001 |",
"| 0.00002 | 0.000000000002 |",
"| 0.00003 | 0.000000000003 |",
"| 0.00004 | 0.000000000004 |",
"| 0.00005 | 0.000000000005 |",
"+---------+----------------+",
];
assert_batches_eq!(expected, &actual);
}
#[tokio::test]
async fn select_distinct_simple_3() {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx).unwrap();
let sql = "SELECT distinct c3 FROM aggregate_simple order by c3";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-------+",
"| c3 |",
"+-------+",
"| false |",
"| true |",
"+-------+",
];
assert_batches_eq!(expected, &actual);
}
#[tokio::test]
async fn select_distinct_simple_4() {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx).unwrap();
let sql = "SELECT distinct c1+c2 as a FROM aggregate_simple";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-------------------------+",
"| a |",
"+-------------------------+",
"| 0.000030000002242136256 |",
"| 0.000040000002989515004 |",
"| 0.000010000000747378751 |",
"| 0.00005000000373689376 |",
"| 0.000020000001494757502 |",
"+-------------------------+",
];
assert_batches_sorted_eq!(expected, &actual);
}
#[tokio::test]
async fn projection_same_fields() -> Result<()> {
let mut ctx = ExecutionContext::new();
let sql = "select (1+1) as a from (select 1 as a);";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec!["+---+", "| a |", "+---+", "| 2 |", "+---+"];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_float64() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx)?;
let sql =
"SELECT COUNT(*) as cnt, c2 FROM aggregate_simple GROUP BY c2 ORDER BY cnt DESC";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----+----------------+",
"| cnt | c2 |",
"+-----+----------------+",
"| 5 | 0.000000000005 |",
"| 4 | 0.000000000004 |",
"| 3 | 0.000000000003 |",
"| 2 | 0.000000000002 |",
"| 1 | 0.000000000001 |",
"+-----+----------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_boolean() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_simple_csv(&mut ctx)?;
let sql =
"SELECT COUNT(*) as cnt, c3 FROM aggregate_simple GROUP BY c3 ORDER BY cnt DESC";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----+-------+",
"| cnt | c3 |",
"+-----+-------+",
"| 9 | true |",
"| 6 | false |",
"+-----+-------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_two_columns() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, c2, MIN(c3) FROM aggregate_test_100 GROUP BY c1, c2";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+----+----------------------------+",
"| c1 | c2 | MIN(aggregate_test_100.c3) |",
"+----+----+----------------------------+",
"| a | 1 | -85 |",
"| a | 2 | -48 |",
"| a | 3 | -72 |",
"| a | 4 | -101 |",
"| a | 5 | -101 |",
"| b | 1 | 12 |",
"| b | 2 | -60 |",
"| b | 3 | -101 |",
"| b | 4 | -117 |",
"| b | 5 | -82 |",
"| c | 1 | -24 |",
"| c | 2 | -117 |",
"| c | 3 | -2 |",
"| c | 4 | -90 |",
"| c | 5 | -94 |",
"| d | 1 | -99 |",
"| d | 2 | 93 |",
"| d | 3 | -76 |",
"| d | 4 | 5 |",
"| d | 5 | -59 |",
"| e | 1 | 36 |",
"| e | 2 | -61 |",
"| e | 3 | -95 |",
"| e | 4 | -56 |",
"| e | 5 | -86 |",
"+----+----+----------------------------+",
];
assert_batches_sorted_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_and_having() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, MIN(c3) AS m FROM aggregate_test_100 GROUP BY c1 HAVING m < -100 AND MAX(c3) > 70";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+------+",
"| c1 | m |",
"+----+------+",
"| a | -101 |",
"| c | -117 |",
"+----+------+",
];
assert_batches_sorted_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_and_having_and_where() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, MIN(c3) AS m
FROM aggregate_test_100
WHERE c1 IN ('a', 'b')
GROUP BY c1
HAVING m < -100 AND MAX(c3) > 70";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+------+",
"| c1 | m |",
"+----+------+",
"| a | -101 |",
"+----+------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn all_where_empty() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT *
FROM aggregate_test_100
WHERE 1=2";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec!["++", "++"];
assert_batches_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_having_without_group_by() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, c2, c3 FROM aggregate_test_100 HAVING c2 >= 4 AND c3 > 90";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+----+-----+",
"| c1 | c2 | c3 |",
"+----+----+-----+",
"| c | 4 | 123 |",
"| c | 5 | 118 |",
"| d | 4 | 102 |",
"| e | 4 | 96 |",
"| e | 4 | 97 |",
"+----+----+-----+",
];
assert_batches_sorted_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_avg_sqrt() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(custom_sqrt(c12)) FROM aggregate_test_100";
let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = vec![vec!["0.6706002946036462"]];
assert_float_eq(&expected, &actual);
Ok(())
}
/// test that casting happens on udfs.
/// c11 is f32, but `custom_sqrt` requires f64. Casting happens but the logical plan and
/// physical plan have the same schema.
#[tokio::test]
async fn csv_query_custom_udf_with_cast() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(custom_sqrt(c11)) FROM aggregate_test_100";
let actual = execute(&mut ctx, sql).await;
let expected = vec![vec!["0.6584408483418833"]];
assert_float_eq(&expected, &actual);
Ok(())
}
/// sqrt(f32) is slightly different than sqrt(CAST(f32 AS double)))
#[tokio::test]
async fn sqrt_f32_vs_f64() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
// sqrt(f32)'s plan passes
let sql = "SELECT avg(sqrt(c11)) FROM aggregate_test_100";
let actual = execute(&mut ctx, sql).await;
let expected = vec![vec!["0.6584407806396484"]];
assert_eq!(actual, expected);
let sql = "SELECT avg(sqrt(CAST(c11 AS double))) FROM aggregate_test_100";
let actual = execute(&mut ctx, sql).await;
let expected = vec![vec!["0.6584408483418833"]];
assert_float_eq(&expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_error() -> Result<()> {
// sin(utf8) should error
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT sin(c1) FROM aggregate_test_100";
let plan = ctx.create_logical_plan(sql);
assert!(plan.is_err());
Ok(())
}
// this query used to deadlock due to the call udf(udf())
#[tokio::test]
async fn csv_query_sqrt_sqrt() -> Result<()> {
let mut ctx = create_ctx()?;
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT sqrt(sqrt(c12)) FROM aggregate_test_100 LIMIT 1";
let actual = execute(&mut ctx, sql).await;
// sqrt(sqrt(c12=0.9294097332465232)) = 0.9818650561397431
let expected = vec![vec!["0.9818650561397431"]];
assert_float_eq(&expected, &actual);
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn create_ctx() -> Result<ExecutionContext> {
let mut ctx = ExecutionContext::new();
// register a custom UDF
ctx.register_udf(create_udf(
"custom_sqrt",
vec![DataType::Float64],
Arc::new(DataType::Float64),
Arc::new(custom_sqrt),
));
Ok(ctx)
}
fn custom_sqrt(args: &[ColumnarValue]) -> Result<ColumnarValue> {
let arg = &args[0];
if let ColumnarValue::Array(v) = arg {
let input = v
.as_any()
.downcast_ref::<Float64Array>()
.expect("cast failed");
let array: Float64Array = input.iter().map(|v| v.map(|x| x.sqrt())).collect();
Ok(ColumnarValue::Array(Arc::new(array)))
} else {
unimplemented!()
}
}
#[tokio::test]
async fn csv_query_avg() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(c12) FROM aggregate_test_100";
let mut actual = execute(&mut ctx, sql).await;
actual.sort();
let expected = vec![vec!["0.5089725099127211"]];
assert_float_eq(&expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_avg() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c1, avg(c12) FROM aggregate_test_100 GROUP BY c1";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+----+-----------------------------+",
"| c1 | AVG(aggregate_test_100.c12) |",
"+----+-----------------------------+",
"| a | 0.48754517466109415 |",
"| b | 0.41040709263815384 |",
"| c | 0.6600456536439784 |",
"| d | 0.48855379387549824 |",
"| e | 0.48600669271341534 |",
"+----+-----------------------------+",
];
assert_batches_sorted_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_group_by_avg_with_projection() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(c12), c1 FROM aggregate_test_100 GROUP BY c1";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----------------------------+----+",
"| AVG(aggregate_test_100.c12) | c1 |",
"+-----------------------------+----+",
"| 0.41040709263815384 | b |",
"| 0.48600669271341534 | e |",
"| 0.48754517466109415 | a |",
"| 0.48855379387549824 | d |",
"| 0.6600456536439784 | c |",
"+-----------------------------+----+",
];
assert_batches_sorted_eq!(expected, &actual);
Ok(())
}
#[tokio::test]
async fn csv_query_avg_multi_batch() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT avg(c12) FROM aggregate_test_100";
let plan = ctx.create_logical_plan(sql).unwrap();
let plan = ctx.optimize(&plan).unwrap();
let plan = ctx.create_physical_plan(&plan).await.unwrap();
let results = collect(plan).await.unwrap();
let batch = &results[0];
let column = batch.column(0);
let array = column.as_any().downcast_ref::<Float64Array>().unwrap();
let actual = array.value(0);
let expected = 0.5089725;
// Due to float number's accuracy, different batch size will lead to different
// answers.
assert!((expected - actual).abs() < 0.01);
Ok(())
}
#[tokio::test]
async fn csv_query_nullif_divide_by_0() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT c8/nullif(c7, 0) FROM aggregate_test_100";
let actual = execute(&mut ctx, sql).await;
let actual = &actual[80..90]; // We just want to compare rows 80-89
let expected = vec![
vec!["258"],
vec!["664"],
vec!["NULL"],
vec!["22"],
vec!["164"],
vec!["448"],
vec!["365"],
vec!["1640"],
vec!["671"],
vec!["203"],
];
assert_eq!(expected, actual);
Ok(())
}
#[tokio::test]
async fn csv_query_count() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "SELECT count(c12) FROM aggregate_test_100";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-------------------------------+",
"| COUNT(aggregate_test_100.c12) |",
"+-------------------------------+",
"| 100 |",
"+-------------------------------+",
];
assert_batches_eq!(expected, &actual);
Ok(())
}
/// for window functions without order by the first, last, and nth function call does not make sense
#[tokio::test]
async fn csv_query_window_with_empty_over() -> Result<()> {
let mut ctx = ExecutionContext::new();
register_aggregate_csv(&mut ctx)?;
let sql = "select \
c9, \
count(c5) over (), \
max(c5) over (), \
min(c5) over () \
from aggregate_test_100 \
order by c9 \
limit 5";
let actual = execute_to_batches(&mut ctx, sql).await;
let expected = vec![
"+-----------+------------------------------+----------------------------+----------------------------+",
"| c9 | COUNT(aggregate_test_100.c5) | MAX(aggregate_test_100.c5) | MIN(aggregate_test_100.c5) |",