rusqlite/column.rs
1use std::str;
2
3use crate::{Error, Result, Statement};
4
5/// Information about a column of a SQLite query.
6#[cfg(feature = "column_decltype")]
7#[cfg_attr(docsrs, doc(cfg(feature = "column_decltype")))]
8#[derive(Debug)]
9pub struct Column<'stmt> {
10 name: &'stmt str,
11 decl_type: Option<&'stmt str>,
12}
13
14#[cfg(feature = "column_decltype")]
15#[cfg_attr(docsrs, doc(cfg(feature = "column_decltype")))]
16impl Column<'_> {
17 /// Returns the name of the column.
18 #[inline]
19 #[must_use]
20 pub fn name(&self) -> &str {
21 self.name
22 }
23
24 /// Returns the type of the column (`None` for expression).
25 #[inline]
26 #[must_use]
27 pub fn decl_type(&self) -> Option<&str> {
28 self.decl_type
29 }
30}
31
32impl Statement<'_> {
33 /// Get all the column names in the result set of the prepared statement.
34 ///
35 /// If associated DB schema can be altered concurrently, you should make
36 /// sure that current statement has already been stepped once before
37 /// calling this method.
38 pub fn column_names(&self) -> Vec<&str> {
39 let n = self.column_count();
40 let mut cols = Vec::with_capacity(n);
41 for i in 0..n {
42 let s = self.column_name_unwrap(i);
43 cols.push(s);
44 }
45 cols
46 }
47
48 /// Return the number of columns in the result set returned by the prepared
49 /// statement.
50 ///
51 /// If associated DB schema can be altered concurrently, you should make
52 /// sure that current statement has already been stepped once before
53 /// calling this method.
54 #[inline]
55 pub fn column_count(&self) -> usize {
56 self.stmt.column_count()
57 }
58
59 /// Check that column name reference lifetime is limited:
60 /// https://www.sqlite.org/c3ref/column_name.html
61 /// > The returned string pointer is valid...
62 ///
63 /// `column_name` reference can become invalid if `stmt` is reprepared
64 /// (because of schema change) when `query_row` is called. So we assert
65 /// that a compilation error happens if this reference is kept alive:
66 /// ```compile_fail
67 /// use rusqlite::{Connection, Result};
68 /// fn main() -> Result<()> {
69 /// let db = Connection::open_in_memory()?;
70 /// let mut stmt = db.prepare("SELECT 1 as x")?;
71 /// let column_name = stmt.column_name(0)?;
72 /// let x = stmt.query_row([], |r| r.get::<_, i64>(0))?; // E0502
73 /// assert_eq!(1, x);
74 /// assert_eq!("x", column_name);
75 /// Ok(())
76 /// }
77 /// ```
78 #[inline]
79 pub(super) fn column_name_unwrap(&self, col: usize) -> &str {
80 // Just panic if the bounds are wrong for now, we never call this
81 // without checking first.
82 self.column_name(col).expect("Column out of bounds")
83 }
84
85 /// Returns the name assigned to a particular column in the result set
86 /// returned by the prepared statement.
87 ///
88 /// If associated DB schema can be altered concurrently, you should make
89 /// sure that current statement has already been stepped once before
90 /// calling this method.
91 ///
92 /// ## Failure
93 ///
94 /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid
95 /// column range for this row.
96 ///
97 /// # Panics
98 ///
99 /// Panics when column name is not valid UTF-8.
100 #[inline]
101 pub fn column_name(&self, col: usize) -> Result<&str> {
102 self.stmt
103 .column_name(col)
104 // clippy::or_fun_call (nightly) vs clippy::unnecessary-lazy-evaluations (stable)
105 .ok_or(Error::InvalidColumnIndex(col))
106 .map(|slice| {
107 str::from_utf8(slice.to_bytes()).expect("Invalid UTF-8 sequence in column name")
108 })
109 }
110
111 /// Returns the column index in the result set for a given column name.
112 ///
113 /// If there is no AS clause then the name of the column is unspecified and
114 /// may change from one release of SQLite to the next.
115 ///
116 /// If associated DB schema can be altered concurrently, you should make
117 /// sure that current statement has already been stepped once before
118 /// calling this method.
119 ///
120 /// # Failure
121 ///
122 /// Will return an `Error::InvalidColumnName` when there is no column with
123 /// the specified `name`.
124 #[inline]
125 pub fn column_index(&self, name: &str) -> Result<usize> {
126 let bytes = name.as_bytes();
127 let n = self.column_count();
128 for i in 0..n {
129 // Note: `column_name` is only fallible if `i` is out of bounds,
130 // which we've already checked.
131 if bytes.eq_ignore_ascii_case(self.stmt.column_name(i).unwrap().to_bytes()) {
132 return Ok(i);
133 }
134 }
135 Err(Error::InvalidColumnName(String::from(name)))
136 }
137
138 /// Returns a slice describing the columns of the result of the query.
139 ///
140 /// If associated DB schema can be altered concurrently, you should make
141 /// sure that current statement has already been stepped once before
142 /// calling this method.
143 #[cfg(feature = "column_decltype")]
144 #[cfg_attr(docsrs, doc(cfg(feature = "column_decltype")))]
145 pub fn columns(&self) -> Vec<Column> {
146 let n = self.column_count();
147 let mut cols = Vec::with_capacity(n);
148 for i in 0..n {
149 let name = self.column_name_unwrap(i);
150 let slice = self.stmt.column_decltype(i);
151 let decl_type = slice.map(|s| {
152 str::from_utf8(s.to_bytes()).expect("Invalid UTF-8 sequence in column declaration")
153 });
154 cols.push(Column { name, decl_type });
155 }
156 cols
157 }
158}
159
160#[cfg(test)]
161mod test {
162 use crate::{Connection, Result};
163
164 #[test]
165 #[cfg(feature = "column_decltype")]
166 fn test_columns() -> Result<()> {
167 use super::Column;
168
169 let db = Connection::open_in_memory()?;
170 let query = db.prepare("SELECT * FROM sqlite_master")?;
171 let columns = query.columns();
172 let column_names: Vec<&str> = columns.iter().map(Column::name).collect();
173 assert_eq!(
174 column_names.as_slice(),
175 &["type", "name", "tbl_name", "rootpage", "sql"]
176 );
177 let column_types: Vec<Option<String>> = columns
178 .iter()
179 .map(|col| col.decl_type().map(str::to_lowercase))
180 .collect();
181 assert_eq!(
182 &column_types[..3],
183 &[
184 Some("text".to_owned()),
185 Some("text".to_owned()),
186 Some("text".to_owned()),
187 ]
188 );
189 Ok(())
190 }
191
192 #[test]
193 fn test_column_name_in_error() -> Result<()> {
194 use crate::{types::Type, Error};
195 let db = Connection::open_in_memory()?;
196 db.execute_batch(
197 "BEGIN;
198 CREATE TABLE foo(x INTEGER, y TEXT);
199 INSERT INTO foo VALUES(4, NULL);
200 END;",
201 )?;
202 let mut stmt = db.prepare("SELECT x as renamed, y FROM foo")?;
203 let mut rows = stmt.query([])?;
204 let row = rows.next()?.unwrap();
205 match row.get::<_, String>(0).unwrap_err() {
206 Error::InvalidColumnType(idx, name, ty) => {
207 assert_eq!(idx, 0);
208 assert_eq!(name, "renamed");
209 assert_eq!(ty, Type::Integer);
210 }
211 e => {
212 panic!("Unexpected error type: {e:?}");
213 }
214 }
215 match row.get::<_, String>("y").unwrap_err() {
216 Error::InvalidColumnType(idx, name, ty) => {
217 assert_eq!(idx, 1);
218 assert_eq!(name, "y");
219 assert_eq!(ty, Type::Null);
220 }
221 e => {
222 panic!("Unexpected error type: {e:?}");
223 }
224 }
225 Ok(())
226 }
227
228 /// `column_name` reference should stay valid until `stmt` is reprepared (or
229 /// reset) even if DB schema is altered (SQLite documentation is
230 /// ambiguous here because it says reference "is valid until (...) the next
231 /// call to sqlite3_column_name() or sqlite3_column_name16() on the same
232 /// column.". We assume that reference is valid if only
233 /// `sqlite3_column_name()` is used):
234 #[test]
235 #[cfg(feature = "modern_sqlite")]
236 fn test_column_name_reference() -> Result<()> {
237 let db = Connection::open_in_memory()?;
238 db.execute_batch("CREATE TABLE y (x);")?;
239 let stmt = db.prepare("SELECT x FROM y;")?;
240 let column_name = stmt.column_name(0)?;
241 assert_eq!("x", column_name);
242 db.execute_batch("ALTER TABLE y RENAME COLUMN x TO z;")?;
243 // column name is not refreshed until statement is re-prepared
244 let same_column_name = stmt.column_name(0)?;
245 assert_eq!(same_column_name, column_name);
246 Ok(())
247 }
248}