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
use super::Modelable;
use sqlite::Bindable;

macro_rules! integral {
    ($i:ty) => {
        impl Modelable for $i {
            fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
                (*self as i64).bind(stmt, col)
            }
            fn build_from(
                stmt: &sqlite::Statement,
                col_offset: usize,
            ) -> sqlite::Result<(Self, usize)>
            where
                Self: Sized,
            {
                stmt.read::<i64>(col_offset).map(|x| (x as Self, 1))
            }

            fn column_type() -> &'static str
            where
                Self: Sized,
            {
                "integer"
            }
        }
    };
}

integral!(i8);
integral!(u8);
integral!(i16);
integral!(u16);
integral!(i32);
integral!(u32);
integral!(i64);
integral!(u64);
integral!(usize);

impl Modelable for f64 {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        self.bind(stmt, col)
    }
    fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        stmt.read(col_offset).map(|x| (x, 1))
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        "numeric"
    }
}

impl Modelable for bool {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        let val = if self == &true { 1i64 } else { 0i64 };
        val.bind(stmt, col)
    }
    fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        stmt.read(col_offset).map(|x: i64| (x != 0, 1))
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        "integer"
    }
}

impl<'a> Modelable for &'a str {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        self.bind(stmt, col)
    }
    fn build_from(_stmt: &sqlite::Statement, _col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        unreachable!("sqlite only gives Strings back, not &strs!");
    }

    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        "text"
    }
}

impl Modelable for str {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        self.bind(stmt, col)
    }
}

impl Modelable for std::string::String {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        self.as_str().bind(stmt, col)
    }
    fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        stmt.read(col_offset).map(|x| (x, 1))
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        "text"
    }
}

impl<'a> Modelable for &'a [u8] {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        self.bind(stmt, col)
    }
    fn build_from(_stmt: &sqlite::Statement, _col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        unreachable!("sqlite only gives Vec<u8> back, not &[u8]!");
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        "blob"
    }
}

impl<'a, T: Modelable> Modelable for &'a T {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        <T as Modelable>::bind_to(self, stmt, col)
    }
    fn build_from(_stmt: &sqlite::Statement, _col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        unreachable!();
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        unreachable!();
    }
}

impl<T: Modelable> Modelable for Option<T> {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        match self.as_ref() {
            Some(val) => val.bind_to(stmt, col),
            None => stmt.bind(col, &sqlite::Value::Null),
        }
    }
    fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        // note: this is needlessly expensive since we read things twice.
        let val = stmt.read::<sqlite::Value>(col_offset)?;
        if val.kind() == sqlite::Type::Null {
            Ok((None, 1))
        } else {
            let (val, size) = T::build_from(stmt, col_offset)?;
            Ok((Some(val), size))
        }
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        T::column_type()
    }
}

impl<T: Modelable + serde::Serialize + serde::de::DeserializeOwned + 'static> Modelable for Vec<T> {
    fn bind_to(&self, stmt: &mut sqlite::Statement, col: usize) -> sqlite::Result<()> {
        // We serialize Vec<u8> types directly as a blob
        if std::mem::size_of::<T>() == 1
            && std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>()
        {
            // this bit is unsafe, but is perfectly reasonable...
            let byte_slice =
                unsafe { std::slice::from_raw_parts(self.as_ptr() as *const u8, self.len()) };
            return byte_slice.bind_to(stmt, col);
        }
        serde_json::to_string(self).unwrap().bind_to(stmt, col)
    }
    fn build_from(stmt: &sqlite::Statement, col_offset: usize) -> sqlite::Result<(Self, usize)>
    where
        Self: Sized,
    {
        // Deserialize one-byte types directly from the blob
        if std::mem::size_of::<T>() == 1
            && std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>()
        {
            let blob: Vec<u8> = stmt.read(col_offset)?;

            // we know the return value is a u8 because the typeid matches, so while normally this
            // is hilariously unsafe, right now it's perfectly okay.
            Ok((unsafe { std::mem::transmute::<Vec<u8>, Vec<T>>(blob) }, 1))
        } else {
            let s = String::build_from(stmt, col_offset)?;
            Ok((
                serde_json::from_str::<Vec<T>>(s.0.as_str()).map_err(|e| sqlite::Error {
                    code: None,
                    message: Some(e.to_string()),
                })?,
                1,
            ))
        }
    }
    fn column_type() -> &'static str
    where
        Self: Sized,
    {
        "blob"
    }
}