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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use ffi;
use libc::{c_double, c_int};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::rc::Rc;

use cursor::{Cursor, CursorWithOwnership, Row};
use error::Result;
use value::{Type, Value};

// https://sqlite.org/c3ref/c_static.html
macro_rules! transient(
    () => (::std::mem::transmute(!0 as *const ::libc::c_void));
);

/// A prepared statement.
#[derive(Debug, Clone)]
pub struct Statement {
    raw: *mut ffi::sqlite3_stmt,
    column_names: Vec<String>,
    column_mapping: Rc<HashMap<String, usize>>,
    phantom: PhantomData<ffi::sqlite3_stmt>,
}

unsafe impl<'l> Sync for Statement {}
unsafe impl<'l> Send for Statement {}

/// A type suitable for binding to a prepared statement.
pub trait Bindable {
    /// Bind to a parameter.
    fn bind(self, _: &mut Statement) -> Result<()>;
}

/// A type suitable for binding to a prepared statement given a parameter index.
pub trait BindableWithIndex {
    /// Bind to a parameter.
    ///
    /// In case of integer indices, the first parameter has index 1.
    fn bind<T: ParameterIndex>(self, _: &mut Statement, _: T) -> Result<()>;
}

/// A type suitable for indexing columns in a prepared statement.
pub trait ColumnIndex: Copy + std::fmt::Debug {
    /// Identify the ordinal position.
    ///
    /// The first column has index 0.
    fn index(self, statement: &Statement) -> Result<usize>;
}

/// A type suitable for indexing parameters in a prepared statement.
pub trait ParameterIndex: Copy + std::fmt::Debug {
    /// Identify the ordinal position.
    ///
    /// The first parameter has index 1.
    fn index(self, statement: &Statement) -> Result<usize>;
}

/// A type suitable for reading from a prepared statement given a column index.
pub trait ReadableWithIndex: Sized {
    /// Read from a column.
    ///
    /// In case of integer indices, the first column has index 0.
    fn read<T: ColumnIndex>(_: &Statement, _: T) -> Result<Self>;
}

/// The state of a prepared statement.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
    /// There is a row available for reading.
    Row,
    /// The statement has been entirely evaluated.
    Done,
}

impl Statement {
    /// Bind values to parameters.
    ///
    /// In case of integer indices, the first parameter has index 1.
    ///
    /// # Examples
    ///
    /// ```
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let query = "SELECT * FROM users WHERE name = ?";
    /// let mut statement = connection.prepare(query)?;
    /// statement.bind((1, "Bob"))?;
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    ///
    /// ```
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let query = "SELECT * FROM users WHERE name = ?";
    /// let mut statement = connection.prepare(query)?;
    /// statement.bind(&[(1, "Bob")][..])?;
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    ///
    /// ```
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let query = "SELECT * FROM users WHERE name = :name";
    /// let mut statement = connection.prepare(query)?;
    /// statement.bind((":name", "Bob"))?;
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    ///
    /// ```
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let query = "SELECT * FROM users WHERE name = :name";
    /// let mut statement = connection.prepare(query)?;
    /// statement.bind(&[(":name", "Bob")][..])?;
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    ///
    /// ```
    /// # use sqlite_bindings_lunatic::Value;
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let query = "SELECT * FROM users WHERE id = :id AND name = :name";
    /// let mut statement = connection.prepare(query)?;
    /// statement.bind::<&[(_, Value)]>(&[
    ///     (":id", 1.into()),
    ///     (":name", "Bob".into()),
    /// ][..])?;
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    #[inline]
    pub fn bind<T: Bindable>(&mut self, value: T) -> Result<()> {
        value.bind(self)?;
        Ok(())
    }

    /// Bind values to parameters via an iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sqlite_bindings_lunatic::Value;
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (id INTEGER, name STRING)");
    /// let query = "INSERT INTO users VALUES (:id, :name)";
    /// let mut statement = connection.prepare(query)?;
    /// statement.bind_iter::<_, (_, Value)>([
    ///     (":name", "Bob".into()),
    ///     (":id", 42.into()),
    /// ])?;
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    pub fn bind_iter<T, U>(&mut self, value: T) -> Result<()>
    where
        T: IntoIterator<Item = U>,
        U: Bindable,
    {
        for value in value {
            self.bind(value)?;
        }
        Ok(())
    }

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

    #[doc(hidden)]
    #[inline]
    pub fn column_mapping(&self) -> Rc<HashMap<String, usize>> {
        self.column_mapping.clone()
    }

    /// Return the name of a column.
    ///
    /// In case of integer indices, the first column has index 0.
    #[inline]
    pub fn column_name<T: ColumnIndex>(&self, index: T) -> Result<&str> {
        Ok(&self.column_names[index.index(self)?])
    }

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

    /// Return the type of a column.
    ///
    /// The type becomes available after taking a step. In case of integer
    /// indices, the first column has index 0.
    pub fn column_type<T: ColumnIndex>(&self, index: T) -> Result<Type> {
        Ok(
            match unsafe { ffi::sqlite3_column_type(self.raw, index.index(self)? as c_int) } {
                ffi::SQLITE_BLOB => Type::Binary,
                ffi::SQLITE_FLOAT => Type::Float,
                ffi::SQLITE_INTEGER => Type::Integer,
                ffi::SQLITE_TEXT => Type::String,
                ffi::SQLITE_NULL => Type::Null,
                _ => unreachable!(),
            },
        )
    }

    /// Create a cursor.
    #[inline]
    pub fn iter(&mut self) -> Cursor {
        self.into()
    }

    /// Advance to the next state.
    ///
    /// The function should be called multiple times until `State::Done` is
    /// reached in order to evaluate the statement entirely.
    pub fn next(&mut self) -> Result<State> {
        Ok(match unsafe { ffi::sqlite3_step(self.raw) } {
            ffi::SQLITE_ROW => State::Row,
            ffi::SQLITE_DONE => State::Done,
            code => {
                return Err(::Error {
                    code: Some(code as isize),
                    message: None,
                })
            }
        })
    }

    /// Return the index for a named parameter if exists.
    ///
    /// # Examples
    ///
    /// ```
    /// # let connection = sqlite_bindings_lunatic::open(":memory:").unwrap();
    /// # connection.execute("CREATE TABLE users (name STRING)");
    /// let query = "SELECT * FROM users WHERE name = :name";
    /// let statement = connection.prepare(query)?;
    /// assert_eq!(statement.parameter_index(":name")?.unwrap(), 1);
    /// assert_eq!(statement.parameter_index(":asdf")?, None);
    /// # Ok::<(), sqlite_bindings_lunatic::Error>(())
    /// ```
    #[inline]
    pub fn parameter_index(&self, parameter: &str) -> Result<Option<usize>> {
        let index = unsafe {
            ffi::sqlite3_bind_parameter_index(self.raw, str_to_cstr!(parameter).as_ptr())
        };
        match index {
            0 => Ok(None),
            _ => Ok(Some(index as usize)),
        }
    }

    /// Read a value from a column.
    ///
    /// In case of integer indices, the first column has index 0.
    #[inline]
    pub fn read<T, U>(&self, index: U) -> Result<T>
    where
        T: ReadableWithIndex,
        U: ColumnIndex,
    {
        ReadableWithIndex::read(self, index)
    }

    /// Reset the internal state.
    #[inline]
    pub fn reset(&mut self) -> Result<()> {
        unsafe { ok!(ffi::sqlite3_reset(self.raw)) };
        Ok(())
    }

    #[doc(hidden)]
    #[inline]
    pub fn as_raw(&self) -> *mut ffi::sqlite3_stmt {
        self.raw
    }
}

impl Drop for Statement {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::sqlite3_finalize(self.raw) };
    }
}

impl<'m> From<&'m mut Statement> for Cursor<'m> {
    #[inline]
    fn from(statement: &'m mut Statement) -> Self {
        ::cursor::new(statement)
    }
}

impl IntoIterator for Statement {
    type Item = Result<Row>;
    type IntoIter = CursorWithOwnership;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        ::cursor::new_with_ownership(self)
    }
}

impl<T, U> Bindable for (T, U)
where
    T: ParameterIndex,
    U: BindableWithIndex,
{
    #[inline]
    fn bind(self, statement: &mut Statement) -> Result<()> {
        self.1.bind(statement, self.0)
    }
}

impl<T> Bindable for &[T]
where
    T: BindableWithIndex + Clone,
{
    fn bind(self, statement: &mut Statement) -> Result<()> {
        for (index, value) in self.iter().enumerate() {
            value.clone().bind(statement, index + 1)?;
        }
        Ok(())
    }
}

impl<T, U> Bindable for &[(T, U)]
where
    T: ParameterIndex,
    U: BindableWithIndex + Clone,
{
    fn bind(self, statement: &mut Statement) -> Result<()> {
        for (index, value) in self.iter() {
            value.clone().bind(statement, *index)?;
        }
        Ok(())
    }
}

impl BindableWithIndex for &[u8] {
    #[inline]
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        unsafe {
            ok!(ffi::sqlite3_bind_blob(
                statement.raw,
                index.index(statement)? as c_int,
                self.as_ptr() as *const _,
                self.len() as c_int,
                transient!(),
            ));
        }
        Ok(())
    }
}

impl BindableWithIndex for f64 {
    #[inline]
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        unsafe {
            ok!(ffi::sqlite3_bind_double(
                statement.raw,
                index.index(statement)? as c_int,
                self as c_double
            ));
        }
        Ok(())
    }
}

impl BindableWithIndex for i64 {
    #[inline]
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        unsafe {
            ok!(ffi::sqlite3_bind_int64(
                statement.raw,
                index.index(statement)? as c_int,
                self as ffi::sqlite3_int64
            ));
        }
        Ok(())
    }
}

impl BindableWithIndex for &str {
    #[inline]
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        unsafe {
            let value = ffi::sqlite3_bind_text(
                statement.raw,
                index.index(statement)? as c_int,
                self.as_ptr() as *const _,
                self.len() as c_int,
                transient!(),
            );
            ok!(value);
        }
        Ok(())
    }
}

impl BindableWithIndex for () {
    #[inline]
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        unsafe {
            ok!(ffi::sqlite3_bind_null(
                statement.raw,
                index.index(statement)? as c_int
            ));
        }
        Ok(())
    }
}

impl BindableWithIndex for Value {
    #[inline]
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        (index, &self).bind(statement)
    }
}

impl BindableWithIndex for &Value {
    fn bind<T: ParameterIndex>(self, statement: &mut Statement, index: T) -> Result<()> {
        match self {
            &Value::Binary(ref value) => (value as &[u8]).bind(statement, index),
            &Value::Float(value) => value.bind(statement, index),
            &Value::Integer(value) => value.bind(statement, index),
            &Value::String(ref value) => (value as &str).bind(statement, index),
            &Value::Null => ().bind(statement, index),
        }
    }
}

impl<T> BindableWithIndex for Option<T>
where
    T: BindableWithIndex,
{
    #[inline]
    fn bind<U: ParameterIndex>(self, statement: &mut Statement, index: U) -> Result<()> {
        match self {
            Some(value) => value.bind(statement, index),
            None => ().bind(statement, index),
        }
    }
}

impl<T> BindableWithIndex for &Option<T>
where
    T: BindableWithIndex + Clone,
{
    #[inline]
    fn bind<U: ParameterIndex>(self, statement: &mut Statement, index: U) -> Result<()> {
        match self {
            Some(value) => value.clone().bind(statement, index),
            None => ().bind(statement, index),
        }
    }
}

impl ColumnIndex for &str {
    #[inline]
    fn index(self, statement: &Statement) -> Result<usize> {
        if statement.column_mapping.contains_key(self) {
            Ok(statement.column_mapping[self])
        } else {
            raise!("the index is out of range ({})", self);
        }
    }
}

impl ColumnIndex for usize {
    #[inline]
    fn index(self, statement: &Statement) -> Result<usize> {
        if self < statement.column_count() {
            Ok(self)
        } else {
            raise!("the index is out of range ({})", self);
        }
    }
}

impl ParameterIndex for &str {
    #[inline]
    fn index(self, statement: &Statement) -> Result<usize> {
        match statement.parameter_index(self)? {
            Some(index) => return Ok(index),
            _ => raise!("the index is out of range ({})", self),
        }
    }
}

impl ParameterIndex for usize {
    #[inline]
    fn index(self, _: &Statement) -> Result<usize> {
        if self > 0 {
            Ok(self)
        } else {
            raise!("the index is out of range ({})", self);
        }
    }
}

impl ReadableWithIndex for Value {
    fn read<T: ColumnIndex>(statement: &Statement, index: T) -> Result<Self> {
        Ok(match statement.column_type(index)? {
            Type::Binary => Value::Binary(ReadableWithIndex::read(statement, index)?),
            Type::Float => Value::Float(ReadableWithIndex::read(statement, index)?),
            Type::Integer => Value::Integer(ReadableWithIndex::read(statement, index)?),
            Type::String => Value::String(ReadableWithIndex::read(statement, index)?),
            Type::Null => Value::Null,
        })
    }
}

impl ReadableWithIndex for f64 {
    #[inline]
    fn read<T: ColumnIndex>(statement: &Statement, index: T) -> Result<Self> {
        Ok(unsafe {
            ffi::sqlite3_column_double(statement.raw, index.index(statement)? as c_int) as f64
        })
    }
}

impl ReadableWithIndex for i64 {
    #[inline]
    fn read<T: ColumnIndex>(statement: &Statement, index: T) -> Result<Self> {
        Ok(unsafe {
            ffi::sqlite3_column_int64(statement.raw, index.index(statement)? as c_int) as i64
        })
    }
}

impl ReadableWithIndex for String {
    #[inline]
    fn read<T: ColumnIndex>(statement: &Statement, index: T) -> Result<Self> {
        unsafe {
            let pointer = ffi::sqlite3_column_text(statement.raw, index.index(statement)? as c_int);
            if pointer.is_null() {
                raise!("cannot read a text column");
            }
            Ok(c_str_to_string!(pointer))
        }
    }
}

impl ReadableWithIndex for Vec<u8> {
    #[inline]
    fn read<T: ColumnIndex>(statement: &Statement, index: T) -> Result<Self> {
        use std::ptr::copy_nonoverlapping as copy;
        unsafe {
            let pointer = ffi::sqlite3_column_blob(statement.raw, index.index(statement)? as c_int);
            if pointer.is_null() {
                return Ok(vec![]);
            }
            let count =
                ffi::sqlite3_column_bytes(statement.raw, index.index(statement)? as c_int) as usize;
            let mut buffer = Vec::with_capacity(count);
            buffer.set_len(count);
            copy(pointer as *const u8, buffer.as_mut_ptr(), count);
            Ok(buffer)
        }
    }
}

impl<T: ReadableWithIndex> ReadableWithIndex for Option<T> {
    #[inline]
    fn read<U: ColumnIndex>(statement: &Statement, index: U) -> Result<Self> {
        if statement.column_type(index)? == Type::Null {
            Ok(None)
        } else {
            T::read(statement, index).map(Some)
        }
    }
}

#[inline]
pub fn new<'l, T>(raw_connection: *mut ffi::sqlite3, statement: T) -> Result<Statement>
where
    T: AsRef<str>,
{
    let mut raw_statement = 0 as *mut _;
    unsafe {
        ok!(
            raw_connection,
            ffi::sqlite3_prepare_v2(
                raw_connection,
                str_to_cstr!(statement.as_ref()).as_ptr(),
                -1,
                &mut raw_statement,
                0 as *mut _,
            )
        );
    }
    let column_count = unsafe { ffi::sqlite3_column_count(raw_statement) as usize };
    let column_names = (0..column_count)
        .map(|index| unsafe {
            let raw = ffi::sqlite3_column_name(raw_statement, index as c_int);
            debug_assert!(!raw.is_null());
            c_str_to_str!(raw).unwrap().to_string()
        })
        .collect::<Vec<_>>();
    let column_mapping = column_names
        .iter()
        .enumerate()
        .map(|(index, name)| (name.to_string(), index))
        .collect();
    Ok(Statement {
        raw: raw_statement,
        column_names: column_names,
        column_mapping: Rc::new(column_mapping),
        phantom: PhantomData,
    })
}