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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#![allow(dead_code)]
use indoc::formatdoc;
use num::Float;
#[cfg(feature = "python")]
use pyo3::prelude::*;
#[cfg(feature = "sql")]
use sqlparser::ast::{ColumnDef, DataType, Expr, Ident, Value};
pub trait TValue {}

#[derive(Hash, PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "python", derive(FromPyObject))]
pub struct IntegerValue {
    inner: i64,
}
impl IntegerValue {
    pub fn try_from(x: String) -> Result<Self, String> {
        match x.parse::<i64>() {
            Ok(val) => Ok(Self { inner: val }),
            Err(_) => Err(format!("Could not parse {} as int.", &x).into()),
        }
    }
    pub fn as_sql(&self) -> String {
        format!("{}", self.inner).to_string()
    }
}
#[derive(Hash, PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "python", derive(FromPyObject))]
pub struct StringValue {
    inner: String,
}
impl StringValue {
    pub fn from(inner: String) -> Self {
        Self { inner }
    }
    pub fn as_sql(&self) -> String {
        format!("\"{}\"", self.inner).to_string()
    }
}
#[derive(Hash, PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "python", derive(FromPyObject))]
pub struct FloatValue {
    sign: i8,
    mantissa: u64,
    exponent: i16,
}
impl FloatValue {
    pub fn try_from(x: String) -> Result<Self, String> {
        match x.parse::<f64>() {
            Ok(val) => {
                let (mantissa, exponent, sign) = Float::integer_decode(val);
                Ok(Self {
                    sign,
                    mantissa,
                    exponent,
                })
            }
            Err(_) => Err(format!("Could not parse {} as float.", &x).into()),
        }
    }
    pub fn as_sql(&self) -> String {
        let num = 2.0f64;
        let sign_f = self.sign as f64;
        let mantissa_f = self.mantissa as f64;
        let exponent_f = num.powf(self.exponent as f64);
        format!("{}", (sign_f * mantissa_f * exponent_f)).to_string()
    }
}

impl TValue for IntegerValue {}
impl TValue for StringValue {}
impl TValue for FloatValue {}

#[derive(Hash, PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "python", derive(FromPyObject))]
pub enum AttributeValue {
    IntegerValue(IntegerValue),
    StringValue(StringValue),
    FloatValue(FloatValue),
}
impl AttributeValue {
    #[cfg(feature = "sql")]
    pub fn try_from(x: Expr) -> Result<Self, String> {
        match x {
            Expr::Value(val) => match val {
                Value::Number(inner, _) => match inner.contains(".") {
                    true => Ok(Self::FloatValue(FloatValue::try_from(inner)?)),
                    false => Ok(Self::IntegerValue(IntegerValue::try_from(inner)?)),
                },
                Value::SingleQuotedString(inner) => Ok(Self::StringValue(StringValue::from(inner))),
                _ => Err("Only numbers and singlue quoted strings supported as literals".into()),
            },
            _ => Err("Only values supported as nodes".into()),
        }
    }
    pub fn as_sql(&self) -> String {
        match &self {
            AttributeValue::IntegerValue(x) => x.as_sql(),
            AttributeValue::StringValue(x) => x.as_sql(),
            AttributeValue::FloatValue(x) => x.as_sql(),
        }
    }
}

pub trait TAttribute
where
    Self::Value: TValue,
{
    type Value;
    fn get_name(&self) -> &String;
    fn get_comment(&self) -> &Option<String>;
    fn is_nullable(&self) -> bool;
}
pub trait TPrestoAttribute: TAttribute {
    fn get_presto_type(&self) -> String;
    fn get_presto_schema(&self, max_attribute_length: usize) -> String {
        let name = self.get_name();
        let num_middle_spaces = (max_attribute_length - name.len()) + 1;
        let spaces = (0..num_middle_spaces).map(|_| " ").collect::<String>();
        let first_line = format!("{}{}{}", self.get_name(), spaces, self.get_presto_type(),);
        if let Some(comment) = self.get_comment() {
            let formatted_with_comment = formatdoc!(
                "
                {first_line}
                     COMMENT '{comment}'",
                first_line = first_line,
                comment = comment.trim().replace("'", "\\'").to_string()
            );
            return formatted_with_comment;
        }
        first_line
    }
}
pub trait TOrcAttribute: TAttribute {
    fn get_orc_type(&self) -> String;
    fn get_orc_schema(&self) -> String {
        format!("{}:{}", self.get_name(), self.get_orc_type()).to_string()
    }
}
#[cfg(feature = "sql")]
pub trait TSQLAttribute: TAttribute {
    fn get_sql_type(&self) -> DataType;
    fn get_coldef(&self) -> ColumnDef {
        ColumnDef {
            name: Ident::new(self.get_name()),
            data_type: self.get_sql_type(),
            collation: None,
            // TODO: add comments here
            options: Vec::new(),
        }
    }
}

pub trait TSQLiteAttribute: TAttribute {
    fn get_sqlite_type(&self) -> String;
    fn get_sqlite_coldef(&self) -> String {
        format!("{} {}", self.get_name(), self.get_sqlite_type()).to_string()
    }
}
pub trait TPostgresAttribute: TAttribute {
    fn get_postgres_type(&self) -> String;
    fn get_postgres_coldef(&self) -> String {
        format!(
            "{} {}{}",
            self.get_name(),
            self.get_postgres_type(),
            match self.is_nullable() {
                true => "NOT NULL",
                false => "",
            },
        )
        .to_string()
    }
    fn psycopg2_value_json_serializable(&self) -> bool {
        true
    }
}
pub trait TBigQueryAttribute: TAttribute {
    fn get_bigquery_type(&self) -> String;
    fn get_bigquery_coldef(&self) -> String {
        format!("{} {}", self.get_name(), self.get_bigquery_type()).to_string()
    }
}
include!(concat!(env!("OUT_DIR"), "/attributes.rs"));