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
// 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.

use std::{
    collections::{
        hash_map::{Entry, Entry::Occupied},
        HashMap,
    },
    error::Error,
    fmt,
};

use crate::value::{convert::ToValue, Value};

/// `FromValue` conversion error.
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct MissingNamedParameterError(pub Vec<u8>);

impl fmt::Display for MissingNamedParameterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Missing named parameter `{}` for statement",
            String::from_utf8_lossy(&self.0)
        )
    }
}

impl Error for MissingNamedParameterError {
    fn description(&self) -> &str {
        "Missing named parameter for statement"
    }
}

/// Representations of parameters of a prepared statement.
#[derive(Clone, PartialEq)]
pub enum Params {
    Empty,
    Named(HashMap<Vec<u8>, Value>),
    Positional(Vec<Value>),
}

impl fmt::Debug for Params {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "Empty"),
            Self::Named(arg0) => {
                let arg0 = arg0
                    .iter()
                    .map(|(k, v)| (String::from_utf8_lossy(k), v))
                    .collect::<HashMap<_, _>>();
                f.debug_tuple("Named").field(&arg0).finish()
            }
            Self::Positional(arg0) => f.debug_tuple("Positional").field(arg0).finish(),
        }
    }
}

impl Params {
    /// Will convert named parameters into positional assuming order passed in `named_params`
    /// attribute.
    pub fn into_positional(
        self,
        named_params: &[Vec<u8>],
    ) -> Result<Params, MissingNamedParameterError> {
        match self {
            Params::Named(mut map) => {
                let mut params: Vec<Value> = Vec::new();
                'params: for (i, name) in named_params.iter().enumerate() {
                    match map.entry(name.clone()) {
                        Occupied(entry) => {
                            let mut x = named_params.len() - 1;
                            while x > i {
                                if *name == named_params[x] {
                                    params.push(entry.get().clone());
                                    continue 'params;
                                }
                                x -= 1;
                            }
                            params.push(entry.remove());
                        }
                        _ => return Err(MissingNamedParameterError(name.clone())),
                    }
                }
                Ok(Params::Positional(params))
            }
            params => Ok(params),
        }
    }
}

impl<'a, T: Into<Params> + Clone> From<&'a T> for Params {
    fn from(x: &'a T) -> Params {
        x.clone().into()
    }
}

impl<T> From<Vec<T>> for Params
where
    Value: From<T>,
{
    fn from(x: Vec<T>) -> Params {
        let mut raw_params: Vec<Value> = Vec::new();
        for v in x.into_iter() {
            raw_params.push(Value::from(v));
        }
        if raw_params.is_empty() {
            Params::Empty
        } else {
            Params::Positional(raw_params)
        }
    }
}

impl<N, V> From<Vec<(N, V)>> for Params
where
    Vec<u8>: From<N>,
    Value: From<V>,
{
    fn from(x: Vec<(N, V)>) -> Params {
        let mut map = HashMap::default();
        for (name, value) in x.into_iter() {
            let name: Vec<u8> = name.into();
            match map.entry(name) {
                Entry::Vacant(entry) => entry.insert(Value::from(value)),
                Entry::Occupied(entry) => {
                    panic!(
                        "Redefinition of named parameter `{}'",
                        String::from_utf8_lossy(entry.key())
                    );
                }
            };
        }
        Params::Named(map)
    }
}

impl<'a> From<&'a [&'a dyn ToValue]> for Params {
    fn from(x: &'a [&'a dyn ToValue]) -> Params {
        let mut raw_params: Vec<Value> = Vec::new();
        for v in x {
            raw_params.push(v.to_value());
        }
        if raw_params.is_empty() {
            Params::Empty
        } else {
            Params::Positional(raw_params)
        }
    }
}

impl From<()> for Params {
    fn from(_: ()) -> Params {
        Params::Empty
    }
}

macro_rules! into_params_impl {
    ($([$A:ident,$a:ident]),*) => (
        impl<$($A: Into<Value>,)*> From<($($A,)*)> for Params {
            fn from(x: ($($A,)*)) -> Params {
                let ($($a,)*) = x;
                Params::Positional(vec![
                    $($a.into(),)*
                ])
            }
        }
    );
}

into_params_impl!([A, a]);
into_params_impl!([A, a], [B, b]);
into_params_impl!([A, a], [B, b], [C, c]);
into_params_impl!([A, a], [B, b], [C, c], [D, d]);
into_params_impl!([A, a], [B, b], [C, c], [D, d], [E, e]);
into_params_impl!([A, a], [B, b], [C, c], [D, d], [E, e], [F, f]);
into_params_impl!([A, a], [B, b], [C, c], [D, d], [E, e], [F, f], [G, g]);
into_params_impl!(
    [A, a],
    [B, b],
    [C, c],
    [D, d],
    [E, e],
    [F, f],
    [G, g],
    [H, h]
);
into_params_impl!(
    [A, a],
    [B, b],
    [C, c],
    [D, d],
    [E, e],
    [F, f],
    [G, g],
    [H, h],
    [I, i]
);
into_params_impl!(
    [A, a],
    [B, b],
    [C, c],
    [D, d],
    [E, e],
    [F, f],
    [G, g],
    [H, h],
    [I, i],
    [J, j]
);
into_params_impl!(
    [A, a],
    [B, b],
    [C, c],
    [D, d],
    [E, e],
    [F, f],
    [G, g],
    [H, h],
    [I, i],
    [J, j],
    [K, k]
);
into_params_impl!(
    [A, a],
    [B, b],
    [C, c],
    [D, d],
    [E, e],
    [F, f],
    [G, g],
    [H, h],
    [I, i],
    [J, j],
    [K, k],
    [L, l]
);