odbc_api/buffers/
columnar.rs

1use std::{
2    collections::HashSet,
3    num::NonZeroUsize,
4    str::{from_utf8, Utf8Error},
5};
6
7use crate::{
8    columnar_bulk_inserter::BoundInputSlice,
9    cursor::TruncationInfo,
10    fixed_sized::Pod,
11    handles::{CDataMut, Statement, StatementRef},
12    parameter::WithDataType,
13    result_set_metadata::utf8_display_sizes,
14    Error, ResultSetMetadata, RowSetBuffer,
15};
16
17use super::{Indicator, TextColumn};
18
19impl<C: ColumnBuffer> ColumnarBuffer<C> {
20    /// Create a new instance from columns with unique indicies. Capacity of the buffer will be the
21    /// minimum capacity of the columns. The constructed buffer is always empty (i.e. the number of
22    /// valid rows is considered to be zero).
23    ///
24    /// You do not want to call this constructor directly unless you want to provide your own buffer
25    /// implentation. Most users of this crate may want to use the constructors like
26    /// [`crate::buffers::ColumnarAnyBuffer::from_descs`] or
27    /// [`crate::buffers::TextRowSet::from_max_str_lens`] instead.
28    pub fn new(columns: Vec<(u16, C)>) -> Self {
29        // Assert capacity
30        let capacity = columns
31            .iter()
32            .map(|(_, col)| col.capacity())
33            .min()
34            .unwrap_or(0);
35
36        // Assert uniqueness of indices
37        let mut indices = HashSet::new();
38        if columns
39            .iter()
40            .any(move |&(col_index, _)| !indices.insert(col_index))
41        {
42            panic!("Column indices must be unique.")
43        }
44
45        unsafe { Self::new_unchecked(capacity, columns) }
46    }
47
48    /// # Safety
49    ///
50    /// * Indices must be unique
51    /// * Columns all must have enough `capacity`.
52    pub unsafe fn new_unchecked(capacity: usize, columns: Vec<(u16, C)>) -> Self {
53        ColumnarBuffer {
54            num_rows: Box::new(0),
55            row_capacity: capacity,
56            columns,
57        }
58    }
59
60    /// Number of valid rows in the buffer.
61    pub fn num_rows(&self) -> usize {
62        *self.num_rows
63    }
64
65    /// Return the number of columns in the row set.
66    pub fn num_cols(&self) -> usize {
67        self.columns.len()
68    }
69
70    /// Use this method to gain read access to the actual column data.
71    ///
72    /// # Parameters
73    ///
74    /// * `buffer_index`: Please note that the buffer index is not identical to the ODBC column
75    ///   index. For one it is zero based. It also indexes the buffer bound, and not the columns of
76    ///   the output result set. This is important, because not every column needs to be bound. Some
77    ///   columns may simply be ignored. That being said, if every column of the output is bound in
78    ///   the buffer, in the same order in which they are enumerated in the result set, the
79    ///   relationship between column index and buffer index is `buffer_index = column_index - 1`.
80    pub fn column(&self, buffer_index: usize) -> C::View<'_> {
81        self.columns[buffer_index].1.view(*self.num_rows)
82    }
83}
84
85unsafe impl<C> RowSetBuffer for ColumnarBuffer<C>
86where
87    C: ColumnBuffer,
88{
89    fn bind_type(&self) -> usize {
90        0 // Specify columnar binding
91    }
92
93    fn row_array_size(&self) -> usize {
94        self.row_capacity
95    }
96
97    fn mut_num_fetch_rows(&mut self) -> &mut usize {
98        self.num_rows.as_mut()
99    }
100
101    unsafe fn bind_colmuns_to_cursor(&mut self, mut cursor: StatementRef<'_>) -> Result<(), Error> {
102        for (col_number, column) in &mut self.columns {
103            cursor.bind_col(*col_number, column).into_result(&cursor)?;
104        }
105        Ok(())
106    }
107
108    fn find_truncation(&self) -> Option<TruncationInfo> {
109        self.columns
110            .iter()
111            .enumerate()
112            .find_map(|(buffer_index, (_col_index, col_buffer))| {
113                col_buffer
114                    .has_truncated_values(*self.num_rows)
115                    .map(|indicator| TruncationInfo {
116                        indicator: indicator.length(),
117                        buffer_index,
118                    })
119            })
120    }
121}
122
123/// A columnar buffer intended to be bound with [crate::Cursor::bind_buffer] in order to obtain
124/// results from a cursor.
125///
126/// Binds to the result set column wise. This is usually helpful in dataengineering or data sciense
127/// tasks. This buffer type can be used in situations there the schema of the queried data is known
128/// at compile time, as well as for generic applications which do work with wide range of different
129/// data.
130///
131/// # Example: Fetching results column wise with `ColumnarBuffer`.
132///
133/// Consider querying a table with two columns `year` and `name`.
134///
135/// ```no_run
136/// use odbc_api::{
137///     Environment, Cursor, ConnectionOptions,
138///     buffers::{AnySlice, BufferDesc, Item, ColumnarAnyBuffer},
139/// };
140///
141/// let env = Environment::new()?;
142///
143/// let batch_size = 1000; // Maximum number of rows in each row set
144/// let buffer_description = [
145///     // We know year to be a Nullable SMALLINT
146///     BufferDesc::I16 { nullable: true },
147///     // and name to be a required VARCHAR
148///     BufferDesc::Text { max_str_len: 255 },
149/// ];
150///
151/// /// Creates a columnar buffer fitting the buffer description with the capacity of `batch_size`.
152/// let mut buffer = ColumnarAnyBuffer::from_descs(batch_size, buffer_description);
153///
154/// let mut conn = env.connect(
155///     "YourDatabase", "SA", "My@Test@Password1",
156///     ConnectionOptions::default(),
157/// )?;
158/// if let Some(cursor) = conn.execute("SELECT year, name FROM Birthdays;", ())? {
159///     // Bind buffer to cursor. We bind the buffer as a mutable reference here, which makes it
160///     // easier to reuse for other queries, but we could have taken ownership.
161///     let mut row_set_cursor = cursor.bind_buffer(&mut buffer)?;
162///     // Loop over row sets
163///     while let Some(row_set) = row_set_cursor.fetch()? {
164///         // Process years in row set
165///         let year_col = row_set.column(0);
166///         for year in i16::as_nullable_slice(year_col)
167///             .expect("Year column buffer expected to be nullable Int")
168///         {
169///             // Iterate over `Option<i16>` with it ..
170///         }
171///         // Process names in row set
172///         let name_col = row_set.column(1);
173///         for name in name_col
174///             .as_text_view()
175///             .expect("Name column buffer expected to be text")
176///             .iter()
177///         {
178///             // Iterate over `Option<&CStr> ..
179///         }
180///     }
181/// }
182/// # Ok::<(), odbc_api::Error>(())
183/// ```
184///
185/// This second examples changes two things, we do not know the schema in advance and use the
186/// SQL DataType to determine the best fit for the buffers. Also we want to do everything in a
187/// function and return a `Cursor` with an already bound buffer. This approach is best if you have
188/// few and very long query, so the overhead of allocating buffers is negligible and you want to
189/// have an easier time with the borrow checker.
190///
191/// ```no_run
192/// use odbc_api::{
193///     Connection, BlockCursor, Error, Cursor, Nullability, ResultSetMetadata,
194///     buffers::{ AnyBuffer, BufferDesc, ColumnarAnyBuffer, ColumnarBuffer }
195/// };
196///
197/// fn get_birthdays<'a>(conn: &'a mut Connection)
198///     -> Result<BlockCursor<impl Cursor + 'a, ColumnarAnyBuffer>, Error>
199/// {
200///     let mut cursor = conn.execute("SELECT year, name FROM Birthdays;", ())?.unwrap();
201///     let mut column_description = Default::default();
202///     let buffer_description : Vec<_> = (0..cursor.num_result_cols()?).map(|index| {
203///         cursor.describe_col(index as u16 + 1, &mut column_description)?;
204///         let nullable = matches!(
205///             column_description.nullability,
206///             Nullability::Unknown | Nullability::Nullable
207///         );
208///         let desc = BufferDesc::from_data_type(
209///             column_description.data_type,
210///             nullable
211///         ).unwrap_or(BufferDesc::Text{ max_str_len: 255 });
212///         Ok(desc)
213///     }).collect::<Result<_, Error>>()?;
214///
215///     // Row set size of 5000 rows.
216///     let buffer = ColumnarAnyBuffer::from_descs(5000, buffer_description);
217///     // Bind buffer and take ownership over it.
218///     cursor.bind_buffer(buffer)
219/// }
220/// ```
221pub struct ColumnarBuffer<C> {
222    /// A mutable pointer to num_rows_fetched is passed to the C-API. It is used to write back the
223    /// number of fetched rows. `num_rows` is heap allocated, so the pointer is not invalidated,
224    /// even if the `ColumnarBuffer` instance is moved in memory.
225    num_rows: Box<usize>,
226    /// aka: batch size, row array size
227    row_capacity: usize,
228    /// Column index and bound buffer
229    columns: Vec<(u16, C)>,
230}
231
232/// A buffer for a single column intended to be used together with [`ColumnarBuffer`].
233///
234/// # Safety
235///
236/// Views must not allow access to unintialized / invalid rows.
237pub unsafe trait ColumnBuffer: CDataMut {
238    /// Immutable view on the column data. Used in safe abstractions. User must not be able to
239    /// access uninitialized or invalid memory of the buffer through this interface.
240    type View<'a>
241    where
242        Self: 'a;
243
244    /// Num rows may not exceed the actual amount of valid num_rows filled by the ODBC API. The
245    /// column buffer does not know how many elements were in the last row group, and therefore can
246    /// not guarantee the accessed element to be valid and in a defined state. It also can not panic
247    /// on accessing an undefined element.
248    fn view(&self, valid_rows: usize) -> Self::View<'_>;
249
250    /// Fills the column with the default representation of values, between `from` and `to` index.
251    fn fill_default(&mut self, from: usize, to: usize);
252
253    /// Current capacity of the column
254    fn capacity(&self) -> usize;
255
256    /// `Some` if any value is truncated in the range [0, num_rows).
257    ///
258    /// After fetching data we may want to know if any value has been truncated due to the buffer
259    /// not being able to hold elements of that size. This method checks the indicator buffer
260    /// element wise.
261    fn has_truncated_values(&self, num_rows: usize) -> Option<Indicator>;
262}
263
264unsafe impl<T> ColumnBuffer for WithDataType<T>
265where
266    T: ColumnBuffer,
267{
268    type View<'a>
269        = T::View<'a>
270    where
271        T: 'a;
272
273    fn view(&self, valid_rows: usize) -> T::View<'_> {
274        self.value.view(valid_rows)
275    }
276
277    fn fill_default(&mut self, from: usize, to: usize) {
278        self.value.fill_default(from, to)
279    }
280
281    fn capacity(&self) -> usize {
282        self.value.capacity()
283    }
284
285    fn has_truncated_values(&self, num_rows: usize) -> Option<Indicator> {
286        self.value.has_truncated_values(num_rows)
287    }
288}
289
290unsafe impl<'a, T> BoundInputSlice<'a> for WithDataType<T>
291where
292    T: BoundInputSlice<'a>,
293{
294    type SliceMut = T::SliceMut;
295
296    unsafe fn as_view_mut(
297        &'a mut self,
298        parameter_index: u16,
299        stmt: StatementRef<'a>,
300    ) -> Self::SliceMut {
301        self.value.as_view_mut(parameter_index, stmt)
302    }
303}
304
305/// This row set binds a string buffer to each column, which is large enough to hold the maximum
306/// length string representation for each element in the row set at once.
307///
308/// # Example
309///
310/// ```no_run
311/// //! A program executing a query and printing the result as csv to standard out. Requires
312/// //! `anyhow` and `csv` crate.
313///
314/// use anyhow::Error;
315/// use odbc_api::{buffers::TextRowSet, Cursor, Environment, ConnectionOptions, ResultSetMetadata};
316/// use std::{
317///     ffi::CStr,
318///     io::{stdout, Write},
319///     path::PathBuf,
320/// };
321///
322/// /// Maximum number of rows fetched with one row set. Fetching batches of rows is usually much
323/// /// faster than fetching individual rows.
324/// const BATCH_SIZE: usize = 5000;
325///
326/// fn main() -> Result<(), Error> {
327///     // Write csv to standard out
328///     let out = stdout();
329///     let mut writer = csv::Writer::from_writer(out);
330///
331///     // We know this is going to be the only ODBC environment in the entire process, so this is
332///     // safe.
333///     let environment = unsafe { Environment::new() }?;
334///
335///     // Connect using a DSN. Alternatively we could have used a connection string
336///     let mut connection = environment.connect(
337///         "DataSourceName",
338///         "Username",
339///         "Password",
340///         ConnectionOptions::default(),
341///     )?;
342///
343///     // Execute a one of query without any parameters.
344///     match connection.execute("SELECT * FROM TableName", ())? {
345///         Some(mut cursor) => {
346///             // Write the column names to stdout
347///             let mut headline : Vec<String> = cursor.column_names()?.collect::<Result<_,_>>()?;
348///             writer.write_record(headline)?;
349///
350///             // Use schema in cursor to initialize a text buffer large enough to hold the largest
351///             // possible strings for each column up to an upper limit of 4KiB
352///             let mut buffers = TextRowSet::for_cursor(BATCH_SIZE, &mut cursor, Some(4096))?;
353///             // Bind the buffer to the cursor. It is now being filled with every call to fetch.
354///             let mut row_set_cursor = cursor.bind_buffer(&mut buffers)?;
355///
356///             // Iterate over batches
357///             while let Some(batch) = row_set_cursor.fetch()? {
358///                 // Within a batch, iterate over every row
359///                 for row_index in 0..batch.num_rows() {
360///                     // Within a row iterate over every column
361///                     let record = (0..batch.num_cols()).map(|col_index| {
362///                         batch
363///                             .at(col_index, row_index)
364///                             .unwrap_or(&[])
365///                     });
366///                     // Writes row as csv
367///                     writer.write_record(record)?;
368///                 }
369///             }
370///         }
371///         None => {
372///             eprintln!(
373///                 "Query came back empty. No output has been created."
374///             );
375///         }
376///     }
377///
378///     Ok(())
379/// }
380/// ```
381pub type TextRowSet = ColumnarBuffer<TextColumn<u8>>;
382
383impl TextRowSet {
384    /// The resulting text buffer is not in any way tied to the cursor, other than that its buffer
385    /// sizes a tailor fitted to result set the cursor is iterating over.
386    ///
387    /// This method performs fallible buffer allocations, if no upper bound is set, so you may see
388    /// a speedup, by setting an upper bound using `max_str_limit`.
389    ///
390    ///
391    /// # Parameters
392    ///
393    /// * `batch_size`: The maximum number of rows the buffer is able to hold.
394    /// * `cursor`: Used to query the display size for each column of the row set. For character
395    ///   data the length in characters is multiplied by 4 in order to have enough space for 4 byte
396    ///   utf-8 characters. This is a pessimization for some data sources (e.g. SQLite 3) which do
397    ///   interpret the size of a `VARCHAR(5)` column as 5 bytes rather than 5 characters.
398    /// * `max_str_limit`: Some queries make it hard to estimate a sensible upper bound and
399    ///   sometimes drivers are just not that good at it. This argument allows you to specify an
400    ///   upper bound for the length of character data. Any size reported by the driver is capped to
401    ///   this value. In case the upper bound can not inferred by the metadata reported by the
402    ///   driver the element size is set to this upper bound, too.
403    pub fn for_cursor(
404        batch_size: usize,
405        cursor: &mut impl ResultSetMetadata,
406        max_str_limit: Option<usize>,
407    ) -> Result<TextRowSet, Error> {
408        let buffers = utf8_display_sizes(cursor)?
409            .enumerate()
410            .map(|(buffer_index, reported_len)| {
411                let buffer_index = buffer_index as u16;
412                let col_index = buffer_index + 1;
413                let max_str_len = reported_len?;
414                let buffer = if let Some(upper_bound) = max_str_limit {
415                    let max_str_len = max_str_len
416                        .map(NonZeroUsize::get)
417                        .unwrap_or(upper_bound)
418                        .min(upper_bound);
419                    TextColumn::new(batch_size, max_str_len)
420                } else {
421                    let max_str_len = max_str_len.map(NonZeroUsize::get).ok_or(
422                        Error::TooLargeColumnBufferSize {
423                            buffer_index,
424                            num_elements: batch_size,
425                            element_size: usize::MAX,
426                        },
427                    )?;
428                    TextColumn::try_new(batch_size, max_str_len).map_err(|source| {
429                        Error::TooLargeColumnBufferSize {
430                            buffer_index,
431                            num_elements: source.num_elements,
432                            element_size: source.element_size,
433                        }
434                    })?
435                };
436
437                Ok::<_, Error>((col_index, buffer))
438            })
439            .collect::<Result<_, _>>()?;
440        Ok(TextRowSet {
441            row_capacity: batch_size,
442            num_rows: Box::new(0),
443            columns: buffers,
444        })
445    }
446
447    /// Creates a text buffer large enough to hold `batch_size` rows with one column for each item
448    /// `max_str_lengths` of respective size.
449    pub fn from_max_str_lens(
450        row_capacity: usize,
451        max_str_lengths: impl IntoIterator<Item = usize>,
452    ) -> Result<Self, Error> {
453        let buffers = max_str_lengths
454            .into_iter()
455            .enumerate()
456            .map(|(index, max_str_len)| {
457                Ok::<_, Error>((
458                    (index + 1).try_into().unwrap(),
459                    TextColumn::try_new(row_capacity, max_str_len)
460                        .map_err(|source| source.add_context(index.try_into().unwrap()))?,
461                ))
462            })
463            .collect::<Result<_, _>>()?;
464        Ok(TextRowSet {
465            row_capacity,
466            num_rows: Box::new(0),
467            columns: buffers,
468        })
469    }
470
471    /// Access the element at the specified position in the row set.
472    pub fn at(&self, buffer_index: usize, row_index: usize) -> Option<&[u8]> {
473        assert!(row_index < *self.num_rows);
474        self.columns[buffer_index].1.value_at(row_index)
475    }
476
477    /// Access the element at the specified position in the row set.
478    pub fn at_as_str(&self, col_index: usize, row_index: usize) -> Result<Option<&str>, Utf8Error> {
479        self.at(col_index, row_index).map(from_utf8).transpose()
480    }
481
482    /// Indicator value at the specified position. Useful to detect truncation of data.
483    ///
484    /// # Example
485    ///
486    /// ```
487    /// use odbc_api::buffers::{Indicator, TextRowSet};
488    ///
489    /// fn is_truncated(buffer: &TextRowSet, col_index: usize, row_index: usize) -> bool {
490    ///     match buffer.indicator_at(col_index, row_index) {
491    ///         // There is no value, therefore there is no value not fitting in the column buffer.
492    ///         Indicator::Null => false,
493    ///         // The value did not fit into the column buffer, we do not even know, by how much.
494    ///         Indicator::NoTotal => true,
495    ///         Indicator::Length(total_length) => {
496    ///             // If the maximum string length is shorter than the values total length, the
497    ///             // has been truncated to fit into the buffer.
498    ///             buffer.max_len(col_index) < total_length
499    ///         }
500    ///     }
501    /// }
502    /// ```
503    pub fn indicator_at(&self, buf_index: usize, row_index: usize) -> Indicator {
504        assert!(row_index < *self.num_rows);
505        self.columns[buf_index].1.indicator_at(row_index)
506    }
507
508    /// Maximum length in bytes of elements in a column.
509    pub fn max_len(&self, buf_index: usize) -> usize {
510        self.columns[buf_index].1.max_len()
511    }
512}
513
514unsafe impl<T> ColumnBuffer for Vec<T>
515where
516    T: Pod,
517{
518    type View<'a> = &'a [T];
519
520    fn view(&self, valid_rows: usize) -> &[T] {
521        &self[..valid_rows]
522    }
523
524    fn fill_default(&mut self, from: usize, to: usize) {
525        for item in &mut self[from..to] {
526            *item = Default::default();
527        }
528    }
529
530    fn capacity(&self) -> usize {
531        self.len()
532    }
533
534    fn has_truncated_values(&self, _num_rows: usize) -> Option<Indicator> {
535        None
536    }
537}
538
539#[cfg(test)]
540mod tests {
541
542    use crate::buffers::{BufferDesc, ColumnarAnyBuffer};
543
544    #[test]
545    #[should_panic(expected = "Column indices must be unique.")]
546    fn assert_unique_column_indices() {
547        let bd = BufferDesc::I32 { nullable: false };
548        ColumnarAnyBuffer::from_descs_and_indices(1, [(1, bd), (2, bd), (1, bd)].iter().cloned());
549    }
550}