Struct odbc_api::parameter::VarChar

source ·
pub struct VarChar<B> { /* private fields */ }
Expand description

Binds a byte array as Variadic sized character data. It can not be used for columnar bulk fetches, but if the buffer type is stack allocated it can be utilized in row wise bulk fetches.

Meaningful instantiations of this type are:

Implementations§

Constructs a ‘missing’ value.

Examples found in repository?
src/into_parameter.rs (line 65)
62
63
64
65
66
67
    fn into_parameter(self) -> Self::Parameter {
        match self {
            Some(str) => str.into_parameter(),
            None => VarCharBox::null(),
        }
    }

Create an owned parameter containing the character data from the passed string.

Examples found in repository?
src/into_parameter.rs (line 55)
54
55
56
    fn into_parameter(self) -> Self::Parameter {
        VarCharBox::from_string(self)
    }

Create a VarChar box from a Vec.

Examples found in repository?
src/parameter/varchar.rs (line 57)
56
57
58
    pub fn from_string(val: String) -> Self {
        Self::from_vec(val.into_bytes())
    }

Creates a new instance from an existing buffer. Should the indicator be NoTotal or indicate a length longer than buffer, the last element in the buffer must be nul (\0).

Examples found in repository?
src/parameter/varchar.rs (line 52)
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
    pub fn null() -> Self {
        // We do not want to use the empty buffer (`&[]`) here. It would be bound as `VARCHAR(0)`
        // which caused errors with Microsoft Access and older versions of the Microsoft SQL Server
        // ODBC driver.
        Self::from_buffer(Box::new([0]), Indicator::Null)
    }

    /// Create an owned parameter containing the character data from the passed string.
    pub fn from_string(val: String) -> Self {
        Self::from_vec(val.into_bytes())
    }

    /// Create a VarChar box from a `Vec`.
    pub fn from_vec(val: Vec<u8>) -> Self {
        let indicator = Indicator::Length(val.len());
        let buffer = val.into_boxed_slice();
        Self::from_buffer(buffer, indicator)
    }
}

impl<B> VarChar<B>
where
    B: Borrow<[u8]>,
{
    /// Creates a new instance from an existing buffer. Should the indicator be `NoTotal` or indicate
    /// a length longer than buffer, the last element in the buffer must be nul (`\0`).
    pub fn from_buffer(buffer: B, indicator: Indicator) -> Self {
        let buf = buffer.borrow();
        match indicator {
            Indicator::Null => (),
            Indicator::NoTotal => {
                if buf.is_empty() || *buf.last().unwrap() != 0 {
                    panic!("Truncated value must be terminated with zero.")
                }
            }
            Indicator::Length(len) => {
                if len > buf.len() && (buf.is_empty() || *buf.last().unwrap() != 0) {
                    panic!("Truncated value must be terminated with zero.")
                }
            }
        };
        Self {
            buffer,
            indicator: indicator.to_isize(),
        }
    }

    /// Returns the binary representation of the string, excluding the terminating zero or `None` in
    /// case the indicator is `NULL_DATA`.
    pub fn as_bytes(&self) -> Option<&[u8]> {
        let slice = self.buffer.borrow();
        match self.indicator() {
            Indicator::Null => None,
            Indicator::NoTotal => Some(&slice[..(slice.len() - 1)]),
            Indicator::Length(len) => {
                if self.is_complete() {
                    Some(&slice[..len])
                } else {
                    Some(&slice[..(slice.len() - 1)])
                }
            }
        }
    }

    /// Call this method to ensure that the entire field content did fit into the buffer. If you
    /// retrieve a field using [`crate::CursorRow::get_data`], you can repeat the call until this
    /// method is false to read all the data.
    ///
    /// ```
    /// use odbc_api::{CursorRow, parameter::VarCharArray, Error, handles::Statement};
    ///
    /// fn process_large_text(
    ///     col_index: u16,
    ///     row: &mut CursorRow<'_>
    /// ) -> Result<(), Error>{
    ///     let mut buf = VarCharArray::<512>::NULL;
    ///     row.get_data(col_index, &mut buf)?;
    ///     while !buf.is_complete() {
    ///         // Process bytes in stream without allocation. We can assume repeated calls to
    ///         // get_data do not return `None` since it would have done so on the first call.
    ///         process_text_slice(buf.as_bytes().unwrap());
    ///     }
    ///     Ok(())
    /// }
    ///
    /// fn process_text_slice(text: &[u8]) { /*...*/}
    ///
    /// ```
    pub fn is_complete(&self) -> bool {
        let slice = self.buffer.borrow();
        match self.indicator() {
            Indicator::Null => true,
            Indicator::NoTotal => false,
            Indicator::Length(len) => {
                len < slice.len() || slice.is_empty() || *slice.last().unwrap() != 0
            }
        }
    }

    /// Read access to the underlying ODBC indicator. After data has been fetched the indicator
    /// value is set to the length the buffer should have had, excluding the terminating zero. It
    /// may also be `NULL_DATA` to indicate `NULL` or `NO_TOTAL` which tells us the data source
    /// does not know how big the buffer must be to hold the complete value. `NO_TOTAL` implies that
    /// the content of the current buffer is valid up to its maximum capacity.
    pub fn indicator(&self) -> Indicator {
        Indicator::from_isize(self.indicator)
    }
}

impl<B> VarChar<B>
where
    B: Borrow<[u8]>,
{
    /// Call this method to reset the indicator to a value which matches the length returned by the
    /// [`Self::as_bytes`] method. This is useful if you want to insert values into the database
    /// despite the fact, that they might have been truncated. Otherwise the behaviour of databases
    /// in this situation is driver specific. Some drivers insert up to the terminating zero, others
    /// detect the truncation and throw an error.
    pub fn hide_truncation(&mut self) {
        if !self.is_complete() {
            self.indicator = (self.buffer.borrow().len() - 1).try_into().unwrap();
        }
    }
}

unsafe impl<B> CData for VarChar<B>
where
    B: Borrow<[u8]>,
{
    fn cdata_type(&self) -> CDataType {
        CDataType::Char
    }

    fn indicator_ptr(&self) -> *const isize {
        &self.indicator as *const isize
    }

    fn value_ptr(&self) -> *const c_void {
        self.buffer.borrow().as_ptr() as *const c_void
    }

    fn buffer_length(&self) -> isize {
        // This is the maximum buffer length, but it is NOT the length of an instance of Self due to
        // the missing size of the indicator value. As such the buffer length can not be used to
        // correctly index a columnar buffer of Self.
        self.buffer.borrow().len().try_into().unwrap()
    }
}

impl<B> HasDataType for VarChar<B>
where
    B: Borrow<[u8]>,
{
    fn data_type(&self) -> DataType {
        // Since we might use as an input buffer, we report the full buffer length in the type and
        // do not deduct 1 for the terminating zero.
        DataType::Varchar {
            length: self.buffer.borrow().len(),
        }
    }
}

unsafe impl<B> CDataMut for VarChar<B>
where
    B: BorrowMut<[u8]>,
{
    fn mut_indicator_ptr(&mut self) -> *mut isize {
        &mut self.indicator as *mut isize
    }

    fn mut_value_ptr(&mut self) -> *mut c_void {
        self.buffer.borrow_mut().as_mut_ptr() as *mut c_void
    }
}

/// Binds a byte array as a VarChar input parameter.
///
/// While a byte array can provide us with a pointer to the start of the array and the length of the
/// array itself, it can not provide us with a pointer to the length of the buffer. So to bind
/// strings which are not zero terminated we need to store the length in a separate value.
///
/// This type is created if `into_parameter` of the `IntoParameter` trait is called on a `&str`.
///
/// # Example
///
/// ```no_run
/// use odbc_api::{Environment, IntoParameter};
///
/// let env = Environment::new()?;
///
/// let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
/// if let Some(cursor) = conn.execute(
///     "SELECT year FROM Birthdays WHERE name=?;",
///     &"Bernd".into_parameter())?
/// {
///     // Use cursor to process query results.
/// };
/// # Ok::<(), odbc_api::Error>(())
/// ```
pub type VarCharSlice<'a> = VarChar<&'a [u8]>;

impl<'a> VarCharSlice<'a> {
    /// Indicates missing data
    pub const NULL: Self = Self {
        // We do not want to use the empty buffer (`&[]`) here. It would be bound as `VARCHAR(0)`
        // which caused errors with Microsoft Access and older versions of the Microsoft SQL Server
        // ODBC driver.
        buffer: &[0],
        indicator: NULL_DATA,
    };

    /// Constructs a new VarChar containing the text in the specified buffer.
    ///
    /// Caveat: This constructor is going to create a truncated value in case the input slice ends
    /// with `nul`. Should you want to insert an actual string those payload ends with `nul` into
    /// the database you need a buffer one byte longer than the string. You can instantiate such a
    /// value using [`Self::from_buffer`].
    pub fn new(value: &'a [u8]) -> Self {
        Self::from_buffer(value, Indicator::Length(value.len()))
    }
More examples
Hide additional examples
src/cursor.rs (line 126)
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
    pub fn get_text(&mut self, col_or_param_num: u16, buf: &mut Vec<u8>) -> Result<bool, Error> {
        // Utilize all of the allocated buffer. We must make sure buffer can at least hold the
        // terminating zero. We do a bit more than that though, to avoid to many repeated calls to
        // get_data.
        buf.resize(max(256, buf.capacity()), 0);
        // We repeatedly fetch data and add it to the buffer. The buffer length is therefore the
        // accumulated value size. This variable keeps track of the number of bytes we added with
        // the next call to get_data.
        let mut fetch_size = buf.len();
        let mut target = VarCharSliceMut::from_buffer(buf.as_mut_slice(), Indicator::Null);
        // Fetch binary data into buffer.
        self.get_data(col_or_param_num, &mut target)?;
        let not_null = loop {
            match target.indicator() {
                // Value is `NULL`. We are done here.
                Indicator::Null => {
                    buf.clear();
                    break false;
                }
                // We do not know how large the value is. Let's fetch the data with repeated calls
                // to get_data.
                Indicator::NoTotal => {
                    let old_len = buf.len();
                    // Use an exponential strategy for increasing buffer size.
                    buf.resize(old_len * 2, 0);
                    let buf_extend = &mut buf[(old_len - 1)..];
                    fetch_size = buf_extend.len();
                    target = VarCharSliceMut::from_buffer(buf_extend, Indicator::Null);
                    self.get_data(col_or_param_num, &mut target)?;
                }
                // We did get the complete value, including the terminating zero. Let's resize the
                // buffer to match the retrieved value exactly (excluding terminating zero).
                Indicator::Length(len) if len < fetch_size => {
                    // Since the indicator refers to value length without terminating zero, this
                    // also implicitly drops the terminating zero at the end of the buffer.
                    let shrink_by = fetch_size - len;
                    buf.resize(buf.len() - shrink_by, 0);
                    break true;
                }
                // We did not get all of the value in one go, but the data source has been friendly
                // enough to tell us how much is missing.
                Indicator::Length(len) => {
                    let still_missing = len - fetch_size + 1;
                    let old_len = buf.len();
                    buf.resize(old_len + still_missing, 0);
                    let buf_extend = &mut buf[(old_len - 1)..];
                    fetch_size = buf_extend.len();
                    target = VarCharSliceMut::from_buffer(buf_extend, Indicator::Null);
                    self.get_data(col_or_param_num, &mut target)?;
                }
            }
        };
        Ok(not_null)
    }

Returns the binary representation of the string, excluding the terminating zero or None in case the indicator is NULL_DATA.

Call this method to ensure that the entire field content did fit into the buffer. If you retrieve a field using crate::CursorRow::get_data, you can repeat the call until this method is false to read all the data.

use odbc_api::{CursorRow, parameter::VarCharArray, Error, handles::Statement};

fn process_large_text(
    col_index: u16,
    row: &mut CursorRow<'_>
) -> Result<(), Error>{
    let mut buf = VarCharArray::<512>::NULL;
    row.get_data(col_index, &mut buf)?;
    while !buf.is_complete() {
        // Process bytes in stream without allocation. We can assume repeated calls to
        // get_data do not return `None` since it would have done so on the first call.
        process_text_slice(buf.as_bytes().unwrap());
    }
    Ok(())
}

fn process_text_slice(text: &[u8]) { /*...*/}
Examples found in repository?
src/parameter/varchar.rs (line 103)
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
    pub fn as_bytes(&self) -> Option<&[u8]> {
        let slice = self.buffer.borrow();
        match self.indicator() {
            Indicator::Null => None,
            Indicator::NoTotal => Some(&slice[..(slice.len() - 1)]),
            Indicator::Length(len) => {
                if self.is_complete() {
                    Some(&slice[..len])
                } else {
                    Some(&slice[..(slice.len() - 1)])
                }
            }
        }
    }

    /// Call this method to ensure that the entire field content did fit into the buffer. If you
    /// retrieve a field using [`crate::CursorRow::get_data`], you can repeat the call until this
    /// method is false to read all the data.
    ///
    /// ```
    /// use odbc_api::{CursorRow, parameter::VarCharArray, Error, handles::Statement};
    ///
    /// fn process_large_text(
    ///     col_index: u16,
    ///     row: &mut CursorRow<'_>
    /// ) -> Result<(), Error>{
    ///     let mut buf = VarCharArray::<512>::NULL;
    ///     row.get_data(col_index, &mut buf)?;
    ///     while !buf.is_complete() {
    ///         // Process bytes in stream without allocation. We can assume repeated calls to
    ///         // get_data do not return `None` since it would have done so on the first call.
    ///         process_text_slice(buf.as_bytes().unwrap());
    ///     }
    ///     Ok(())
    /// }
    ///
    /// fn process_text_slice(text: &[u8]) { /*...*/}
    ///
    /// ```
    pub fn is_complete(&self) -> bool {
        let slice = self.buffer.borrow();
        match self.indicator() {
            Indicator::Null => true,
            Indicator::NoTotal => false,
            Indicator::Length(len) => {
                len < slice.len() || slice.is_empty() || *slice.last().unwrap() != 0
            }
        }
    }

    /// Read access to the underlying ODBC indicator. After data has been fetched the indicator
    /// value is set to the length the buffer should have had, excluding the terminating zero. It
    /// may also be `NULL_DATA` to indicate `NULL` or `NO_TOTAL` which tells us the data source
    /// does not know how big the buffer must be to hold the complete value. `NO_TOTAL` implies that
    /// the content of the current buffer is valid up to its maximum capacity.
    pub fn indicator(&self) -> Indicator {
        Indicator::from_isize(self.indicator)
    }
}

impl<B> VarChar<B>
where
    B: Borrow<[u8]>,
{
    /// Call this method to reset the indicator to a value which matches the length returned by the
    /// [`Self::as_bytes`] method. This is useful if you want to insert values into the database
    /// despite the fact, that they might have been truncated. Otherwise the behaviour of databases
    /// in this situation is driver specific. Some drivers insert up to the terminating zero, others
    /// detect the truncation and throw an error.
    pub fn hide_truncation(&mut self) {
        if !self.is_complete() {
            self.indicator = (self.buffer.borrow().len() - 1).try_into().unwrap();
        }
    }

Read access to the underlying ODBC indicator. After data has been fetched the indicator value is set to the length the buffer should have had, excluding the terminating zero. It may also be NULL_DATA to indicate NULL or NO_TOTAL which tells us the data source does not know how big the buffer must be to hold the complete value. NO_TOTAL implies that the content of the current buffer is valid up to its maximum capacity.

Examples found in repository?
src/parameter/varchar.rs (line 99)
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
    pub fn as_bytes(&self) -> Option<&[u8]> {
        let slice = self.buffer.borrow();
        match self.indicator() {
            Indicator::Null => None,
            Indicator::NoTotal => Some(&slice[..(slice.len() - 1)]),
            Indicator::Length(len) => {
                if self.is_complete() {
                    Some(&slice[..len])
                } else {
                    Some(&slice[..(slice.len() - 1)])
                }
            }
        }
    }

    /// Call this method to ensure that the entire field content did fit into the buffer. If you
    /// retrieve a field using [`crate::CursorRow::get_data`], you can repeat the call until this
    /// method is false to read all the data.
    ///
    /// ```
    /// use odbc_api::{CursorRow, parameter::VarCharArray, Error, handles::Statement};
    ///
    /// fn process_large_text(
    ///     col_index: u16,
    ///     row: &mut CursorRow<'_>
    /// ) -> Result<(), Error>{
    ///     let mut buf = VarCharArray::<512>::NULL;
    ///     row.get_data(col_index, &mut buf)?;
    ///     while !buf.is_complete() {
    ///         // Process bytes in stream without allocation. We can assume repeated calls to
    ///         // get_data do not return `None` since it would have done so on the first call.
    ///         process_text_slice(buf.as_bytes().unwrap());
    ///     }
    ///     Ok(())
    /// }
    ///
    /// fn process_text_slice(text: &[u8]) { /*...*/}
    ///
    /// ```
    pub fn is_complete(&self) -> bool {
        let slice = self.buffer.borrow();
        match self.indicator() {
            Indicator::Null => true,
            Indicator::NoTotal => false,
            Indicator::Length(len) => {
                len < slice.len() || slice.is_empty() || *slice.last().unwrap() != 0
            }
        }
    }
More examples
Hide additional examples
src/cursor.rs (line 130)
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
    pub fn get_text(&mut self, col_or_param_num: u16, buf: &mut Vec<u8>) -> Result<bool, Error> {
        // Utilize all of the allocated buffer. We must make sure buffer can at least hold the
        // terminating zero. We do a bit more than that though, to avoid to many repeated calls to
        // get_data.
        buf.resize(max(256, buf.capacity()), 0);
        // We repeatedly fetch data and add it to the buffer. The buffer length is therefore the
        // accumulated value size. This variable keeps track of the number of bytes we added with
        // the next call to get_data.
        let mut fetch_size = buf.len();
        let mut target = VarCharSliceMut::from_buffer(buf.as_mut_slice(), Indicator::Null);
        // Fetch binary data into buffer.
        self.get_data(col_or_param_num, &mut target)?;
        let not_null = loop {
            match target.indicator() {
                // Value is `NULL`. We are done here.
                Indicator::Null => {
                    buf.clear();
                    break false;
                }
                // We do not know how large the value is. Let's fetch the data with repeated calls
                // to get_data.
                Indicator::NoTotal => {
                    let old_len = buf.len();
                    // Use an exponential strategy for increasing buffer size.
                    buf.resize(old_len * 2, 0);
                    let buf_extend = &mut buf[(old_len - 1)..];
                    fetch_size = buf_extend.len();
                    target = VarCharSliceMut::from_buffer(buf_extend, Indicator::Null);
                    self.get_data(col_or_param_num, &mut target)?;
                }
                // We did get the complete value, including the terminating zero. Let's resize the
                // buffer to match the retrieved value exactly (excluding terminating zero).
                Indicator::Length(len) if len < fetch_size => {
                    // Since the indicator refers to value length without terminating zero, this
                    // also implicitly drops the terminating zero at the end of the buffer.
                    let shrink_by = fetch_size - len;
                    buf.resize(buf.len() - shrink_by, 0);
                    break true;
                }
                // We did not get all of the value in one go, but the data source has been friendly
                // enough to tell us how much is missing.
                Indicator::Length(len) => {
                    let still_missing = len - fetch_size + 1;
                    let old_len = buf.len();
                    buf.resize(old_len + still_missing, 0);
                    let buf_extend = &mut buf[(old_len - 1)..];
                    fetch_size = buf_extend.len();
                    target = VarCharSliceMut::from_buffer(buf_extend, Indicator::Null);
                    self.get_data(col_or_param_num, &mut target)?;
                }
            }
        };
        Ok(not_null)
    }

Call this method to reset the indicator to a value which matches the length returned by the Self::as_bytes method. This is useful if you want to insert values into the database despite the fact, that they might have been truncated. Otherwise the behaviour of databases in this situation is driver specific. Some drivers insert up to the terminating zero, others detect the truncation and throw an error.

Indicates missing data

Constructs a new VarChar containing the text in the specified buffer.

Caveat: This constructor is going to create a truncated value in case the input slice ends with nul. Should you want to insert an actual string those payload ends with nul into the database you need a buffer one byte longer than the string. You can instantiate such a value using Self::from_buffer.

Examples found in repository?
src/into_parameter.rs (line 36)
35
36
37
    fn into_parameter(self) -> Self::Parameter {
        VarCharSlice::new(self.as_bytes())
    }

Indicates a missing value.

Construct from a slice. If value is longer than LENGTH it will be truncated. In that case the last byte will be set to 0.

Trait Implementations§

The identifier of the C data type of the value buffer. When it is retrieving data from the data source with fetch, the driver converts the data to this type. When it sends data to the source, the driver converts the data from this type.
Indicates the length of variable sized types. May be zero for fixed sized types. Used to determine the size or existence of input parameters.
Pointer to a value corresponding to the one described by cdata_type.
Maximum length of the type in bytes (not characters). It is required to index values in bound buffers, if more than one parameter is bound. Can be set to zero for types not bound as parameter arrays, i.e. CStr.
Indicates the length of variable sized types. May be zero for fixed sized types.
Pointer to a value corresponding to the one described by cdata_type.
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
The SQL data as which the parameter is bound to ODBC.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.