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
use {
crate::{ExecuteError, JoinError, Result, Value},
serde::Serialize,
sqlparser::ast::{ObjectName as AstObjectName, TableFactor},
std::fmt::Debug,
};
pub type Alias = Option<String>;
pub type Label = String;
pub type Row = Vec<Value>;
pub type LabelsAndRows = (Vec<Label>, Vec<Row>);
pub type ObjectName = Vec<String>;
#[derive(Debug, Clone)]
pub struct ColumnInfo {
pub table: ComplexTableName,
pub name: String,
pub index: Option<String>,
}
pub(crate) fn get_first_name(names: &[AstObjectName]) -> Result<String> {
names
.get(0)
.and_then(|name| name.0.get(0).map(|name| name.value.clone()))
.ok_or(ExecuteError::ObjectNotRecognised.into())
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ComplexTableName {
pub database: Option<String>,
pub alias: Alias,
pub name: String,
}
impl TryFrom<&AstObjectName> for ComplexTableName {
type Error = crate::Error;
fn try_from(name: &AstObjectName) -> Result<Self> {
let name_parts = name.0.len();
if !(1..=2).contains(&name_parts) {
return Err(JoinError::UnimplementedNumberOfComponents.into());
}
let database = if name_parts == 2 {
Some(name.0.get(0).unwrap().value.clone())
} else {
None
};
let name = name.0.last().unwrap().value.clone();
Ok(Self {
database,
name,
alias: None,
})
}
}
impl TryFrom<TableFactor> for ComplexTableName {
type Error = crate::Error;
fn try_from(table: TableFactor) -> Result<Self> {
match table {
TableFactor::Table { name, alias, .. } => {
let name_parts = name.0.len();
if !(1..=2).contains(&name_parts) {
return Err(JoinError::UnimplementedNumberOfComponents.into());
}
let database = if name_parts == 2 {
Some(name.0.get(0).unwrap().value.clone())
} else {
None
};
let name = name.0.last().unwrap().value.clone();
let alias = alias.map(|alias| alias.name.value);
Ok(Self {
database,
name,
alias,
})
}
_ => Err(JoinError::UnimplementedTableType.into()),
}
}
}
impl ColumnInfo {
pub fn of_name(name: String) -> Self {
ColumnInfo {
table: ComplexTableName {
database: None,
name: String::new(),
alias: None,
},
name,
index: None,
}
}
}
impl PartialEq<ObjectName> for ColumnInfo {
fn eq(&self, other: &ObjectName) -> bool {
let mut other = other.clone();
other.reverse();
let names_eq = other
.get(0)
.map(|column| column == &self.name)
.unwrap_or(false);
let tables_eq = other
.get(1)
.map(|table| {
table == &self.table.name
|| self
.table
.alias
.as_ref()
.map(|alias| table == alias)
.unwrap_or(false)
})
.unwrap_or(true);
names_eq && tables_eq
}
}