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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
// vim: set expandtab ts=4 sw=4:

use std::fmt; 
use crate::keywords::{escape_if_keyword};
use crate::{
    SqlType,
    create::{
        CodecList,
        ColumnTTL,
    },
};

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Column {
    pub name: String,
    pub alias: Option<String>,
    pub table: Option<String>,
}

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

impl<'a> From<&'a str> for Column {
    fn from(c: &str) -> Column {
        match c.find(".") {
            None => Column {
                name: String::from(c),
                alias: None,
                table: None,
            },
            Some(i) => Column {
                name: String::from(&c[i + 1..]),
                alias: None,
                table: Some(String::from(&c[0..i])),
            },
        }
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum ColumnOption {
    DefaultValue(String),
    Materialized(String),
}

impl fmt::Display for ColumnOption {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ColumnOption::DefaultValue(ref literal) => {
                write!(f, "DEFAULT {}", literal.to_string())
            }
            ColumnOption::Materialized(ref literal) => {
                write!(f, "MATERIALIZED {}", literal.to_string())
            }
        }
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ColumnSpecification {
    pub column: Column,
    pub sql_type: SqlType,
    pub codec: Option<CodecList>,
    pub ttl: Option<ColumnTTL>,
    pub nullable: bool,
    pub option: Option<ColumnOption>,
    pub comment: Option<String>,
    pub lowcardinality: bool,
}

impl fmt::Display for ColumnSpecification {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "`{}` ", escape_if_keyword(&self.column.name))?;
        match (self.lowcardinality, self.nullable) {
            (false,false) => write!(f, "{}", self.sql_type),
            (true,false) => write!(f, "LowCardinality({})", self.sql_type),
            (false,true) => write!(f, "Nullable({})", self.sql_type),
            (true,true) => write!(f, "LowCardinality(Nullable({}))", self.sql_type),
        }?;
        if let Some(ref opt) = self.option {
            write!(f, " {}", opt)?;
        }
        if let Some(ref comment) = self.comment {
            write!(f, " COMMENT '{}'", comment)?;
        }
        if let Some(ref codec) = self.codec {
            write!(f, " CODEC({})",
                codec.0
                    .iter()
                    .map(|c| format!("{}", c)) 
                    .collect::<Vec<String>>()
                    .join(", ")
            )?;
        }
        if let Some(ref ttl) = self.ttl {
            write!(f, " {}", ttl)?;
        }
        Ok(())
    }
}

impl ColumnSpecification {
    pub fn new(column: Column, sql_type: SqlType) -> ColumnSpecification {
        ColumnSpecification {
            column,
            sql_type,
            codec: None,
            ttl: None,
            nullable: false,
            option: None,
            comment: None,
            lowcardinality: false,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        TypeSize16,
    };

    #[test]
    fn t_column_display() {
        let cs = ColumnSpecification::new(
            "time_local".into(),
            SqlType::DateTime(None)
        );

        let exp = "`time_local` DateTime";
        assert_eq!(exp, format!("{}", cs).as_str());
    }

    #[test]
    fn t_column_display_enum() {
        let cs = ColumnSpecification::new(
            "device".into(),
            SqlType::Enum(Some(TypeSize16::B8), vec![("desktop".into(), 1), ("mobile".into(),2)]),
        );

        let exp = "`device` Enum8('desktop' = 1, 'mobile' = 2)";
        assert_eq!(exp, format!("{}", cs).as_str());
    }

}