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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
use std::fmt::Display;

use serde::{Deserialize, Serialize};

use crate::ToSqlite;

/// A column type and its options / properties
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ColumnType {
    /// Identifier column type (Primary Key) which is a UUID (TEXT)
    Identifier(ColumnTypeOptions),
    /// Foreign Key column type with the table name
    ForeignKey(ColumnTypeOptions),
    /// Text column type with options
    Text(ColumnTypeOptions),
    /// Integer column type with options
    Integer(ColumnTypeOptions),
    /// Boolean column type with options
    Boolean(ColumnTypeOptions),
    /// Blob / Vec / List column type with options
    Blob(ColumnTypeOptions),
}

impl Display for ColumnType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ColumnType::Identifier(_) => write!(f, "PrimaryKey"),
            ColumnType::ForeignKey(fk) => write!(f, "ForeignKey<{}>", fk),
            ColumnType::Text(_) => write!(f, "Text"),
            ColumnType::Integer(_) => write!(f, "Integer"),
            ColumnType::Boolean(_) => write!(f, "Boolean"),
            ColumnType::Blob(_) => write!(f, "Blob"),
        }
    }
}

impl ToSqlite for ColumnType {
    fn on_create(&self, query: &crate::QueryBuilder) -> Result<String, crate::Error> {
        Ok(match self {
            ColumnType::Identifier(opts) => {
                format!("INTEGER {}", opts.on_create(query)?)
            }
            ColumnType::ForeignKey(options) => {
                // TODO(geekmasher): What type is the foreign key?
                let opts = options.on_create(query)?;
                if opts.is_empty() {
                    return Ok("INTEGER".to_string());
                }
                format!("INTEGER {}", opts)
            }
            ColumnType::Text(options) => {
                let opts = options.on_create(query)?;
                if opts.is_empty() {
                    return Ok("TEXT".to_string());
                }
                format!("TEXT {}", options.on_create(query)?)
            }
            ColumnType::Integer(options) => {
                let opts = options.on_create(query)?;
                if opts.is_empty() {
                    return Ok("INTEGER".to_string());
                }
                format!("INTEGER {}", options.on_create(query)?)
            }
            ColumnType::Boolean(options) => {
                let opts = options.on_create(query)?;
                if opts.is_empty() {
                    return Ok("INTEGER".to_string());
                }
                format!("INTEGER {}", options.on_create(query)?)
            }
            ColumnType::Blob(options) => {
                let opts = options.on_create(query)?;
                if opts.is_empty() {
                    return Ok("BLOB".to_string());
                }
                format!("BLOB {}", options.on_create(query)?)
            }
        })
    }
}

impl ColumnType {
    /// Check if the column type is a primary key
    pub fn is_primary_key(&self) -> bool {
        matches!(self, ColumnType::Identifier(_))
    }

    /// Check if the column type is an auto increment
    pub fn is_auto_increment(&self) -> bool {
        match self {
            ColumnType::Identifier(opts) => opts.auto_increment,
            ColumnType::Integer(opts) => opts.auto_increment,
            _ => false,
        }
    }

    /// Check if the column type is a foreign key
    pub fn is_foreign_key(&self) -> bool {
        matches!(self, ColumnType::ForeignKey(_))
    }
    /// Get the foreign key table & column name
    pub fn is_foreign_key_table(&self, table: &String) -> bool {
        match self {
            ColumnType::ForeignKey(opts) => {
                let (t, _) = opts.foreign_key.split_once('.').unwrap();
                t == table
            }
            _ => false,
        }
    }
}

/// Column type options / properties
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ColumnTypeOptions {
    /// Is the column a primary key for the table
    pub primary_key: bool,
    /// Is the column a foreign key
    /// TableName::ColumnName
    pub foreign_key: String,
    /// Is the column unique
    pub unique: bool,
    /// Is the column nullable
    pub not_null: bool,
    /// Auto increment the column
    pub auto_increment: bool,
}

impl ColumnTypeOptions {
    pub(crate) fn primary_key() -> Self {
        ColumnTypeOptions {
            primary_key: true,
            auto_increment: true,
            ..Default::default()
        }
    }

    pub(crate) fn foreign_key(key: String) -> Self {
        ColumnTypeOptions {
            primary_key: false,
            foreign_key: key,
            unique: false,
            not_null: true,
            auto_increment: false,
        }
    }

    pub(crate) fn unique() -> Self {
        ColumnTypeOptions {
            unique: true,
            ..Default::default()
        }
    }

    pub(crate) fn null() -> Self {
        ColumnTypeOptions {
            not_null: false,
            ..Default::default()
        }
    }
}

impl Display for ColumnTypeOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if !self.foreign_key.is_empty() {
            return write!(f, "{}", self.foreign_key);
        }
        Err(std::fmt::Error)
    }
}

impl ToSqlite for ColumnTypeOptions {
    fn on_create(&self, _query: &crate::QueryBuilder) -> Result<String, crate::Error> {
        let mut sql = Vec::new();
        if self.not_null {
            sql.push("NOT NULL");
        }
        if self.primary_key {
            sql.push("PRIMARY KEY");
        }
        if self.unique {
            sql.push("UNIQUE");
        }
        if self.auto_increment {
            sql.push("AUTOINCREMENT");
        }
        Ok(sql.join(" "))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn query() -> crate::QueryBuilder {
        crate::QueryBuilder::default()
    }

    #[test]
    fn test_column_type_boolean() {
        let column_type = ColumnType::Boolean(ColumnTypeOptions::default());
        let query = query();
        assert_eq!(column_type.on_create(&query).unwrap(), "INTEGER");
    }

    #[test]
    fn test_column_type_to_sql() {
        let query = query();
        let column_type = ColumnType::Text(ColumnTypeOptions::default());
        assert_eq!(column_type.on_create(&query).unwrap(), "TEXT");

        let column_type = ColumnType::Integer(ColumnTypeOptions::default());
        assert_eq!(column_type.on_create(&query).unwrap(), "INTEGER");
    }

    #[test]
    fn test_column_type_options_to_sql() {
        let query = query();
        let column_type_options = ColumnTypeOptions::default();
        assert_eq!(column_type_options.on_create(&query).unwrap(), "");

        let column_type_options = ColumnTypeOptions {
            primary_key: true,
            ..Default::default()
        };
        assert_eq!(
            column_type_options.on_create(&query).unwrap(),
            "PRIMARY KEY"
        );

        let column_type_options = ColumnTypeOptions {
            primary_key: true,
            not_null: true,
            ..Default::default()
        };
        assert_eq!(
            column_type_options.on_create(&query).unwrap(),
            "NOT NULL PRIMARY KEY"
        );
    }
}