Files
aho_corasick
bigdecimal
bitflags
byteorder
cfg_if
chrono
diesel
associations
connection
expression
expression_methods
macros
migration
mysql
pg
query_builder
query_dsl
query_source
sql_types
sqlite
type_impls
types
diesel_derives
diesel_migrations
env_logger
idna
instant
ipnetwork
itoa
kernel32
libc
libsqlite3_sys
lock_api
log
matches
memchr
migrations_internals
migrations_macros
mysqlclient_sys
num_bigint
num_integer
num_traits
parking_lot
parking_lot_core
percent_encoding
pq_sys
proc_macro2
quickcheck
quote
r2d2
regex
regex_syntax
ryu
scheduled_thread_pool
scopeguard
serde
serde_derive
serde_json
smallvec
syn
thread_id
thread_local
time
tinyvec
tinyvec_macros
unicode_bidi
unicode_normalization
unicode_xid
url
utf8_ranges
uuid
winapi
  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
use std::collections::HashMap;

use super::{ffi, libc, Binds, Statement, StatementMetadata};
use mysql::{Mysql, MysqlType};
use result::QueryResult;
use row::*;
use sql_types::IsSigned;

pub struct StatementIterator<'a> {
    stmt: &'a mut Statement,
    output_binds: Binds,
}

#[allow(clippy::should_implement_trait)] // don't neet `Iterator` here
impl<'a> StatementIterator<'a> {
    #[allow(clippy::new_ret_no_self)]
    pub fn new(stmt: &'a mut Statement, types: Vec<(MysqlType, IsSigned)>) -> QueryResult<Self> {
        let mut output_binds = Binds::from_output_types(types);

        execute_statement(stmt, &mut output_binds)?;

        Ok(StatementIterator {
            stmt: stmt,
            output_binds: output_binds,
        })
    }

    pub fn map<F, T>(mut self, mut f: F) -> QueryResult<Vec<T>>
    where
        F: FnMut(MysqlRow) -> QueryResult<T>,
    {
        let mut results = Vec::new();
        while let Some(row) = self.next() {
            results.push(f(row?)?);
        }
        Ok(results)
    }

    fn next(&mut self) -> Option<QueryResult<MysqlRow>> {
        match populate_row_buffers(self.stmt, &mut self.output_binds) {
            Ok(Some(())) => Some(Ok(MysqlRow {
                col_idx: 0,
                binds: &mut self.output_binds,
            })),
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}

pub struct MysqlRow<'a> {
    col_idx: usize,
    binds: &'a Binds,
}

impl<'a> Row<Mysql> for MysqlRow<'a> {
    fn take(&mut self) -> Option<&[u8]> {
        let current_idx = self.col_idx;
        self.col_idx += 1;
        self.binds.field_data(current_idx)
    }

    fn next_is_null(&self, count: usize) -> bool {
        (0..count).all(|i| self.binds.field_data(self.col_idx + i).is_none())
    }
}

pub struct NamedStatementIterator<'a> {
    stmt: &'a mut Statement,
    output_binds: Binds,
    metadata: StatementMetadata,
}

#[allow(clippy::should_implement_trait)] // don't need `Iterator` here
impl<'a> NamedStatementIterator<'a> {
    #[allow(clippy::new_ret_no_self)]
    pub fn new(stmt: &'a mut Statement) -> QueryResult<Self> {
        let metadata = stmt.metadata()?;
        let mut output_binds = Binds::from_result_metadata(metadata.fields());

        execute_statement(stmt, &mut output_binds)?;

        Ok(NamedStatementIterator {
            stmt,
            output_binds,
            metadata,
        })
    }

    pub fn map<F, T>(mut self, mut f: F) -> QueryResult<Vec<T>>
    where
        F: FnMut(NamedMysqlRow) -> QueryResult<T>,
    {
        let mut results = Vec::new();
        while let Some(row) = self.next() {
            results.push(f(row?)?);
        }
        Ok(results)
    }

    fn next(&mut self) -> Option<QueryResult<NamedMysqlRow>> {
        match populate_row_buffers(self.stmt, &mut self.output_binds) {
            Ok(Some(())) => Some(Ok(NamedMysqlRow {
                binds: &self.output_binds,
                column_indices: self.metadata.column_indices(),
            })),
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}

pub struct NamedMysqlRow<'a> {
    binds: &'a Binds,
    column_indices: &'a HashMap<&'a str, usize>,
}

impl<'a> NamedRow<Mysql> for NamedMysqlRow<'a> {
    fn index_of(&self, column_name: &str) -> Option<usize> {
        self.column_indices.get(column_name).cloned()
    }

    fn get_raw_value(&self, idx: usize) -> Option<&[u8]> {
        self.binds.field_data(idx)
    }
}

fn execute_statement(stmt: &mut Statement, binds: &mut Binds) -> QueryResult<()> {
    unsafe {
        binds.with_mysql_binds(|bind_ptr| stmt.bind_result(bind_ptr))?;
        stmt.execute()?;
    }
    Ok(())
}

fn populate_row_buffers(stmt: &Statement, binds: &mut Binds) -> QueryResult<Option<()>> {
    let next_row_result = unsafe { ffi::mysql_stmt_fetch(stmt.stmt.as_ptr()) };
    match next_row_result as libc::c_uint {
        ffi::MYSQL_NO_DATA => Ok(None),
        ffi::MYSQL_DATA_TRUNCATED => binds.populate_dynamic_buffers(stmt).map(Some),
        0 => {
            binds.update_buffer_lengths();
            Ok(Some(()))
        }
        _error => stmt.did_an_error_occur().map(Some),
    }
}