Skip to main content

datafusion_common/
column.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Column
6
7use 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/// A named reference to a qualified field in a schema.
17#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct Column {
19    /// relation/table reference.
20    pub relation: Option<TableReference>,
21    /// field/column name.
22    pub name: String,
23    /// Original source code location, if known
24    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    /// Create Column from optional qualifier and name. The optional qualifier, if present,
38    /// will be parsed and normalized by default.
39    ///
40    /// See full details on [`TableReference::parse_str`]
41    ///
42    /// [`TableReference::parse_str`]: crate::TableReference::parse_str
43    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    /// Convenience method for when there is no qualifier
55    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    /// Create Column from unqualified name.
64    ///
65    /// Alias for `Column::new_unqualified`
66    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    /// Create a Column from multiple normalized identifiers
75    ///
76    /// For example, `foo.bar` would be represented as a two element vector
77    /// `["foo", "bar"]`
78    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            // any expression that failed to parse or has more than 4 period delimited
103            // identifiers will be treated as an unqualified column name
104            _ => return None,
105        };
106        Some(Self {
107            relation,
108            name,
109            spans: Spans::new(),
110        })
111    }
112
113    /// Deserialize a fully qualified name string into a column
114    ///
115    /// Treats the name as a SQL identifier. For example
116    /// `foo.BAR` would be parsed to a reference to relation `foo`, column name `bar` (lower case)
117    /// where `"foo.BAR"` would be parsed to a reference to column named `foo.BAR`
118    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    /// Deserialize a fully qualified name string into a column preserving column text case
130    #[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    /// return the column's name.
148    ///
149    /// Note: This ignores the relation and returns the column name only.
150    pub fn name(&self) -> &str {
151        &self.name
152    }
153
154    /// Serialize column into a flat name string
155    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    /// Serialize column into a quoted flat name string
163    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    /// Qualify column if not done yet.
177    ///
178    /// If this column already has a [relation](Self::relation), it will be returned as is and the given parameters are
179    /// ignored. Otherwise this will search through the given schemas to find the column.
180    ///
181    /// Will check for ambiguity at each level of `schemas`.
182    ///
183    /// A schema matches if there is a single column that -- when unqualified -- matches this column. There is an
184    /// exception for `USING` statements, see below.
185    ///
186    /// # Using columns
187    /// Take the following SQL statement:
188    ///
189    /// ```sql
190    /// SELECT id FROM t1 JOIN t2 USING(id)
191    /// ```
192    ///
193    /// In this case, both `t1.id` and `t2.id` will match unqualified column `id`. To express this possibility, use
194    /// `using_columns`. Each entry in this array is a set of columns that are bound together via a `USING` clause. So
195    /// in this example this would be `[{t1.id, t2.id}]`.
196    ///
197    /// Regarding ambiguity check, `schemas` is structured to allow levels of schemas to be passed in.
198    /// For example:
199    ///
200    /// ```text
201    /// schemas = &[
202    ///    &[schema1, schema2], // first level
203    ///    &[schema3, schema4], // second level
204    /// ]
205    /// ```
206    ///
207    /// Will search for a matching field in all schemas in the first level. If a matching field according to above
208    /// mentioned conditions is not found, then will check the next level. If found more than one matching column across
209    /// all schemas in a level, that isn't a USING column, will return an error due to ambiguous column.
210    ///
211    /// If checked all levels and couldn't find field, will return field not found error.
212    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                    // More than 1 fields in this schema have their names set to self.name.
231                    //
232                    // This should only happen when a JOIN query with USING constraint references
233                    // join columns using unqualified column name. For example:
234                    //
235                    // ```sql
236                    // SELECT id FROM t1 JOIN t2 USING(id)
237                    // ```
238                    //
239                    // In this case, both `t1.id` and `t2.id` will match unqualified column `id`.
240                    // We will use the relation from the first matched field to normalize self.
241
242                    // Compare matched fields with one USING JOIN clause at a time
243                    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                        // All matched fields belong to the same using column set, in other words
250                        // the same join clause. We simply pick the qualifier from the first match.
251                        if all_matched {
252                            return Ok(columns[0].clone());
253                        }
254                    }
255
256                    // If not due to USING columns then due to ambiguous column name
257                    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                        // TODO If [`DFSchema`] had spans, we could show the
266                        // user which columns are candidates, or which table
267                        // they come from. For now, let's list the table names
268                        // only.
269                        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    /// Returns a reference to the set of locations in the SQL query where this
292    /// column appears, if known.
293    pub fn spans(&self) -> &Spans {
294        &self.spans
295    }
296
297    /// Returns a mutable reference to the set of locations in the SQL query
298    /// where this column appears, if known.
299    pub fn spans_mut(&mut self) -> &mut Spans {
300        &mut self.spans
301    }
302
303    /// Replaces the set of locations in the SQL query where this column
304    /// appears, if known.
305    pub fn with_spans(mut self, spans: Spans) -> Self {
306        self.spans = spans;
307        self
308    }
309
310    /// Qualifies the column with the given table reference.
311    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
325/// Create a column, cloning the string
326impl From<&String> for Column {
327    fn from(c: &String) -> Self {
328        Self::from_qualified_name(c)
329    }
330}
331
332/// Create a column, reusing the existing string
333impl From<String> for Column {
334    fn from(c: String) -> Self {
335        Self::from_qualified_name(c)
336    }
337}
338
339/// Create a column, use qualifier and field name
340impl 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
346/// Create a column, use qualifier and field name
347impl 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        // already normalized
392        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        // should find in first level (schema1)
397        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        // should find in second level (schema3)
405        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        // using column in first level (pick schema1)
413        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        // not found in any level
424        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        // ambiguous column reference
436        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}