odbc/statement/
input.rs

1use super::types::OdbcType;
2use odbc_safe::AutocommitMode;
3use statement::types::EncodedValue;
4use {ffi, Handle, Raii, Result, Return, Statement};
5
6impl<'a, 'b, S, R, AC: AutocommitMode> Statement<'a, 'b, S, R, AC> {
7    /// Binds a parameter to a parameter marker in an SQL statement.
8    ///
9    /// # Result
10    /// This method will destroy the statement and create a new one which may not outlive the bound
11    /// parameter. This is to ensure that the statement will not dereference an invalid pointer
12    /// during execution.
13    ///
14    /// # Arguments
15    /// * `parameter_index` - Index of the marker to bind to the parameter. Starting at `1`
16    /// * `value` - Reference to bind to the marker
17    ///
18    /// # Example
19    /// ```
20    /// # use odbc::*;
21    /// # fn do_odbc_stuff() -> std::result::Result<(), Box<std::error::Error>> {
22    /// let env = create_environment_v3().map_err(|e| e.unwrap())?;
23    /// let conn = env.connect("TestDataSource", "", "")?;
24    /// let stmt = Statement::with_parent(&conn)?;
25    /// let param = 1968;
26    /// let stmt = stmt.bind_parameter(1, &param)?;
27    /// let sql_text = "SELECT TITLE FROM MOVIES WHERE YEAR = ?";
28    /// if let Data(mut stmt) = stmt.exec_direct(sql_text)? {
29    ///     // ...
30    /// }
31    /// #   Ok(())
32    /// # }
33    /// ```
34    pub fn bind_parameter<'c, T>(
35        mut self,
36        parameter_index: u16,
37        value: &'c T,
38    ) -> Result<Statement<'a, 'c, S, R, AC>>
39    where
40        T: OdbcType<'c>,
41        T: ?Sized,
42        'b: 'c,
43    {
44        let ind = if value.value_ptr() == 0 as *const Self as ffi::SQLPOINTER {
45            ffi::SQL_NULL_DATA
46        } else {
47            value.column_size() as ffi::SQLLEN
48        };
49
50        let ind_ptr = self.param_ind_buffers.alloc(parameter_index as usize, ind);
51
52        //the result of value_ptr is changed per calling.
53        //binding and saving must have the same value.
54        let enc_value = value.encoded_value();
55
56        self.raii
57            .bind_input_parameter(parameter_index, value, ind_ptr, &enc_value)
58            .into_result(&self)?;
59
60        // save encoded value to avoid memory reuse.
61        if enc_value.has_value() {
62            self.encoded_values.push(enc_value);
63        }
64
65        Ok(self)
66    }
67
68    /// Releasing all parameter buffers set by `bind_parameter`. This method consumes the statement
69    /// and returns a new one those lifetime is no longer limited by the buffers bound.
70    pub fn reset_parameters(mut self) -> Result<Statement<'a, 'a, S, R, AC>> {
71        self.param_ind_buffers.clear();
72        self.encoded_values.clear();
73        self.raii.reset_parameters().into_result(&mut self)?;
74        Ok(Statement::with_raii(self.raii))
75    }
76}
77
78impl<'p> Raii<'p, ffi::Stmt> {
79    fn bind_input_parameter<'c, T>(
80        &mut self,
81        parameter_index: u16,
82        value: &'c T,
83        str_len_or_ind_ptr: *mut ffi::SQLLEN,
84        enc_value: &EncodedValue,
85    ) -> Return<()>
86    where
87        T: OdbcType<'c>,
88        T: ?Sized,
89    {
90        //if encoded value exists, use it.
91        let (column_size, value_ptr) = if enc_value.has_value() {
92            (enc_value.column_size(), enc_value.value_ptr())
93        } else {
94            (value.column_size(), value.value_ptr())
95        };
96
97        match unsafe {
98            ffi::SQLBindParameter(
99                self.handle(),
100                parameter_index,
101                ffi::SQL_PARAM_INPUT,
102                T::c_data_type(),
103                T::sql_data_type(),
104                column_size,
105                value.decimal_digits(),
106                value_ptr,
107                0,                  // buffer length
108                str_len_or_ind_ptr, // Note that this ptr has to be valid until statement is executed
109            )
110        } {
111            ffi::SQL_SUCCESS => Return::Success(()),
112            ffi::SQL_SUCCESS_WITH_INFO => Return::SuccessWithInfo(()),
113            ffi::SQL_ERROR => Return::Error,
114            r => panic!("Unexpected return from SQLBindParameter: {:?}", r),
115        }
116    }
117
118    fn reset_parameters(&mut self) -> Return<()> {
119        match unsafe { ffi::SQLFreeStmt(self.handle(), ffi::SQL_RESET_PARAMS) } {
120            ffi::SQL_SUCCESS => Return::Success(()),
121            ffi::SQL_SUCCESS_WITH_INFO => Return::SuccessWithInfo(()),
122            ffi::SQL_ERROR => Return::Error,
123            r => panic!("SQLFreeStmt returned unexpected result: {:?}", r),
124        }
125    }
126}