Skip to main content

sqlive/
sql_value.rs

1//! Owned SQLite storage values for observation. Unlike rusqlite's UTF-8 String
2//! value, this representation also retains text containing invalid UTF-8.
3
4use rusqlite::{
5    types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef},
6    ToSql,
7};
8
9/// A value SQLite stores.
10#[derive(Clone, Debug, PartialEq)]
11pub enum SqlValue {
12    /// NULL.
13    Null,
14    /// An integer.
15    Integer(i64),
16    /// A floating-point number.
17    Real(f64),
18    /// Text, as the bytes SQLite stores, which may not be valid UTF-8.
19    Text(Vec<u8>),
20    /// A blob.
21    Blob(Vec<u8>),
22}
23
24impl FromSql for SqlValue {
25    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
26        Ok(value.into())
27    }
28}
29
30impl From<ValueRef<'_>> for SqlValue {
31    fn from(value: ValueRef<'_>) -> Self {
32        match value {
33            ValueRef::Null => Self::Null,
34            ValueRef::Integer(value) => Self::Integer(value),
35            ValueRef::Real(value) => Self::Real(value),
36            ValueRef::Text(value) => Self::Text(value.to_vec()),
37            ValueRef::Blob(value) => Self::Blob(value.to_vec()),
38        }
39    }
40}
41
42impl SqlValue {
43    /// The value as SQLite reports it.
44    pub fn as_value_ref(&self) -> ValueRef<'_> {
45        match self {
46            Self::Null => ValueRef::Null,
47            Self::Integer(value) => ValueRef::Integer(*value),
48            Self::Real(value) => ValueRef::Real(*value),
49            Self::Text(value) => ValueRef::Text(value),
50            Self::Blob(value) => ValueRef::Blob(value),
51        }
52    }
53}
54
55impl ToSql for SqlValue {
56    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
57        Ok(ToSqlOutput::Borrowed(self.as_value_ref()))
58    }
59}
60
61/// The values `params` binds to `statement`'s parameters, in parameter order,
62/// with one entry for each index, including anonymous parameters and indices
63/// that no parameter in the SQL uses.
64pub(crate) fn parameters<P: rusqlite::Params>(
65    connection: &rusqlite::Connection,
66    statement: &rusqlite::Statement<'_>,
67    params: P,
68) -> rusqlite::Result<Vec<SqlValue>> {
69    let count = statement.parameter_count();
70    let sql = if count == 0 {
71        "SELECT NULL WHERE 0".into()
72    } else {
73        let values = (1..=count)
74            .map(|index| {
75                // Walking every index preserves anonymous slots and holes, and
76                // retains exactly the original names for named binding validation.
77                let parameter = statement.parameter_name(index).unwrap_or("?");
78                format!("({parameter})")
79            })
80            .collect::<Vec<_>>()
81            .join(",");
82        format!("VALUES {values}")
83    };
84    let mut capture = connection.prepare(&sql)?;
85    let values = capture.query_map(params, |row| row.get(0))?.collect();
86    values
87}