sql_middleware/sqlite/
params.rs

1use std::fmt::Write;
2
3use rusqlite;
4
5use crate::middleware::{ConversionMode, ParamConverter, RowValues, SqlMiddlewareDbError};
6
7// Thread-local buffer for efficient timestamp formatting
8thread_local! {
9    static TIMESTAMP_BUF: std::cell::RefCell<String> = std::cell::RefCell::new(String::with_capacity(32));
10}
11
12/// Convert a single `RowValue` to a rusqlite `Value`.
13#[must_use]
14pub fn row_value_to_sqlite_value(value: &RowValues, for_execute: bool) -> rusqlite::types::Value {
15    match value {
16        RowValues::Int(i) => rusqlite::types::Value::Integer(*i),
17        RowValues::Float(f) => rusqlite::types::Value::Real(*f),
18        RowValues::Text(s) => {
19            if for_execute {
20                // For execute, we can move the owned String directly
21                rusqlite::types::Value::Text(s.clone())
22            } else {
23                // For queries, we need to clone
24                rusqlite::types::Value::Text(s.clone())
25            }
26        }
27        RowValues::Bool(b) => rusqlite::types::Value::Integer(i64::from(*b)),
28        // Format timestamps once for better performance
29        RowValues::Timestamp(dt) => {
30            // Use a thread_local buffer for timestamp formatting to avoid allocation
31            TIMESTAMP_BUF.with(|buf| {
32                let mut borrow = buf.borrow_mut();
33                borrow.clear();
34                // Format directly into the string buffer
35                write!(borrow, "{}", dt.format("%F %T%.f")).unwrap();
36                rusqlite::types::Value::Text(borrow.clone())
37            })
38        }
39        RowValues::Null => rusqlite::types::Value::Null,
40        RowValues::JSON(jval) => {
41            // Only serialize once to avoid multiple allocations
42            let json_str = jval.to_string();
43            rusqlite::types::Value::Text(json_str)
44        }
45        RowValues::Blob(bytes) => {
46            if for_execute {
47                // For execute, we can directly use the bytes
48                rusqlite::types::Value::Blob(bytes.clone())
49            } else {
50                rusqlite::types::Value::Blob(bytes.clone())
51            }
52        }
53    }
54}
55
56/// Unified `SQLite` parameter container.
57pub struct Params(pub Vec<rusqlite::types::Value>);
58
59impl Params {
60    /// Convert middleware row values into `SQLite` values.
61    ///
62    /// # Errors
63    ///
64    /// Returns `SqlMiddlewareDbError::ConversionError` if parameter conversion fails.
65    pub fn convert(params: &[RowValues]) -> Result<Self, SqlMiddlewareDbError> {
66        let mut vec_values = Vec::with_capacity(params.len());
67        for p in params {
68            vec_values.push(row_value_to_sqlite_value(p, true));
69        }
70        Ok(Params(vec_values))
71    }
72
73    /// Borrow the underlying values.
74    #[must_use]
75    pub fn as_values(&self) -> &[rusqlite::types::Value] {
76        &self.0
77    }
78
79    /// Build a borrowed params slice suitable for rusqlite execution.
80    #[must_use]
81    pub fn as_refs(&self) -> Vec<&dyn rusqlite::ToSql> {
82        self.0.iter().map(|v| v as &dyn rusqlite::ToSql).collect()
83    }
84}
85
86impl ParamConverter<'_> for Params {
87    type Converted = Params;
88
89    fn convert_sql_params(
90        params: &[RowValues],
91        _mode: ConversionMode,
92    ) -> Result<Self::Converted, SqlMiddlewareDbError> {
93        Self::convert(params)
94    }
95
96    fn supports_mode(mode: ConversionMode) -> bool {
97        // Single Params type supports both query and execute.
98        matches!(mode, ConversionMode::Query | ConversionMode::Execute)
99    }
100}