datafusion_common/table_reference.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
5use crate::utils::parse_identifiers_normalized;
6use crate::utils::quote_identifier;
7use std::sync::Arc;
8
9/// A fully resolved path to a table of the form "catalog.schema.table"
10#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct ResolvedTableReference {
12 /// The catalog (aka database) containing the table
13 pub catalog: Arc<str>,
14 /// The schema containing the table
15 pub schema: Arc<str>,
16 /// The table name
17 pub table: Arc<str>,
18}
19
20impl std::fmt::Display for ResolvedTableReference {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 write!(f, "{}.{}.{}", self.catalog, self.schema, self.table)
23 }
24}
25
26/// A multi part identifier (path) to a table that may require further
27/// resolution (e.g. `foo.bar`).
28///
29/// [`TableReference`]s are cheap to `clone()` as they are implemented with
30/// `Arc`.
31///
32/// See [`ResolvedTableReference`] for a fully resolved table reference.
33///
34/// # Creating [`TableReference`]
35///
36/// When converting strings to [`TableReference`]s, the string is parsed as
37/// though it were a SQL identifier, normalizing (convert to lowercase) any
38/// unquoted identifiers. [`TableReference::bare`] creates references without
39/// applying normalization semantics.
40///
41/// # Examples
42/// ```
43/// # use datafusion_common::TableReference;
44/// // Get a table reference to 'mytable'
45/// let table_reference = TableReference::from("mytable");
46/// assert_eq!(table_reference, TableReference::bare("mytable"));
47///
48/// // Get a table reference to 'mytable' (note the capitalization)
49/// let table_reference = TableReference::from("MyTable");
50/// assert_eq!(table_reference, TableReference::bare("mytable"));
51///
52/// // Get a table reference to 'MyTable' (note the capitalization) using double quotes
53/// // (programmatically it is better to use `TableReference::bare` for this)
54/// let table_reference = TableReference::from(r#""MyTable""#);
55/// assert_eq!(table_reference, TableReference::bare("MyTable"));
56///
57/// // Get a table reference to 'myschema.mytable' (note the capitalization)
58/// let table_reference = TableReference::from("MySchema.MyTable");
59/// assert_eq!(
60/// table_reference,
61/// TableReference::partial("myschema", "mytable")
62/// );
63/// ```
64#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
65pub enum TableReference {
66 /// An unqualified table reference, e.g. "table"
67 Bare {
68 /// The table name
69 table: Arc<str>,
70 },
71 /// A partially resolved table reference, e.g. "schema.table"
72 Partial {
73 /// The schema containing the table
74 schema: Arc<str>,
75 /// The table name
76 table: Arc<str>,
77 },
78 /// A fully resolved table reference, e.g. "catalog.schema.table"
79 Full {
80 /// The catalog (aka database) containing the table
81 catalog: Arc<str>,
82 /// The schema containing the table
83 schema: Arc<str>,
84 /// The table name
85 table: Arc<str>,
86 },
87}
88
89impl std::fmt::Display for TableReference {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 TableReference::Bare { table } => write!(f, "{table}"),
93 TableReference::Partial { schema, table } => {
94 write!(f, "{schema}.{table}")
95 }
96 TableReference::Full {
97 catalog,
98 schema,
99 table,
100 } => write!(f, "{catalog}.{schema}.{table}"),
101 }
102 }
103}
104
105impl TableReference {
106 /// Convenience method for creating a typed none `None`
107 pub fn none() -> Option<TableReference> {
108 None
109 }
110
111 /// Convenience method for creating a [`TableReference::Bare`]
112 ///
113 /// As described on [`TableReference`] this does *NO* normalization at
114 /// all, so "Foo.Bar" stays as a reference to the table named
115 /// "Foo.Bar" (rather than "foo"."bar")
116 pub fn bare(table: impl Into<Arc<str>>) -> TableReference {
117 TableReference::Bare {
118 table: table.into(),
119 }
120 }
121
122 /// Convenience method for creating a [`TableReference::Partial`].
123 ///
124 /// Note: *NO* normalization is applied to the schema or table name.
125 pub fn partial(
126 schema: impl Into<Arc<str>>,
127 table: impl Into<Arc<str>>,
128 ) -> TableReference {
129 TableReference::Partial {
130 schema: schema.into(),
131 table: table.into(),
132 }
133 }
134
135 /// Convenience method for creating a [`TableReference::Full`]
136 ///
137 /// Note: *NO* normalization is applied to the catalog, schema or table
138 /// name.
139 pub fn full(
140 catalog: impl Into<Arc<str>>,
141 schema: impl Into<Arc<str>>,
142 table: impl Into<Arc<str>>,
143 ) -> TableReference {
144 TableReference::Full {
145 catalog: catalog.into(),
146 schema: schema.into(),
147 table: table.into(),
148 }
149 }
150
151 /// Retrieve the table name, regardless of qualification.
152 pub fn table(&self) -> &str {
153 match self {
154 Self::Full { table, .. }
155 | Self::Partial { table, .. }
156 | Self::Bare { table } => table,
157 }
158 }
159
160 /// Retrieve the schema name if [`Self::Partial]` or [`Self::`Full`],
161 /// `None` otherwise.
162 pub fn schema(&self) -> Option<&str> {
163 match self {
164 Self::Full { schema, .. } | Self::Partial { schema, .. } => Some(schema),
165 _ => None,
166 }
167 }
168
169 /// Retrieve the catalog name if [`Self::Full`], `None` otherwise.
170 pub fn catalog(&self) -> Option<&str> {
171 match self {
172 Self::Full { catalog, .. } => Some(catalog),
173 _ => None,
174 }
175 }
176
177 /// Compare with another [`TableReference`] as if both are resolved.
178 /// This allows comparing across variants. If a field is not present
179 /// in both variants being compared then it is ignored in the comparison.
180 ///
181 /// e.g. this allows a [`TableReference::Bare`] to be considered equal to a
182 /// fully qualified [`TableReference::Full`] if the table names match.
183 pub fn resolved_eq(&self, other: &Self) -> bool {
184 match self {
185 TableReference::Bare { table } => **table == *other.table(),
186 TableReference::Partial { schema, table } => {
187 **table == *other.table() && other.schema().is_none_or(|s| *s == **schema)
188 }
189 TableReference::Full {
190 catalog,
191 schema,
192 table,
193 } => {
194 **table == *other.table()
195 && other.schema().is_none_or(|s| *s == **schema)
196 && other.catalog().is_none_or(|c| *c == **catalog)
197 }
198 }
199 }
200
201 /// Given a default catalog and schema, ensure this table reference is fully
202 /// resolved
203 pub fn resolve(
204 self,
205 default_catalog: &str,
206 default_schema: &str,
207 ) -> ResolvedTableReference {
208 match self {
209 Self::Full {
210 catalog,
211 schema,
212 table,
213 } => ResolvedTableReference {
214 catalog,
215 schema,
216 table,
217 },
218 Self::Partial { schema, table } => ResolvedTableReference {
219 catalog: default_catalog.into(),
220 schema,
221 table,
222 },
223 Self::Bare { table } => ResolvedTableReference {
224 catalog: default_catalog.into(),
225 schema: default_schema.into(),
226 table,
227 },
228 }
229 }
230
231 /// Forms a string where the identifiers are quoted
232 ///
233 /// # Example
234 /// ```
235 /// # use datafusion_common::TableReference;
236 /// let table_reference = TableReference::partial("myschema", "mytable");
237 /// assert_eq!(table_reference.to_quoted_string(), "myschema.mytable");
238 ///
239 /// let table_reference = TableReference::partial("MySchema", "MyTable");
240 /// assert_eq!(
241 /// table_reference.to_quoted_string(),
242 /// r#""MySchema"."MyTable""#
243 /// );
244 /// ```
245 pub fn to_quoted_string(&self) -> String {
246 match self {
247 TableReference::Bare { table } => quote_identifier(table).to_string(),
248 TableReference::Partial { schema, table } => {
249 format!("{}.{}", quote_identifier(schema), quote_identifier(table))
250 }
251 TableReference::Full {
252 catalog,
253 schema,
254 table,
255 } => format!(
256 "{}.{}.{}",
257 quote_identifier(catalog),
258 quote_identifier(schema),
259 quote_identifier(table)
260 ),
261 }
262 }
263
264 /// Forms a [`TableReference`] by parsing `s` as a multipart SQL
265 /// identifier, normalizing `s` to lowercase.
266 /// See docs on [`TableReference`] for more details.
267 pub fn parse_str(s: &str) -> Self {
268 Self::parse_str_normalized(s, false)
269 }
270
271 /// Forms a [`TableReference`] by parsing `s` as a multipart SQL
272 /// identifier, normalizing `s` to lowercase if `ignore_case` is `false`.
273 /// See docs on [`TableReference`] for more details.
274 pub fn parse_str_normalized(s: &str, ignore_case: bool) -> Self {
275 let table_parts = parse_identifiers_normalized(s, ignore_case);
276
277 Self::from_vec(table_parts).unwrap_or_else(|| Self::Bare { table: s.into() })
278 }
279
280 /// Consume a vector of identifier parts to compose a [`TableReference`]. The input vector
281 /// should contain 1 <= N <= 3 elements in the following sequence:
282 /// ```no_rust
283 /// [<catalog>, <schema>, table]
284 /// ```
285 fn from_vec(mut parts: Vec<String>) -> Option<Self> {
286 match parts.len() {
287 1 => Some(Self::Bare {
288 table: parts.pop()?.into(),
289 }),
290 2 => Some(Self::Partial {
291 table: parts.pop()?.into(),
292 schema: parts.pop()?.into(),
293 }),
294 3 => Some(Self::Full {
295 table: parts.pop()?.into(),
296 schema: parts.pop()?.into(),
297 catalog: parts.pop()?.into(),
298 }),
299 _ => None,
300 }
301 }
302
303 /// Decompose a [`TableReference`] to separate parts. The result vector contains
304 /// at most three elements in the following sequence:
305 /// ```no_rust
306 /// [<catalog>, <schema>, table]
307 /// ```
308 pub fn to_vec(&self) -> Vec<String> {
309 match self {
310 TableReference::Bare { table } => vec![table.to_string()],
311 TableReference::Partial { schema, table } => {
312 vec![schema.to_string(), table.to_string()]
313 }
314 TableReference::Full {
315 catalog,
316 schema,
317 table,
318 } => vec![catalog.to_string(), schema.to_string(), table.to_string()],
319 }
320 }
321}
322
323/// Parse a string into a TableReference, normalizing where appropriate
324///
325/// See full details on [`TableReference::parse_str`]
326impl<'a> From<&'a str> for TableReference {
327 fn from(s: &'a str) -> Self {
328 Self::parse_str(s)
329 }
330}
331
332impl<'a> From<&'a String> for TableReference {
333 fn from(s: &'a String) -> Self {
334 Self::parse_str(s)
335 }
336}
337
338impl From<String> for TableReference {
339 fn from(s: String) -> Self {
340 Self::parse_str(&s)
341 }
342}
343
344impl From<ResolvedTableReference> for TableReference {
345 fn from(resolved: ResolvedTableReference) -> Self {
346 Self::Full {
347 catalog: resolved.catalog,
348 schema: resolved.schema,
349 table: resolved.table,
350 }
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 #[test]
359 fn test_table_reference_from_str_normalizes() {
360 let expected = TableReference::Full {
361 catalog: "catalog".into(),
362 schema: "FOO\".bar".into(),
363 table: "table".into(),
364 };
365 let actual = TableReference::from("catalog.\"FOO\"\".bar\".TABLE");
366 assert_eq!(expected, actual);
367
368 let expected = TableReference::Partial {
369 schema: "FOO\".bar".into(),
370 table: "table".into(),
371 };
372 let actual = TableReference::from("\"FOO\"\".bar\".TABLE");
373 assert_eq!(expected, actual);
374
375 let expected = TableReference::Bare {
376 table: "table".into(),
377 };
378 let actual = TableReference::from("TABLE");
379 assert_eq!(expected, actual);
380
381 // Disable this test for non-sql features so that we don't need to reproduce
382 // things like table function upper case conventions, since those will not
383 // be used if SQL is not selected.
384 #[cfg(feature = "sql")]
385 {
386 // if fail to parse, take entire input string as identifier
387 let expected = TableReference::Bare {
388 table: "TABLE()".into(),
389 };
390 let actual = TableReference::from("TABLE()");
391 assert_eq!(expected, actual);
392 }
393 }
394
395 #[test]
396 fn test_table_reference_to_vector() {
397 let table_reference = TableReference::from("table");
398 assert_eq!(vec!["table".to_string()], table_reference.to_vec());
399
400 let table_reference = TableReference::from("schema.table");
401 assert_eq!(
402 vec!["schema".to_string(), "table".to_string()],
403 table_reference.to_vec()
404 );
405
406 let table_reference = TableReference::from("catalog.schema.table");
407 assert_eq!(
408 vec![
409 "catalog".to_string(),
410 "schema".to_string(),
411 "table".to_string()
412 ],
413 table_reference.to_vec()
414 );
415 }
416}