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::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 ffi::sqlite3_bind_text64(
657 ptr,
658 ndx as c_int,
659 c_str,
660 len,
661 destructor,
662 ffi::SQLITE_UTF8 as _,
663 )
664 },
665 ValueRef::Blob(b) => unsafe {
666 let length = b.len();
667 if length == 0 {
668 ffi::sqlite3_bind_zeroblob(ptr, ndx as c_int, 0)
669 } else {
670 ffi::sqlite3_bind_blob64(
671 ptr,
672 ndx as c_int,
673 b.as_ptr().cast::<c_void>(),
674 length as ffi::sqlite3_uint64,
675 ffi::SQLITE_TRANSIENT(),
676 )
677 }
678 },
679 })
680 }
681
682 #[inline]
683 fn execute_with_bound_parameters(&mut self) -> Result<usize> {
684 self.check_update()?;
685 let r = self.stmt.step();
686 let rr = self.stmt.reset();
687 match r {
688 ffi::SQLITE_DONE => match rr {
689 ffi::SQLITE_OK => Ok(self.conn.changes() as usize),
690 _ => Err(self.conn.decode_result(rr).unwrap_err()),
691 },
692 ffi::SQLITE_ROW => Err(Error::ExecuteReturnedResults),
693 _ => Err(self.conn.decode_result(r).unwrap_err()),
694 }
695 }
696
697 #[inline]
698 fn finalize_(&mut self) -> Result<()> {
699 let mut stmt = unsafe { RawStatement::new(ptr::null_mut()) };
700 mem::swap(&mut stmt, &mut self.stmt);
701 self.conn.decode_result(stmt.finalize())
702 }
703
704 #[cfg(feature = "extra_check")]
705 #[inline]
706 fn check_update(&self) -> Result<()> {
707 if self.column_count() > 0 && self.stmt.readonly() {
708 return Err(Error::ExecuteReturnedResults);
709 }
710 Ok(())
711 }
712
713 #[cfg(not(feature = "extra_check"))]
714 #[inline]
715 #[expect(clippy::unnecessary_wraps)]
716 fn check_update(&self) -> Result<()> {
717 Ok(())
718 }
719
720 /// Returns a string containing the SQL text of prepared statement with
721 /// bound parameters expanded.
722 pub fn expanded_sql(&self) -> Option<String> {
723 self.stmt
724 .expanded_sql()
725 .map(|s| s.to_string_lossy().to_string())
726 }
727
728 /// Get the value for one of the status counters for this statement.
729 #[inline]
730 pub fn get_status(&self, status: StatementStatus) -> i32 {
731 self.stmt.get_status(status, false)
732 }
733
734 /// Reset the value of one of the status counters for this statement,
735 #[inline]
736 /// returning the value it had before resetting.
737 pub fn reset_status(&self, status: StatementStatus) -> i32 {
738 self.stmt.get_status(status, true)
739 }
740
741 /// Returns 1 if the prepared statement is an EXPLAIN statement,
742 /// or 2 if the statement is an EXPLAIN QUERY PLAN,
743 /// or 0 if it is an ordinary statement or a NULL pointer.
744 #[inline]
745 pub fn is_explain(&self) -> i32 {
746 self.stmt.is_explain()
747 }
748
749 /// Returns true if the statement is read only.
750 #[inline]
751 pub fn readonly(&self) -> bool {
752 self.stmt.readonly()
753 }
754
755 /// Safety: This is unsafe, because using `sqlite3_stmt` after the
756 /// connection has closed is illegal, but `RawStatement` does not enforce
757 /// this, as it loses our protective `'conn` lifetime bound.
758 #[inline]
759 #[cfg(feature = "cache")]
760 pub(crate) unsafe fn into_raw(mut self) -> RawStatement {
761 let mut stmt = RawStatement::new(ptr::null_mut());
762 mem::swap(&mut stmt, &mut self.stmt);
763 stmt
764 }
765
766 /// Reset all bindings
767 pub fn clear_bindings(&mut self) {
768 self.stmt.clear_bindings();
769 }
770
771 pub(crate) unsafe fn ptr(&self) -> *mut ffi::sqlite3_stmt {
772 self.stmt.ptr()
773 }
774}
775
776impl fmt::Debug for Statement<'_> {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 let sql = if self.stmt.is_null() {
779 Ok("")
780 } else {
781 self.stmt.sql().unwrap().to_str()
782 };
783 f.debug_struct("Statement")
784 .field("conn", self.conn)
785 .field("stmt", &self.stmt)
786 .field("sql", &sql)
787 .finish()
788 }
789}
790
791impl Drop for Statement<'_> {
792 #[expect(unused_must_use)]
793 #[inline]
794 fn drop(&mut self) {
795 self.finalize_();
796 }
797}
798
799impl Statement<'_> {
800 #[inline]
801 pub(super) fn new(conn: &Connection, stmt: RawStatement) -> Statement<'_> {
802 Statement { conn, stmt }
803 }
804
805 pub(super) fn value_ref(&self, col: usize) -> ValueRef<'_> {
806 let raw = unsafe { self.stmt.ptr() };
807
808 match self.stmt.column_type(col) {
809 ffi::SQLITE_NULL => ValueRef::Null,
810 ffi::SQLITE_INTEGER => {
811 ValueRef::Integer(unsafe { ffi::sqlite3_column_int64(raw, col as c_int) })
812 }
813 ffi::SQLITE_FLOAT => {
814 ValueRef::Real(unsafe { ffi::sqlite3_column_double(raw, col as c_int) })
815 }
816 ffi::SQLITE_TEXT => {
817 let s = unsafe {
818 // Quoting from "Using SQLite" book:
819 // To avoid problems, an application should first extract the desired type using
820 // a sqlite3_column_xxx() function, and then call the
821 // appropriate sqlite3_column_bytes() function.
822 let text = ffi::sqlite3_column_text(raw, col as c_int);
823 let len = ffi::sqlite3_column_bytes(raw, col as c_int);
824 assert!(
825 !text.is_null(),
826 "unexpected SQLITE_TEXT column type with NULL data"
827 );
828 from_raw_parts(text.cast::<u8>(), len as usize)
829 };
830
831 ValueRef::Text(s)
832 }
833 ffi::SQLITE_BLOB => {
834 let (blob, len) = unsafe {
835 (
836 ffi::sqlite3_column_blob(raw, col as c_int),
837 ffi::sqlite3_column_bytes(raw, col as c_int),
838 )
839 };
840
841 assert!(
842 len >= 0,
843 "unexpected negative return from sqlite3_column_bytes"
844 );
845 if len > 0 {
846 assert!(
847 !blob.is_null(),
848 "unexpected SQLITE_BLOB column type with NULL data"
849 );
850 ValueRef::Blob(unsafe { from_raw_parts(blob.cast::<u8>(), len as usize) })
851 } else {
852 // The return value from sqlite3_column_blob() for a zero-length BLOB
853 // is a NULL pointer.
854 ValueRef::Blob(&[])
855 }
856 }
857 _ => unreachable!("sqlite3_column_type returned invalid value"),
858 }
859 }
860
861 #[inline]
862 pub(super) fn step(&self) -> Result<bool> {
863 match self.stmt.step() {
864 ffi::SQLITE_ROW => Ok(true),
865 ffi::SQLITE_DONE => Ok(false),
866 code => Err(self.conn.decode_result(code).unwrap_err()),
867 }
868 }
869
870 #[inline]
871 pub(super) fn reset(&self) -> Result<()> {
872 match self.stmt.reset() {
873 ffi::SQLITE_OK => Ok(()),
874 code => Err(self.conn.decode_result(code).unwrap_err()),
875 }
876 }
877}
878
879/// Prepared statement status counters.
880///
881/// See `https://www.sqlite.org/c3ref/c_stmtstatus_counter.html`
882/// for explanations of each.
883///
884/// Note that depending on your version of SQLite, all of these
885/// may not be available.
886#[repr(i32)]
887#[derive(Clone, Copy, PartialEq, Eq)]
888#[non_exhaustive]
889pub enum StatementStatus {
890 /// Equivalent to `SQLITE_STMTSTATUS_FULLSCAN_STEP`
891 FullscanStep = 1,
892 /// Equivalent to `SQLITE_STMTSTATUS_SORT`
893 Sort = 2,
894 /// Equivalent to `SQLITE_STMTSTATUS_AUTOINDEX`
895 AutoIndex = 3,
896 /// Equivalent to `SQLITE_STMTSTATUS_VM_STEP`
897 VmStep = 4,
898 /// Equivalent to `SQLITE_STMTSTATUS_REPREPARE` (3.20.0)
899 RePrepare = 5,
900 /// Equivalent to `SQLITE_STMTSTATUS_RUN` (3.20.0)
901 Run = 6,
902 /// Equivalent to `SQLITE_STMTSTATUS_FILTER_MISS`
903 FilterMiss = 7,
904 /// Equivalent to `SQLITE_STMTSTATUS_FILTER_HIT`
905 FilterHit = 8,
906 /// Equivalent to `SQLITE_STMTSTATUS_MEMUSED` (3.20.0)
907 MemUsed = 99,
908}
909
910#[cfg(test)]
911mod test {
912 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
913 use wasm_bindgen_test::wasm_bindgen_test as test;
914
915 use crate::types::ToSql;
916 use crate::{params_from_iter, Connection, Error, Result};
917
918 #[test]
919 fn test_execute_named() -> Result<()> {
920 let db = Connection::open_in_memory()?;
921 db.execute_batch("CREATE TABLE foo(x INTEGER)")?;
922
923 assert_eq!(
924 db.execute("INSERT INTO foo(x) VALUES (:x)", &[(":x", &1i32)])?,
925 1
926 );
927 assert_eq!(
928 db.execute("INSERT INTO foo(x) VALUES (:x)", &[(":x", &2i32)])?,
929 1
930 );
931 assert_eq!(
932 db.execute(
933 "INSERT INTO foo(x) VALUES (:x)",
934 crate::named_params! {":x": 3i32}
935 )?,
936 1
937 );
938
939 assert_eq!(
940 6i32,
941 db.query_row::<i32, _, _>(
942 "SELECT SUM(x) FROM foo WHERE x > :x",
943 &[(":x", &0i32)],
944 |r| r.get(0)
945 )?
946 );
947 assert_eq!(
948 5i32,
949 db.query_row::<i32, _, _>(
950 "SELECT SUM(x) FROM foo WHERE x > :x",
951 &[(":x", &1i32)],
952 |r| r.get(0)
953 )?
954 );
955 Ok(())
956 }
957
958 #[test]
959 fn test_stmt_execute_named() -> Result<()> {
960 let db = Connection::open_in_memory()?;
961 let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
962 INTEGER)";
963 db.execute_batch(sql)?;
964
965 let mut stmt = db.prepare("INSERT INTO test (name) VALUES (:name)")?;
966 stmt.execute(&[(":name", "one")])?;
967 stmt.execute(vec![(":name", "one")].as_slice())?;
968
969 let mut stmt = db.prepare("SELECT COUNT(*) FROM test WHERE name = :name")?;
970 assert_eq!(
971 2i32,
972 stmt.query_row::<i32, _, _>(&[(":name", "one")], |r| r.get(0))?
973 );
974 Ok(())
975 }
976
977 #[test]
978 fn test_query_named() -> Result<()> {
979 let db = Connection::open_in_memory()?;
980 let sql = r#"
981 CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
982 INSERT INTO test(id, name) VALUES (1, "one");
983 "#;
984 db.execute_batch(sql)?;
985
986 let mut stmt = db.prepare("SELECT id FROM test where name = :name")?;
987 let mut rows = stmt.query(&[(":name", "one")])?;
988 let id: Result<i32> = rows.next()?.unwrap().get(0);
989 assert_eq!(Ok(1), id);
990 Ok(())
991 }
992
993 #[test]
994 fn test_query_map_named() -> Result<()> {
995 let db = Connection::open_in_memory()?;
996 let sql = r#"
997 CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
998 INSERT INTO test(id, name) VALUES (1, "one");
999 "#;
1000 db.execute_batch(sql)?;
1001
1002 let mut stmt = db.prepare("SELECT id FROM test where name = :name")?;
1003 let mut rows = stmt.query_map(&[(":name", "one")], |row| {
1004 let id: Result<i32> = row.get(0);
1005 id.map(|i| 2 * i)
1006 })?;
1007
1008 let doubled_id: i32 = rows.next().unwrap()?;
1009 assert_eq!(2, doubled_id);
1010 Ok(())
1011 }
1012
1013 #[test]
1014 fn test_query_and_then_by_name() -> Result<()> {
1015 let db = Connection::open_in_memory()?;
1016 let sql = r#"
1017 CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
1018 INSERT INTO test(id, name) VALUES (1, "one");
1019 INSERT INTO test(id, name) VALUES (2, "one");
1020 "#;
1021 db.execute_batch(sql)?;
1022
1023 let mut stmt = db.prepare("SELECT id FROM test where name = :name ORDER BY id ASC")?;
1024 let mut rows = stmt.query_and_then(&[(":name", "one")], |row| {
1025 let id: i32 = row.get(0)?;
1026 if id == 1 {
1027 Ok(id)
1028 } else {
1029 Err(Error::SqliteSingleThreadedMode)
1030 }
1031 })?;
1032
1033 // first row should be Ok
1034 let doubled_id: i32 = rows.next().unwrap()?;
1035 assert_eq!(1, doubled_id);
1036
1037 // second row should be an `Err`
1038 #[expect(clippy::match_wild_err_arm)]
1039 match rows.next().unwrap() {
1040 Ok(_) => panic!("invalid Ok"),
1041 Err(Error::SqliteSingleThreadedMode) => (),
1042 Err(_) => panic!("invalid Err"),
1043 }
1044 Ok(())
1045 }
1046
1047 #[test]
1048 fn test_unbound_parameters_are_null() -> Result<()> {
1049 let db = Connection::open_in_memory()?;
1050 let sql = "CREATE TABLE test (x TEXT, y TEXT)";
1051 db.execute_batch(sql)?;
1052
1053 let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)")?;
1054 stmt.execute(&[(":x", "one")])?;
1055
1056 let result: Option<String> = db.one_column("SELECT y FROM test WHERE x = 'one'", [])?;
1057 assert!(result.is_none());
1058 Ok(())
1059 }
1060
1061 #[test]
1062 fn test_raw_binding() -> Result<()> {
1063 let db = Connection::open_in_memory()?;
1064 db.execute_batch("CREATE TABLE test (name TEXT, value INTEGER)")?;
1065 {
1066 let mut stmt = db.prepare("INSERT INTO test (name, value) VALUES (:name, ?3)")?;
1067
1068 stmt.raw_bind_parameter(c":name", "example")?;
1069 stmt.raw_bind_parameter(":name", "example")?;
1070 stmt.raw_bind_parameter(3, 50i32)?;
1071 let n = stmt.raw_execute()?;
1072 assert_eq!(n, 1);
1073 }
1074
1075 {
1076 let mut stmt = db.prepare("SELECT name, value FROM test WHERE value = ?2")?;
1077 stmt.raw_bind_parameter(2, 50)?;
1078 let mut rows = stmt.raw_query();
1079 {
1080 let row = rows.next()?.unwrap();
1081 let name: String = row.get(0)?;
1082 assert_eq!(name, "example");
1083 let value: i32 = row.get(1)?;
1084 assert_eq!(value, 50);
1085 }
1086 assert!(rows.next()?.is_none());
1087 }
1088
1089 Ok(())
1090 }
1091
1092 #[test]
1093 fn test_unbound_parameters_are_reused() -> Result<()> {
1094 let db = Connection::open_in_memory()?;
1095 let sql = "CREATE TABLE test (x TEXT, y TEXT)";
1096 db.execute_batch(sql)?;
1097
1098 let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)")?;
1099 stmt.execute(&[(":x", "one")])?;
1100 stmt.execute(&[(c":y", "two")])?;
1101
1102 let result: String = db.one_column("SELECT x FROM test WHERE y = 'two'", [])?;
1103 assert_eq!(result, "one");
1104 Ok(())
1105 }
1106
1107 #[test]
1108 fn test_insert() -> Result<()> {
1109 let db = Connection::open_in_memory()?;
1110 db.execute_batch("CREATE TABLE foo(x INTEGER UNIQUE)")?;
1111 let mut stmt = db.prepare("INSERT OR IGNORE INTO foo (x) VALUES (?1)")?;
1112 assert_eq!(stmt.insert([1i32])?, 1);
1113 assert_eq!(stmt.insert([2i32])?, 2);
1114 match stmt.insert([1i32]).unwrap_err() {
1115 Error::StatementChangedRows(0) => (),
1116 err => panic!("Unexpected error {err}"),
1117 }
1118 let mut multi = db.prepare("INSERT INTO foo (x) SELECT 3 UNION ALL SELECT 4")?;
1119 match multi.insert([]).unwrap_err() {
1120 Error::StatementChangedRows(2) => (),
1121 err => panic!("Unexpected error {err}"),
1122 }
1123 Ok(())
1124 }
1125
1126 #[test]
1127 fn test_insert_different_tables() -> Result<()> {
1128 // Test for https://github.com/rusqlite/rusqlite/issues/171
1129 let db = Connection::open_in_memory()?;
1130 db.execute_batch(
1131 r"
1132 CREATE TABLE foo(x INTEGER);
1133 CREATE TABLE bar(x INTEGER);
1134 ",
1135 )?;
1136
1137 assert_eq!(db.prepare("INSERT INTO foo VALUES (10)")?.insert([])?, 1);
1138 assert_eq!(db.prepare("INSERT INTO bar VALUES (10)")?.insert([])?, 1);
1139 Ok(())
1140 }
1141
1142 #[test]
1143 fn test_exists() -> Result<()> {
1144 let db = Connection::open_in_memory()?;
1145 let sql = "BEGIN;
1146 CREATE TABLE foo(x INTEGER);
1147 INSERT INTO foo VALUES(1);
1148 INSERT INTO foo VALUES(2);
1149 END;";
1150 db.execute_batch(sql)?;
1151 let mut stmt = db.prepare("SELECT 1 FROM foo WHERE x = ?1")?;
1152 assert!(stmt.exists([1i32])?);
1153 assert!(stmt.exists([2i32])?);
1154 assert!(!stmt.exists([0i32])?);
1155 Ok(())
1156 }
1157 #[test]
1158 fn test_tuple_params() -> Result<()> {
1159 let db = Connection::open_in_memory()?;
1160 let s = db.query_row("SELECT printf('[%s]', ?1)", ("abc",), |r| {
1161 r.get::<_, String>(0)
1162 })?;
1163 assert_eq!(s, "[abc]");
1164 let s = db.query_row(
1165 "SELECT printf('%d %s %d', ?1, ?2, ?3)",
1166 (1i32, "abc", 2i32),
1167 |r| r.get::<_, String>(0),
1168 )?;
1169 assert_eq!(s, "1 abc 2");
1170 let s = db.query_row(
1171 "SELECT printf('%d %s %d %d', ?1, ?2, ?3, ?4)",
1172 (1, "abc", 2i32, 4i64),
1173 |r| r.get::<_, String>(0),
1174 )?;
1175 assert_eq!(s, "1 abc 2 4");
1176 #[rustfmt::skip]
1177 let bigtup = (
1178 0, "a", 1, "b", 2, "c", 3, "d",
1179 4, "e", 5, "f", 6, "g", 7, "h",
1180 );
1181 let query = "SELECT printf(
1182 '%d %s | %d %s | %d %s | %d %s || %d %s | %d %s | %d %s | %d %s',
1183 ?1, ?2, ?3, ?4,
1184 ?5, ?6, ?7, ?8,
1185 ?9, ?10, ?11, ?12,
1186 ?13, ?14, ?15, ?16
1187 )";
1188 let s = db.query_row(query, bigtup, |r| r.get::<_, String>(0))?;
1189 assert_eq!(s, "0 a | 1 b | 2 c | 3 d || 4 e | 5 f | 6 g | 7 h");
1190 Ok(())
1191 }
1192
1193 #[test]
1194 fn test_query_row() -> Result<()> {
1195 let db = Connection::open_in_memory()?;
1196 let sql = "BEGIN;
1197 CREATE TABLE foo(x INTEGER, y INTEGER);
1198 INSERT INTO foo VALUES(1, 3);
1199 INSERT INTO foo VALUES(2, 4);
1200 END;";
1201 db.execute_batch(sql)?;
1202 let mut stmt = db.prepare("SELECT y FROM foo WHERE x = ?1")?;
1203 let y: Result<i64> = stmt.query_row([1i32], |r| r.get(0));
1204 assert_eq!(3i64, y?);
1205 Ok(())
1206 }
1207
1208 #[test]
1209 fn query_one() -> Result<()> {
1210 let db = Connection::open_in_memory()?;
1211 db.execute_batch("CREATE TABLE foo(x INTEGER, y INTEGER);")?;
1212 let mut stmt = db.prepare("SELECT y FROM foo WHERE x = ?1")?;
1213 let y: Result<i64> = stmt.query_one([1i32], |r| r.get(0));
1214 assert_eq!(Error::QueryReturnedNoRows, y.unwrap_err());
1215 db.execute_batch("INSERT INTO foo VALUES(1, 3);")?;
1216 let y: Result<i64> = stmt.query_one([1i32], |r| r.get(0));
1217 assert_eq!(3i64, y?);
1218 db.execute_batch("INSERT INTO foo VALUES(1, 3);")?;
1219 let y: Result<i64> = stmt.query_one([1i32], |r| r.get(0));
1220 assert_eq!(Error::QueryReturnedMoreThanOneRow, y.unwrap_err());
1221 Ok(())
1222 }
1223
1224 #[test]
1225 fn test_query_by_column_name() -> Result<()> {
1226 let db = Connection::open_in_memory()?;
1227 let sql = "BEGIN;
1228 CREATE TABLE foo(x INTEGER, y INTEGER);
1229 INSERT INTO foo VALUES(1, 3);
1230 END;";
1231 db.execute_batch(sql)?;
1232 let mut stmt = db.prepare("SELECT y FROM foo")?;
1233 let y: Result<i64> = stmt.query_row([], |r| r.get("y"));
1234 assert_eq!(3i64, y?);
1235 Ok(())
1236 }
1237
1238 #[test]
1239 fn test_query_by_column_name_ignore_case() -> Result<()> {
1240 let db = Connection::open_in_memory()?;
1241 let sql = "BEGIN;
1242 CREATE TABLE foo(x INTEGER, y INTEGER);
1243 INSERT INTO foo VALUES(1, 3);
1244 END;";
1245 db.execute_batch(sql)?;
1246 let mut stmt = db.prepare("SELECT y as Y FROM foo")?;
1247 let y: Result<i64> = stmt.query_row([], |r| r.get("y"));
1248 assert_eq!(3i64, y?);
1249 Ok(())
1250 }
1251
1252 #[test]
1253 fn test_expanded_sql() -> Result<()> {
1254 let db = Connection::open_in_memory()?;
1255 let stmt = db.prepare("SELECT ?1")?;
1256 stmt.bind_parameter(&1, 1)?;
1257 assert_eq!(Some("SELECT 1".to_owned()), stmt.expanded_sql());
1258 Ok(())
1259 }
1260
1261 #[test]
1262 fn test_bind_parameters() -> Result<()> {
1263 let db = Connection::open_in_memory()?;
1264 // dynamic slice:
1265 db.query_row(
1266 "SELECT ?1, ?2, ?3",
1267 [&1u8 as &dyn ToSql, &"one", &Some("one")],
1268 |row| row.get::<_, u8>(0),
1269 )?;
1270 // existing collection:
1271 let data = vec![1, 2, 3];
1272 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(&data), |row| {
1273 row.get::<_, u8>(0)
1274 })?;
1275 db.query_row(
1276 "SELECT ?1, ?2, ?3",
1277 params_from_iter(data.as_slice()),
1278 |row| row.get::<_, u8>(0),
1279 )?;
1280 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(data), |row| {
1281 row.get::<_, u8>(0)
1282 })?;
1283
1284 use std::collections::BTreeSet;
1285 let data: BTreeSet<String> = ["one", "two", "three"]
1286 .iter()
1287 .map(|s| (*s).to_string())
1288 .collect();
1289 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(&data), |row| {
1290 row.get::<_, String>(0)
1291 })?;
1292
1293 let data = [0; 3];
1294 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(&data), |row| {
1295 row.get::<_, u8>(0)
1296 })?;
1297 db.query_row("SELECT ?1, ?2, ?3", params_from_iter(data.iter()), |row| {
1298 row.get::<_, u8>(0)
1299 })?;
1300 Ok(())
1301 }
1302
1303 #[test]
1304 fn test_parameter_name() -> Result<()> {
1305 let db = Connection::open_in_memory()?;
1306 db.execute_batch("CREATE TABLE test (name TEXT, value INTEGER)")?;
1307 let stmt = db.prepare("INSERT INTO test (name, value) VALUES (:name, ?3)")?;
1308 assert_eq!(stmt.parameter_name(0), None);
1309 assert_eq!(stmt.parameter_name(1), Some(":name"));
1310 assert_eq!(stmt.parameter_name(2), None);
1311 Ok(())
1312 }
1313
1314 #[test]
1315 fn test_empty_stmt() -> Result<()> {
1316 let conn = Connection::open_in_memory()?;
1317 let mut stmt = conn.prepare("")?;
1318 assert_eq!(0, stmt.column_count());
1319 stmt.parameter_index("test")?;
1320 let err = stmt.step().unwrap_err();
1321 assert_eq!(err.sqlite_error_code(), Some(crate::ErrorCode::ApiMisuse));
1322 // error msg is different with sqlcipher, so we use assert_ne:
1323 assert_ne!(err.to_string(), "not an error".to_owned());
1324 stmt.reset()?; // SQLITE_OMIT_AUTORESET = false
1325 stmt.execute([]).unwrap_err();
1326 Ok(())
1327 }
1328
1329 #[test]
1330 fn test_comment_stmt() -> Result<()> {
1331 let conn = Connection::open_in_memory()?;
1332 conn.prepare("/*SELECT 1;*/")?;
1333 Ok(())
1334 }
1335
1336 #[test]
1337 fn test_comment_and_sql_stmt() -> Result<()> {
1338 let conn = Connection::open_in_memory()?;
1339 let stmt = conn.prepare("/*...*/ SELECT 1;")?;
1340 assert_eq!(1, stmt.column_count());
1341 Ok(())
1342 }
1343
1344 #[test]
1345 fn test_semi_colon_stmt() -> Result<()> {
1346 let conn = Connection::open_in_memory()?;
1347 let stmt = conn.prepare(";")?;
1348 assert_eq!(0, stmt.column_count());
1349 Ok(())
1350 }
1351
1352 #[test]
1353 fn test_utf16_conversion() -> Result<()> {
1354 let db = Connection::open_in_memory()?;
1355 db.pragma_update(None, "encoding", "UTF-16le")?;
1356 let encoding: String = db.pragma_query_value(None, "encoding", |row| row.get(0))?;
1357 assert_eq!("UTF-16le", encoding);
1358 db.execute_batch("CREATE TABLE foo(x TEXT)")?;
1359 let expected = "ใในใ";
1360 db.execute("INSERT INTO foo(x) VALUES (?1)", [&expected])?;
1361 let actual: String = db.one_column("SELECT x FROM foo", [])?;
1362 assert_eq!(expected, actual);
1363 Ok(())
1364 }
1365
1366 #[test]
1367 fn test_nul_byte() -> Result<()> {
1368 let db = Connection::open_in_memory()?;
1369 let expected = "a\x00b";
1370 let actual: String = db.one_column("SELECT ?1", [expected])?;
1371 assert_eq!(expected, actual);
1372 Ok(())
1373 }
1374
1375 #[test]
1376 fn is_explain() -> Result<()> {
1377 let db = Connection::open_in_memory()?;
1378 let stmt = db.prepare("SELECT 1;")?;
1379 assert_eq!(0, stmt.is_explain());
1380 Ok(())
1381 }
1382
1383 #[test]
1384 fn readonly() -> Result<()> {
1385 let db = Connection::open_in_memory()?;
1386 let stmt = db.prepare("SELECT 1;")?;
1387 assert!(stmt.readonly());
1388 Ok(())
1389 }
1390
1391 #[test]
1392 #[cfg(feature = "modern_sqlite")] // SQLite >= 3.38.0
1393 fn test_error_offset() -> Result<()> {
1394 use crate::ffi::ErrorCode;
1395 let db = Connection::open_in_memory()?;
1396 let r = db.execute_batch("SELECT INVALID_FUNCTION;");
1397 match r.unwrap_err() {
1398 Error::SqlInputError { error, offset, .. } => {
1399 assert_eq!(error.code, ErrorCode::Unknown);
1400 assert_eq!(offset, 7);
1401 }
1402 err => panic!("Unexpected error {err}"),
1403 }
1404 Ok(())
1405 }
1406}