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