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
use crate::{structs::ExecuteResponse, utils::from_base64};
use anyhow::{Context, Result};

pub trait Deserializer {
    fn deserialize_raw(input: Vec<&str>) -> Result<Self>
    where
        Self: Sized;
}

impl ExecuteResponse {
    pub fn deserialize<T>(&self) -> Result<T>
    where
        T: Deserializer,
    {
        if let Some(res) = &self.result {
            if let Some(rows) = &res.rows {
                if rows.len() != 1 {
                    anyhow::bail!("Expected 1 row, got {}", rows.len());
                }

                let row = &rows[0];
                let row_str = from_base64(&row.values);
                let row_str = String::from_utf8(row_str).unwrap();

                let lengths: Vec<usize> = row
                    .lengths
                    .iter()
                    .map(|l| l.parse::<usize>().unwrap())
                    .collect();

                let mut row_vec: Vec<&str> = Vec::new();
                let mut last = 0;
                for length in lengths {
                    row_vec.push(&row_str[last..(last + length)]);
                    last += length;
                }

                let res = T::deserialize_raw(row_vec).context("Failed to deserialize row")?;
                return Ok(res);
            }
        }

        anyhow::bail!("No results found");
    }

    pub fn deserialize_multiple<T>(&self) -> Result<Vec<T>>
    where
        T: Deserializer,
    {
        if let Some(res) = &self.result {
            if let Some(rows) = &res.rows {
                let mut out: Vec<T> = Vec::new();
                for row in rows {
                    let row_str = from_base64(&row.values);
                    let row_str = String::from_utf8(row_str).unwrap();

                    let lengths: Vec<usize> = row
                        .lengths
                        .iter()
                        .map(|l| l.parse::<usize>().unwrap())
                        .collect();

                    let mut row_vec: Vec<&str> = Vec::new();
                    let mut last = 0;
                    for length in lengths {
                        row_vec.push(&row_str[last..(last + length)]);
                        last += length;
                    }

                    out.push(T::deserialize_raw(row_vec).context("Failed to deserialize row")?);
                }

                return Ok(out);
            }
        }

        anyhow::bail!("No results found");
    }
}