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
use ffi;
use statement::{State, Statement};
use std::collections::HashMap;

use {Result, Value};

/// An iterator over rows.
pub struct Cursor<'l> {
    state: Option<State>,
    columns: Option<HashMap<String, usize>>,
    values: Option<Vec<Value>>,
    statement: Statement<'l>,
}

/// A row.
#[derive(Debug)]
pub struct Row {
    columns: HashMap<String, usize>,
    values: Vec<Value>,
}

/// A type suitable for indexing columns.
pub trait ColumnIndex: std::fmt::Debug {
    fn get<'l>(&self, row: &'l Row) -> &'l Value;
}

/// A type that values can be converted into.
pub trait ValueInto: Sized {
    fn into(value: &Value) -> Option<Self>;
}

impl<'l> Cursor<'l> {
    /// Bind values to parameters by index.
    ///
    /// The index of each value is assumed to be the value’s position in the array.
    pub fn bind(mut self, values: &[Value]) -> Result<Self> {
        self.state = None;
        self.statement = self.statement.reset()?;
        for (i, value) in values.iter().enumerate() {
            self.statement = self.statement.bind(i + 1, value)?;
        }
        Ok(self)
    }

    /// Bind values to parameters by name.
    ///
    /// Parameters that are not part of the statement will be ignored.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sqlite::Value;
    /// # let connection = sqlite::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let statement = connection.prepare("INSERT INTO users VALUES (:id, :name)")?;
    /// let mut cursor = statement
    ///     .into_cursor()
    ///     .bind_by_name(vec![
    ///         (":name", Value::String("Bob".to_owned())),
    ///         (":id", Value::Integer(42)),
    ///     ])?;
    /// cursor.try_next()?;
    /// # Ok::<(), sqlite::Error>(())
    /// ```
    pub fn bind_by_name<T, U>(mut self, values: U) -> Result<Self>
    where
        T: AsRef<str>,
        U: IntoIterator<Item = (T, Value)>,
    {
        self.state = None;
        self.statement = self.statement.reset()?;
        for (name, value) in values {
            if let Some(i) = self.statement.parameter_index(name.as_ref())? {
                self.statement = self.statement.bind(i, &value)?;
            }
        }
        Ok(self)
    }

    /// Return the number of columns.
    #[inline]
    pub fn column_count(&self) -> usize {
        self.statement.column_count()
    }

    /// Return column names.
    #[inline]
    pub fn column_names(&self) -> Vec<&str> {
        self.statement.column_names()
    }

    /// Advance to the next row and read all columns.
    pub fn try_next(&mut self) -> Result<Option<&[Value]>> {
        match self.state {
            Some(State::Row) => {}
            Some(State::Done) => return Ok(None),
            _ => {
                self.state = Some(self.statement.next()?);
                return self.try_next();
            }
        }
        self.values = match self.values.take() {
            Some(mut values) => {
                for (i, value) in values.iter_mut().enumerate() {
                    *value = self.statement.read(i)?;
                }
                Some(values)
            }
            _ => {
                let count = self.statement.column_count();
                let mut values = Vec::with_capacity(count);
                for i in 0..count {
                    values.push(self.statement.read(i)?);
                }
                Some(values)
            }
        };
        self.state = Some(self.statement.next()?);
        Ok(Some(self.values.as_ref().unwrap()))
    }

    /// Return the raw pointer.
    #[inline]
    pub fn as_raw(&self) -> *mut ffi::sqlite3_stmt {
        self.statement.as_raw()
    }
}

impl<'l> Iterator for Cursor<'l> {
    type Item = Result<Row>;

    fn next(&mut self) -> Option<Self::Item> {
        let columns = match self.columns.clone() {
            Some(columns) => columns,
            None => {
                self.columns = Some(
                    (0..self.statement.column_count())
                        .map(|i| (self.statement.column_name(i).to_string(), i))
                        .collect(),
                );
                self.columns.clone().unwrap()
            }
        };

        self.try_next()
            .map(|option| {
                option.map(|values| Row {
                    columns,
                    values: values.to_vec(),
                })
            })
            .transpose()
    }
}

impl Row {
    /// Get the value of a column in the row.
    ///
    /// # Panics
    ///
    /// Panics if the column could not be read.
    #[track_caller]
    #[inline]
    pub fn get<T: ValueInto, U: ColumnIndex>(&self, column: U) -> T {
        self.try_get(column).unwrap()
    }

    /// Try to get the value of a column in the row.
    ///
    /// It returns an error if the column could not be read.
    #[track_caller]
    #[inline]
    pub fn try_get<T: ValueInto, U: ColumnIndex>(&self, column: U) -> Result<T> {
        match T::into(column.get(self)) {
            Some(value) => Ok(value),
            None => raise!("column {:?} could not be read", column),
        }
    }
}

impl ColumnIndex for &str {
    #[inline]
    fn get<'l>(&self, row: &'l Row) -> &'l Value {
        debug_assert!(
            row.columns.contains_key(*self),
            "invalid column name: {}",
            self
        );
        &row.values[row.columns[*self]]
    }
}

impl ColumnIndex for usize {
    #[inline]
    fn get<'l>(&self, row: &'l Row) -> &'l Value {
        debug_assert!(row.values.len() > *self, "invalid column index: {}", self);
        &row.values[*self]
    }
}

impl ValueInto for Value {
    #[inline]
    fn into(value: &Value) -> Option<Self> {
        Some(value.clone())
    }
}

impl ValueInto for i64 {
    #[inline]
    fn into(value: &Value) -> Option<Self> {
        value.as_integer()
    }
}

impl ValueInto for f64 {
    #[inline]
    fn into(value: &Value) -> Option<Self> {
        value.as_float()
    }
}

impl ValueInto for String {
    #[inline]
    fn into(value: &Value) -> Option<Self> {
        value.as_string().map(|slice| slice.to_string())
    }
}

impl ValueInto for Vec<u8> {
    #[inline]
    fn into(value: &Value) -> Option<Self> {
        value.as_binary().map(|bytes| bytes.to_vec())
    }
}

impl<T: ValueInto> ValueInto for Option<T> {
    #[inline]
    fn into(value: &Value) -> Option<Self> {
        match value {
            Value::Null => Some(None),
            _ => T::into(value).map(Some),
        }
    }
}

#[inline]
pub fn new<'l>(statement: Statement<'l>) -> Cursor<'l> {
    Cursor {
        state: None,
        columns: None,
        values: None,
        statement: statement,
    }
}