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
use anyhow::{anyhow, Result};
use crate::to_sql::{Dialect, ToSql};

#[derive(Debug, Clone, Copy)]
pub enum Type {
    Boolean,
    // integer types
    SmallInt,
    BigInt,
    Integer,
    // float types
    Numeric,
    // byte types
    Bytes,
    // date types
    Date,
    DateTime,
    NaiveDateTime,
    Duration,
    // json types
    Json,
    Jsonb,
    // extension types
    Uuid,
    // string types
    Text,
}

impl Type {
    pub fn from_str(s: &str) -> Result<Self> {
        use Type::*;
        let s = match s {
            "bigint" => BigInt,
            "boolean" => Boolean,
            "date" => Date,
            "bytea" => Bytes,
            "timestamp with time zone" => DateTime,
            "timestamp without time zone" => NaiveDateTime,
            "interval" => Duration,
            "json" => Json,
            "jsonb" => Jsonb,
            "numeric" => Numeric,
            "uuid" => Uuid,
            "smallint" => SmallInt,
            "text" => Text,
            "character varying" => Text,
            "integer" => Integer,
            _ => return Err(anyhow!("Unknown type: {}", s)),
        };
        Ok(s)
    }
}

impl ToSql for Type {
    fn write_sql(&self, buf: &mut String, _: Dialect) {
        use self::Type::*;
        let s = match self {
            BigInt => "bigint",
            Boolean => "boolean",
            Bytes => "bytea",
            Date => "date",
            DateTime => "timestamptz",
            NaiveDateTime => "timestamp without time zone",
            Duration => "interval",
            Json => "json",
            Jsonb => "jsonb",
            Numeric => "numeric",
            SmallInt => "smallint",
            Uuid => "uuid",
            Integer => "integer",
            Text => "character varying",
        };
        buf.push_str(s);
    }
}