-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathdiagnostic.rs
More file actions
522 lines (475 loc) · 18.4 KB
/
diagnostic.rs
File metadata and controls
522 lines (475 loc) · 18.4 KB
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
// 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 datafusion_functions::string;
use insta::assert_snapshot;
use std::{collections::HashMap, sync::Arc};
use datafusion_common::{Diagnostic, Location, Result, Span};
use datafusion_sql::{
parser::{DFParser, DFParserBuilder},
planner::{ParserOptions, SqlToRel},
};
use regex::Regex;
use crate::{MockContextProvider, MockSessionState};
fn do_query(sql: &'static str) -> Diagnostic {
let statement = DFParserBuilder::new(sql)
.build()
.expect("unable to create parser")
.parse_statement()
.expect("unable to parse query");
let options = ParserOptions {
collect_spans: true,
..ParserOptions::default()
};
let state = MockSessionState::default()
.with_scalar_function(Arc::new(string::concat().as_ref().clone()));
let context = MockContextProvider { state };
let sql_to_rel = SqlToRel::new_with_options(&context, options);
match sql_to_rel.statement_to_plan(statement) {
Ok(_) => panic!("expected error"),
Err(err) => match err.diagnostic() {
Some(diag) => diag.clone(),
None => panic!("expected diagnostic"),
},
}
}
/// Given a query that contains tag delimited spans, returns a mapping from the
/// span name to the [`Span`]. Tags are comments of the form `/*tag*/`. In case
/// you want the same location to open two spans, or close open and open
/// another, you can use '+' to separate the names (the order matters). The
/// names of spans can only contain letters, digits, underscores, and dashes.
///
///
/// ## Example
///
/// ```rust
/// let spans = get_spans("SELECT /*myspan*/car/*myspan*/ FROM cars");
/// // myspan is ^^^
/// dbg!(&spans["myspan"]);
/// ```
///
/// ## Example
///
/// ```rust
/// let spans = get_spans(
/// "SELECT /*whole+left*/speed/*left*/ + /*right*/10/*right+whole*/ FROM cars",
/// // whole is ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// // left is ^^^^^
/// // right is ^^
/// );
/// dbg!(&spans["whole"]);
/// dbg!(&spans["left"]);
/// dbg!(&spans["right"]);
/// ```
fn get_spans(query: &'static str) -> HashMap<String, Span> {
let mut spans = HashMap::new();
let mut bytes_per_line = vec![];
for line in query.lines() {
bytes_per_line.push(line.len());
}
let byte_offset_to_loc = |s: &str, byte_offset: usize| -> Location {
let mut line = 1;
let mut column = 1;
for (i, c) in s.chars().enumerate() {
if i == byte_offset {
return Location { line, column };
}
if c == '\n' {
line += 1;
column = 1;
} else {
column += 1;
}
}
Location { line, column }
};
let re = Regex::new(r#"/\*([\w\d\+_-]+)\*/"#).unwrap();
let mut stack: Vec<(String, usize)> = vec![];
for c in re.captures_iter(query) {
let m = c.get(0).unwrap();
let tags = c.get(1).unwrap().as_str().split("+").collect::<Vec<_>>();
for tag in tags {
if stack.last().map(|(top_tag, _)| top_tag.as_str()) == Some(tag) {
let (_, start) = stack.pop().unwrap();
let end = m.start();
spans.insert(
tag.to_string(),
Span::new(
byte_offset_to_loc(query, start),
byte_offset_to_loc(query, end),
),
);
} else {
stack.push((tag.to_string(), m.end()));
}
}
}
if !stack.is_empty() {
panic!("unbalanced tags");
}
spans
}
#[test]
fn test_table_not_found() -> Result<()> {
let query = "SELECT * FROM /*a*/personx/*a*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"table 'personx' not found");
assert_eq!(diag.span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_unqualified_column_not_found() -> Result<()> {
let query = "SELECT /*a*/first_namex/*a*/ FROM person";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"column 'first_namex' not found");
assert_eq!(diag.span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_qualified_column_not_found() -> Result<()> {
let query = "SELECT /*a*/person.first_namex/*a*/ FROM person";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"column 'first_namex' not found in 'person'");
assert_eq!(diag.span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_union_wrong_number_of_columns() -> Result<()> {
let query = "/*whole+left*/SELECT first_name FROM person/*left*/ UNION ALL /*right*/SELECT first_name, last_name FROM person/*right+whole*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"UNION queries have different number of columns");
assert_eq!(diag.span, Some(spans["whole"]));
assert_snapshot!(diag.notes[0].message, @"this side has 1 fields");
assert_eq!(diag.notes[0].span, Some(spans["left"]));
assert_snapshot!(diag.notes[1].message, @"this side has 2 fields");
assert_eq!(diag.notes[1].span, Some(spans["right"]));
Ok(())
}
#[test]
fn test_missing_non_aggregate_in_group_by() -> Result<()> {
let query = "SELECT id, /*a*/first_name/*a*/ FROM person GROUP BY id";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"'person.first_name' must appear in GROUP BY clause because it's not an aggregate expression");
assert_eq!(diag.span, Some(spans["a"]));
assert_snapshot!(diag.helps[0].message, @"Either add 'person.first_name' to GROUP BY clause, or use an aggregate function like ANY_VALUE(person.first_name)");
Ok(())
}
#[test]
fn test_ambiguous_reference() -> Result<()> {
let query = "SELECT /*a*/first_name/*a*/ FROM person a, person b";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"column 'first_name' is ambiguous");
assert_eq!(diag.span, Some(spans["a"]));
assert_snapshot!(diag.notes[0].message, @"possible column a.first_name");
assert_snapshot!(diag.notes[1].message, @"possible column b.first_name");
Ok(())
}
#[test]
fn test_incompatible_types_binary_arithmetic() -> Result<()> {
let query = "SELECT /*whole+left*/id/*left*/ + /*right*/first_name/*right+whole*/ FROM person";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"expressions have incompatible types");
assert_eq!(diag.span, Some(spans["whole"]));
assert_snapshot!(diag.notes[0].message, @"has type UInt32");
assert_eq!(diag.notes[0].span, Some(spans["left"]));
assert_snapshot!(diag.notes[1].message, @"has type Utf8");
assert_eq!(diag.notes[1].span, Some(spans["right"]));
Ok(())
}
#[test]
fn test_field_not_found_suggestion() -> Result<()> {
let query = "SELECT /*whole*/first_na/*whole*/ FROM person";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"column 'first_na' not found");
assert_eq!(diag.span, Some(spans["whole"]));
assert_eq!(diag.notes.len(), 1);
let mut suggested_fields: Vec<String> = diag
.notes
.iter()
.filter_map(|note| {
if note.message.starts_with("possible column") {
Some(note.message.replace("possible column ", ""))
} else {
None
}
})
.collect();
suggested_fields.sort();
assert_snapshot!(suggested_fields[0], @"person.first_name");
Ok(())
}
#[test]
fn test_ambiguous_column_suggestion() -> Result<()> {
let query = "SELECT /*whole*/id/*whole*/ FROM test_decimal, person";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"column 'id' is ambiguous");
assert_eq!(diag.span, Some(spans["whole"]));
assert_eq!(diag.notes.len(), 2);
let mut suggested_fields: Vec<String> = diag
.notes
.iter()
.filter_map(|note| {
if note.message.starts_with("possible column") {
Some(note.message.replace("possible column ", ""))
} else {
None
}
})
.collect();
suggested_fields.sort();
assert_eq!(suggested_fields, vec!["person.id", "test_decimal.id"]);
Ok(())
}
#[test]
fn test_invalid_function() -> Result<()> {
let query = "SELECT /*whole*/concat_not_exist/*whole*/()";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"Invalid function 'concat_not_exist'");
assert_snapshot!(diag.notes[0].message, @"Possible function 'concat'");
assert_eq!(diag.span, Some(spans["whole"]));
Ok(())
}
#[test]
fn test_scalar_subquery_multiple_columns() -> Result<(), Box<dyn std::error::Error>> {
let query = "SELECT (SELECT 1 AS /*x*/x/*x*/, 2 AS /*y*/y/*y*/) AS col";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"Too many columns! The subquery should only return one column");
let expected_span = Some(Span {
start: spans["x"].start,
end: spans["y"].end,
});
assert_eq!(diag.span, expected_span);
assert_eq!(
diag.notes
.iter()
.map(|n| (n.message.as_str(), n.span))
.collect::<Vec<_>>(),
vec![("Extra column 1", Some(spans["y"]))]
);
assert_eq!(
diag.helps
.iter()
.map(|h| h.message.as_str())
.collect::<Vec<_>>(),
vec!["Select only one column in the subquery"]
);
Ok(())
}
#[test]
fn test_in_subquery_multiple_columns() -> Result<(), Box<dyn std::error::Error>> {
// This query uses an IN subquery with multiple columns - this should trigger an error
let query = "SELECT * FROM person WHERE id IN (SELECT /*id*/id/*id*/, /*first*/first_name/*first*/ FROM person)";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"Too many columns! The subquery should only return one column");
let expected_span = Some(Span {
start: spans["id"].start,
end: spans["first"].end,
});
assert_eq!(diag.span, expected_span);
assert_eq!(
diag.notes
.iter()
.map(|n| (n.message.as_str(), n.span))
.collect::<Vec<_>>(),
vec![("Extra column 1", Some(spans["first"]))]
);
assert_eq!(
diag.helps
.iter()
.map(|h| h.message.as_str())
.collect::<Vec<_>>(),
vec!["Select only one column in the subquery"]
);
Ok(())
}
#[test]
fn test_unary_op_plus_with_column() -> Result<()> {
// Test with a direct query that references a column with an incompatible type
let query = "SELECT +/*whole*/first_name/*whole*/ FROM person";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"+ cannot be used with Utf8");
assert_eq!(diag.span, Some(spans["whole"]));
assert_snapshot!(diag.notes[0].message, @"+ can only be used with numbers, intervals, and timestamps");
assert_snapshot!(diag.helps[0].message, @"perhaps you need to cast person.first_name");
Ok(())
}
#[test]
fn test_unary_op_plus_with_non_column() -> Result<()> {
// create a table with a column of type varchar
let query = "SELECT +'a'";
let diag = do_query(query);
assert_eq!(diag.message, "+ cannot be used with Utf8");
assert_snapshot!(diag.notes[0].message, @"+ can only be used with numbers, intervals, and timestamps");
assert_eq!(diag.notes[0].span, None);
assert_snapshot!(diag.helps[0].message, @r#"perhaps you need to cast Utf8("a")"#);
assert_eq!(diag.helps[0].span, None);
assert_eq!(diag.span, None);
Ok(())
}
#[test]
fn test_syntax_error() -> Result<()> {
// create a table with a column of type varchar
let query = "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV PARTITIONED BY (c1, p1 /*int*/int/*int*/) LOCATION 'foo.csv'";
let spans = get_spans(query);
match DFParser::parse_sql(query) {
Ok(_) => panic!("expected error"),
Err(err) => match err.diagnostic() {
Some(diag) => {
let diag = diag.clone();
assert_snapshot!(diag.message, @"Expected: ',' or ')' after partition definition, found: int at Line: 1, Column: 77");
println!("{spans:?}");
assert_eq!(diag.span, Some(spans["int"]));
Ok(())
}
None => {
panic!("expected diagnostic")
}
},
}
}
#[test]
fn test_duplicate_cte_name() -> Result<()> {
let query = "WITH /*a*/cte/*a*/ AS (SELECT 1 AS col), /*b*/cte/*b*/ AS (SELECT 2 AS col) SELECT 1";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @r#"WITH query name "cte" specified more than once"#);
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"previously defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_table_alias() -> Result<()> {
let query = "SELECT * FROM person /*a*/a/*a*/, person /*b*/a/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_table_alias_not_first() -> Result<()> {
let query = "SELECT * FROM person a, test_decimal /*b*/b/*b*/, person /*c*/b/*c*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["c"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["b"]));
Ok(())
}
#[test]
fn test_duplicate_bare_table_in_from() -> Result<()> {
let query = "SELECT * FROM /*a*/person/*a*/, /*b*/person/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_alias_non_overlapping_columns() -> Result<()> {
let query = "SELECT * FROM j1 AS /*a*/t/*a*/, j2 AS /*b*/t/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_alias_non_overlapping_three_tables() -> Result<()> {
let query = "SELECT * FROM j1 AS x, j2 AS /*a*/t/*a*/, j3 AS y, j1 AS /*b*/t/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_derived_subquery_alias() -> Result<()> {
let query = "SELECT * FROM (SELECT 1) AS /*a*/t/*a*/, (SELECT 2) AS /*b*/t/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_alias_table_and_derived() -> Result<()> {
let query = "SELECT * FROM person AS /*a*/t/*a*/, (SELECT 1) AS /*b*/t/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_alias_derived_and_table() -> Result<()> {
let query = "SELECT * FROM (SELECT 1) AS /*a*/t/*a*/, person AS /*b*/t/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}
#[test]
fn test_duplicate_nested_join_alias() -> Result<()> {
let query = "SELECT * FROM (person CROSS JOIN j1) AS /*a*/t/*a*/, (person CROSS JOIN j2) AS /*b*/t/*b*/";
let spans = get_spans(query);
let diag = do_query(query);
assert_snapshot!(diag.message, @"duplicate table alias in FROM clause");
assert_eq!(diag.span, Some(spans["b"]));
assert_eq!(diag.notes.len(), 1);
assert_snapshot!(diag.notes[0].message, @"first defined here");
assert_eq!(diag.notes[0].span, Some(spans["a"]));
Ok(())
}