-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathsql_integration.rs
4579 lines (4069 loc) Β· 170 KB
/
sql_integration.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;
#[cfg(test)]
use std::collections::HashMap;
use std::{sync::Arc, vec};
use arrow_schema::TimeUnit::Nanosecond;
use arrow_schema::*;
use datafusion_sql::planner::PlannerContext;
use datafusion_sql::unparser::{expr_to_sql, plan_to_sql};
use sqlparser::dialect::{Dialect, GenericDialect, HiveDialect, MySqlDialect};
use datafusion_common::{
config::ConfigOptions, DataFusionError, Result, ScalarValue, TableReference,
};
use datafusion_common::{plan_err, DFSchema, ParamValues};
use datafusion_expr::{
logical_plan::{LogicalPlan, Prepare},
AggregateUDF, ColumnarValue, ScalarUDF, ScalarUDFImpl, Signature, TableSource,
Volatility, WindowUDF,
};
use datafusion_sql::{
parser::DFParser,
planner::{ContextProvider, ParserOptions, SqlToRel},
};
use rstest::rstest;
use sqlparser::parser::Parser;
#[test]
fn parse_decimals() {
let test_data = [
("1", "Int64(1)"),
("001", "Int64(1)"),
("0.1", "Decimal128(Some(1),1,1)"),
("0.01", "Decimal128(Some(1),2,2)"),
("1.0", "Decimal128(Some(10),2,1)"),
("10.01", "Decimal128(Some(1001),4,2)"),
(
"10000000000000000000.00",
"Decimal128(Some(1000000000000000000000),22,2)",
),
("18446744073709551615", "UInt64(18446744073709551615)"),
(
"18446744073709551616",
"Decimal128(Some(18446744073709551616),20,0)",
),
];
for (a, b) in test_data {
let sql = format!("SELECT {a}");
let expected = format!("Projection: {b}\n EmptyRelation");
quick_test_with_options(
&sql,
&expected,
ParserOptions {
parse_float_as_decimal: true,
enable_ident_normalization: false,
},
);
}
}
#[test]
fn parse_ident_normalization() {
let test_data = [
(
"SELECT LENGTH('str')",
"Ok(Projection: character_length(Utf8(\"str\"))\n EmptyRelation)",
false,
),
(
"SELECT CONCAT('Hello', 'World')",
"Ok(Projection: concat(Utf8(\"Hello\"), Utf8(\"World\"))\n EmptyRelation)",
false,
),
(
"SELECT age FROM person",
"Ok(Projection: person.age\n TableScan: person)",
true,
),
(
"SELECT AGE FROM PERSON",
"Ok(Projection: person.age\n TableScan: person)",
true,
),
(
"SELECT AGE FROM PERSON",
"Error during planning: No table named: PERSON found",
false,
),
(
"SELECT Id FROM UPPERCASE_test",
"Ok(Projection: UPPERCASE_test.Id\
\n TableScan: UPPERCASE_test)",
false,
),
(
"SELECT \"Id\", lower FROM \"UPPERCASE_test\"",
"Ok(Projection: UPPERCASE_test.Id, UPPERCASE_test.lower\
\n TableScan: UPPERCASE_test)",
true,
),
];
for (sql, expected, enable_ident_normalization) in test_data {
let plan = logical_plan_with_options(
sql,
ParserOptions {
parse_float_as_decimal: false,
enable_ident_normalization,
},
);
if plan.is_ok() {
assert_eq!(expected, format!("{plan:?}"));
} else {
assert_eq!(expected, plan.unwrap_err().strip_backtrace());
}
}
}
#[test]
fn select_no_relation() {
quick_test(
"SELECT 1",
"Projection: Int64(1)\
\n EmptyRelation",
);
}
#[test]
fn test_real_f32() {
quick_test(
"SELECT CAST(1.1 AS REAL)",
"Projection: CAST(Float64(1.1) AS Float32)\
\n EmptyRelation",
);
}
#[test]
fn test_int_decimal_default() {
quick_test(
"SELECT CAST(10 AS DECIMAL)",
"Projection: CAST(Int64(10) AS Decimal128(38, 10))\
\n EmptyRelation",
);
}
#[test]
fn test_int_decimal_no_scale() {
quick_test(
"SELECT CAST(10 AS DECIMAL(5))",
"Projection: CAST(Int64(10) AS Decimal128(5, 0))\
\n EmptyRelation",
);
}
#[test]
fn test_tinyint() {
quick_test(
"SELECT CAST(6 AS TINYINT)",
"Projection: CAST(Int64(6) AS Int8)\
\n EmptyRelation",
);
}
#[test]
fn cast_from_subquery() {
quick_test(
"SELECT CAST (a AS FLOAT) FROM (SELECT 1 AS a)",
"Projection: CAST(a AS Float32)\
\n Projection: Int64(1) AS a\
\n EmptyRelation",
);
}
#[test]
fn try_cast_from_aggregation() {
quick_test(
"SELECT TRY_CAST(SUM(age) AS FLOAT) FROM person",
"Projection: TRY_CAST(SUM(person.age) AS Float32)\
\n Aggregate: groupBy=[[]], aggr=[[SUM(person.age)]]\
\n TableScan: person",
);
}
#[test]
fn cast_to_invalid_decimal_type_precision_0() {
// precision == 0
{
let sql = "SELECT CAST(10 AS DECIMAL(0))";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Decimal(precision = 0, scale = 0) should satisfy `0 < precision <= 76`, and `scale <= precision`.",
err.strip_backtrace()
);
}
}
#[test]
fn cast_to_invalid_decimal_type_precision_gt_38() {
// precision > 38
{
let sql = "SELECT CAST(10 AS DECIMAL(39))";
let plan = "Projection: CAST(Int64(10) AS Decimal256(39, 0))\n EmptyRelation";
quick_test(sql, plan);
}
}
#[test]
fn cast_to_invalid_decimal_type_precision_gt_76() {
// precision > 76
{
let sql = "SELECT CAST(10 AS DECIMAL(79))";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Decimal(precision = 79, scale = 0) should satisfy `0 < precision <= 76`, and `scale <= precision`.",
err.strip_backtrace()
);
}
}
#[test]
fn cast_to_invalid_decimal_type_precision_lt_scale() {
// precision < scale
{
let sql = "SELECT CAST(10 AS DECIMAL(5, 10))";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Decimal(precision = 5, scale = 10) should satisfy `0 < precision <= 76`, and `scale <= precision`.",
err.strip_backtrace()
);
}
}
#[test]
fn plan_create_table_with_pk() {
let sql = "create table person (id int, name string, primary key(id))";
let plan = r#"
CreateMemoryTable: Bare { table: "person" } constraints=[PrimaryKey([0])]
EmptyRelation
"#
.trim();
quick_test(sql, plan);
let sql = "create table person (id int primary key, name string)";
let plan = r#"
CreateMemoryTable: Bare { table: "person" } constraints=[PrimaryKey([0])]
EmptyRelation
"#
.trim();
quick_test(sql, plan);
let sql =
"create table person (id int, name string unique not null, primary key(id))";
let plan = r#"
CreateMemoryTable: Bare { table: "person" } constraints=[PrimaryKey([0]), Unique([1])]
EmptyRelation
"#
.trim();
quick_test(sql, plan);
let sql = "create table person (id int, name varchar, primary key(name, id));";
let plan = r#"
CreateMemoryTable: Bare { table: "person" } constraints=[PrimaryKey([1, 0])]
EmptyRelation
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn plan_create_table_with_multi_pk() {
let sql = "create table person (id int, name string primary key, primary key(id))";
let plan = r#"
CreateMemoryTable: Bare { table: "person" } constraints=[PrimaryKey([0]), PrimaryKey([1])]
EmptyRelation
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn plan_create_table_with_unique() {
let sql = "create table person (id int unique, name string)";
let plan = "CreateMemoryTable: Bare { table: \"person\" } constraints=[Unique([0])]\n EmptyRelation";
quick_test(sql, plan);
}
#[test]
fn plan_create_table_no_pk() {
let sql = "create table person (id int, name string)";
let plan = r#"
CreateMemoryTable: Bare { table: "person" }
EmptyRelation
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn plan_create_table_check_constraint() {
let sql = "create table person (id int, name string, unique(id))";
let plan = "CreateMemoryTable: Bare { table: \"person\" } constraints=[Unique([0])]\n EmptyRelation";
quick_test(sql, plan);
}
#[test]
fn plan_start_transaction() {
let sql = "start transaction";
let plan = "TransactionStart: ReadWrite Serializable";
quick_test(sql, plan);
}
#[test]
fn plan_start_transaction_isolation() {
let sql = "start transaction isolation level read committed";
let plan = "TransactionStart: ReadWrite ReadCommitted";
quick_test(sql, plan);
}
#[test]
fn plan_start_transaction_read_only() {
let sql = "start transaction read only";
let plan = "TransactionStart: ReadOnly Serializable";
quick_test(sql, plan);
}
#[test]
fn plan_start_transaction_fully_qualified() {
let sql = "start transaction isolation level read committed read only";
let plan = "TransactionStart: ReadOnly ReadCommitted";
quick_test(sql, plan);
}
#[test]
fn plan_start_transaction_overly_qualified() {
let sql = r#"start transaction
isolation level read committed
read only
isolation level repeatable read
"#;
let plan = "TransactionStart: ReadOnly RepeatableRead";
quick_test(sql, plan);
}
#[test]
fn plan_commit_transaction() {
let sql = "commit transaction";
let plan = "TransactionEnd: Commit chain:=false";
quick_test(sql, plan);
}
#[test]
fn plan_commit_transaction_chained() {
let sql = "commit transaction and chain";
let plan = "TransactionEnd: Commit chain:=true";
quick_test(sql, plan);
}
#[test]
fn plan_rollback_transaction() {
let sql = "rollback transaction";
let plan = "TransactionEnd: Rollback chain:=false";
quick_test(sql, plan);
}
#[test]
fn plan_rollback_transaction_chained() {
let sql = "rollback transaction and chain";
let plan = "TransactionEnd: Rollback chain:=true";
quick_test(sql, plan);
}
#[test]
fn plan_copy_to() {
let sql = "COPY test_decimal to 'output.csv'";
let plan = r#"
CopyTo: format=csv output_url=output.csv options: ()
TableScan: test_decimal
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn plan_explain_copy_to() {
let sql = "EXPLAIN COPY test_decimal to 'output.csv'";
let plan = r#"
Explain
CopyTo: format=csv output_url=output.csv options: ()
TableScan: test_decimal
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn plan_copy_to_query() {
let sql = "COPY (select * from test_decimal limit 10) to 'output.csv'";
let plan = r#"
CopyTo: format=csv output_url=output.csv options: ()
Limit: skip=0, fetch=10
Projection: test_decimal.id, test_decimal.price
TableScan: test_decimal
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn plan_insert() {
let sql =
"insert into person (id, first_name, last_name) values (1, 'Alan', 'Turing')";
let plan = "Dml: op=[Insert Into] table=[person]\
\n Projection: CAST(column1 AS UInt32) AS id, column2 AS first_name, column3 AS last_name, \
CAST(NULL AS Int32) AS age, CAST(NULL AS Utf8) AS state, CAST(NULL AS Float64) AS salary, \
CAST(NULL AS Timestamp(Nanosecond, None)) AS birth_date, CAST(NULL AS Int32) AS π\
\n Values: (Int64(1), Utf8(\"Alan\"), Utf8(\"Turing\"))";
quick_test(sql, plan);
}
#[test]
fn plan_insert_no_target_columns() {
let sql = "INSERT INTO test_decimal VALUES (1, 2), (3, 4)";
let plan = r#"
Dml: op=[Insert Into] table=[test_decimal]
Projection: CAST(column1 AS Int32) AS id, CAST(column2 AS Decimal128(10, 2)) AS price
Values: (Int64(1), Int64(2)), (Int64(3), Int64(4))
"#
.trim();
quick_test(sql, plan);
}
#[rstest]
#[case::duplicate_columns(
"INSERT INTO test_decimal (id, price, price) VALUES (1, 2, 3), (4, 5, 6)",
"Schema error: Schema contains duplicate unqualified field name price"
)]
#[case::non_existing_column(
"INSERT INTO test_decimal (nonexistent, price) VALUES (1, 2), (4, 5)",
"Schema error: No field named nonexistent. Valid fields are id, price."
)]
#[case::target_column_count_mismatch(
"INSERT INTO person (id, first_name, last_name) VALUES ($1, $2)",
"Error during planning: Column count doesn't match insert query!"
)]
#[case::source_column_count_mismatch(
"INSERT INTO person VALUES ($1, $2)",
"Error during planning: Column count doesn't match insert query!"
)]
#[case::extra_placeholder(
"INSERT INTO person (id, first_name, last_name) VALUES ($1, $2, $3, $4)",
"Error during planning: Placeholder $4 refers to a non existent column"
)]
#[case::placeholder_type_unresolved(
"INSERT INTO person (id, first_name, last_name) VALUES ($2, $4, $6)",
"Error during planning: Placeholder type could not be resolved. Make sure that the placeholder is bound to a concrete type, e.g. by providing parameter values."
)]
#[case::placeholder_type_unresolved(
"INSERT INTO person (id, first_name, last_name) VALUES ($id, $first_name, $last_name)",
"Error during planning: Can't parse placeholder: $id"
)]
#[test]
fn test_insert_schema_errors(#[case] sql: &str, #[case] error: &str) {
let err = logical_plan(sql).unwrap_err();
assert_eq!(err.strip_backtrace(), error)
}
#[test]
fn plan_update() {
let sql = "update person set last_name='Kay' where id=1";
let plan = r#"
Dml: op=[Update] table=[person]
Projection: person.id AS id, person.first_name AS first_name, Utf8("Kay") AS last_name, person.age AS age, person.state AS state, person.salary AS salary, person.birth_date AS birth_date, person.π AS π
Filter: person.id = Int64(1)
TableScan: person
"#
.trim();
quick_test(sql, plan);
}
#[rstest]
#[case::missing_assignement_target("UPDATE person SET doesnotexist = true")]
#[case::missing_assignement_expression("UPDATE person SET age = doesnotexist + 42")]
#[case::missing_selection_expression(
"UPDATE person SET age = 42 WHERE doesnotexist = true"
)]
#[test]
fn update_column_does_not_exist(#[case] sql: &str) {
let err = logical_plan(sql).expect_err("query should have failed");
assert_field_not_found(err, "doesnotexist");
}
#[test]
fn plan_delete() {
let sql = "delete from person where id=1";
let plan = r#"
Dml: op=[Delete] table=[person]
Filter: id = Int64(1)
TableScan: person
"#
.trim();
quick_test(sql, plan);
}
#[test]
fn select_column_does_not_exist() {
let sql = "SELECT doesnotexist FROM person";
let err = logical_plan(sql).expect_err("query should have failed");
assert_field_not_found(err, "doesnotexist");
}
#[test]
fn select_repeated_column() {
let sql = "SELECT age, age FROM person";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Projections require unique expression names but the expression \"person.age\" at position 0 and \"person.age\" at position 1 have the same name. Consider aliasing (\"AS\") one of them.",
err.strip_backtrace()
);
}
#[test]
fn select_wildcard_with_repeated_column() {
let sql = "SELECT *, age FROM person";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Projections require unique expression names but the expression \"person.age\" at position 3 and \"person.age\" at position 8 have the same name. Consider aliasing (\"AS\") one of them.",
err.strip_backtrace()
);
}
#[test]
fn select_wildcard_with_repeated_column_but_is_aliased() {
quick_test(
"SELECT *, first_name AS fn from person",
"Projection: person.id, person.first_name, person.last_name, person.age, person.state, person.salary, person.birth_date, person.π, person.first_name AS fn\
\n TableScan: person",
);
}
#[test]
fn select_scalar_func_with_literal_no_relation() {
quick_test(
"SELECT sqrt(9)",
"Projection: sqrt(Int64(9))\
\n EmptyRelation",
);
}
#[test]
fn select_simple_filter() {
let sql = "SELECT id, first_name, last_name \
FROM person WHERE state = 'CO'";
let expected = "Projection: person.id, person.first_name, person.last_name\
\n Filter: person.state = Utf8(\"CO\")\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_filter_column_does_not_exist() {
let sql = "SELECT first_name FROM person WHERE doesnotexist = 'A'";
let err = logical_plan(sql).expect_err("query should have failed");
assert_field_not_found(err, "doesnotexist");
}
#[test]
fn select_filter_cannot_use_alias() {
let sql = "SELECT first_name AS x FROM person WHERE x = 'A'";
let err = logical_plan(sql).expect_err("query should have failed");
assert_field_not_found(err, "x");
}
#[test]
fn select_neg_filter() {
let sql = "SELECT id, first_name, last_name \
FROM person WHERE NOT state";
let expected = "Projection: person.id, person.first_name, person.last_name\
\n Filter: NOT person.state\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_compound_filter() {
let sql = "SELECT id, first_name, last_name \
FROM person WHERE state = 'CO' AND age >= 21 AND age <= 65";
let expected = "Projection: person.id, person.first_name, person.last_name\
\n Filter: person.state = Utf8(\"CO\") AND person.age >= Int64(21) AND person.age <= Int64(65)\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn test_timestamp_filter() {
let sql = "SELECT state FROM person WHERE birth_date < CAST (158412331400600000 as timestamp)";
let expected = "Projection: person.state\
\n Filter: person.birth_date < CAST(CAST(Int64(158412331400600000) AS Timestamp(Second, None)) AS Timestamp(Nanosecond, None))\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn test_date_filter() {
let sql = "SELECT state FROM person WHERE birth_date < CAST ('2020-01-01' as date)";
let expected = "Projection: person.state\
\n Filter: person.birth_date < CAST(Utf8(\"2020-01-01\") AS Date32)\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_all_boolean_operators() {
let sql = "SELECT age, first_name, last_name \
FROM person \
WHERE age = 21 \
AND age != 21 \
AND age > 21 \
AND age >= 21 \
AND age < 65 \
AND age <= 65";
let expected = "Projection: person.age, person.first_name, person.last_name\
\n Filter: person.age = Int64(21) \
AND person.age != Int64(21) \
AND person.age > Int64(21) \
AND person.age >= Int64(21) \
AND person.age < Int64(65) \
AND person.age <= Int64(65)\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_between() {
let sql = "SELECT state FROM person WHERE age BETWEEN 21 AND 65";
let expected = "Projection: person.state\
\n Filter: person.age BETWEEN Int64(21) AND Int64(65)\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_between_negated() {
let sql = "SELECT state FROM person WHERE age NOT BETWEEN 21 AND 65";
let expected = "Projection: person.state\
\n Filter: person.age NOT BETWEEN Int64(21) AND Int64(65)\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_nested() {
let sql = "SELECT fn2, last_name
FROM (
SELECT fn1 as fn2, last_name, birth_date
FROM (
SELECT first_name AS fn1, last_name, birth_date, age
FROM person
) AS a
) AS b";
let expected = "Projection: b.fn2, b.last_name\
\n SubqueryAlias: b\
\n Projection: a.fn1 AS fn2, a.last_name, a.birth_date\
\n SubqueryAlias: a\
\n Projection: person.first_name AS fn1, person.last_name, person.birth_date, person.age\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_nested_with_filters() {
let sql = "SELECT fn1, age
FROM (
SELECT first_name AS fn1, age
FROM person
WHERE age > 20
) AS a
WHERE fn1 = 'X' AND age < 30";
let expected = "Projection: a.fn1, a.age\
\n Filter: a.fn1 = Utf8(\"X\") AND a.age < Int64(30)\
\n SubqueryAlias: a\
\n Projection: person.first_name AS fn1, person.age\
\n Filter: person.age > Int64(20)\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn table_with_column_alias() {
let sql = "SELECT a, b, c
FROM lineitem l (a, b, c)";
let expected = "Projection: l.a, l.b, l.c\
\n SubqueryAlias: l\
\n Projection: lineitem.l_item_id AS a, lineitem.l_description AS b, lineitem.price AS c\
\n TableScan: lineitem";
quick_test(sql, expected);
}
#[test]
fn table_with_column_alias_number_cols() {
let sql = "SELECT a, b, c
FROM lineitem l (a, b)";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Source table contains 3 columns but only 2 names given as column alias",
err.strip_backtrace()
);
}
#[test]
fn select_with_ambiguous_column() {
let sql = "SELECT id FROM person a, person b";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Schema error: Ambiguous reference to unqualified field id",
err.strip_backtrace()
);
}
#[test]
fn join_with_ambiguous_column() {
// This is legal.
let sql = "SELECT id FROM person a join person b using(id)";
let expected = "Projection: a.id\
\n Inner Join: Using a.id = b.id\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn where_selection_with_ambiguous_column() {
let sql = "SELECT * FROM person a, person b WHERE id = id + 1";
let err = logical_plan(sql)
.expect_err("query should have failed")
.strip_backtrace();
assert_eq!(
"\"Schema error: Ambiguous reference to unqualified field id\"",
format!("{err:?}")
);
}
#[test]
fn natural_join() {
let sql = "SELECT * FROM lineitem a NATURAL JOIN lineitem b";
let expected = "Projection: a.l_item_id, a.l_description, a.price\
\n Inner Join: Using a.l_item_id = b.l_item_id, a.l_description = b.l_description, a.price = b.price\
\n SubqueryAlias: a\
\n TableScan: lineitem\
\n SubqueryAlias: b\
\n TableScan: lineitem";
quick_test(sql, expected);
}
#[test]
fn natural_left_join() {
let sql = "SELECT l_item_id FROM lineitem a NATURAL LEFT JOIN lineitem b";
let expected = "Projection: a.l_item_id\
\n Left Join: Using a.l_item_id = b.l_item_id, a.l_description = b.l_description, a.price = b.price\
\n SubqueryAlias: a\
\n TableScan: lineitem\
\n SubqueryAlias: b\
\n TableScan: lineitem";
quick_test(sql, expected);
}
#[test]
fn natural_right_join() {
let sql = "SELECT l_item_id FROM lineitem a NATURAL RIGHT JOIN lineitem b";
let expected = "Projection: a.l_item_id\
\n Right Join: Using a.l_item_id = b.l_item_id, a.l_description = b.l_description, a.price = b.price\
\n SubqueryAlias: a\
\n TableScan: lineitem\
\n SubqueryAlias: b\
\n TableScan: lineitem";
quick_test(sql, expected);
}
#[test]
fn natural_join_no_common_becomes_cross_join() {
let sql = "SELECT * FROM person a NATURAL JOIN lineitem b";
let expected = "Projection: a.id, a.first_name, a.last_name, a.age, a.state, a.salary, a.birth_date, a.π, b.l_item_id, b.l_description, b.price\
\n CrossJoin:\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: lineitem";
quick_test(sql, expected);
}
#[test]
fn using_join_multiple_keys() {
let sql = "SELECT * FROM person a join person b using (id, age)";
let expected = "Projection: a.id, a.first_name, a.last_name, a.age, a.state, a.salary, a.birth_date, a.π, \
b.first_name, b.last_name, b.state, b.salary, b.birth_date, b.π\
\n Inner Join: Using a.id = b.id, a.age = b.age\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn using_join_multiple_keys_subquery() {
let sql =
"SELECT age FROM (SELECT * FROM person a join person b using (id, age, state))";
let expected = "Projection: a.age\
\n Projection: a.id, a.first_name, a.last_name, a.age, a.state, a.salary, a.birth_date, a.π, \
b.first_name, b.last_name, b.salary, b.birth_date, b.π\
\n Inner Join: Using a.id = b.id, a.age = b.age, a.state = b.state\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn using_join_multiple_keys_qualified_wildcard_select() {
let sql = "SELECT a.* FROM person a join person b using (id, age)";
let expected =
"Projection: a.id, a.first_name, a.last_name, a.age, a.state, a.salary, a.birth_date, a.π\
\n Inner Join: Using a.id = b.id, a.age = b.age\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn using_join_multiple_keys_select_all_columns() {
let sql = "SELECT a.*, b.* FROM person a join person b using (id, age)";
let expected = "Projection: a.id, a.first_name, a.last_name, a.age, a.state, a.salary, a.birth_date, a.π, \
b.id, b.first_name, b.last_name, b.age, b.state, b.salary, b.birth_date, b.π\
\n Inner Join: Using a.id = b.id, a.age = b.age\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn using_join_multiple_keys_multiple_joins() {
let sql = "SELECT * FROM person a join person b using (id, age, state) join person c using (id, age, state)";
let expected = "Projection: a.id, a.first_name, a.last_name, a.age, a.state, a.salary, a.birth_date, a.π, \
b.first_name, b.last_name, b.salary, b.birth_date, b.π, \
c.first_name, c.last_name, c.salary, c.birth_date, c.π\
\n Inner Join: Using a.id = c.id, a.age = c.age, a.state = c.state\
\n Inner Join: Using a.id = b.id, a.age = b.age, a.state = b.state\
\n SubqueryAlias: a\
\n TableScan: person\
\n SubqueryAlias: b\
\n TableScan: person\
\n SubqueryAlias: c\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_with_having() {
let sql = "SELECT id, age
FROM person
HAVING age > 100 AND age < 200";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: HAVING clause references: person.age > Int64(100) AND person.age < Int64(200) must appear in the GROUP BY clause or be used in an aggregate function",
err.strip_backtrace()
);
}
#[test]
fn select_with_having_referencing_column_not_in_select() {
let sql = "SELECT id, age
FROM person
HAVING first_name = 'M'";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: HAVING clause references: person.first_name = Utf8(\"M\") must appear in the GROUP BY clause or be used in an aggregate function",
err.strip_backtrace()
);
}
#[test]
fn select_with_having_refers_to_invalid_column() {
let sql = "SELECT id, MAX(age)
FROM person
GROUP BY id
HAVING first_name = 'M'";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: HAVING clause references non-aggregate values: Expression person.first_name could not be resolved from available columns: person.id, MAX(person.age)",
err.strip_backtrace()
);
}
#[test]
fn select_with_having_referencing_column_nested_in_select_expression() {
let sql = "SELECT id, age + 1
FROM person
HAVING age > 100";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: HAVING clause references: person.age > Int64(100) must appear in the GROUP BY clause or be used in an aggregate function",
err.strip_backtrace()
);
}
#[test]
fn select_with_having_with_aggregate_not_in_select() {
let sql = "SELECT first_name
FROM person
HAVING MAX(age) > 100";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: Projection references non-aggregate values: Expression person.first_name could not be resolved from available columns: MAX(person.age)",
err.strip_backtrace()
);
}
#[test]
fn select_aggregate_with_having_that_reuses_aggregate() {
let sql = "SELECT MAX(age)
FROM person
HAVING MAX(age) < 30";
let expected = "Projection: MAX(person.age)\
\n Filter: MAX(person.age) < Int64(30)\
\n Aggregate: groupBy=[[]], aggr=[[MAX(person.age)]]\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_aggregate_with_having_with_aggregate_not_in_select() {
let sql = "SELECT MAX(age)
FROM person
HAVING MAX(first_name) > 'M'";
let expected = "Projection: MAX(person.age)\
\n Filter: MAX(person.first_name) > Utf8(\"M\")\
\n Aggregate: groupBy=[[]], aggr=[[MAX(person.age), MAX(person.first_name)]]\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_aggregate_with_having_referencing_column_not_in_select() {
let sql = "SELECT COUNT(*)
FROM person
HAVING first_name = 'M'";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
"Error during planning: HAVING clause references non-aggregate values: Expression person.first_name could not be resolved from available columns: COUNT(*)",
err.strip_backtrace()
);
}
#[test]
fn select_aggregate_aliased_with_having_referencing_aggregate_by_its_alias() {
let sql = "SELECT MAX(age) as max_age
FROM person
HAVING max_age < 30";
// FIXME: add test for having in execution
let expected = "Projection: MAX(person.age) AS max_age\
\n Filter: MAX(person.age) < Int64(30)\
\n Aggregate: groupBy=[[]], aggr=[[MAX(person.age)]]\
\n TableScan: person";
quick_test(sql, expected);
}
#[test]
fn select_aggregate_aliased_with_having_that_reuses_aggregate_but_not_by_its_alias() {
let sql = "SELECT MAX(age) as max_age