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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#[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: Clone;
    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 IF NOT EXISTS {} 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 IF NOT EXISTS {} 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 insert_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,
        )
    }

    fn update_query_with_params(self) -> (String, Vec<(String, Self::ValueType)>) {
        let pairs = self.map_to_sql();
        let keys = pairs.iter().map(|(k, _)| k).collect::<Vec<_>>();
        let primary_keys_cond = Self::primary_key_columns(std::marker::PhantomData::<Self>)
            .into_iter()
            .map(|v| format!("{} = :{}", v, v))
            .collect::<Vec<_>>()
            .join(" and ");

        (
            format!(
                "UPDATE {} SET {} WHERE {}",
                Self::table_name(std::marker::PhantomData::<Self>),
                keys.iter()
                    .map(|k| format!("{} = :{}", k, k))
                    .collect::<Vec<_>>()
                    .join(", "),
                primary_keys_cond
            ),
            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;
}