rusqlite/statement.rs
1use std::ffi::{c_int, c_void};
2#[cfg(feature = "array")]
3use std::rc::Rc;
4use std::slice::from_raw_parts;
5use std::{fmt, mem, ptr, str};
6
7use super::ffi;
8use super::{len_as_c_int, str_for_sqlite};
9use super::{
10 AndThenRows, Connection, Error, MappedRows, Params, RawStatement, Result, Row, Rows, ValueRef,
11};
12use crate::bind::BindIndex;
13use crate::types::{ToSql, ToSqlOutput};
14#[cfg(feature = "array")]
15use crate::vtab::array::{free_array, ARRAY_TYPE};
16
17/// A prepared statement.
18pub struct Statement<'conn> {
19 pub(crate) conn: &'conn Connection,
20 pub(crate) stmt: RawStatement,
21}
22
23impl Statement<'_> {
24 /// Execute the prepared statement.
25 ///
26 /// On success, returns the number of rows that were changed or inserted or
27 /// deleted (via `sqlite3_changes`).
28 ///
29 /// ## Example
30 ///
31 /// ### Use with positional parameters
32 ///
33 /// ```rust,no_run
34 /// # use rusqlite::{Connection, Result, params};
35 /// fn update_rows(conn: &Connection) -> Result<()> {
36 /// let mut stmt = conn.prepare("UPDATE foo SET bar = ?1 WHERE qux = ?2")?;
37 /// // For a single parameter, or a parameter where all the values have
38 /// // the same type, just passing an array is simplest.
39 /// stmt.execute([2i32])?;
40 /// // The `rusqlite::params!` macro is mostly useful when the parameters do not
41 /// // all have the same type, or if there are more than 32 parameters
42 /// // at once, but it can be used in other cases.
43 /// stmt.execute(params![1i32])?;
44 /// // However, it's not required, many cases are fine as:
45 /// stmt.execute(&[&2i32])?;
46 /// // Or even:
47 /// stmt.execute([2i32])?;
48 /// // If you really want to, this is an option as well.
49 /// stmt.execute((2i32,))?;
50 /// Ok(())
51 /// }
52 /// ```
53 ///
54 /// #### Heterogeneous positional parameters
55 ///
56 /// ```
57 /// use rusqlite::{Connection, Result};
58 /// fn store_file(conn: &Connection, path: &str, data: &[u8]) -> Result<()> {
59 /// # // no need to do it for real.
60 /// # fn sha256(_: &[u8]) -> [u8; 32] { [0; 32] }
61 /// let query = "INSERT OR REPLACE INTO files(path, hash, data) VALUES (?1, ?2, ?3)";
62 /// let mut stmt = conn.prepare_cached(query)?;
63 /// let hash: [u8; 32] = sha256(data);
64 /// // The easiest way to pass positional parameters of have several
65 /// // different types is by using a tuple.
66 /// stmt.execute((path, hash, data))?;
67 /// // Using the `params!` macro also works, and supports longer parameter lists:
68 /// stmt.execute(rusqlite::params![path, hash, data])?;
69 /// Ok(())
70 /// }
71 /// # let c = Connection::open_in_memory().unwrap();
72 /// # c.execute_batch("CREATE TABLE files(path TEXT PRIMARY KEY, hash BLOB, data BLOB)").unwrap();
73 /// # store_file(&c, "foo/bar.txt", b"bibble").unwrap();
74 /// # store_file(&c, "foo/baz.txt", b"bobble").unwrap();
75 /// ```
76 ///
77 /// ### Use with named parameters
78 ///
79 /// ```rust,no_run
80 /// # use rusqlite::{Connection, Result, named_params};
81 /// fn insert(conn: &Connection) -> Result<()> {
82 /// let mut stmt = conn.prepare("INSERT INTO test (key, value) VALUES (:key, :value)")?;
83 /// // The `rusqlite::named_params!` macro (like `params!`) is useful for heterogeneous
84 /// // sets of parameters (where all parameters are not the same type), or for queries
85 /// // with many (more than 32) statically known parameters.
86 /// stmt.execute(named_params! { ":key": "one", ":val": 2 })?;
87 /// // However, named parameters can also be passed like:
88 /// stmt.execute(&[(":key", "three"), (":val", "four")])?;
89 /// // Or even: (note that a &T is required for the value type, currently)
90 /// stmt.execute(&[(":key", &100), (":val", &200)])?;
91 /// Ok(())
92 /// }
93 /// ```
94 ///
95 /// ### Use without parameters
96 ///
97 /// ```rust,no_run
98 /// # use rusqlite::{Connection, Result, params};
99 /// fn delete_all(conn: &Connection) -> Result<()> {
100 /// let mut stmt = conn.prepare("DELETE FROM users")?;
101 /// stmt.execute([])?;
102 /// Ok(())
103 /// }
104 /// ```
105 ///
106 /// # Failure
107 ///
108 /// Will return `Err` if binding parameters fails, the executed statement
109 /// returns rows (in which case `query` should be used instead), or the
110 /// underlying SQLite call fails.
111 #[inline]
112 pub fn execute<P: Params>(&mut self, params: P) -> Result<usize> {
113 params.__bind_in(self)?;
114 self.execute_with_bound_parameters()
115 }
116
117 /// Execute an INSERT and return the ROWID.
118 ///
119 /// # Note
120 ///
121 /// This function is a convenience wrapper around
122 /// [`execute()`](Statement::execute) intended for queries that insert a
123 /// single item. It is possible to misuse this function in a way that it
124 /// cannot detect, such as by calling it on a statement which _updates_
125 /// a single item rather than inserting one. Please don't do that.
126 ///
127 /// # Failure
128 ///
129 /// Will return `Err` if no row is inserted or many rows are inserted.
130 #[inline]
131 pub fn insert<P: Params>(&mut self, params: P) -> Result<i64> {
132 let changes = self.execute(params)?;
133 match changes {
134 1 => Ok(self.conn.last_insert_rowid()),
135 _ => Err(Error::StatementChangedRows(changes)),
136 }
137 }
138
139 /// Execute the prepared statement, returning a handle to the resulting
140 /// rows.
141 ///
142 /// Due to lifetime restrictions, the rows handle returned by `query` does
143 /// not implement the `Iterator` trait. Consider using
144 /// [`query_map`](Statement::query_map) or
145 /// [`query_and_then`](Statement::query_and_then) instead, which do.
146 ///
147 /// ## Example
148 ///
149 /// ### Use without parameters
150 ///
151 /// ```rust,no_run
152 /// # use rusqlite::{Connection, Result};
153 /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
154 /// let mut stmt = conn.prepare("SELECT name FROM people")?;
155 /// let mut rows = stmt.query([])?;
156 ///
157 /// let mut names = Vec::new();
158 /// while let Some(row) = rows.next()? {
159 /// names.push(row.get(0)?);
160 /// }
161 ///
162 /// Ok(names)
163 /// }
164 /// ```
165 ///
166 /// ### Use with positional parameters
167 ///
168 /// ```rust,no_run
169 /// # use rusqlite::{Connection, Result};
170 /// fn query(conn: &Connection, name: &str) -> Result<()> {
171 /// let mut stmt = conn.prepare("SELECT * FROM test where name = ?1")?;
172 /// let mut rows = stmt.query(rusqlite::params![name])?;
173 /// while let Some(row) = rows.next()? {
174 /// // ...
175 /// }
176 /// Ok(())
177 /// }
178 /// ```
179 ///
180 /// Or, equivalently (but without the [`crate::params!`] macro).
181 ///
182 /// ```rust,no_run
183 /// # use rusqlite::{Connection, Result};
184 /// fn query(conn: &Connection, name: &str) -> Result<()> {
185 /// let mut stmt = conn.prepare("SELECT * FROM test where name = ?1")?;
186 /// let mut rows = stmt.query([name])?;
187 /// while let Some(row) = rows.next()? {
188 /// // ...
189 /// }
190 /// Ok(())
191 /// }
192 /// ```
193 ///
194 /// ### Use with named parameters
195 ///
196 /// ```rust,no_run
197 /// # use rusqlite::{Connection, Result};
198 /// fn query(conn: &Connection) -> Result<()> {
199 /// let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
200 /// let mut rows = stmt.query(&[(":name", "one")])?;
201 /// while let Some(row) = rows.next()? {
202 /// // ...
203 /// }
204 /// Ok(())
205 /// }
206 /// ```
207 ///
208 /// Note, the `named_params!` macro is provided for syntactic convenience,
209 /// and so the above example could also be written as:
210 ///
211 /// ```rust,no_run
212 /// # use rusqlite::{Connection, Result, named_params};
213 /// fn query(conn: &Connection) -> Result<()> {
214 /// let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
215 /// let mut rows = stmt.query(named_params! { ":name": "one" })?;
216 /// while let Some(row) = rows.next()? {
217 /// // ...
218 /// }
219 /// Ok(())
220 /// }
221 /// ```
222 ///
223 /// ## Failure
224 ///
225 /// Will return `Err` if binding parameters fails.
226 #[inline]
227 pub fn query<P: Params>(&mut self, params: P) -> Result<Rows<'_>> {
228 params.__bind_in(self)?;
229 Ok(Rows::new(self))
230 }
231
232 /// Executes the prepared statement and maps a function over the resulting
233 /// rows, returning an iterator over the mapped function results.
234 ///
235 /// `f` is used to transform the _streaming_ iterator into a _standard_
236 /// iterator.
237 ///
238 /// This is equivalent to `stmt.query(params)?.mapped(f)`.
239 ///
240 /// ## Example
241 ///
242 /// ### Use with positional params
243 ///
244 /// ```rust,no_run
245 /// # use rusqlite::{Connection, Result};
246 /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
247 /// let mut stmt = conn.prepare("SELECT name FROM people")?;
248 /// let rows = stmt.query_map([], |row| row.get(0))?;
249 ///
250 /// let mut names = Vec::new();
251 /// for name_result in rows {
252 /// names.push(name_result?);
253 /// }
254 ///
255 /// Ok(names)
256 /// }
257 /// ```
258 ///
259 /// ### Use with named params
260 ///
261 /// ```rust,no_run
262 /// # use rusqlite::{Connection, Result};
263 /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
264 /// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
265 /// let rows = stmt.query_map(&[(":id", &"one")], |row| row.get(0))?;
266 ///
267 /// let mut names = Vec::new();
268 /// for name_result in rows {
269 /// names.push(name_result?);
270 /// }
271 ///
272 /// Ok(names)
273 /// }
274 /// ```
275 /// ## Failure
276 ///
277 /// Will return `Err` if binding parameters fails.
278 pub fn query_map<T, P, F>(&mut self, params: P, f: F) -> Result<MappedRows<'_, F>>
279 where
280 P: Params,
281 F: FnMut(&Row<'_>) -> Result<T>,
282 {
283 self.query(params).map(|rows| rows.mapped(f))
284 }
285
286 /// Executes the prepared statement and maps a function over the resulting
287 /// rows, where the function returns a `Result` with `Error` type
288 /// implementing `std::convert::From<Error>` (so errors can be unified).
289 ///
290 /// This is equivalent to `stmt.query(params)?.and_then(f)`.
291 ///
292 /// ## Example
293 ///
294 /// ### Use with named params
295 ///
296 /// ```rust,no_run
297 /// # use rusqlite::{Connection, Result};
298 /// struct Person {
299 /// name: String,
300 /// };
301 ///
302 /// fn name_to_person(name: String) -> Result<Person> {
303 /// // ... check for valid name
304 /// Ok(Person { name })
305 /// }
306 ///
307 /// fn get_names(conn: &Connection) -> Result<Vec<Person>> {
308 /// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
309 /// let rows = stmt.query_and_then(&[(":id", "one")], |row| name_to_person(row.get(0)?))?;
310 ///
311 /// let mut persons = Vec::new();
312 /// for person_result in rows {
313 /// persons.push(person_result?);
314 /// }
315 ///
316 /// Ok(persons)
317 /// }
318 /// ```
319 ///
320 /// ### Use with positional params
321 ///
322 /// ```rust,no_run
323 /// # use rusqlite::{Connection, Result};
324 /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
325 /// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = ?1")?;
326 /// let rows = stmt.query_and_then(["one"], |row| row.get::<_, String>(0))?;
327 ///
328 /// let mut persons = Vec::new();
329 /// for person_result in rows {
330 /// persons.push(person_result?);
331 /// }
332 ///
333 /// Ok(persons)
334 /// }
335 /// ```
336 ///
337 /// # Failure
338 ///
339 /// Will return `Err` if binding parameters fails.
340 #[inline]
341 pub fn query_and_then<T, E, P, F>(&mut self, params: P, f: F) -> Result<AndThenRows<'_, F>>
342 where
343 P: Params,
344 E: From<Error>,
345 F: FnMut(&Row<'_>) -> Result<T, E>,
346 {
347 self.query(params).map(|rows| rows.and_then(f))
348 }
349
350 /// Return `true` if a query in the SQL statement it executes returns one
351 /// or more rows and `false` if the SQL returns an empty set.
352 #[inline]
353 pub fn exists<P: Params>(&mut self, params: P) -> Result<bool> {
354 let mut rows = self.query(params)?;
355 let exists = rows.next()?.is_some();
356 Ok(exists)
357 }
358
359 /// Convenience method to execute a query that is expected to return a
360 /// single row.
361 ///
362 /// If the query returns more than one row, all rows except the first are
363 /// ignored.
364 ///
365 /// Returns `Err(QueryReturnedNoRows)` if no results are returned. If the
366 /// query truly is optional, you can call
367 /// [`.optional()`](crate::OptionalExtension::optional) on the result of
368 /// this to get a `Result<Option<T>>` (requires that the trait
369 /// `rusqlite::OptionalExtension` is imported).
370 ///
371 /// # Failure
372 ///
373 /// Will return `Err` if the underlying SQLite call fails.
374 pub fn query_row<T, P, F>(&mut self, params: P, f: F) -> Result<T>
375 where
376 P: Params,
377 F: FnOnce(&Row<'_>) -> Result<T>,
378 {
379 let mut rows = self.query(params)?;
380
381 rows.get_expected_row().and_then(f)
382 }
383
384 /// Convenience method to execute a query that is expected to return exactly
385 /// one row.
386 ///
387 /// Returns `Err(QueryReturnedMoreThanOneRow)` if the query returns more than one row.
388 ///
389 /// Returns `Err(QueryReturnedNoRows)` if no results are returned. If the
390 /// query truly is optional, you can call
391 /// [`.optional()`](crate::OptionalExtension::optional) on the result of
392 /// this to get a `Result<Option<T>>` (requires that the trait
393 /// `rusqlite::OptionalExtension` is imported).
394 ///
395 /// # Failure
396 ///
397 /// Will return `Err` if the underlying SQLite call fails.
398 pub fn query_one<T, P, F>(&mut self, params: P, f: F) -> Result<T>
399 where
400 P: Params,
401 F: FnOnce(&Row<'_>) -> Result<T>,
402 {
403 let mut rows = self.query(params)?;
404 let row = rows.get_expected_row().and_then(f)?;
405 if rows.next()?.is_some() {
406 return Err(Error::QueryReturnedMoreThanOneRow);
407 }
408 Ok(row)
409 }
410
411 /// Consumes the statement.
412 ///
413 /// Functionally equivalent to the `Drop` implementation, but allows
414 /// callers to see any errors that occur.
415 ///
416 /// # Failure
417 ///
418 /// Will return `Err` if the underlying SQLite call fails.
419 #[inline]
420 pub fn finalize(mut self) -> Result<()> {
421 self.finalize_()
422 }
423
424 /// Return the (one-based) index of an SQL parameter given its name.
425 ///
426 /// Note that the initial ":" or "$" or "@" or "?" used to specify the
427 /// parameter is included as part of the name.
428 ///
429 /// ```rust,no_run
430 /// # use rusqlite::{Connection, Result};
431 /// fn example(conn: &Connection) -> Result<()> {
432 /// let stmt = conn.prepare("SELECT * FROM test WHERE name = :example")?;
433 /// let index = stmt.parameter_index(":example")?;
434 /// assert_eq!(index, Some(1));
435 /// Ok(())
436 /// }
437 /// ```
438 ///
439 /// # Failure
440 ///
441 /// Will return Err if `name` is invalid. Will return Ok(None) if the name
442 /// is valid but not a bound parameter of this statement.
443 #[inline]
444 pub fn parameter_index(&self, name: &str) -> Result<Option<usize>> {
445 Ok(self.stmt.bind_parameter_index(name))
446 }
447
448 /// Return the SQL parameter name given its (one-based) index (the inverse
449 /// of [`Statement::parameter_index`]).
450 ///
451 /// ```rust,no_run
452 /// # use rusqlite::{Connection, Result};
453 /// fn example(conn: &Connection) -> Result<()> {
454 /// let stmt = conn.prepare("SELECT * FROM test WHERE name = :example")?;
455 /// let index = stmt.parameter_name(1);
456 /// assert_eq!(index, Some(":example"));
457 /// Ok(())
458 /// }
459 /// ```
460 ///
461 /// # Failure
462 ///
463 /// Will return `None` if the column index is out of bounds or if the
464 /// parameter is positional.
465 ///
466 /// # Panics
467 ///
468 /// Panics when parameter name is not valid UTF-8.
469 #[inline]
470 pub fn parameter_name(&self, index: usize) -> Option<&'_ str> {
471 self.stmt.bind_parameter_name(index as i32).map(|name| {
472 name.to_str()
473 .expect("Invalid UTF-8 sequence in parameter name")
474 })
475 }
476
477 #[inline]
478 pub(crate) fn bind_parameters<P>(&mut self, params: P) -> Result<()>
479 where
480 P: IntoIterator,
481 P::Item: ToSql,
482 {
483 let expected = self.stmt.bind_parameter_count();
484 let mut index = 0;
485 for p in params {
486 index += 1; // The leftmost SQL parameter has an index of 1.
487 if index > expected {
488 break;
489 }
490 self.bind_parameter(&p, index)?;
491 }
492 if index != expected {
493 Err(Error::InvalidParameterCount(index, expected))
494 } else {
495 Ok(())
496 }
497 }
498
499 #[inline]
500 pub(crate) fn ensure_parameter_count(&self, n: usize) -> Result<()> {
501 let count = self.parameter_count();
502 if count != n {
503 Err(Error::InvalidParameterCount(n, count))
504 } else {
505 Ok(())
506 }
507 }
508
509 #[inline]
510 pub(crate) fn bind_parameters_named<S: BindIndex, T: ToSql>(
511 &mut self,
512 params: &[(S, T)],
513 ) -> Result<()> {
514 for (name, value) in params {
515 let i = name.idx(self)?;
516 let ts: &dyn ToSql = &value;
517 self.bind_parameter(ts, i)?;
518 }
519 Ok(())
520 }
521
522 /// Return the number of parameters that can be bound to this statement.
523 #[inline]
524 pub fn parameter_count(&self) -> usize {
525 self.stmt.bind_parameter_count()
526 }
527
528 /// Low level API to directly bind a parameter to a given index.
529 ///
530 /// Note that the index is one-based, that is, the first parameter index is
531 /// 1 and not 0. This is consistent with the SQLite API and the values given
532 /// to parameters bound as `?NNN`.
533 ///
534 /// The valid values for `one_based_col_index` begin at `1`, and end at
535 /// [`Statement::parameter_count`], inclusive.
536 ///
537 /// # Caveats
538 ///
539 /// This should not generally be used, but is available for special cases
540 /// such as:
541 ///
542 /// - binding parameters where a gap exists.
543 /// - binding named and positional parameters in the same query.
544 /// - separating parameter binding from query execution.
545 ///
546 /// In general, statements that have had *any* parameters bound this way
547 /// should have *all* parameters bound this way, and be queried or executed
548 /// by [`Statement::raw_query`] or [`Statement::raw_execute`], other usage
549 /// is unsupported and will likely, probably in surprising ways.
550 ///
551 /// That is: Do not mix the "raw" statement functions with the rest of the
552 /// API, or the results may be surprising, and may even change in future
553 /// versions without comment.
554 ///
555 /// # Example
556 ///
557 /// ```rust,no_run
558 /// # use rusqlite::{Connection, Result};
559 /// fn query(conn: &Connection) -> Result<()> {
560 /// let mut stmt = conn.prepare("SELECT * FROM test WHERE name = :name AND value > ?2")?;
561 /// stmt.raw_bind_parameter(c":name", "foo")?;
562 /// stmt.raw_bind_parameter(2, 100)?;
563 /// let mut rows = stmt.raw_query();
564 /// while let Some(row) = rows.next()? {
565 /// // ...
566 /// }
567 /// Ok(())
568 /// }
569 /// ```
570 #[inline]
571 pub fn raw_bind_parameter<I: BindIndex, T: ToSql>(
572 &mut self,
573 one_based_index: I,
574 param: T,
575 ) -> Result<()> {
576 // This is the same as `bind_parameter` but slightly more ergonomic and
577 // correctly takes `&mut self`.
578 self.bind_parameter(¶m, one_based_index.idx(self)?)
579 }
580
581 /// Low level API to execute a statement given that all parameters were
582 /// bound explicitly with the [`Statement::raw_bind_parameter`] API.
583 ///
584 /// # Caveats
585 ///
586 /// Any unbound parameters will have `NULL` as their value.
587 ///
588 /// This should not generally be used outside special cases, and
589 /// functions in the [`Statement::execute`] family should be preferred.
590 ///
591 /// # Failure
592 ///
593 /// Will return `Err` if the executed statement returns rows (in which case
594 /// `query` should be used instead), or the underlying SQLite call fails.
595 #[inline]
596 pub fn raw_execute(&mut self) -> Result<usize> {
597 self.execute_with_bound_parameters()
598 }
599
600 /// Low level API to get `Rows` for this query given that all parameters
601 /// were bound explicitly with the [`Statement::raw_bind_parameter`] API.
602 ///
603 /// # Caveats
604 ///
605 /// Any unbound parameters will have `NULL` as their value.
606 ///
607 /// This should not generally be used outside special cases, and
608 /// functions in the [`Statement::query`] family should be preferred.
609 ///
610 /// Note that if the SQL does not return results, [`Statement::raw_execute`]
611 /// should be used instead.
612 #[inline]
613 pub fn raw_query(&mut self) -> Rows<'_> {
614 Rows::new(self)
615 }
616
617 // generic because many of these branches can constant fold away.
618 fn bind_parameter<P: ?Sized + ToSql>(&self, param: &P, ndx: usize) -> Result<()> {
619 let value = param.to_sql()?;
620
621 let ptr = unsafe { self.stmt.ptr() };
622 let value = match value {
623 ToSqlOutput::Borrowed(v) => v,
624 ToSqlOutput::Owned(ref v) => ValueRef::from(v),
625
626 #[cfg(feature = "blob")]
627 ToSqlOutput::ZeroBlob(len) => {
628 // TODO sqlite3_bind_zeroblob64 // 3.8.11
629 return self
630 .conn
631 .decode_result(unsafe { ffi::sqlite3_bind_zeroblob(ptr, ndx as c_int, len) });
632 }
633 #[cfg(feature = "functions")]
634 ToSqlOutput::Arg(_) => {
635 return Err(err!(ffi::SQLITE_MISUSE, "Unsupported value \"{value:?}\""));
636 }
637 #[cfg(feature = "array")]
638 ToSqlOutput::Array(a) => {
639 return self.conn.decode_result(unsafe {
640 ffi::sqlite3_bind_pointer(
641 ptr,
642 ndx as c_int,
643 Rc::into_raw(a) as *mut c_void,
644 ARRAY_TYPE,
645 Some(free_array),
646 )
647 });
648 }
649 };
650 self.conn.decode_result(match value {
651 ValueRef::Null => unsafe { ffi::sqlite3_bind_null(ptr, ndx as c_int) },
652 ValueRef::Integer(i) => unsafe { ffi::sqlite3_bind_int64(ptr, ndx as c_int, i) },
653 ValueRef::Real(r) => unsafe { ffi::sqlite3_bind_double(ptr, ndx as c_int, r) },
654 ValueRef::Text(s) => unsafe {
655 let (c_str, len, destructor) = str_for_sqlite(s)?;
656 // TODO sqlite3_bind_text64 // 3.8.7
657 ffi::sqlite3_bind_text(ptr, ndx as c_int, c_str, len, destructor)
658 },
659 ValueRef::Blob(b) => unsafe {
660 let length = len_as_c_int(b.len())?;
661 if length == 0 {
662 ffi::sqlite3_bind_zeroblob(ptr, ndx as c_int, 0)
663 } else {
664 // TODO sqlite3_bind_blob64 // 3.8.7
665 ffi::sqlite3_bind_blob(
666 ptr,
667 ndx as c_int,
668 b.as_ptr().cast::<c_void>(),
669 length,
670 ffi::SQLITE_TRANSIENT(),
671 )
672 }
673 },
674 })
675 }
676
677 #[inline]
678 fn execute_with_bound_parameters(&mut self) -> Result<usize> {
679 self.check_update()?;
680 let r = self.stmt.step();
681 let rr = self.stmt.reset();
682 match r {
683 ffi::SQLITE_DONE => match rr {
684 ffi::SQLITE_OK => Ok(self.conn.changes() as usize),
685 _ => Err(self.conn.decode_result(rr).unwrap_err()),
686 },
687 ffi::SQLITE_ROW => Err(Error::ExecuteReturnedResults),
688 _ => Err(self.conn.decode_result(r).unwrap_err()),
689 }
690 }
691
692 #[inline]
693 fn finalize_(&mut self) -> Result<()> {
694 let mut stmt = unsafe { RawStatement::new(ptr::null_mut()) };
695 mem::swap(&mut stmt, &mut self.stmt);
696 self.conn.decode_result(stmt.finalize())
697 }
698
699 #[cfg(feature = "extra_check")]
700 #[inline]
701 fn check_update(&self) -> Result<()> {
702 if self.column_count() > 0 && self.stmt.readonly() {
703 return Err(Error::ExecuteReturnedResults);
704 }
705 Ok(())
706 }
707
708 #[cfg(not(feature = "extra_check"))]
709 #[inline]
710 #[expect(clippy::unnecessary_wraps)]
711 fn check_update(&self) -> Result<()> {
712 Ok(())
713 }
714
715 /// Returns a string containing the SQL text of prepared statement with
716 /// bound parameters expanded.
717 pub fn expanded_sql(&self) -> Option<String> {
718 self.stmt
719 .expanded_sql()
720 .map(|s| s.to_string_lossy().to_string())
721 }
722
723 /// Get the value for one of the status counters for this statement.
724 #[inline]
725 pub fn get_status(&self, status: StatementStatus) -> i32 {
726 self.stmt.get_status(status, false)
727 }
728
729 /// Reset the value of one of the status counters for this statement,
730 #[inline]
731 /// returning the value it had before resetting.
732 pub fn reset_status(&self, status: StatementStatus) -> i32 {
733 self.stmt.get_status(status, true)
734 }
735
736 /// Returns 1 if the prepared statement is an EXPLAIN statement,
737 /// or 2 if the statement is an EXPLAIN QUERY PLAN,
738 /// or 0 if it is an ordinary statement or a NULL pointer.
739 #[inline]
740 #[cfg(feature = "modern_sqlite")] // 3.28.0
741 pub fn is_explain(&self) -> i32 {
742 self.stmt.is_explain()
743 }
744
745 /// Returns true if the statement is read only.
746 #[inline]
747 pub fn readonly(&self) -> bool {
748 self.stmt.readonly()
749 }
750
751 /// Safety: This is unsafe, because using `sqlite3_stmt` after the
752 /// connection has closed is illegal, but `RawStatement` does not enforce
753 /// this, as it loses our protective `'conn` lifetime bound.
754 #[inline]
755 pub(crate) unsafe fn into_raw(mut self) -> RawStatement {
756 let mut stmt = RawStatement::new(ptr::null_mut());
757 mem::swap(&mut stmt, &mut self.stmt);
758 stmt
759 }
760
761 /// Reset all bindings
762 pub fn clear_bindings(&mut self) {
763 self.stmt.clear_bindings();
764 }
765
766 pub(crate) unsafe fn ptr(&self) -> *mut ffi::sqlite3_stmt {
767 self.stmt.ptr()
768 }
769}
770
771impl fmt::Debug for Statement<'_> {
772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
773 let sql = if self.stmt.is_null() {
774 Ok("")
775 } else {
776 self.stmt.sql().unwrap().to_str()
777 };
778 f.debug_struct("Statement")
779 .field("conn", self.conn)
780 .field("stmt", &self.stmt)
781 .field("sql", &sql)
782 .finish()
783 }
784}
785
786impl Drop for Statement<'_> {
787 #[expect(unused_must_use)]
788 #[inline]
789 fn drop(&mut self) {
790 self.finalize_();
791 }
792}
793
794impl Statement<'_> {
795 #[inline]
796 pub(super) fn new(conn: &Connection, stmt: RawStatement) -> Statement<'_> {
797 Statement { conn, stmt }
798 }
799
800 pub(super) fn value_ref(&self, col: usize) -> ValueRef<'_> {
801 let raw = unsafe { self.stmt.ptr() };
802
803 match self.stmt.column_type(col) {
804 ffi::SQLITE_NULL => ValueRef::Null,
805 ffi::SQLITE_INTEGER => {
806 ValueRef::Integer(unsafe { ffi::sqlite3_column_int64(raw, col as c_int) })
807 }
808 ffi::SQLITE_FLOAT => {
809 ValueRef::Real(unsafe { ffi::sqlite3_column_double(raw, col as c_int) })
810 }
811 ffi::SQLITE_TEXT => {
812 let s = unsafe {
813 // Quoting from "Using SQLite" book:
814 // To avoid problems, an application should first extract the desired type using
815 // a sqlite3_column_xxx() function, and then call the
816 // appropriate sqlite3_column_bytes() function.
817 let text = ffi::sqlite3_column_text(raw, col as c_int);
818 let len = ffi::sqlite3_column_bytes(raw, col as c_int);
819 assert!(
820 !text.is_null(),
821 "unexpected SQLITE_TEXT column type with NULL data"
822 );
823 from_raw_parts(text.cast::<u8>(), len as usize)
824 };
825
826 ValueRef::Text(s)
827 }
828 ffi::SQLITE_BLOB => {
829 let (blob, len) = unsafe {
830 (
831 ffi::sqlite3_column_blob(raw, col as c_int),
832 ffi::sqlite3_column_bytes(raw, col as c_int),
833 )
834 };
835
836 assert!(
837 len >= 0,
838 "unexpected negative return from sqlite3_column_bytes"
839 );
840 if len > 0 {
841 assert!(
842 !blob.is_null(),
843 "unexpected SQLITE_BLOB column type with NULL data"
844 );
845 ValueRef::Blob(unsafe { from_raw_parts(blob.cast::<u8>(), len as usize) })
846 } else {
847 // The return value from sqlite3_column_blob() for a zero-length BLOB
848 // is a NULL pointer.
849 ValueRef::Blob(&[])
850 }
851 }
852 _ => unreachable!("sqlite3_column_type returned invalid value"),
853 }
854 }
855
856 #[inline]
857 pub(super) fn step(&self) -> Result<bool> {
858 match self.stmt.step() {
859 ffi::SQLITE_ROW => Ok(true),
860 ffi::SQLITE_DONE => Ok(false),
861 code => Err(self.conn.decode_result(code).unwrap_err()),
862 }
863 }
864
865 #[inline]
866 pub(super) fn reset(&self) -> Result<()> {
867 match self.stmt.reset() {
868 ffi::SQLITE_OK => Ok(()),
869 code => Err(self.conn.decode_result(code).unwrap_err()),
870 }
871 }
872}
873
874/// Prepared statement status counters.
875///
876/// See `https://www.sqlite.org/c3ref/c_stmtstatus_counter.html`
877/// for explanations of each.
878///
879/// Note that depending on your version of SQLite, all of these
880/// may not be available.
881#[repr(i32)]
882#[derive(Clone, Copy, PartialEq, Eq)]
883#[non_exhaustive]
884pub enum StatementStatus {
885 /// Equivalent to `SQLITE_STMTSTATUS_FULLSCAN_STEP`
886 FullscanStep = 1,
887 /// Equivalent to `SQLITE_STMTSTATUS_SORT`
888 Sort = 2,
889 /// Equivalent to `SQLITE_STMTSTATUS_AUTOINDEX`
890 AutoIndex = 3,
891 /// Equivalent to `SQLITE_STMTSTATUS_VM_STEP`
892 VmStep = 4,
893 /// Equivalent to `SQLITE_STMTSTATUS_REPREPARE` (3.20.0)
894 RePrepare = 5,
895 /// Equivalent to `SQLITE_STMTSTATUS_RUN` (3.20.0)
896 Run = 6,
897 /// Equivalent to `SQLITE_STMTSTATUS_FILTER_MISS`
898 FilterMiss = 7,
899 /// Equivalent to `SQLITE_STMTSTATUS_FILTER_HIT`
900 FilterHit = 8,
901 /// Equivalent to `SQLITE_STMTSTATUS_MEMUSED` (3.20.0)
902 MemUsed = 99,
903}
904
905#[cfg(test)]
906mod test {
907 use crate::types::ToSql;
908 use crate::{params_from_iter, Connection, Error, Result};
909
910 #[test]
911 fn test_execute_named() -> Result<()> {
912 let db = Connection::open_in_memory()?;
913 db.execute_batch("CREATE TABLE foo(x INTEGER)")?;
914
915 assert_eq!(
916 db.execute("INSERT INTO foo(x) VALUES (:x)", &[(":x", &1i32)])?,
917 1
918 );
919 assert_eq!(
920 db.execute("INSERT INTO foo(x) VALUES (:x)", &[(":x", &2i32)])?,
921 1
922 );
923 assert_eq!(
924 db.execute(
925 "INSERT INTO foo(x) VALUES (:x)",
926 crate::named_params! {":x": 3i32}
927 )?,
928 1
929 );
930
931 assert_eq!(
932 6i32,
933 db.query_row::<i32, _, _>(
934 "SELECT SUM(x) FROM foo WHERE x > :x",
935 &[(":x", &0i32)],
936 |r| r.get(0)
937 )?
938 );
939 assert_eq!(
940 5i32,
941 db.query_row::<i32, _, _>(
942 "SELECT SUM(x) FROM foo WHERE x > :x",
943 &[(":x", &1i32)],
944 |r| r.get(0)
945 )?
946 );
947 Ok(())
948 }
949
950 #[test]
951 fn test_stmt_execute_named() -> Result<()> {
952 let db = Connection::open_in_memory()?;
953 let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
954 INTEGER)";
955 db.execute_batch(sql)?;
956
957 let mut stmt = db.prepare("INSERT INTO test (name) VALUES (:name)")?;
958 stmt.execute(&[(":name", "one")])?;
959 stmt.execute(vec![(":name", "one")].as_slice())?;
960
961 let mut stmt = db.prepare("SELECT COUNT(*) FROM test WHERE name = :name")?;
962 assert_eq!(
963 2i32,
964 stmt.query_row::<i32, _, _>(&[(":name", "one")], |r| r.get(0))?
965 );
966 Ok(())
967 }
968
969 #[test]
970 fn test_query_named() -> Result<()> {
971 let db = Connection::open_in_memory()?;
972 let sql = r#"
973 CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
974 INSERT INTO test(id, name) VALUES (1, "one");
975 "#;
976 db.execute_batch(sql)?;
977
978 let mut stmt = db.prepare("SELECT id FROM test where name = :name")?;
979 let mut rows = stmt.query(&[(":name", "one")])?;
980 let id: Result<i32> = rows.next()?.unwrap().get(0);
981 assert_eq!(Ok(1), id);
982 Ok(())
983 }
984
985 #[test]
986 fn test_query_map_named() -> Result<()> {
987 let db = Connection::open_in_memory()?;
988 let sql = r#"
989 CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
990 INSERT INTO test(id, name) VALUES (1, "one");
991 "#;
992 db.execute_batch(sql)?;
993
994 let mut stmt = db.prepare("SELECT id FROM test where name = :name")?;
995 let mut rows = stmt.query_map(&[(":name", "one")], |row| {
996 let id: Result<i32> = row.get(0);
997 id.map(|i| 2 * i)
998 })?;
999
1000 let doubled_id: i32 = rows.next().unwrap()?;
1001 assert_eq!(2, doubled_id);
1002 Ok(())
1003 }
1004
1005 #[test]
1006 fn test_query_and_then_by_name() -> Result<()> {
1007 let db = Connection::open_in_memory()?;
1008 let sql = r#"
1009 CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
1010 INSERT INTO test(id, name) VALUES (1, "one");
1011 INSERT INTO test(id, name) VALUES (2, "one");
1012 "#;
1013 db.execute_batch(sql)?;
1014
1015 let mut stmt = db.prepare("SELECT id FROM test where name = :name ORDER BY id ASC")?;
1016 let mut rows = stmt.query_and_then(&[(":name", "one")], |row| {
1017 let id: i32 = row.get(0)?;
1018 if id == 1 {
1019 Ok(id)
1020 } else {
1021 Err(Error::SqliteSingleThreadedMode)
1022 }
1023 })?;
1024
1025 // first row should be Ok
1026 let doubled_id: i32 = rows.next().unwrap()?;
1027 assert_eq!(1, doubled_id);
1028
1029 // second row should be an `Err`
1030 #[expect(clippy::match_wild_err_arm)]
1031 match rows.next().unwrap() {
1032 Ok(_) => panic!("invalid Ok"),
1033 Err(Error::SqliteSingleThreadedMode) => (),
1034 Err(_) => panic!("invalid Err"),
1035 }
1036 Ok(())
1037 }
1038
1039 #[test]
1040 fn test_unbound_parameters_are_null() -> Result<()> {
1041 let db = Connection::open_in_memory()?;
1042 let sql = "CREATE TABLE test (x TEXT, y TEXT)";
1043 db.execute_batch(sql)?;
1044
1045 let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)")?;
1046 stmt.execute(&[(":x", "one")])?;
1047
1048 let result: Option<String> = db.one_column("SELECT y FROM test WHERE x = 'one'", [])?;
1049 assert!(result.is_none());
1050 Ok(())
1051 }
1052
1053 #[test]
1054 fn test_raw_binding() -> Result<()> {
1055 let db = Connection::open_in_memory()?;
1056 db.execute_batch("CREATE TABLE test (name TEXT, value INTEGER)")?;
1057 {
1058 let mut stmt = db.prepare("INSERT INTO test (name, value) VALUES (:name, ?3)")?;
1059
1060 stmt.raw_bind_parameter(c":name", "example")?;
1061 stmt.raw_bind_parameter(":name", "example")?;
1062 stmt.raw_bind_parameter(3, 50i32)?;
1063 let n = stmt.raw_execute()?;
1064 assert_eq!(n, 1);
1065 }
1066
1067 {
1068 let mut stmt = db.prepare("SELECT name, value FROM test WHERE value = ?2")?;
1069 stmt.raw_bind_parameter(2, 50)?;
1070 let mut rows = stmt.raw_query();
1071 {
1072 let row = rows.next()?.unwrap();
1073 let name: String = row.get(0)?;
1074 assert_eq!(name, "example");
1075 let value: i32 = row.get(1)?;
1076 assert_eq!(value, 50);
1077 }
1078 assert!(rows.next()?.is_none());
1079 }
1080
1081 Ok(())
1082 }
1083
1084 #[test]
1085 fn test_unbound_parameters_are_reused() -> Result<()> {
1086 let db = Connection::open_in_memory()?;
1087 let sql = "CREATE TABLE test (x TEXT, y TEXT)";
1088 db.execute_batch(sql)?;
1089
1090 let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)")?;
1091 stmt.execute(&[(":x", "one")])?;
1092 stmt.execute(&[(c":y", "two")])?;
1093
1094 let result: String = db.one_column("SELECT x FROM test WHERE y = 'two'", [])?;
1095 assert_eq!(result, "one");
1096 Ok(())
1097 }
1098
1099 #[test]
1100 fn test_insert() -> Result<()> {
1101 let db = Connection::open_in_memory()?;
1102 db.execute_batch("CREATE TABLE foo(x INTEGER UNIQUE)")?;
1103 let mut stmt = db.prepare("INSERT OR IGNORE INTO foo (x) VALUES (?1)")?;
1104 assert_eq!(stmt.insert([1i32])?, 1);
1105 assert_eq!(stmt.insert([2i32])?, 2);
1106 match stmt.insert([1i32]).unwrap_err() {
1107 Error::StatementChangedRows(0) => (),
1108 err => panic!("Unexpected error {err}"),
1109 }
1110 let mut multi = db.prepare("INSERT INTO foo (x) SELECT 3 UNION ALL SELECT 4")?;
1111 match multi.insert([]).unwrap_err() {
1112 Error::StatementChangedRows(2) => (),
1113 err => panic!("Unexpected error {err}"),
1114 }
1115 Ok(())
1116 }
1117
1118 #[test]
1119 fn test_insert_different_tables() -> Result<()> {
1120 // Test for https://github.com/rusqlite/rusqlite/issues/171
1121 let db = Connection::open_in_memory()?;
1122 db.execute_batch(
1123 r"
1124 CREATE TABLE foo(x INTEGER);
1125 CREATE TABLE bar(x INTEGER);
1126 ",
1127 )?;
1128
1129 assert_eq!(db.prepare("INSERT INTO foo VALUES (10)")?.insert([])?, 1);
1130 assert_eq!(db.prepare("INSERT INTO bar VALUES (10)")?.insert([])?, 1);
1131 Ok(())
1132 }
1133
1134 #[test]
1135 fn test_exists() -> Result<()> {
1136 let db = Connection::open_in_memory()?;
1137 let sql = "BEGIN;
1138 CREATE TABLE foo(x INTEGER);
1139 INSERT INTO foo VALUES(1);
1140 INSERT INTO foo VALUES(2);
1141 END;";
1142 db.execute_batch(sql)?;
1143 let mut stmt = db.prepare("SELECT 1 FROM foo WHERE x = ?1")?;
1144 assert!(stmt.exists([1i32])?);
1145 assert!(stmt.exists([2i32])?);
1146 assert!(!stmt.exists([0i32])?);
1147 Ok(())
1148 }
1149 #[test]
1150 fn test_tuple_params() -> Result<()> {
1151 let db = Connection::open_in_memory()?;
1152 let s = db.query_row("SELECT printf('[%s]', ?1)", ("abc",), |r| {
1153 r.get::<_, String>(0)
1154 })?;
1155 assert_eq!(s, "[abc]");
1156 let s = db.query_row(
1157 "SELECT printf('%d %s %d', ?1, ?2, ?3)",
1158 (1i32, "abc", 2i32),
1159 |r| r.get::<_, String>(0),
1160 )?;
1161 assert_eq!(s, "1 abc 2");
1162 let s = db.query_row(
1163 "SELECT printf('%d %s %d %d', ?1, ?2, ?3, ?4)",
1164 (1, "abc", 2i32, 4i64),
1165 |r| r.get::<_, String>(0),
1166 )?;
1167 assert_eq!(s, "1 abc 2 4");
1168 #[rustfmt::skip]
1169 let bigtup = (
1170 0, "a", 1, "b", 2, "c", 3, "d",
1171 4, "e", 5, "f", 6, "g", 7, "h",
1172 );
1173 let query = "SELECT printf(
1174 '%d %s | %d %s | %d %s | %d %s || %d %s | %d %s | %d %s | %d %s',
1175 ?1, ?2, ?3, ?4,
1176 ?5, ?6, ?7, ?8,
1177 ?9, ?10, ?11, ?12,
1178 ?13, ?14, ?15, ?16
1179 )";
1180 let s = db.query_row(query, bigtup, |r| r.get::<_, String>(0))?;
1181 assert_eq!(s, "0 a | 1 b | 2 c | 3 d || 4 e | 5 f | 6 g | 7 h");
1182 Ok(())
1183 }
1184
1185 #[test]
1186 fn test_query_row() -> Result<()> {
1187 let db = Connection::open_in_memory()?;
1188 let sql = "BEGIN;
1189 CREATE TABLE foo(x INTEGER, y INTEGER);
1190 INSERT INTO foo VALUES(1, 3);
1191 INSERT INTO foo VALUES(2, 4);
1192 END;";
1193 db.execute_batch(sql)?;
1194 let mut stmt = db.prepare("SELECT y FROM foo WHERE x = ?1")?;
1195 let y: Result<i64> = stmt.query_row([1i32], |r| r.get(0));
1196 assert_eq!(3i64, y?);
1197 Ok(())
1198 }
1199
1200 #[test]
1201 fn query_one() -> Result<()> {
1202 let db = Connection::open_in_memory()?;
1203 db.execute_batch("CREATE TABLE foo(x INTEGER, y INTEGER);")?;
1204 let mut stmt = db.prepare("SELECT y FROM foo WHERE x = ?1")?;
1205 let y: Result<i64> = stmt.query_one([1i32], |r| r.get(0));
1206 assert_eq!(Error::QueryReturnedNoRows, y.unwrap_err());
1207 db.execute_batch("INSERT INTO foo VALUES(1, 3);")?;
1208 let y: Result<i64> = stmt.query_one([1i32], |r| r.get(0));
1209 assert_eq!(3i64, y?);
1210 db.execute_batch("INSERT INTO foo VALUES(1, 3);")?;
1211 let y: Result<i64> = stmt.query_one([1i32], |r| r.get(0));
1212 assert_eq!(Error::QueryReturnedMoreThanOneRow, y.unwrap_err());
1213 Ok(())
1214 }
1215
1216 #[test]
1217 fn test_query_by_column_name() -> Result<()> {
1218 let db = Connection::open_in_memory()?;
1219 let sql = "BEGIN;
1220 CREATE TABLE foo(x INTEGER, y INTEGER);
1221 INSERT INTO foo VALUES(1, 3);
1222 END;";
1223 db.execute_batch(sql)?;
1224 let mut stmt = db.prepare("SELECT y FROM foo")?;
1225 let y: Result<i64> = stmt.query_row([], |r| r.get("y"));
1226 assert_eq!(3i64, y?);
1227 Ok(())
1228 }
1229
1230 #[test]
1231 fn test_query_by_column_name_ignore_case() -> Result<()> {
1232 let db = Connection::open_in_memory()?;
1233 let sql = "BEGIN;
1234 CREATE TABLE foo(x INTEGER, y INTEGER);
1235 INSERT INTO foo VALUES(1, 3);
1236 END;";
1237 db.execute_batch(sql)?;
1238 let mut stmt = db.prepare("SELECT y as Y FROM foo")?;
1239 let y: Result<i64> = stmt.query_row([], |r| r.get("y"));
1240 assert_eq!(3i64, y?);
1241 Ok(())
1242 }
1243
1244 #[test]
1245 fn test_expanded_sql() -> Result<()> {
1246 let db = Connection::open_in_memory()?;
1247 let stmt = db.prepare("SELECT ?1")?;
1248 stmt.bind_parameter(&1, 1)?;
1249 assert_eq!(Some("SELECT 1".to_owned()), stmt.expanded_sql());
1250 Ok(())
1251 }
1252
1253 #[test]
1254 fn test_bind_parameters() -> Result<()> {
1255 let db = Connection::open_in_memory()?;
1256 // dynamic slice:
1257 db.query_row(
1258 "SELECT ?1, ?2, ?3",
1259 [&1u8 as &dyn ToSql, &"one", &Some("one")],
1260 |row| row.get::<_, u8>(0),
1261 )?;
1262 // existing collection:
1263 let data = vec![1, 2, 3];
1264 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(&data), |row| {
1265 row.get::<_, u8>(0)
1266 })?;
1267 db.query_row(
1268 "SELECT ?1, ?2, ?3",
1269 params_from_iter(data.as_slice()),
1270 |row| row.get::<_, u8>(0),
1271 )?;
1272 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(data), |row| {
1273 row.get::<_, u8>(0)
1274 })?;
1275
1276 use std::collections::BTreeSet;
1277 let data: BTreeSet<String> = ["one", "two", "three"]
1278 .iter()
1279 .map(|s| (*s).to_string())
1280 .collect();
1281 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(&data), |row| {
1282 row.get::<_, String>(0)
1283 })?;
1284
1285 let data = [0; 3];
1286 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(&data), |row| {
1287 row.get::<_, u8>(0)
1288 })?;
1289 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(data.iter()), |row| {
1290 row.get::<_, u8>(0)
1291 })?;
1292 Ok(())
1293 }
1294
1295 #[test]
1296 fn test_parameter_name() -> Result<()> {
1297 let db = Connection::open_in_memory()?;
1298 db.execute_batch("CREATE TABLE test (name TEXT, value INTEGER)")?;
1299 let stmt = db.prepare("INSERT INTO test (name, value) VALUES (:name, ?3)")?;
1300 assert_eq!(stmt.parameter_name(0), None);
1301 assert_eq!(stmt.parameter_name(1), Some(":name"));
1302 assert_eq!(stmt.parameter_name(2), None);
1303 Ok(())
1304 }
1305
1306 #[test]
1307 fn test_empty_stmt() -> Result<()> {
1308 let conn = Connection::open_in_memory()?;
1309 let mut stmt = conn.prepare("")?;
1310 assert_eq!(0, stmt.column_count());
1311 stmt.parameter_index("test")?;
1312 let err = stmt.step().unwrap_err();
1313 assert_eq!(err.sqlite_error_code(), Some(crate::ErrorCode::ApiMisuse));
1314 // error msg is different with sqlcipher, so we use assert_ne:
1315 assert_ne!(err.to_string(), "not an error".to_owned());
1316 stmt.reset()?; // SQLITE_OMIT_AUTORESET = false
1317 stmt.execute([]).unwrap_err();
1318 Ok(())
1319 }
1320
1321 #[test]
1322 fn test_comment_stmt() -> Result<()> {
1323 let conn = Connection::open_in_memory()?;
1324 conn.prepare("/*SELECT 1;*/")?;
1325 Ok(())
1326 }
1327
1328 #[test]
1329 fn test_comment_and_sql_stmt() -> Result<()> {
1330 let conn = Connection::open_in_memory()?;
1331 let stmt = conn.prepare("/*...*/ SELECT 1;")?;
1332 assert_eq!(1, stmt.column_count());
1333 Ok(())
1334 }
1335
1336 #[test]
1337 fn test_semi_colon_stmt() -> Result<()> {
1338 let conn = Connection::open_in_memory()?;
1339 let stmt = conn.prepare(";")?;
1340 assert_eq!(0, stmt.column_count());
1341 Ok(())
1342 }
1343
1344 #[test]
1345 fn test_utf16_conversion() -> Result<()> {
1346 let db = Connection::open_in_memory()?;
1347 db.pragma_update(None, "encoding", "UTF-16le")?;
1348 let encoding: String = db.pragma_query_value(None, "encoding", |row| row.get(0))?;
1349 assert_eq!("UTF-16le", encoding);
1350 db.execute_batch("CREATE TABLE foo(x TEXT)")?;
1351 let expected = "ใในใ";
1352 db.execute("INSERT INTO foo(x) VALUES (?1)", [&expected])?;
1353 let actual: String = db.one_column("SELECT x FROM foo", [])?;
1354 assert_eq!(expected, actual);
1355 Ok(())
1356 }
1357
1358 #[test]
1359 fn test_nul_byte() -> Result<()> {
1360 let db = Connection::open_in_memory()?;
1361 let expected = "a\x00b";
1362 let actual: String = db.one_column("SELECT ?1", [expected])?;
1363 assert_eq!(expected, actual);
1364 Ok(())
1365 }
1366
1367 #[test]
1368 #[cfg(feature = "modern_sqlite")]
1369 fn is_explain() -> Result<()> {
1370 let db = Connection::open_in_memory()?;
1371 let stmt = db.prepare("SELECT 1;")?;
1372 assert_eq!(0, stmt.is_explain());
1373 Ok(())
1374 }
1375
1376 #[test]
1377 fn readonly() -> Result<()> {
1378 let db = Connection::open_in_memory()?;
1379 let stmt = db.prepare("SELECT 1;")?;
1380 assert!(stmt.readonly());
1381 Ok(())
1382 }
1383
1384 #[test]
1385 #[cfg(feature = "modern_sqlite")] // SQLite >= 3.38.0
1386 fn test_error_offset() -> Result<()> {
1387 use crate::ffi::ErrorCode;
1388 let db = Connection::open_in_memory()?;
1389 let r = db.execute_batch("SELECT INVALID_FUNCTION;");
1390 match r.unwrap_err() {
1391 Error::SqlInputError { error, offset, .. } => {
1392 assert_eq!(error.code, ErrorCode::Unknown);
1393 assert_eq!(offset, 7);
1394 }
1395 err => panic!("Unexpected error {err}"),
1396 }
1397 Ok(())
1398 }
1399}