Skip to main content

rusqlite/
column.rs

1use std::ffi::{CStr, CString, c_char};
2use std::ptr;
3use std::str;
4
5use crate::ffi;
6use crate::{Connection, Error, Name, Result, Statement};
7
8/// Information about a column of a SQLite query.
9#[cfg(feature = "column_decltype")]
10#[derive(Debug)]
11pub struct Column<'stmt> {
12    name: &'stmt str,
13    decl_type: Option<&'stmt str>,
14}
15
16#[cfg(feature = "column_decltype")]
17impl Column<'_> {
18    /// Returns the name of the column.
19    #[inline]
20    #[must_use]
21    pub fn name(&self) -> &str {
22        self.name
23    }
24
25    /// Returns the type of the column (`None` for expression).
26    #[inline]
27    #[must_use]
28    pub fn decl_type(&self) -> Option<&str> {
29        self.decl_type
30    }
31}
32
33/// Metadata about the origin of a column of a SQLite query
34#[cfg(feature = "column_metadata")]
35#[derive(Debug)]
36pub struct ColumnMetadata<'stmt> {
37    name: &'stmt str,
38    database_name: Option<&'stmt str>,
39    table_name: Option<&'stmt str>,
40    origin_name: Option<&'stmt str>,
41}
42
43#[cfg(feature = "column_metadata")]
44impl ColumnMetadata<'_> {
45    #[inline]
46    #[must_use]
47    /// Returns the name of the column in the query results
48    pub fn name(&self) -> &str {
49        self.name
50    }
51
52    #[inline]
53    #[must_use]
54    /// Returns the database name from which the column originates
55    pub fn database_name(&self) -> Option<&str> {
56        self.database_name
57    }
58
59    #[inline]
60    #[must_use]
61    /// Returns the table name from which the column originates
62    pub fn table_name(&self) -> Option<&str> {
63        self.table_name
64    }
65
66    #[inline]
67    #[must_use]
68    /// Returns the column name from which the column originates
69    pub fn origin_name(&self) -> Option<&str> {
70        self.origin_name
71    }
72}
73
74impl Statement<'_> {
75    /// Get all the column names in the result set of the prepared statement.
76    ///
77    /// If associated DB schema can be altered concurrently, you should make
78    /// sure that current statement has already been stepped once before
79    /// calling this method.
80    pub fn column_names(&self) -> impl DoubleEndedIterator<Item = &str> + ExactSizeIterator {
81        ColumnsIter::new(self, Statement::column_name_unwrap)
82    }
83
84    /// Return the number of columns in the result set returned by the prepared
85    /// statement.
86    ///
87    /// If associated DB schema can be altered concurrently, you should make
88    /// sure that current statement has already been stepped once before
89    /// calling this method.
90    #[inline]
91    pub fn column_count(&self) -> usize {
92        self.stmt.column_count()
93    }
94
95    /// Check that column name reference lifetime is limited:
96    /// <https://www.sqlite.org/c3ref/column_name.html>
97    /// > The returned string pointer is valid...
98    ///
99    /// `column_name` reference can become invalid if `stmt` is reprepared
100    /// (because of schema change) when `query_row` is called. So we assert
101    /// that a compilation error happens if this reference is kept alive:
102    /// ```compile_fail
103    /// use rusqlite::{Connection, Result};
104    /// fn main() -> Result<()> {
105    ///     let db = Connection::open_in_memory()?;
106    ///     let mut stmt = db.prepare("SELECT 1 as x")?;
107    ///     let column_name = stmt.column_name(0)?;
108    ///     let x = stmt.query_row([], |r| r.get::<_, i64>(0))?; // E0502
109    ///     assert_eq!(1, x);
110    ///     assert_eq!("x", column_name);
111    ///     Ok(())
112    /// }
113    /// ```
114    #[inline]
115    pub(super) fn column_name_unwrap(&self, col: usize) -> &str {
116        // Just panic if the bounds are wrong for now, we never call this
117        // without checking first.
118        self.column_name(col).expect("Column out of bounds")
119    }
120
121    /// Returns the name assigned to a particular column in the result set
122    /// returned by the prepared statement.
123    ///
124    /// If associated DB schema can be altered concurrently, you should make
125    /// sure that current statement has already been stepped once before
126    /// calling this method.
127    ///
128    /// ## Failure
129    ///
130    /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid
131    /// column range for this row.
132    ///
133    /// # Panics
134    ///
135    /// Panics when column name is not valid UTF-8.
136    #[inline]
137    pub fn column_name(&self, col: usize) -> Result<&str> {
138        self.stmt
139            .column_name(col)
140            // clippy::or_fun_call (nightly) vs clippy::unnecessary-lazy-evaluations (stable)
141            .ok_or(Error::InvalidColumnIndex(col))
142            .map(|slice| {
143                slice
144                    .to_str()
145                    .expect("Invalid UTF-8 sequence in column name")
146            })
147    }
148
149    /// Returns the column index in the result set for a given column name.
150    ///
151    /// If there is no AS clause then the name of the column is unspecified and
152    /// may change from one release of SQLite to the next.
153    ///
154    /// If associated DB schema can be altered concurrently, you should make
155    /// sure that current statement has already been stepped once before
156    /// calling this method.
157    ///
158    /// # Failure
159    ///
160    /// Will return an `Error::InvalidColumnName` when there is no column with
161    /// the specified `name`.
162    #[inline]
163    pub fn column_index(&self, name: &str) -> Result<usize> {
164        let bytes = name.as_bytes();
165        let n = self.column_count();
166        for i in 0..n {
167            // Note: `column_name` is only fallible if `i` is out of bounds,
168            // which we've already checked.
169            if bytes.eq_ignore_ascii_case(self.stmt.column_name(i).unwrap().to_bytes()) {
170                return Ok(i);
171            }
172        }
173        Err(Error::InvalidColumnName(String::from(name)))
174    }
175
176    /// Returns a slice describing the columns of the result of the query.
177    ///
178    /// If associated DB schema can be altered concurrently, you should make
179    /// sure that current statement has already been stepped once before
180    /// calling this method.
181    #[cfg(feature = "column_decltype")]
182    pub fn columns(&self) -> impl DoubleEndedIterator<Item = Column<'_>> + ExactSizeIterator {
183        ColumnsIter::new(self, |s, i| Column {
184            name: s.column_name_unwrap(i),
185            decl_type: s.stmt.column_decltype(i).map(|s| {
186                s.to_str()
187                    .expect("Invalid UTF-8 sequence in column declaration")
188            }),
189        })
190    }
191
192    /// Returns the names of the database, table, and row from which
193    /// each column of this query's results originate.
194    ///
195    /// Computed or otherwise derived columns will have None values for these fields.
196    #[cfg(feature = "column_metadata")]
197    pub fn columns_with_metadata(
198        &self,
199    ) -> impl DoubleEndedIterator<Item = ColumnMetadata<'_>> + ExactSizeIterator {
200        ColumnsIter::new(self, |s, i| ColumnMetadata {
201            name: s.column_name_unwrap(i),
202            database_name: s.stmt.column_database_name(i).map(|s| {
203                s.to_str()
204                    .expect("Invalid UTF-8 sequence in column db name")
205            }),
206            table_name: s.stmt.column_table_name(i).map(|s| {
207                s.to_str()
208                    .expect("Invalid UTF-8 sequence in column table name")
209            }),
210            origin_name: s.stmt.column_origin_name(i).map(|s| {
211                s.to_str()
212                    .expect("Invalid UTF-8 sequence in column origin name")
213            }),
214        })
215    }
216
217    /// Extract metadata of column at specified index
218    ///
219    /// Returns:
220    /// - database name
221    /// - table name
222    /// - original column name
223    /// - declared data type
224    /// - name of default collation sequence
225    /// - True if column has a NOT NULL constraint
226    /// - True if column is part of the PRIMARY KEY
227    /// - True if column is AUTOINCREMENT
228    ///
229    /// See [`Connection::column_metadata`]
230    #[cfg(feature = "column_metadata")]
231    #[expect(clippy::type_complexity)]
232    pub fn column_metadata(
233        &self,
234        col: usize,
235    ) -> Result<
236        Option<(
237            &CStr,
238            &CStr,
239            &CStr,
240            Option<CString>,
241            Option<CString>,
242            bool,
243            bool,
244            bool,
245        )>,
246    > {
247        let db_name = self.stmt.column_database_name(col);
248        let table_name = self.stmt.column_table_name(col);
249        let origin_name = self.stmt.column_origin_name(col);
250        if db_name.is_none() || table_name.is_none() || origin_name.is_none() {
251            return Ok(None);
252        }
253        let (data_type, coll_seq, not_null, primary_key, auto_inc) =
254            self.conn
255                .column_metadata(db_name, table_name.unwrap(), origin_name.unwrap())?;
256        Ok(Some((
257            db_name.unwrap(),
258            table_name.unwrap(),
259            origin_name.unwrap(),
260            data_type,
261            coll_seq,
262            not_null,
263            primary_key,
264            auto_inc,
265        )))
266    }
267}
268
269impl Connection {
270    /// Check if `table_name`.`column_name` exists.
271    ///
272    /// `db_name` is main, temp, the name in ATTACH, or `None` to search all databases.
273    pub fn column_exists<N: Name>(
274        &self,
275        db_name: Option<N>,
276        table_name: N,
277        column_name: N,
278    ) -> Result<bool> {
279        self.exists(db_name, table_name, Some(column_name))
280    }
281
282    /// Check if `table_name` exists.
283    ///
284    /// `db_name` is main, temp, the name in ATTACH, or `None` to search all databases.
285    pub fn table_exists<N: Name>(&self, db_name: Option<N>, table_name: N) -> Result<bool> {
286        self.exists(db_name, table_name, None)
287    }
288
289    /// Extract metadata of column at specified index
290    ///
291    /// Returns:
292    /// - declared data type
293    /// - name of default collation sequence
294    /// - True if column has a NOT NULL constraint
295    /// - True if column is part of the PRIMARY KEY
296    /// - True if column is AUTOINCREMENT
297    #[expect(clippy::type_complexity)]
298    pub fn column_metadata<N: Name>(
299        &self,
300        db_name: Option<N>,
301        table_name: N,
302        column_name: N,
303    ) -> Result<(Option<CString>, Option<CString>, bool, bool, bool)> {
304        let cs = db_name.as_ref().map(N::as_cstr).transpose()?;
305        let db_name = cs.as_ref().map_or(ptr::null(), |s| s.as_ptr());
306        let table_name = table_name.as_cstr()?;
307        let column_name = column_name.as_cstr()?;
308
309        let mut data_type: *const c_char = ptr::null_mut();
310        let mut coll_seq: *const c_char = ptr::null_mut();
311        let mut not_null = 0;
312        let mut primary_key = 0;
313        let mut auto_inc = 0;
314
315        self.decode_result(unsafe {
316            ffi::sqlite3_table_column_metadata(
317                self.handle(),
318                db_name,
319                table_name.as_ptr(),
320                column_name.as_ptr(),
321                &raw mut data_type,
322                &raw mut coll_seq,
323                &raw mut not_null,
324                &raw mut primary_key,
325                &raw mut auto_inc,
326            )
327        })?;
328
329        Ok((
330            if data_type.is_null() {
331                None
332            } else {
333                Some(unsafe { CStr::from_ptr(data_type).to_owned() })
334            },
335            if coll_seq.is_null() {
336                None
337            } else {
338                Some(unsafe { CStr::from_ptr(coll_seq).to_owned() })
339            },
340            not_null != 0,
341            primary_key != 0,
342            auto_inc != 0,
343        ))
344    }
345
346    fn exists<N: Name>(
347        &self,
348        db_name: Option<N>,
349        table_name: N,
350        column_name: Option<N>,
351    ) -> Result<bool> {
352        let cs = db_name.as_ref().map(N::as_cstr).transpose()?;
353        let db_name = cs.as_ref().map_or(ptr::null(), |s| s.as_ptr());
354        let table_name = table_name.as_cstr()?;
355        let cn = column_name.as_ref().map(N::as_cstr).transpose()?;
356        let column_name = cn.as_ref().map_or(ptr::null(), |s| s.as_ptr());
357        let r = unsafe {
358            ffi::sqlite3_table_column_metadata(
359                self.handle(),
360                db_name,
361                table_name.as_ptr(),
362                column_name,
363                ptr::null_mut(),
364                ptr::null_mut(),
365                ptr::null_mut(),
366                ptr::null_mut(),
367                ptr::null_mut(),
368            )
369        };
370        match r {
371            ffi::SQLITE_OK => Ok(true),
372            ffi::SQLITE_ERROR => Ok(false),
373            _ => self.db.borrow().decode_result(r).map(|()| false),
374        }
375    }
376}
377
378struct ColumnsIter<'s, T> {
379    stmt: &'s Statement<'s>,
380    range: std::ops::Range<usize>,
381    map: fn(stmt: &'s Statement<'s>, col: usize) -> T,
382}
383impl<'s, T> ColumnsIter<'s, T> {
384    fn new(stmt: &'s Statement<'s>, map: fn(stmt: &'s Statement<'s>, col: usize) -> T) -> Self {
385        Self {
386            stmt,
387            range: 0..stmt.column_count(),
388            map,
389        }
390    }
391}
392impl<T> Iterator for ColumnsIter<'_, T> {
393    type Item = T;
394
395    #[inline]
396    fn next(&mut self) -> Option<Self::Item> {
397        Some((self.map)(self.stmt, self.range.next()?))
398    }
399
400    #[inline]
401    fn nth(&mut self, n: usize) -> Option<Self::Item> {
402        Some((self.map)(self.stmt, self.range.nth(n)?))
403    }
404
405    #[inline]
406    fn size_hint(&self) -> (usize, Option<usize>) {
407        self.range.size_hint()
408    }
409}
410impl<T> DoubleEndedIterator for ColumnsIter<'_, T> {
411    #[inline]
412    fn next_back(&mut self) -> Option<Self::Item> {
413        Some((self.map)(self.stmt, self.range.next_back()?))
414    }
415
416    #[inline]
417    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
418        Some((self.map)(self.stmt, self.range.nth_back(n)?))
419    }
420}
421impl<T> ExactSizeIterator for ColumnsIter<'_, T> {}
422
423#[cfg(all(test, not(miri)))]
424mod test {
425    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
426    use wasm_bindgen_test::wasm_bindgen_test as test;
427
428    use crate::{Connection, Result};
429
430    #[test]
431    #[cfg(feature = "column_decltype")]
432    fn test_columns() -> Result<()> {
433        use super::Column;
434
435        let db = Connection::open_in_memory()?;
436        let query = db.prepare("SELECT * FROM sqlite_master")?;
437        let columns = query.columns().collect::<Vec<_>>();
438        let column_names: Vec<&str> = columns.iter().map(Column::name).collect();
439        assert_eq!(
440            column_names.as_slice(),
441            &["type", "name", "tbl_name", "rootpage", "sql"]
442        );
443        let column_types: Vec<Option<String>> = columns
444            .iter()
445            .map(|col| col.decl_type().map(str::to_lowercase))
446            .collect();
447        assert_eq!(
448            &column_types[..3],
449            &[
450                Some("text".to_owned()),
451                Some("text".to_owned()),
452                Some("text".to_owned()),
453            ]
454        );
455        Ok(())
456    }
457
458    #[test]
459    #[cfg(feature = "column_metadata")]
460    fn test_columns_with_metadata() -> Result<()> {
461        let db = Connection::open_in_memory()?;
462        let query = db.prepare("SELECT *, 1 FROM sqlite_master")?;
463
464        let col_mets = query.columns_with_metadata().collect::<Vec<_>>();
465
466        assert_eq!(col_mets.len(), 6);
467
468        for col in col_mets.iter().take(5) {
469            assert_eq!(&col.database_name(), &Some("main"));
470            assert_eq!(&col.table_name(), &Some("sqlite_master"));
471        }
472
473        assert!(col_mets[5].database_name().is_none());
474        assert!(col_mets[5].table_name().is_none());
475        assert!(col_mets[5].origin_name().is_none());
476
477        let col_origins: Vec<Option<&str>> = col_mets.iter().map(|col| col.origin_name()).collect();
478
479        assert_eq!(
480            &col_origins[..5],
481            &[
482                Some("type"),
483                Some("name"),
484                Some("tbl_name"),
485                Some("rootpage"),
486                Some("sql"),
487            ]
488        );
489
490        Ok(())
491    }
492
493    #[test]
494    fn test_column_name_in_error() -> Result<()> {
495        use crate::{Error, types::Type};
496        let db = Connection::open_in_memory()?;
497        db.execute_batch(
498            "BEGIN;
499             CREATE TABLE foo(x INTEGER, y TEXT);
500             INSERT INTO foo VALUES(4, NULL);
501             END;",
502        )?;
503        let mut stmt = db.prepare("SELECT x as renamed, y FROM foo")?;
504        let mut rows = stmt.query([])?;
505        let row = rows.next()?.unwrap();
506        match row.get::<_, String>(0).unwrap_err() {
507            Error::InvalidColumnType(idx, name, ty) => {
508                assert_eq!(idx, 0);
509                assert_eq!(name, "renamed");
510                assert_eq!(ty, Type::Integer);
511            }
512            e => {
513                panic!("Unexpected error type: {e:?}");
514            }
515        }
516        match row.get::<_, String>("y").unwrap_err() {
517            Error::InvalidColumnType(idx, name, ty) => {
518                assert_eq!(idx, 1);
519                assert_eq!(name, "y");
520                assert_eq!(ty, Type::Null);
521            }
522            e => {
523                panic!("Unexpected error type: {e:?}");
524            }
525        }
526        Ok(())
527    }
528
529    /// `column_name` reference should stay valid until `stmt` is reprepared (or
530    /// reset) even if DB schema is altered (SQLite documentation is
531    /// ambiguous here because it says reference "is valid until (...) the next
532    /// call to `sqlite3_column_name()` or `sqlite3_column_name16()` on the same
533    /// column.". We assume that reference is valid if only
534    /// `sqlite3_column_name()` is used):
535    #[test]
536    #[cfg(feature = "modern_sqlite")]
537    fn test_column_name_reference() -> Result<()> {
538        let db = Connection::open_in_memory()?;
539        db.execute_batch("CREATE TABLE y (x);")?;
540        let stmt = db.prepare("SELECT x FROM y;")?;
541        let column_name = stmt.column_name(0)?;
542        assert_eq!("x", column_name);
543        db.execute_batch("ALTER TABLE y RENAME COLUMN x TO z;")?;
544        // column name is not refreshed until statement is re-prepared
545        let same_column_name = stmt.column_name(0)?;
546        assert_eq!(same_column_name, column_name);
547        Ok(())
548    }
549
550    #[test]
551    #[cfg(feature = "column_metadata")]
552    fn stmt_column_metadata() -> Result<()> {
553        let db = Connection::open_in_memory()?;
554        let query = db.prepare("SELECT *, 1 FROM sqlite_master")?;
555        let (db_name, table_name, col_name, data_type, coll_seq, not_null, primary_key, auto_inc) =
556            query.column_metadata(0)?.unwrap();
557        assert_eq!(db_name, crate::MAIN_DB);
558        assert_eq!(table_name, c"sqlite_master");
559        assert_eq!(col_name, c"type");
560        assert_eq!(data_type.as_deref(), Some(c"TEXT"));
561        assert_eq!(coll_seq.as_deref(), Some(c"BINARY"));
562        assert!(!not_null);
563        assert!(!primary_key);
564        assert!(!auto_inc);
565        assert!(query.column_metadata(5)?.is_none());
566        Ok(())
567    }
568
569    #[test]
570    fn column_exists() -> Result<()> {
571        let db = Connection::open_in_memory()?;
572        assert!(db.column_exists(None, c"sqlite_master", c"type")?);
573        assert!(db.column_exists(Some(crate::TEMP_DB), c"sqlite_master", c"type")?);
574        assert!(!db.column_exists(Some(crate::MAIN_DB), c"sqlite_temp_master", c"type")?);
575        Ok(())
576    }
577
578    #[test]
579    fn table_exists() -> Result<()> {
580        let db = Connection::open_in_memory()?;
581        assert!(db.table_exists(None, c"sqlite_master")?);
582        assert!(db.table_exists(Some(crate::TEMP_DB), c"sqlite_master")?);
583        assert!(!db.table_exists(Some(crate::MAIN_DB), c"sqlite_temp_master")?);
584        Ok(())
585    }
586
587    #[test]
588    fn column_metadata() -> Result<()> {
589        let db = Connection::open_in_memory()?;
590        let (data_type, coll_seq, not_null, primary_key, auto_inc) =
591            db.column_metadata(None, c"sqlite_master", c"type")?;
592        assert_eq!(
593            data_type.map(|cs| cs.to_str().unwrap().to_ascii_uppercase()),
594            Some("TEXT".to_owned())
595        );
596        assert_eq!(coll_seq.as_deref(), Some(c"BINARY"));
597        assert!(!not_null);
598        assert!(!primary_key);
599        assert!(!auto_inc);
600        assert!(db.column_metadata(None, c"sqlite_master", c"foo").is_err());
601        Ok(())
602    }
603}