odbc_api/
result_set_metadata.rs

1use std::num::NonZeroUsize;
2
3use odbc_sys::SqlDataType;
4
5use crate::{
6    handles::{slice_to_utf8, AsStatementRef, SqlChar, Statement},
7    ColumnDescription, DataType, Error,
8};
9
10/// Provides Metadata of the resulting the result set. Implemented by `Cursor` types and prepared
11/// queries. Fetching metadata from a prepared query might be expensive (driver dependent), so your
12/// application should fetch the Metadata it requires from the `Cursor` if possible.
13///
14/// See also:
15/// <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/result-set-metadata>
16pub trait ResultSetMetadata: AsStatementRef {
17    /// Fetch a column description using the column index.
18    ///
19    /// # Parameters
20    ///
21    /// * `column_number`: Column index. `0` is the bookmark column. The other column indices start
22    ///   with `1`.
23    /// * `column_description`: Holds the description of the column after the call. This method does
24    ///   not provide strong exception safety as the value of this argument is undefined in case of
25    ///   an error.
26    fn describe_col(
27        &mut self,
28        column_number: u16,
29        column_description: &mut ColumnDescription,
30    ) -> Result<(), Error> {
31        let stmt = self.as_stmt_ref();
32        stmt.describe_col(column_number, column_description)
33            .into_result(&stmt)
34    }
35
36    /// Number of columns in result set. Can also be used to see whether executing a prepared
37    /// Statement ([`crate::Prepared`]) would yield a result set, as this would return `0` if it
38    /// does not.
39    ///
40    /// See also:
41    /// <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlnumresultcols-function>
42    fn num_result_cols(&mut self) -> Result<i16, Error> {
43        let stmt = self.as_stmt_ref();
44        stmt.num_result_cols().into_result(&stmt)
45    }
46
47    /// `true` if a given column in a result set is unsigned or not a numeric type, `false`
48    /// otherwise.
49    ///
50    /// `column_number`: Index of the column, starting at 1.
51    fn column_is_unsigned(&mut self, column_number: u16) -> Result<bool, Error> {
52        let stmt = self.as_stmt_ref();
53        stmt.is_unsigned_column(column_number).into_result(&stmt)
54    }
55
56    /// Size in bytes of the columns. For variable sized types this is the maximum size, excluding a
57    /// terminating zero.
58    ///
59    /// `column_number`: Index of the column, starting at 1.
60    fn col_octet_length(&mut self, column_number: u16) -> Result<Option<NonZeroUsize>, Error> {
61        let stmt = self.as_stmt_ref();
62        stmt.col_octet_length(column_number)
63            .into_result(&stmt)
64            .map(|signed| NonZeroUsize::new(signed.max(0) as usize))
65    }
66
67    /// Maximum number of characters required to display data from the column. If the driver is
68    /// unable to provide a maximum `None` is returned.
69    ///
70    /// `column_number`: Index of the column, starting at 1.
71    fn col_display_size(&mut self, column_number: u16) -> Result<Option<NonZeroUsize>, Error> {
72        let stmt = self.as_stmt_ref();
73        stmt.col_display_size(column_number)
74            .into_result(&stmt)
75            // Map negative values to `0`. `0` is used by MSSQL to indicate a missing upper bound
76            // `-4` (`NO_TOTAL`) is used by MySQL to do the same. Mapping them both to the same
77            // value allows for less error prone generic applications. Making this value `None`
78            // instead of zero makes it explicit, that an upper bound can not always be known. It
79            // also prevents the order from being misunderstood, because the largest possible value
80            // is obviously `> 0` in this case, yet `0` is smaller than any other value.
81            .map(|signed| NonZeroUsize::new(signed.max(0) as usize))
82    }
83
84    /// Precision of the column.
85    ///
86    /// Denotes the applicable precision. For data types SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP, and all
87    /// the interval data types that represent a time interval, its value is the applicable
88    /// precision of the fractional seconds component.
89    fn col_precision(&mut self, column_number: u16) -> Result<isize, Error> {
90        let stmt = self.as_stmt_ref();
91        stmt.col_precision(column_number).into_result(&stmt)
92    }
93
94    /// The applicable scale for a numeric data type. For DECIMAL and NUMERIC data types, this is
95    /// the defined scale. It is undefined for all other data types.
96    fn col_scale(&mut self, column_number: u16) -> Result<isize, Error> {
97        let stmt = self.as_stmt_ref();
98        stmt.col_scale(column_number).into_result(&stmt)
99    }
100
101    /// The column alias, if it applies. If the column alias does not apply, the column name is
102    /// returned. If there is no column name or a column alias, an empty string is returned.
103    fn col_name(&mut self, column_number: u16) -> Result<String, Error> {
104        let stmt = self.as_stmt_ref();
105        let mut buf = vec![0; 1024];
106        stmt.col_name(column_number, &mut buf).into_result(&stmt)?;
107        Ok(slice_to_utf8(&buf).unwrap())
108    }
109
110    /// Use this if you want to iterate over all column names and allocate a `String` for each one.
111    ///
112    /// This is a wrapper around `col_name` introduced for convenience.
113    fn column_names(&mut self) -> Result<ColumnNamesIt<'_, Self>, Error> {
114        ColumnNamesIt::new(self)
115    }
116
117    /// Data type of the specified column.
118    ///
119    /// `column_number`: Index of the column, starting at 1.
120    fn col_data_type(&mut self, column_number: u16) -> Result<DataType, Error> {
121        let stmt = self.as_stmt_ref();
122        let kind = stmt.col_concise_type(column_number).into_result(&stmt)?;
123        let dt = match kind {
124            SqlDataType::UNKNOWN_TYPE => DataType::Unknown,
125            SqlDataType::EXT_VAR_BINARY => DataType::Varbinary {
126                length: self.col_octet_length(column_number)?,
127            },
128            SqlDataType::EXT_LONG_VAR_BINARY => DataType::LongVarbinary {
129                length: self.col_octet_length(column_number)?,
130            },
131            SqlDataType::EXT_BINARY => DataType::Binary {
132                length: self.col_octet_length(column_number)?,
133            },
134            SqlDataType::EXT_W_VARCHAR => DataType::WVarchar {
135                length: self.col_display_size(column_number)?,
136            },
137            SqlDataType::EXT_W_CHAR => DataType::WChar {
138                length: self.col_display_size(column_number)?,
139            },
140            SqlDataType::EXT_LONG_VARCHAR => DataType::LongVarchar {
141                length: self.col_display_size(column_number)?,
142            },
143            SqlDataType::CHAR => DataType::Char {
144                length: self.col_display_size(column_number)?,
145            },
146            SqlDataType::VARCHAR => DataType::Varchar {
147                length: self.col_display_size(column_number)?,
148            },
149            SqlDataType::NUMERIC => DataType::Numeric {
150                precision: self.col_precision(column_number)?.try_into().unwrap(),
151                scale: self.col_scale(column_number)?.try_into().unwrap(),
152            },
153            SqlDataType::DECIMAL => DataType::Decimal {
154                precision: self.col_precision(column_number)?.try_into().unwrap(),
155                scale: self.col_scale(column_number)?.try_into().unwrap(),
156            },
157            SqlDataType::INTEGER => DataType::Integer,
158            SqlDataType::SMALLINT => DataType::SmallInt,
159            SqlDataType::FLOAT => DataType::Float {
160                precision: self.col_precision(column_number)?.try_into().unwrap(),
161            },
162            SqlDataType::REAL => DataType::Real,
163            SqlDataType::DOUBLE => DataType::Double,
164            SqlDataType::DATE => DataType::Date,
165            SqlDataType::TIME => DataType::Time {
166                precision: self.col_precision(column_number)?.try_into().unwrap(),
167            },
168            SqlDataType::TIMESTAMP => DataType::Timestamp {
169                precision: self.col_precision(column_number)?.try_into().unwrap(),
170            },
171            SqlDataType::EXT_BIG_INT => DataType::BigInt,
172            SqlDataType::EXT_TINY_INT => DataType::TinyInt,
173            SqlDataType::EXT_BIT => DataType::Bit,
174            other => {
175                let mut column_description = ColumnDescription::default();
176                self.describe_col(column_number, &mut column_description)?;
177                DataType::Other {
178                    data_type: other,
179                    column_size: column_description.data_type.column_size(),
180                    decimal_digits: column_description.data_type.decimal_digits(),
181                }
182            }
183        };
184        Ok(dt)
185    }
186}
187
188/// Buffer sizes able to hold the display size of each column in utf-8 encoding. You may call this
189/// method to figure out suitable buffer sizes for text columns. [`buffers::TextRowSet::for_cursor`]
190/// will invoke this function for you.
191///
192/// # Parameters
193///
194/// * `metadata`: Used to query the display size for each column of the row set. For character
195///   data the length in characters is multiplied by 4 in order to have enough space for 4 byte
196///   utf-8 characters. This is a pessimization for some data sources (e.g. SQLite 3) which do
197///   interpret the size of a `VARCHAR(5)` column as 5 bytes rather than 5 characters.
198pub fn utf8_display_sizes(
199    metadata: &mut impl ResultSetMetadata,
200) -> Result<impl Iterator<Item = Result<Option<NonZeroUsize>, Error>> + '_, Error> {
201    let num_cols: u16 = metadata.num_result_cols()?.try_into().unwrap();
202    let it = (1..(num_cols + 1)).map(move |col_index| {
203        // Ask driver for buffer length
204        let max_str_len = if let Some(encoded_len) = metadata.col_data_type(col_index)?.utf8_len() {
205            Some(encoded_len)
206        } else {
207            metadata.col_display_size(col_index)?
208        };
209        Ok(max_str_len)
210    });
211    Ok(it)
212}
213
214/// An iterator calling `col_name` for each column_name and converting the result into UTF-8. See
215/// [`ResultSetMetada::column_names`].
216pub struct ColumnNamesIt<'c, C: ?Sized> {
217    cursor: &'c mut C,
218    buffer: Vec<SqlChar>,
219    column: u16,
220    num_cols: u16,
221}
222
223impl<'c, C: ResultSetMetadata + ?Sized> ColumnNamesIt<'c, C> {
224    fn new(cursor: &'c mut C) -> Result<Self, Error> {
225        let num_cols = cursor.num_result_cols()?.try_into().unwrap();
226        Ok(Self {
227            cursor,
228            // Some ODBC drivers do not report the required size to hold the column name. Starting
229            // with a reasonable sized buffers, allows us to fetch reasonable sized column alias
230            // even from those.
231            buffer: Vec::with_capacity(128),
232            num_cols,
233            column: 1,
234        })
235    }
236}
237
238impl<C> Iterator for ColumnNamesIt<'_, C>
239where
240    C: ResultSetMetadata,
241{
242    type Item = Result<String, Error>;
243
244    fn next(&mut self) -> Option<Self::Item> {
245        if self.column <= self.num_cols {
246            // stmt instead of cursor.col_name, so we can efficently reuse the buffer and avoid
247            // extra allocations.
248            let stmt = self.cursor.as_stmt_ref();
249
250            let result = stmt
251                .col_name(self.column, &mut self.buffer)
252                .into_result(&stmt)
253                .map(|()| slice_to_utf8(&self.buffer).unwrap());
254            self.column += 1;
255            Some(result)
256        } else {
257            None
258        }
259    }
260
261    fn size_hint(&self) -> (usize, Option<usize>) {
262        let num_cols = self.num_cols as usize;
263        (num_cols, Some(num_cols))
264    }
265}
266
267impl<C> ExactSizeIterator for ColumnNamesIt<'_, C> where C: ResultSetMetadata {}