Skip to main content

rust_ef_mysql/
type_mapping.rs

1pub struct MySqlTypeMapping;
2
3impl MySqlTypeMapping {
4    pub fn map_type(rust_type: &str) -> &'static str {
5        match rust_type {
6            "i16" => "SMALLINT",
7            "i32" => "INT",
8            "i64" => "BIGINT",
9            "u16" => "SMALLINT UNSIGNED",
10            "u32" => "INT UNSIGNED",
11            "u64" => "BIGINT UNSIGNED",
12            "f32" => "FLOAT",
13            "f64" => "DOUBLE",
14            "bool" => "BOOLEAN",
15            "String" => "TEXT",
16            "Vec<u8>" => "BLOB",
17            _ => "TEXT",
18        }
19    }
20
21    pub fn map_auto_increment_type(rust_type: &str) -> &'static str {
22        match rust_type {
23            "i16" => "SMALLINT AUTO_INCREMENT",
24            "i32" => "INT AUTO_INCREMENT",
25            "i64" => "BIGINT AUTO_INCREMENT",
26            _ => "INT AUTO_INCREMENT",
27        }
28    }
29
30    pub fn column_definition(
31        _column_name: &str,
32        rust_type: &str,
33        is_required: bool,
34        is_auto_increment: bool,
35        max_length: Option<usize>,
36    ) -> String {
37        let base_type = if is_auto_increment {
38            Self::map_auto_increment_type(rust_type).to_string()
39        } else {
40            let base = Self::map_type(rust_type);
41            match (base, max_length) {
42                ("TEXT", Some(n)) => format!("VARCHAR({})", n),
43                (t, _) => t.to_string(),
44            }
45        };
46
47        if is_required {
48            format!("{} NOT NULL", base_type)
49        } else {
50            base_type
51        }
52    }
53}