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
// Copyright (c) 2017 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! `FromRow` implementation for `frunk::HList`.

#![cfg(feature = "frunk")]

use frunk::{hlist::h_cons, prelude::HList};
pub use frunk::{HCons, HNil};

use super::{FromRow, FromRowError};
use crate::{
    row::{new_row_raw, Row},
    value::{
        convert::{ConvIr, FromValue, FromValueError},
        Value,
    },
};

impl FromRow for HNil {
    fn from_row_opt(row: Row) -> Result<Self, FromRowError>
    where
        Self: Sized,
    {
        if !row.is_empty() {
            return Err(FromRowError(row));
        }
        Ok(HNil)
    }
}

impl<H, T> FromRow for HCons<H, T>
where
    H: FromValue,
    T: FromRow + sealed::HlistFromRow,
    T: HList,
{
    fn from_row_opt(row: Row) -> Result<Self, FromRowError>
    where
        Self: Sized,
    {
        use sealed::HlistFromRow;

        if row.len() != Self::LEN {
            return Err(FromRowError(row));
        }

        let columns = row.columns();
        let values = row.unwrap_raw();

        Self::hlist_from_row_opt(values)
            .map_err(|values| FromRowError(new_row_raw(values, columns)))
    }
}

mod sealed {
    use super::*;

    /// Helper trait for `FromRow for HList`.
    pub trait HlistFromRow: Sized {
        fn hlist_from_row_opt(values: Vec<Option<Value>>) -> Result<Self, Vec<Option<Value>>>;
    }

    impl HlistFromRow for HNil {
        fn hlist_from_row_opt(values: Vec<Option<Value>>) -> Result<Self, Vec<Option<Value>>> {
            debug_assert_eq!(values.len(), Self::LEN);
            Ok(HNil)
        }
    }

    impl<H, T> HlistFromRow for HCons<H, T>
    where
        H: FromValue,
        T: HlistFromRow,
        T: HList,
    {
        fn hlist_from_row_opt(mut values: Vec<Option<Value>>) -> Result<Self, Vec<Option<Value>>>
        where
            Self: Sized,
        {
            debug_assert_eq!(values.len(), Self::LEN);

            if values[0].is_none() {
                return Err(values);
            }

            let head = values.remove(0).expect("must be here");

            let ir = match H::get_intermediate(head) {
                Ok(ir) => ir,
                Err(FromValueError(value)) => {
                    values.insert(0, Some(value));
                    return Err(values);
                }
            };

            let tail = match T::hlist_from_row_opt(values) {
                Ok(t) => t,
                Err(mut values) => {
                    values.insert(0, Some(ir.rollback()));
                    return Err(values);
                }
            };

            Ok(h_cons(ir.commit(), tail))
        }
    }
}

#[test]
fn hlist_from_row() {
    use crate::{
        constants::ColumnType::{MYSQL_TYPE_LONG, MYSQL_TYPE_VARCHAR},
        packets::Column,
        row::{convert::from_row, new_row},
        value::Value::*,
    };

    let row = new_row(
        vec![
            Int(0),
            Bytes(vec![b'0']),
            Int(1),
            Bytes(vec![b'1']),
            Int(2),
            Bytes(vec![b'2']),
            Int(3),
            Bytes(vec![b'3']),
            Int(4),
            Bytes(vec![b'4']),
            Int(5),
            Bytes(vec![b'5']),
            Int(6),
            Bytes(vec![b'6']),
            Int(7),
            Bytes(vec![b'7']),
        ],
        vec![
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
            Column::new(MYSQL_TYPE_LONG),
            Column::new(MYSQL_TYPE_VARCHAR),
        ]
        .into_boxed_slice()
        .into(),
    );

    let val: frunk::HList![
        u8,
        Vec<u8>,
        u16,
        String,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8,
        u8
    ] = from_row(row);

    assert_eq!(
        val.into_tuple2(),
        (
            0,
            (
                vec![b'0'],
                (
                    1,
                    (
                        String::from("1"),
                        (2, (2, (3, (3, (4, (4, (5, (5, (6, (6, (7, 7)))))))))))
                    )
                )
            )
        )
    );
}