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
118
119
120
121
122
123
124
125
126
use std::fmt;
use std::str;

use nom::bytes::complete::{tag, tag_no_case};
use nom::character::complete::{multispace0, multispace1};
use nom::combinator::{map, opt};
use nom::multi::many0;
use nom::sequence::{pair, terminated, tuple};
use nom::IResult;

use base::error::ParseSQLError;
use base::{CommonParser, DisplayUtil};

/// **Table Definition**
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Table {
    /// Table name
    pub name: String,
    /// Optional table name alias
    pub alias: Option<String>,
    /// Optional schema/database name
    pub schema: Option<String>,
}

impl Table {
    // Parse list of table names.
    // XXX(malte): add support for aliases
    pub fn table_list(i: &str) -> IResult<&str, Vec<Table>, ParseSQLError<&str>> {
        many0(terminated(
            Table::schema_table_reference,
            opt(CommonParser::ws_sep_comma),
        ))(i)
    }

    // Parse a reference to a named schema.table, with an optional alias
    pub fn schema_table_reference(i: &str) -> IResult<&str, Table, ParseSQLError<&str>> {
        map(
            tuple((
                opt(pair(CommonParser::sql_identifier, tag("."))),
                CommonParser::sql_identifier,
                opt(CommonParser::as_alias),
            )),
            |tup| Table {
                name: String::from(tup.1),
                alias: tup.2.map(String::from),
                schema: tup.0.map(|(schema, _)| String::from(schema)),
            },
        )(i)
    }

    // Parse a reference to a named table, with an optional alias
    pub fn table_reference(i: &str) -> IResult<&str, Table, ParseSQLError<&str>> {
        map(
            pair(CommonParser::sql_identifier, opt(CommonParser::as_alias)),
            |tup| Table {
                name: String::from(tup.0),
                alias: tup.1.map(String::from),
                schema: None,
            },
        )(i)
    }

    /// table alias not allowed in DROP/TRUNCATE/RENAME TABLE statement
    pub fn without_alias(i: &str) -> IResult<&str, Table, ParseSQLError<&str>> {
        map(
            tuple((
                opt(pair(CommonParser::sql_identifier, tag("."))),
                CommonParser::sql_identifier,
            )),
            |tup| Table {
                name: String::from(tup.1),
                alias: None,
                schema: tup.0.map(|(schema, _)| String::from(schema)),
            },
        )(i)
    }

    /// db_name.tb_name TO db_name.tb_name
    pub fn schema_table_reference_to_schema_table_reference(
        i: &str,
    ) -> IResult<&str, (Table, Table), ParseSQLError<&str>> {
        map(
            tuple((
                Self::schema_table_reference,
                multispace0,
                tag_no_case("TO"),
                multispace1,
                Self::schema_table_reference,
            )),
            |(from, _, _, _, to)| (from, to),
        )(i)
    }
}

impl fmt::Display for Table {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref schema) = self.schema {
            write!(f, "{}.", DisplayUtil::escape_if_keyword(schema))?;
        }
        write!(f, "{}", DisplayUtil::escape_if_keyword(&self.name))?;
        if let Some(ref alias) = self.alias {
            write!(f, " AS {}", DisplayUtil::escape_if_keyword(alias))?;
        }
        Ok(())
    }
}

impl<'a> From<&'a str> for Table {
    fn from(t: &str) -> Table {
        Table {
            name: String::from(t),
            alias: None,
            schema: None,
        }
    }
}

impl<'a> From<(&'a str, &'a str)> for Table {
    fn from(t: (&str, &str)) -> Table {
        Table {
            name: String::from(t.1),
            alias: None,
            schema: Some(String::from(t.0)),
        }
    }
}