#[derive(Debug, Clone, Copy)]
pub struct ResolvedTableReference<'a> {
pub catalog: &'a str,
pub schema: &'a str,
pub table: &'a str,
}
impl<'a> std::fmt::Display for ResolvedTableReference<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}.{}", self.catalog, self.schema, self.table)
}
}
#[derive(Debug, Clone, Copy)]
pub enum TableReference<'a> {
Bare {
table: &'a str,
},
Partial {
schema: &'a str,
table: &'a str,
},
Full {
catalog: &'a str,
schema: &'a str,
table: &'a str,
},
}
#[derive(Debug, Clone)]
pub enum OwnedTableReference {
Bare {
table: String,
},
Partial {
schema: String,
table: String,
},
Full {
catalog: String,
schema: String,
table: String,
},
}
impl OwnedTableReference {
pub fn as_table_reference(&self) -> TableReference<'_> {
match self {
Self::Bare { table } => TableReference::Bare { table },
Self::Partial { schema, table } => TableReference::Partial { schema, table },
Self::Full {
catalog,
schema,
table,
} => TableReference::Full {
catalog,
schema,
table,
},
}
}
}
impl std::fmt::Display for OwnedTableReference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OwnedTableReference::Bare { table } => write!(f, "{table}"),
OwnedTableReference::Partial { schema, table } => {
write!(f, "{schema}.{table}")
}
OwnedTableReference::Full {
catalog,
schema,
table,
} => write!(f, "{catalog}.{schema}.{table}"),
}
}
}
impl<'a> From<&'a OwnedTableReference> for TableReference<'a> {
fn from(r: &'a OwnedTableReference) -> Self {
r.as_table_reference()
}
}
impl<'a> TableReference<'a> {
pub fn table(&self) -> &str {
match self {
Self::Full { table, .. }
| Self::Partial { table, .. }
| Self::Bare { table } => table,
}
}
pub fn resolve(
self,
default_catalog: &'a str,
default_schema: &'a str,
) -> ResolvedTableReference<'a> {
match self {
Self::Full {
catalog,
schema,
table,
} => ResolvedTableReference {
catalog,
schema,
table,
},
Self::Partial { schema, table } => ResolvedTableReference {
catalog: default_catalog,
schema,
table,
},
Self::Bare { table } => ResolvedTableReference {
catalog: default_catalog,
schema: default_schema,
table,
},
}
}
pub fn parse_str(s: &'a str) -> Self {
let parts: Vec<&str> = s.split('.').collect();
match parts.len() {
1 => Self::Bare { table: s },
2 => Self::Partial {
schema: parts[0],
table: parts[1],
},
3 => Self::Full {
catalog: parts[0],
schema: parts[1],
table: parts[2],
},
_ => Self::Bare { table: s },
}
}
}
impl<'a> From<&'a str> for TableReference<'a> {
fn from(s: &'a str) -> Self {
Self::parse_str(s)
}
}
impl<'a> From<ResolvedTableReference<'a>> for TableReference<'a> {
fn from(resolved: ResolvedTableReference<'a>) -> Self {
Self::Full {
catalog: resolved.catalog,
schema: resolved.schema,
table: resolved.table,
}
}
}