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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//! # The XML `<database>` format
//!
//! Before the FDB file format was created, older versions of the client used an XML
//! file to store the client database. This was also used for LUPs to add their data
//! independently of the rest of the game.

use displaydoc::Display;
use quick_xml::{events::Event, Reader};
use std::{collections::HashMap, error::Error, io::BufRead, str::FromStr};

use super::common::{expect_elem, expect_named_elem, XmlError};

#[cfg(feature = "serialize")]
use serde::{
    de::{self, Unexpected, Visitor},
    Deserialize, Deserializer,
};
#[cfg(feature = "serialize")]
use std::fmt;

/// The value types for the database
///
/// This is a rustic representation of the data types in Transact-SQL that
/// were/are used in the database.
///
/// See: <https://docs.microsoft.com/en-us/sql/t-sql/data-types>
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ValueType {
    /// `bit`
    Bit,

    /// `float`
    Float,
    /// `real`
    Real,

    /// `int`
    Int,
    /// `bigint`
    BigInt,
    /// `smallint`
    SmallInt,
    /// `tinyint`
    TinyInt,

    /// `binary`
    Binary,
    /// `varbinary`
    VarBinary,

    /// `char`
    Char,
    /// `varchar`
    VarChar,

    /// `nchar`
    NChar,
    /// `nvarchar`
    NVarChar,

    /// `ntext`
    NText,
    /// `text`
    Text,
    /// `image`
    Image,

    /// `datetime`
    DateTime,
    /// `xml`
    Xml,
    /// `null`
    Null,
    ///'smalldatetime'
    SmallDateTime,
}

#[cfg(feature = "serialize")]
impl<'de> Deserialize<'de> for ValueType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(ValueTypeVisitor)
    }
}

#[derive(Debug, Display)]
/// Unknown value type '{0}'
pub struct UnknownValueType(String);

impl Error for UnknownValueType {}

impl FromStr for ValueType {
    type Err = UnknownValueType;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "bit" => Ok(Self::Bit),

            "float" => Ok(Self::Float),
            "real" => Ok(Self::Real),

            "int" => Ok(Self::Int),
            "bigint" => Ok(Self::BigInt),
            "smallint" => Ok(Self::SmallInt),
            "tinyint" => Ok(Self::TinyInt),

            "binary" => Ok(Self::Binary),
            "varbinary" => Ok(Self::VarBinary),

            "char" => Ok(Self::Char),
            "varchar" => Ok(Self::VarChar),

            "nchar" => Ok(Self::NChar),
            "nvarchar" => Ok(Self::NVarChar),

            "text" => Ok(Self::Text),
            "ntext" => Ok(Self::NText),
            "image" => Ok(Self::Image),

            "datetime" => Ok(Self::DateTime),
            "xml" => Ok(Self::Xml),
            "null" => Ok(Self::Null),

            "smalldatetime" => Ok(Self::SmallDateTime),

            _ => Err(UnknownValueType(s.to_owned())),
        }
    }
}

#[cfg(feature = "serialize")]
struct ValueTypeVisitor;

#[cfg(feature = "serialize")]
impl<'de> Visitor<'de> for ValueTypeVisitor {
    type Value = ValueType;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("T-SQL value type")
    }

    fn visit_str<E>(self, value: &str) -> Result<ValueType, E>
    where
        E: de::Error,
    {
        FromStr::from_str(value)
            .map_err(|_| E::invalid_value(Unexpected::Other(value), &"T-SQL value type"))
    }
}

/// A row of the database
#[cfg_attr(feature = "serialize", derive(Deserialize))]
#[derive(Debug, Eq, PartialEq)]
pub struct Row(HashMap<String, String>);

/// Expects an opening `<database>`
pub fn expect_database<B: BufRead>(
    xml: &mut Reader<B>,
    buf: &mut Vec<u8>,
) -> Result<Option<String>, XmlError> {
    expect_named_elem(xml, buf, "database", None)
}

/// Expects an opening `<table>` tag or a closing `</database>` tag
pub fn expect_table<B: BufRead>(
    xml: &mut Reader<B>,
    buf: &mut Vec<u8>,
) -> Result<Option<String>, XmlError> {
    expect_named_elem(xml, buf, "table", Some("database"))
}

/// Expects an opening `<columns>` tag
pub fn expect_columns<B: BufRead>(xml: &mut Reader<B>, buf: &mut Vec<u8>) -> Result<(), XmlError> {
    expect_elem(xml, buf, "columns")
}

/// Expects an opening `<rows>` tag
pub fn expect_rows<B: BufRead>(xml: &mut Reader<B>, buf: &mut Vec<u8>) -> Result<(), XmlError> {
    expect_elem(xml, buf, "rows")
}

/// The information on a column
#[cfg_attr(feature = "serialize", derive(Deserialize))]
pub struct Column {
    /// The name of the column
    pub name: String,
    /// The data type of the column
    pub r#type: ValueType,
}

/*#[derive(Deserialize)]
/// The Columns struct
pub struct Columns {
    /// The columns
    columns: Vec<Column>
}*/

/// Expects an empty `<column …/>` tag or a closing `</columns>` tag
pub fn expect_column_or_end_columns<B: BufRead>(
    xml: &mut Reader<B>,
    buf: &mut Vec<u8>,
) -> Result<Option<Column>, XmlError> {
    match xml.read_event(buf)? {
        Event::Empty(start) => {
            if start.name() == b"column" {
                let mut name = None;
                let mut data_type = None;
                for attr in start.attributes() {
                    let attr = attr?;
                    if attr.key == b"name" {
                        name = Some(xml.decode(&attr.value).into_owned());
                    }

                    if attr.key == b"type" {
                        data_type = Some(
                            xml.decode(&attr.value)
                                .parse()
                                .expect("Expected well-known value type"),
                        );
                    }
                }
                buf.clear();
                Ok(Some(Column {
                    name: name.unwrap(),
                    r#type: data_type.unwrap(),
                }))
            } else {
                todo!();
            }
        }
        Event::End(v) => {
            assert_eq!(v.name(), b"columns");
            Ok(None)
        }
        Event::Eof => Err(XmlError::EofWhileExpecting("column")),
        x => panic!("What? {:?}", x),
    }
}

/// Expects an empty `<row …/>` tag or a closing `</rows>` tag
pub fn expect_row_or_end_rows<B: BufRead>(
    xml: &mut Reader<B>,
    buf: &mut Vec<u8>,
    load_attrs: bool,
) -> Result<Option<HashMap<String, String>>, XmlError> {
    match xml.read_event(buf)? {
        Event::Empty(start) => {
            if start.name() == b"row" {
                let map = if load_attrs {
                    let mut m = HashMap::new();
                    for attr in start.attributes() {
                        let attr = attr?;
                        let key = xml.decode(attr.key).into_owned();
                        let value = attr.unescape_and_decode_value(xml)?;
                        m.insert(key, value);
                    }
                    m
                } else {
                    HashMap::new()
                };
                buf.clear();
                Ok(Some(map))
            } else {
                todo!();
            }
        }
        Event::End(v) => {
            assert_eq!(v.name(), b"rows");
            Ok(None)
        }
        _ => todo!(),
    }
}

#[cfg(test)]
#[cfg(feature = "serialize")]
mod tests {
    use quick_xml::{de::Deserializer, DeError};

    use super::*;
    use quick_xml::Error as XmlError;
    use std::io::BufReader;
    use std::io::Cursor;

    #[test]
    fn test_simple_deserialize() {
        use serde::Deserialize;

        let st = br#"<row foo="bar"/></rows>"#;
        let c = BufReader::new(Cursor::new(st));
        let mut d = Deserializer::from_reader(c);
        let row = Row::deserialize(&mut d).unwrap();
        let mut cmp = HashMap::new();
        let key = String::from("foo");
        let val = String::from("bar");
        cmp.insert(key, val);
        assert_eq!(row.0, cmp);

        if let Err(DeError::Xml(XmlError::EndEventMismatch { expected, found })) =
            Row::deserialize(&mut d)
        {
            assert_eq!(&expected, "");
            assert_eq!(&found, "rows");
        }
    }
}