1use crate::error::{_schema_err, add_possible_columns_to_diag};
8use crate::utils::parse_identifiers_normalized;
9use crate::utils::quote_identifier;
10use crate::{DFSchema, Diagnostic, Result, SchemaError, Spans, TableReference};
11use arrow::datatypes::{Field, FieldRef};
12use itertools::Itertools;
13use std::collections::HashSet;
14use std::fmt;
15
16#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct Column {
19 pub relation: Option<TableReference>,
21 pub name: String,
23 pub spans: Spans,
25}
26
27impl fmt::Debug for Column {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 f.debug_struct("Column")
30 .field("relation", &self.relation)
31 .field("name", &self.name)
32 .finish()
33 }
34}
35
36impl Column {
37 pub fn new(
44 relation: Option<impl Into<TableReference>>,
45 name: impl Into<String>,
46 ) -> Self {
47 Self {
48 relation: relation.map(|r| r.into()),
49 name: name.into(),
50 spans: Spans::new(),
51 }
52 }
53
54 pub fn new_unqualified(name: impl Into<String>) -> Self {
56 Self {
57 relation: None,
58 name: name.into(),
59 spans: Spans::new(),
60 }
61 }
62
63 pub fn from_name(name: impl Into<String>) -> Self {
67 Self {
68 relation: None,
69 name: name.into(),
70 spans: Spans::new(),
71 }
72 }
73
74 fn from_idents(mut idents: Vec<String>) -> Option<Self> {
79 let (relation, name) = match idents.len() {
80 1 => (None, idents.remove(0)),
81 2 => (
82 Some(TableReference::Bare {
83 table: idents.remove(0).into(),
84 }),
85 idents.remove(0),
86 ),
87 3 => (
88 Some(TableReference::Partial {
89 schema: idents.remove(0).into(),
90 table: idents.remove(0).into(),
91 }),
92 idents.remove(0),
93 ),
94 4 => (
95 Some(TableReference::Full {
96 catalog: idents.remove(0).into(),
97 schema: idents.remove(0).into(),
98 table: idents.remove(0).into(),
99 }),
100 idents.remove(0),
101 ),
102 _ => return None,
105 };
106 Some(Self {
107 relation,
108 name,
109 spans: Spans::new(),
110 })
111 }
112
113 pub fn from_qualified_name(flat_name: impl Into<String>) -> Self {
119 let flat_name = flat_name.into();
120 Self::from_idents(parse_identifiers_normalized(&flat_name, false)).unwrap_or_else(
121 || Self {
122 relation: None,
123 name: flat_name,
124 spans: Spans::new(),
125 },
126 )
127 }
128
129 #[cfg(feature = "sql")]
131 pub fn from_qualified_name_ignore_case(flat_name: impl Into<String>) -> Self {
132 let flat_name = flat_name.into();
133 Self::from_idents(parse_identifiers_normalized(&flat_name, true)).unwrap_or_else(
134 || Self {
135 relation: None,
136 name: flat_name,
137 spans: Spans::new(),
138 },
139 )
140 }
141
142 #[cfg(not(feature = "sql"))]
143 pub fn from_qualified_name_ignore_case(flat_name: impl Into<String>) -> Self {
144 Self::from_qualified_name(flat_name)
145 }
146
147 pub fn name(&self) -> &str {
151 &self.name
152 }
153
154 pub fn flat_name(&self) -> String {
156 match &self.relation {
157 Some(r) => format!("{}.{}", r, self.name),
158 None => self.name.clone(),
159 }
160 }
161
162 pub fn quoted_flat_name(&self) -> String {
164 match &self.relation {
165 Some(r) => {
166 format!(
167 "{}.{}",
168 r.to_quoted_string(),
169 quote_identifier(self.name.as_str())
170 )
171 }
172 None => quote_identifier(&self.name).to_string(),
173 }
174 }
175
176 pub fn normalize_with_schemas_and_ambiguity_check(
213 self,
214 schemas: &[&[&DFSchema]],
215 using_columns: &[HashSet<Column>],
216 ) -> Result<Self> {
217 if self.relation.is_some() {
218 return Ok(self);
219 }
220
221 for schema_level in schemas {
222 let qualified_fields = schema_level
223 .iter()
224 .flat_map(|s| s.qualified_fields_with_unqualified_name(&self.name))
225 .collect::<Vec<_>>();
226 match qualified_fields.len() {
227 0 => {}
228 1 => return Ok(Column::from(qualified_fields[0])),
229 _ => {
230 let columns = schema_level
244 .iter()
245 .flat_map(|s| s.columns_with_unqualified_name(&self.name))
246 .collect::<Vec<_>>();
247 for using_col in using_columns {
248 let all_matched = columns.iter().all(|c| using_col.contains(c));
249 if all_matched {
252 return Ok(columns[0].clone());
253 }
254 }
255
256 return _schema_err!(SchemaError::AmbiguousReference {
258 field: Box::new(Column::new_unqualified(&self.name)),
259 })
260 .map_err(|err| {
261 let mut diagnostic = Diagnostic::new_error(
262 format!("column '{}' is ambiguous", self.name),
263 self.spans().first(),
264 );
265 add_possible_columns_to_diag(
270 &mut diagnostic,
271 &Column::new_unqualified(&self.name),
272 &columns,
273 );
274 err.with_diagnostic(diagnostic)
275 });
276 }
277 }
278 }
279
280 _schema_err!(SchemaError::FieldNotFound {
281 field: Box::new(self),
282 valid_fields: schemas
283 .iter()
284 .flat_map(|s| s.iter())
285 .flat_map(|s| s.columns())
286 .unique()
287 .collect(),
288 })
289 }
290
291 pub fn spans(&self) -> &Spans {
294 &self.spans
295 }
296
297 pub fn spans_mut(&mut self) -> &mut Spans {
300 &mut self.spans
301 }
302
303 pub fn with_spans(mut self, spans: Spans) -> Self {
306 self.spans = spans;
307 self
308 }
309
310 pub fn with_relation(&self, relation: TableReference) -> Self {
312 Self {
313 relation: Some(relation),
314 ..self.clone()
315 }
316 }
317}
318
319impl From<&str> for Column {
320 fn from(c: &str) -> Self {
321 Self::from_qualified_name(c)
322 }
323}
324
325impl From<&String> for Column {
327 fn from(c: &String) -> Self {
328 Self::from_qualified_name(c)
329 }
330}
331
332impl From<String> for Column {
334 fn from(c: String) -> Self {
335 Self::from_qualified_name(c)
336 }
337}
338
339impl From<(Option<&TableReference>, &Field)> for Column {
341 fn from((relation, field): (Option<&TableReference>, &Field)) -> Self {
342 Self::new(relation.cloned(), field.name())
343 }
344}
345
346impl From<(Option<&TableReference>, &FieldRef)> for Column {
348 fn from((relation, field): (Option<&TableReference>, &FieldRef)) -> Self {
349 Self::new(relation.cloned(), field.name())
350 }
351}
352
353#[cfg(feature = "sql")]
354impl std::str::FromStr for Column {
355 type Err = std::convert::Infallible;
356
357 fn from_str(s: &str) -> Result<Self, Self::Err> {
358 Ok(s.into())
359 }
360}
361
362impl fmt::Display for Column {
363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364 write!(f, "{}", self.flat_name())
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371 use arrow::datatypes::{DataType, SchemaBuilder};
372 use std::sync::Arc;
373
374 fn create_qualified_schema(qualifier: &str, names: Vec<&str>) -> Result<DFSchema> {
375 let mut schema_builder = SchemaBuilder::new();
376 schema_builder.extend(
377 names
378 .iter()
379 .map(|f| Field::new(*f, DataType::Boolean, true)),
380 );
381 let schema = Arc::new(schema_builder.finish());
382 DFSchema::try_from_qualified_schema(qualifier, &schema)
383 }
384
385 #[test]
386 fn test_normalize_with_schemas_and_ambiguity_check() -> Result<()> {
387 let schema1 = create_qualified_schema("t1", vec!["a", "b"])?;
388 let schema2 = create_qualified_schema("t2", vec!["c", "d"])?;
389 let schema3 = create_qualified_schema("t3", vec!["a", "b", "c", "d", "e"])?;
390
391 let col = Column::new(Some("t1"), "a");
393 let col = col.normalize_with_schemas_and_ambiguity_check(&[], &[])?;
394 assert_eq!(col, Column::new(Some("t1"), "a"));
395
396 let col = Column::from_name("a");
398 let col = col.normalize_with_schemas_and_ambiguity_check(
399 &[&[&schema1, &schema2], &[&schema3]],
400 &[],
401 )?;
402 assert_eq!(col, Column::new(Some("t1"), "a"));
403
404 let col = Column::from_name("e");
406 let col = col.normalize_with_schemas_and_ambiguity_check(
407 &[&[&schema1, &schema2], &[&schema3]],
408 &[],
409 )?;
410 assert_eq!(col, Column::new(Some("t3"), "e"));
411
412 let mut using_columns = HashSet::new();
414 using_columns.insert(Column::new(Some("t1"), "a"));
415 using_columns.insert(Column::new(Some("t3"), "a"));
416 let col = Column::from_name("a");
417 let col = col.normalize_with_schemas_and_ambiguity_check(
418 &[&[&schema1, &schema3], &[&schema2]],
419 &[using_columns],
420 )?;
421 assert_eq!(col, Column::new(Some("t1"), "a"));
422
423 let col = Column::from_name("z");
425 let err = col
426 .normalize_with_schemas_and_ambiguity_check(
427 &[&[&schema1, &schema2], &[&schema3]],
428 &[],
429 )
430 .expect_err("should've failed to find field");
431 let expected = "Schema error: No field named z.\n\
432 Valid fields are t1.a, t1.b, t2.c, t2.d, t3.a, t3.b, t3.c, t3.d, t3.e.";
433 assert_eq!(err.strip_backtrace(), expected);
434
435 let col = Column::from_name("a");
437 let err = col
438 .normalize_with_schemas_and_ambiguity_check(
439 &[&[&schema1, &schema3], &[&schema2]],
440 &[],
441 )
442 .expect_err("should've found ambiguous field");
443 let expected = "Schema error: Ambiguous reference to unqualified field a";
444 assert_eq!(err.strip_backtrace(), expected);
445
446 Ok(())
447 }
448}