diesel/sqlite/connection/
stmt.rs

1#![allow(unsafe_code)] // fii code
2use super::bind_collector::{InternalSqliteBindValue, SqliteBindCollector};
3use super::raw::RawConnection;
4use super::sqlite_value::OwnedSqliteValue;
5use crate::connection::statement_cache::{MaybeCached, PrepareForCache};
6use crate::connection::Instrumentation;
7use crate::query_builder::{QueryFragment, QueryId};
8use crate::result::Error::DatabaseError;
9use crate::result::*;
10use crate::sqlite::{Sqlite, SqliteType};
11#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
12use libsqlite3_sys as ffi;
13#[cfg(all(target_family = "wasm", target_os = "unknown"))]
14use sqlite_wasm_rs as ffi;
15use std::cell::OnceCell;
16use std::ffi::{CStr, CString};
17use std::io::{stderr, Write};
18use std::os::raw as libc;
19use std::ptr::{self, NonNull};
20
21pub(super) struct Statement {
22    inner_statement: NonNull<ffi::sqlite3_stmt>,
23}
24
25// This relies on the invariant that RawConnection or Statement are never
26// leaked. If a reference to one of those was held on a different thread, this
27// would not be thread safe.
28#[allow(unsafe_code)]
29unsafe impl Send for Statement {}
30
31impl Statement {
32    pub(super) fn prepare(
33        raw_connection: &RawConnection,
34        sql: &str,
35        is_cached: PrepareForCache,
36        _: &[SqliteType],
37    ) -> QueryResult<Self> {
38        let mut stmt = ptr::null_mut();
39        let mut unused_portion = ptr::null();
40        let n_byte = sql
41            .len()
42            .try_into()
43            .map_err(|e| Error::SerializationError(Box::new(e)))?;
44        // the cast for `ffi::SQLITE_PREPARE_PERSISTENT` is required for old libsqlite3-sys versions
45        #[allow(clippy::unnecessary_cast)]
46        let prepare_result = unsafe {
47            ffi::sqlite3_prepare_v3(
48                raw_connection.internal_connection.as_ptr(),
49                CString::new(sql)?.as_ptr(),
50                n_byte,
51                if #[allow(non_exhaustive_omitted_patterns)] match is_cached {
    PrepareForCache::Yes { counter: _ } => true,
    _ => false,
}matches!(is_cached, PrepareForCache::Yes { counter: _ }) {
52                    ffi::SQLITE_PREPARE_PERSISTENT as u32
53                } else {
54                    0
55                },
56                &mut stmt,
57                &mut unused_portion,
58            )
59        };
60
61        ensure_sqlite_ok(prepare_result, raw_connection.internal_connection.as_ptr())?;
62
63        // sqlite3_prepare_v3 returns a null pointer for empty statements. This includes
64        // empty or only whitespace strings or any other non-op query string like a comment
65        let inner_statement = NonNull::new(stmt).ok_or_else(|| {
66            crate::result::Error::QueryBuilderError(Box::new(crate::result::EmptyQuery))
67        })?;
68        Ok(Statement { inner_statement })
69    }
70
71    // The caller of this function has to ensure that:
72    // * Any buffer provided as `SqliteBindValue::BorrowedBinary`, `SqliteBindValue::Binary`
73    // `SqliteBindValue::String` or `SqliteBindValue::BorrowedString` is valid
74    // till either a new value is bound to the same parameter or the underlying
75    // prepared statement is dropped.
76    unsafe fn bind(
77        &mut self,
78        tpe: SqliteType,
79        value: InternalSqliteBindValue<'_>,
80        bind_index: i32,
81    ) -> QueryResult<Option<NonNull<[u8]>>> {
82        let mut ret_ptr = None;
83        let result = match (tpe, value) {
84            (_, InternalSqliteBindValue::Null) => unsafe {
85                ffi::sqlite3_bind_null(self.inner_statement.as_ptr(), bind_index)
86            },
87            (SqliteType::Binary, InternalSqliteBindValue::BorrowedBinary(bytes)) => {
88                let n = bytes
89                    .len()
90                    .try_into()
91                    .map_err(|e| Error::SerializationError(Box::new(e)))?;
92                unsafe {
93                    ffi::sqlite3_bind_blob(
94                        self.inner_statement.as_ptr(),
95                        bind_index,
96                        bytes.as_ptr() as *const libc::c_void,
97                        n,
98                        ffi::SQLITE_STATIC(),
99                    )
100                }
101            }
102            (SqliteType::Binary, InternalSqliteBindValue::Binary(mut bytes)) => {
103                let len = bytes
104                    .len()
105                    .try_into()
106                    .map_err(|e| Error::SerializationError(Box::new(e)))?;
107                // We need a separate pointer here to pass it to sqlite
108                // as the returned pointer is a pointer to a dyn sized **slice**
109                // and not the pointer to the first element of the slice
110                let ptr = bytes.as_mut_ptr();
111                ret_ptr = NonNull::new(Box::into_raw(bytes));
112                unsafe {
113                    ffi::sqlite3_bind_blob(
114                        self.inner_statement.as_ptr(),
115                        bind_index,
116                        ptr as *const libc::c_void,
117                        len,
118                        ffi::SQLITE_STATIC(),
119                    )
120                }
121            }
122            (SqliteType::Text, InternalSqliteBindValue::BorrowedString(bytes)) => {
123                let len = bytes
124                    .len()
125                    .try_into()
126                    .map_err(|e| Error::SerializationError(Box::new(e)))?;
127                unsafe {
128                    ffi::sqlite3_bind_text(
129                        self.inner_statement.as_ptr(),
130                        bind_index,
131                        bytes.as_ptr() as *const libc::c_char,
132                        len,
133                        ffi::SQLITE_STATIC(),
134                    )
135                }
136            }
137            (SqliteType::Text, InternalSqliteBindValue::String(bytes)) => {
138                let mut bytes = Box::<[u8]>::from(bytes);
139                let len = bytes
140                    .len()
141                    .try_into()
142                    .map_err(|e| Error::SerializationError(Box::new(e)))?;
143                // We need a separate pointer here to pass it to sqlite
144                // as the returned pointer is a pointer to a dyn sized **slice**
145                // and not the pointer to the first element of the slice
146                let ptr = bytes.as_mut_ptr();
147                ret_ptr = NonNull::new(Box::into_raw(bytes));
148                unsafe {
149                    ffi::sqlite3_bind_text(
150                        self.inner_statement.as_ptr(),
151                        bind_index,
152                        ptr as *const libc::c_char,
153                        len,
154                        ffi::SQLITE_STATIC(),
155                    )
156                }
157            }
158            (SqliteType::Float, InternalSqliteBindValue::F64(value))
159            | (SqliteType::Double, InternalSqliteBindValue::F64(value)) => unsafe {
160                ffi::sqlite3_bind_double(
161                    self.inner_statement.as_ptr(),
162                    bind_index,
163                    value as libc::c_double,
164                )
165            },
166            (SqliteType::SmallInt, InternalSqliteBindValue::I32(value))
167            | (SqliteType::Integer, InternalSqliteBindValue::I32(value)) => unsafe {
168                ffi::sqlite3_bind_int(self.inner_statement.as_ptr(), bind_index, value)
169            },
170            (SqliteType::Long, InternalSqliteBindValue::I64(value)) => unsafe {
171                ffi::sqlite3_bind_int64(self.inner_statement.as_ptr(), bind_index, value)
172            },
173            (t, b) => {
174                return Err(Error::SerializationError(
175                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Type mismatch: Expected {0:?}, got {1}",
                t, b))
    })format!("Type mismatch: Expected {t:?}, got {b}").into(),
176                ))
177            }
178        };
179        match ensure_sqlite_ok(result, self.raw_connection()) {
180            Ok(()) => Ok(ret_ptr),
181            Err(e) => {
182                if let Some(ptr) = ret_ptr {
183                    // This is a `NonNul` ptr so it cannot be null
184                    // It points to a slice internally as we did not apply
185                    // any cast above.
186                    std::mem::drop(unsafe { Box::from_raw(ptr.as_ptr()) })
187                }
188                Err(e)
189            }
190        }
191    }
192
193    fn reset(&mut self) {
194        unsafe { ffi::sqlite3_reset(self.inner_statement.as_ptr()) };
195    }
196
197    fn raw_connection(&self) -> *mut ffi::sqlite3 {
198        unsafe { ffi::sqlite3_db_handle(self.inner_statement.as_ptr()) }
199    }
200}
201
202pub(super) fn ensure_sqlite_ok(
203    code: libc::c_int,
204    raw_connection: *mut ffi::sqlite3,
205) -> QueryResult<()> {
206    if code == ffi::SQLITE_OK {
207        Ok(())
208    } else {
209        Err(last_error(raw_connection))
210    }
211}
212
213fn last_error(raw_connection: *mut ffi::sqlite3) -> Error {
214    let error_message = last_error_message(raw_connection);
215    let error_code = last_error_code(raw_connection);
216    let error_kind = match error_code {
217        ffi::SQLITE_CONSTRAINT_UNIQUE | ffi::SQLITE_CONSTRAINT_PRIMARYKEY => {
218            DatabaseErrorKind::UniqueViolation
219        }
220        ffi::SQLITE_CONSTRAINT_FOREIGNKEY => DatabaseErrorKind::ForeignKeyViolation,
221        // SQLITE_CONSTRAINT_TRIGGER is returned for ON DELETE RESTRICT violations,
222        // which are actually foreign key violations. We check the error message
223        // to distinguish from user-defined trigger failures.
224        ffi::SQLITE_CONSTRAINT_TRIGGER
225            if error_message.contains("FOREIGN KEY constraint failed") =>
226        {
227            DatabaseErrorKind::ForeignKeyViolation
228        }
229        ffi::SQLITE_CONSTRAINT_NOTNULL => DatabaseErrorKind::NotNullViolation,
230        ffi::SQLITE_CONSTRAINT_CHECK => DatabaseErrorKind::CheckViolation,
231        _ => DatabaseErrorKind::Unknown,
232    };
233    let error_information = Box::new(error_message);
234    DatabaseError(error_kind, error_information)
235}
236
237fn last_error_message(conn: *mut ffi::sqlite3) -> String {
238    let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(conn)) };
239    c_str.to_string_lossy().into_owned()
240}
241
242fn last_error_code(conn: *mut ffi::sqlite3) -> libc::c_int {
243    unsafe { ffi::sqlite3_extended_errcode(conn) }
244}
245
246impl Drop for Statement {
247    fn drop(&mut self) {
248        use std::thread::panicking;
249
250        let raw_connection = self.raw_connection();
251        let finalize_result = unsafe { ffi::sqlite3_finalize(self.inner_statement.as_ptr()) };
252        if let Err(e) = ensure_sqlite_ok(finalize_result, raw_connection) {
253            if panicking() {
254                stderr().write_fmt(format_args!("Error finalizing SQLite prepared statement: {0:?}",
        e))write!(
255                    stderr(),
256                    "Error finalizing SQLite prepared statement: {e:?}"
257                )
258                .expect("Error writing to `stderr`");
259            } else {
260                {
    ::core::panicking::panic_fmt(format_args!("Error finalizing SQLite prepared statement: {0:?}",
            e));
};panic!("Error finalizing SQLite prepared statement: {e:?}");
261            }
262        }
263    }
264}
265
266// A warning for future editors:
267// Changing this code to something "simpler" may
268// introduce undefined behaviour. Make sure you read
269// the following discussions for details about
270// the current version:
271//
272// * https://github.com/weiznich/diesel/pull/7
273// * https://users.rust-lang.org/t/code-review-for-unsafe-code-in-diesel/66798/
274// * https://github.com/rust-lang/unsafe-code-guidelines/issues/194
275struct BoundStatement<'stmt, 'query> {
276    statement: MaybeCached<'stmt, Statement>,
277    // we need to store the query here to ensure no one does
278    // drop it till the end of the statement
279    // We use a boxed queryfragment here just to erase the
280    // generic type, we use NonNull to communicate
281    // that this is a shared buffer
282    query: Option<NonNull<dyn QueryFragment<Sqlite> + 'query>>,
283    // we need to store any owned bind values separately, as they are not
284    // contained in the query itself. We use NonNull to
285    // communicate that this is a shared buffer
286    binds_to_free: Vec<(i32, Option<NonNull<[u8]>>)>,
287    instrumentation: &'stmt mut dyn Instrumentation,
288    has_error: bool,
289}
290
291impl<'stmt, 'query> BoundStatement<'stmt, 'query> {
292    fn bind<T>(
293        statement: MaybeCached<'stmt, Statement>,
294        query: T,
295        instrumentation: &'stmt mut dyn Instrumentation,
296    ) -> QueryResult<BoundStatement<'stmt, 'query>>
297    where
298        T: QueryFragment<Sqlite> + QueryId + 'query,
299    {
300        // Don't use a trait object here to prevent using a virtual function call
301        // For sqlite this can introduce a measurable overhead
302        // Query is boxed here to make sure it won't move in memory anymore, so any bind
303        // it could output would stay valid.
304        let query = Box::new(query);
305
306        let mut bind_collector = SqliteBindCollector::new();
307        query.collect_binds(&mut bind_collector, &mut (), &Sqlite)?;
308        let SqliteBindCollector { binds } = bind_collector;
309
310        let mut ret = BoundStatement {
311            statement,
312            query: None,
313            binds_to_free: Vec::new(),
314            instrumentation,
315            has_error: false,
316        };
317
318        ret.bind_buffers(binds)?;
319
320        let query = query as Box<dyn QueryFragment<Sqlite> + 'query>;
321        ret.query = NonNull::new(Box::into_raw(query));
322
323        Ok(ret)
324    }
325
326    // This is a separated function so that
327    // not the whole constructor is generic over the query type T.
328    // This hopefully prevents binary bloat.
329    fn bind_buffers(
330        &mut self,
331        binds: Vec<(InternalSqliteBindValue<'_>, SqliteType)>,
332    ) -> QueryResult<()> {
333        // It is useful to preallocate `binds_to_free` because it
334        // - Guarantees that pushing inside it cannot panic, which guarantees the `Drop`
335        //   impl of `BoundStatement` will always re-`bind` as needed
336        // - Avoids reallocations
337        self.binds_to_free.reserve(
338            binds
339                .iter()
340                .filter(|&(b, _)| {
341                    #[allow(non_exhaustive_omitted_patterns)] match b {
    InternalSqliteBindValue::BorrowedBinary(_) |
        InternalSqliteBindValue::BorrowedString(_) |
        InternalSqliteBindValue::String(_) |
        InternalSqliteBindValue::Binary(_) => true,
    _ => false,
}matches!(
342                        b,
343                        InternalSqliteBindValue::BorrowedBinary(_)
344                            | InternalSqliteBindValue::BorrowedString(_)
345                            | InternalSqliteBindValue::String(_)
346                            | InternalSqliteBindValue::Binary(_)
347                    )
348                })
349                .count(),
350        );
351        for (bind_idx, (bind, tpe)) in (1..).zip(binds) {
352            let is_borrowed_bind = #[allow(non_exhaustive_omitted_patterns)] match bind {
    InternalSqliteBindValue::BorrowedString(_) |
        InternalSqliteBindValue::BorrowedBinary(_) => true,
    _ => false,
}matches!(
353                bind,
354                InternalSqliteBindValue::BorrowedString(_)
355                    | InternalSqliteBindValue::BorrowedBinary(_)
356            );
357
358            // It's safe to call bind here as:
359            // * The type and value matches
360            // * We ensure that corresponding buffers lives long enough below
361            // * The statement is not used yet by `step` or anything else
362            let res = unsafe { self.statement.bind(tpe, bind, bind_idx) }?;
363
364            // it's important to push these only after
365            // the call to bind succeeded, otherwise we might attempt to
366            // call bind to an non-existing bind position in
367            // the destructor
368            if let Some(ptr) = res {
369                // Store the id + pointer for a owned bind
370                // as we must unbind and free them on drop
371                self.binds_to_free.push((bind_idx, Some(ptr)));
372            } else if is_borrowed_bind {
373                // Store the id's of borrowed binds to unbind them on drop
374                self.binds_to_free.push((bind_idx, None));
375            }
376        }
377        Ok(())
378    }
379
380    fn finish_query_with_error(mut self, e: &Error) {
381        self.has_error = true;
382        if let Some(q) = self.query {
383            // it's safe to get a reference from this ptr as it's guaranteed to not be null
384            let q = unsafe { q.as_ref() };
385            self.instrumentation.on_connection_event(
386                crate::connection::InstrumentationEvent::FinishQuery {
387                    query: &crate::debug_query(&q),
388                    error: Some(e),
389                },
390            );
391        }
392    }
393}
394
395impl Drop for BoundStatement<'_, '_> {
396    fn drop(&mut self) {
397        // First reset the statement, otherwise the bind calls
398        // below will fails
399        self.statement.reset();
400
401        for (idx, buffer) in std::mem::take(&mut self.binds_to_free) {
402            unsafe {
403                // It's always safe to bind null values, as there is no buffer that needs to outlife something
404                self.statement
405                    .bind(SqliteType::Text, InternalSqliteBindValue::Null, idx)
406                    .expect(
407                        "Binding a null value should never fail. \
408                             If you ever see this error message please open \
409                             an issue at diesels issue tracker containing \
410                             code how to trigger this message.",
411                    );
412            }
413
414            if let Some(buffer) = buffer {
415                unsafe {
416                    // Constructing the `Box` here is safe as we
417                    // got the pointer from a box + it is guaranteed to be not null.
418                    std::mem::drop(Box::from_raw(buffer.as_ptr()));
419                }
420            }
421        }
422
423        if let Some(query) = self.query {
424            let query = unsafe {
425                // Constructing the `Box` here is safe as we
426                // got the pointer from a box + it is guaranteed to be not null.
427                Box::from_raw(query.as_ptr())
428            };
429            if !self.has_error {
430                self.instrumentation.on_connection_event(
431                    crate::connection::InstrumentationEvent::FinishQuery {
432                        query: &crate::debug_query(&query),
433                        error: None,
434                    },
435                );
436            }
437            std::mem::drop(query);
438            self.query = None;
439        }
440    }
441}
442
443#[allow(missing_debug_implementations)]
444pub struct StatementUse<'stmt, 'query> {
445    statement: BoundStatement<'stmt, 'query>,
446    column_names: OnceCell<Vec<*const str>>,
447}
448
449impl<'stmt, 'query> StatementUse<'stmt, 'query> {
450    pub(super) fn bind<T>(
451        statement: MaybeCached<'stmt, Statement>,
452        query: T,
453        instrumentation: &'stmt mut dyn Instrumentation,
454    ) -> QueryResult<StatementUse<'stmt, 'query>>
455    where
456        T: QueryFragment<Sqlite> + QueryId + 'query,
457    {
458        Ok(Self {
459            statement: BoundStatement::bind(statement, query, instrumentation)?,
460            column_names: OnceCell::new(),
461        })
462    }
463
464    pub(super) fn run(mut self) -> QueryResult<()> {
465        let r = unsafe {
466            // This is safe as we pass `first_step = true`
467            // and we consume the statement so nobody could
468            // access the columns later on anyway.
469            self.step(true).map(|_| ())
470        };
471        if let Err(ref e) = r {
472            self.statement.finish_query_with_error(e);
473        }
474        r
475    }
476
477    // This function is marked as unsafe incorrectly passing `false` to `first_step`
478    // for a first call to this function could cause access to freed memory via
479    // the cached column names.
480    //
481    // It's always safe to call this function with `first_step = true` as this removes
482    // the cached column names
483    pub(super) unsafe fn step(&mut self, first_step: bool) -> QueryResult<bool> {
484        let step_result =
485            unsafe { ffi::sqlite3_step(self.statement.statement.inner_statement.as_ptr()) };
486        let res = match step_result {
487            ffi::SQLITE_DONE => Ok(false),
488            ffi::SQLITE_ROW => Ok(true),
489            _ => Err(last_error(self.statement.statement.raw_connection())),
490        };
491        if first_step {
492            self.column_names = OnceCell::new();
493        }
494        res
495    }
496
497    // The returned string pointer is valid until either the prepared statement is
498    // destroyed by sqlite3_finalize() or until the statement is automatically
499    // reprepared by the first call to sqlite3_step() for a particular run or
500    // until the next call to sqlite3_column_name() or sqlite3_column_name16()
501    // on the same column.
502    //
503    // https://sqlite.org/c3ref/column_name.html
504    //
505    // Note: This function is marked as unsafe, as calling it can invalidate
506    // other existing column name pointers on the same column. To prevent that,
507    // it should maximally be called once per column at all.
508    unsafe fn column_name(&self, idx: i32) -> *const str {
509        let name = {
510            let column_name = unsafe {
511                ffi::sqlite3_column_name(self.statement.statement.inner_statement.as_ptr(), idx)
512            };
513            if !!column_name.is_null() {
    {
        ::core::panicking::panic_fmt(format_args!("The Sqlite documentation states that it only returns a null pointer here if we are in a OOM condition."));
    }
};assert!(
514                !column_name.is_null(),
515                "The Sqlite documentation states that it only returns a \
516                 null pointer here if we are in a OOM condition."
517            );
518            unsafe { CStr::from_ptr(column_name) }
519        };
520        name.to_str().expect(
521            "The Sqlite documentation states that this is UTF8. \
522             If you see this error message something has gone \
523             horribly wrong. Please open an issue at the \
524             diesel repository.",
525        ) as *const str
526    }
527
528    pub(super) fn column_count(&self) -> i32 {
529        unsafe { ffi::sqlite3_column_count(self.statement.statement.inner_statement.as_ptr()) }
530    }
531
532    pub(super) fn index_for_column_name(&mut self, field_name: &str) -> Option<usize> {
533        (0..self.column_count())
534            .find(|idx| self.field_name(*idx) == Some(field_name))
535            .map(|v| {
536                v.try_into()
537                    .expect("Diesel expects to run at least on a 32 bit platform")
538            })
539    }
540
541    pub(super) fn field_name(&self, idx: i32) -> Option<&str> {
542        let column_names = self.column_names.get_or_init(|| {
543            let count = self.column_count();
544            (0..count)
545                .map(|idx| unsafe {
546                    // By initializing the whole vec at once we ensure that
547                    // we really call this only once.
548                    self.column_name(idx)
549                })
550                .collect()
551        });
552
553        column_names
554            .get(usize::try_from(idx).expect("Diesel expects to run at least on a 32 bit platform"))
555            .and_then(|c| unsafe { c.as_ref() })
556    }
557
558    pub(super) fn copy_value(&self, idx: i32) -> Option<OwnedSqliteValue> {
559        OwnedSqliteValue::copy_from_ptr(self.column_value(idx)?)
560    }
561
562    pub(super) fn column_value(&self, idx: i32) -> Option<NonNull<ffi::sqlite3_value>> {
563        let ptr = unsafe {
564            ffi::sqlite3_column_value(self.statement.statement.inner_statement.as_ptr(), idx)
565        };
566        NonNull::new(ptr)
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use crate::prelude::*;
573    use crate::sql_types::Text;
574
575    // this is a regression test for
576    // https://github.com/diesel-rs/diesel/issues/3558
577    #[diesel_test_helper::test]
578    fn check_out_of_bounds_bind_does_not_panic_on_drop() {
579        let mut conn = SqliteConnection::establish(":memory:").unwrap();
580
581        let e = crate::sql_query("SELECT '?'")
582            .bind::<Text, _>("foo")
583            .execute(&mut conn);
584
585        assert!(e.is_err());
586        let e = e.unwrap_err();
587        if let crate::result::Error::DatabaseError(crate::result::DatabaseErrorKind::Unknown, m) = e
588        {
589            assert_eq!(m.message(), "column index out of range");
590        } else {
591            panic!("Wrong error returned");
592        }
593    }
594}