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
184
185
186
187
188
189
190
191
192
193
194
195
196
#[derive(Clone, Debug, PartialEq)]
pub struct FieldAttribute {
    pub size: Option<i32>,
    pub unique: Option<bool>,
    pub not_null: Option<bool>,
}

impl Default for FieldAttribute {
    fn default() -> Self {
        FieldAttribute {
            size: None,
            unique: None,
            not_null: None,
        }
    }
}

pub fn create_column_query(
    column_name: String,
    column_type: String,
    attr: FieldAttribute,
) -> String {
    [
        &[column_name.as_str(), column_type.as_str()],
        vec![
            if attr.unique.unwrap_or(false) {
                Some("UNIQUE")
            } else {
                None
            },
            if attr.not_null.unwrap_or(false) {
                Some("NOT NULL")
            } else {
                None
            },
        ]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .as_slice(),
    ]
    .concat()
    .join(" ")
}

pub trait SQLMapper: Sized {
    type ValueType;
    fn map_from_sql(_: std::collections::HashMap<String, Self::ValueType>) -> Self;
}

pub trait SQLTable: SQLMapper {
    fn table_name(_: std::marker::PhantomData<Self>) -> String;
    fn schema_of(_: std::marker::PhantomData<Self>) -> Vec<(String, String, FieldAttribute)>;

    fn primary_key_columns(_: std::marker::PhantomData<Self>) -> Vec<String>;

    fn constraint_primary_key_query(ty: std::marker::PhantomData<Self>) -> String {
        let columns = SQLTable::primary_key_columns(ty);
        format!("CONSTRAINT primary_key PRIMARY KEY({})", columns.join(","))
    }

    fn map_to_sql(self) -> Vec<(String, Self::ValueType)>;

    fn create_index_query(
        ty: std::marker::PhantomData<Self>,
        index_name: &'static str,
        index_keys: Vec<&'static str>,
    ) -> String {
        let schema = SQLTable::schema_of(ty);
        let table_name = SQLTable::table_name(ty);
        // search if specified keys exist
        for key in index_keys.iter() {
            if !schema
                .iter()
                .map(|(column_name, _, _)| column_name.as_str())
                .collect::<Vec<&str>>()
                .contains(key)
            {
                panic!("index: column {} is not field of {}", key, table_name)
            }
        }
        format!(
            "CREATE INDEX {} ON {}({});",
            index_name,
            table_name,
            index_keys.join(","),
        )
    }

    fn create_unique_index_query(
        ty: std::marker::PhantomData<Self>,
        index_name: &'static str,
        index_keys: Vec<&'static str>,
    ) -> String {
        let schema = SQLTable::schema_of(ty);
        let table_name = SQLTable::table_name(ty);
        // search if specified keys exist
        for key in index_keys.iter() {
            if !schema
                .iter()
                .map(|(column_name, _, _)| column_name.as_str())
                .collect::<Vec<&str>>()
                .contains(key)
            {
                panic!("index: column {} is not field of {}", key, table_name)
            }
        }

        format!(
            "CREATE UNIQUE INDEX {} ON {}({});",
            index_name,
            table_name,
            index_keys.join(","),
        )
    }

    fn create_table_query(ty: std::marker::PhantomData<Self>) -> String {
        let schema = SQLTable::schema_of(ty);

        format!(
            "CREATE TABLE IF NOT EXISTS {} ({}, {})",
            SQLTable::table_name(ty),
            schema
                .into_iter()
                .map(|(name, typ, attr)| create_column_query(name, typ, attr))
                .collect::<Vec<_>>()
                .as_slice()
                .join(", "),
            SQLTable::constraint_primary_key_query(ty),
        )
    }

    fn save_query_with_params(self) -> (String, Vec<(String, Self::ValueType)>) {
        let pairs = self.map_to_sql();
        let keys = pairs.iter().map(|(k, _)| k).collect::<Vec<_>>();

        (
            format!(
                "INSERT INTO {} ({}) VALUES ({})",
                Self::table_name(std::marker::PhantomData::<Self>),
                keys.iter()
                    .map(|k| k.as_str())
                    .collect::<Vec<_>>()
                    .join(", "),
                keys.iter()
                    .map(|s| format!(":{}", s))
                    .collect::<Vec<_>>()
                    .as_slice()
                    .join(", "),
            ),
            pairs,
        )
    }
}

pub fn table_name<T: SQLTable>() -> String {
    SQLTable::table_name(std::marker::PhantomData::<T>)
}

pub fn schema_of<T: SQLTable>() -> Vec<(String, String, FieldAttribute)> {
    SQLTable::schema_of(std::marker::PhantomData::<T>)
}

pub fn primary_key_columns<T: SQLTable>() -> Vec<String> {
    SQLTable::primary_key_columns(std::marker::PhantomData::<T>)
}

pub fn create_index_query<T: SQLTable>(
    index_name: &'static str,
    index_keys: Vec<&'static str>,
) -> String {
    SQLTable::create_index_query(std::marker::PhantomData::<T>, index_name, index_keys)
}

pub fn create_unique_index_query<T: SQLTable>(
    index_name: &'static str,
    index_keys: Vec<&'static str>,
) -> String {
    SQLTable::create_unique_index_query(std::marker::PhantomData::<T>, index_name, index_keys)
}

pub fn map_from_sql<T: SQLMapper>(h: std::collections::HashMap<String, T::ValueType>) -> T {
    SQLMapper::map_from_sql(h)
}

pub fn create_table_query<T: SQLTable>() -> String {
    SQLTable::create_table_query(std::marker::PhantomData::<T>)
}

pub trait SQLValue<Type> {
    // Varchar type requires the size in the type representation, so we need size argument here
    fn column_type(_: std::marker::PhantomData<Type>, size: i32) -> String;

    fn serialize(_: Type) -> Self;
    fn deserialize(self) -> Type;
}