1 use crate::{Result, Statement, ToSql};
2
3 mod sealed {
4 /// This trait exists just to ensure that the only impls of `trait Params`
5 /// that are allowed are ones in this crate.
6 pub trait Sealed {}
7 }
8 use sealed::Sealed;
9
10 /// Trait used for [sets of parameter][params] passed into SQL
11 /// statements/queries.
12 ///
13 /// [params]: https://www.sqlite.org/c3ref/bind_blob.html
14 ///
15 /// Note: Currently, this trait can only be implemented inside this crate.
16 /// Additionally, it's methods (which are `doc(hidden)`) should currently not be
17 /// considered part of the stable API, although it's possible they will
18 /// stabilize in the future.
19 ///
20 /// # Passing parameters to SQLite
21 ///
22 /// Many functions in this library let you pass parameters to SQLite. Doing this
23 /// lets you avoid any risk of SQL injection, and is simpler than escaping
24 /// things manually. Aside from deprecated functions and a few helpers, this is
25 /// indicated by the function taking a generic argument that implements `Params`
26 /// (this trait).
27 ///
28 /// ## Positional parameters
29 ///
30 /// For cases where you want to pass a list of parameters where the number of
31 /// parameters is known at compile time, this can be done in one of the
32 /// following ways:
33 ///
34 /// - For small lists of parameters up to 16 items, they may alternatively be
35 /// passed as a tuple, as in `thing.query((1, "foo"))`.
36 ///
37 /// This is somewhat inconvenient for a single item, since you need a
38 /// weird-looking trailing comma: `thing.query(("example",))`. That case is
39 /// perhaps more cleanly expressed as `thing.query(["example"])`.
40 ///
41 /// - Using the [`rusqlite::params!`](crate::params!) macro, e.g.
42 /// `thing.query(rusqlite::params![1, "foo", bar])`. This is mostly useful for
43 /// heterogeneous lists where the number of parameters greater than 16, or
44 /// homogenous lists of parameters where the number of parameters exceeds 32.
45 ///
46 /// - For small homogeneous lists of parameters, they can either be passed as:
47 ///
48 /// - an array, as in `thing.query([1i32, 2, 3, 4])` or `thing.query(["foo",
49 /// "bar", "baz"])`.
50 ///
51 /// - a reference to an array of references, as in `thing.query(&["foo",
52 /// "bar", "baz"])` or `thing.query(&[&1i32, &2, &3])`.
53 ///
54 /// (Note: in this case we don't implement this for slices for coherence
55 /// reasons, so it really is only for the "reference to array" types —
56 /// hence why the number of parameters must be <= 32 or you need to
57 /// reach for `rusqlite::params!`)
58 ///
59 /// Unfortunately, in the current design it's not possible to allow this for
60 /// references to arrays of non-references (e.g. `&[1i32, 2, 3]`). Code like
61 /// this should instead either use `params!`, an array literal, a `&[&dyn
62 /// ToSql]` or if none of those work, [`ParamsFromIter`].
63 ///
64 /// - As a slice of `ToSql` trait object references, e.g. `&[&dyn ToSql]`. This
65 /// is mostly useful for passing parameter lists around as arguments without
66 /// having every function take a generic `P: Params`.
67 ///
68 /// ### Example (positional)
69 ///
70 /// ```rust,no_run
71 /// # use rusqlite::{Connection, Result, params};
72 /// fn update_rows(conn: &Connection) -> Result<()> {
73 /// let mut stmt = conn.prepare("INSERT INTO test (a, b) VALUES (?, ?)")?;
74 ///
75 /// // Using a tuple:
76 /// stmt.execute((0, "foobar"))?;
77 ///
78 /// // Using `rusqlite::params!`:
79 /// stmt.execute(params![1i32, "blah"])?;
80 ///
81 /// // array literal — non-references
82 /// stmt.execute([2i32, 3i32])?;
83 ///
84 /// // array literal — references
85 /// stmt.execute(["foo", "bar"])?;
86 ///
87 /// // Slice literal, references:
88 /// stmt.execute(&[&2i32, &3i32])?;
89 ///
90 /// // Note: The types behind the references don't have to be `Sized`
91 /// stmt.execute(&["foo", "bar"])?;
92 ///
93 /// // However, this doesn't work (see above):
94 /// // stmt.execute(&[1i32, 2i32])?;
95 /// Ok(())
96 /// }
97 /// ```
98 ///
99 /// ## Named parameters
100 ///
101 /// SQLite lets you name parameters using a number of conventions (":foo",
102 /// "@foo", "$foo"). You can pass named parameters in to SQLite using rusqlite
103 /// in a few ways:
104 ///
105 /// - Using the [`rusqlite::named_params!`](crate::named_params!) macro, as in
106 /// `stmt.execute(named_params!{ ":name": "foo", ":age": 99 })`. Similar to
107 /// the `params` macro, this is most useful for heterogeneous lists of
108 /// parameters, or lists where the number of parameters exceeds 32.
109 ///
110 /// - As a slice of `&[(&str, &dyn ToSql)]`. This is what essentially all of
111 /// these boil down to in the end, conceptually at least. In theory you can
112 /// pass this as `stmt`.
113 ///
114 /// - As array references, similar to the positional params. This looks like
115 /// `thing.query(&[(":foo", &1i32), (":bar", &2i32)])` or
116 /// `thing.query(&[(":foo", "abc"), (":bar", "def")])`.
117 ///
118 /// Note: Unbound named parameters will be left to the value they previously
119 /// were bound with, falling back to `NULL` for parameters which have never been
120 /// bound.
121 ///
122 /// ### Example (named)
123 ///
124 /// ```rust,no_run
125 /// # use rusqlite::{Connection, Result, named_params};
126 /// fn insert(conn: &Connection) -> Result<()> {
127 /// let mut stmt = conn.prepare("INSERT INTO test (key, value) VALUES (:key, :value)")?;
128 /// // Using `rusqlite::params!`:
129 /// stmt.execute(named_params! { ":key": "one", ":val": 2 })?;
130 /// // Alternatively:
131 /// stmt.execute(&[(":key", "three"), (":val", "four")])?;
132 /// // Or:
133 /// stmt.execute(&[(":key", &100), (":val", &200)])?;
134 /// Ok(())
135 /// }
136 /// ```
137 ///
138 /// ## No parameters
139 ///
140 /// You can just use an empty tuple or the empty array literal to run a query
141 /// that accepts no parameters. (The `rusqlite::NO_PARAMS` constant which was
142 /// common in previous versions of this library is no longer needed, and is now
143 /// deprecated).
144 ///
145 /// ### Example (no parameters)
146 ///
147 /// The empty tuple:
148 ///
149 /// ```rust,no_run
150 /// # use rusqlite::{Connection, Result, params};
151 /// fn delete_all_users(conn: &Connection) -> Result<()> {
152 /// // You may also use `()`.
153 /// conn.execute("DELETE FROM users", ())?;
154 /// Ok(())
155 /// }
156 /// ```
157 ///
158 /// The empty array:
159 ///
160 /// ```rust,no_run
161 /// # use rusqlite::{Connection, Result, params};
162 /// fn delete_all_users(conn: &Connection) -> Result<()> {
163 /// // Just use an empty array (e.g. `[]`) for no params.
164 /// conn.execute("DELETE FROM users", [])?;
165 /// Ok(())
166 /// }
167 /// ```
168 ///
169 /// ## Dynamic parameter list
170 ///
171 /// If you have a number of parameters which is unknown at compile time (for
172 /// example, building a dynamic query at runtime), you have two choices:
173 ///
174 /// - Use a `&[&dyn ToSql]`. This is often annoying to construct if you don't
175 /// already have this type on-hand.
176 /// - Use the [`ParamsFromIter`] type. This essentially lets you wrap an
177 /// iterator some `T: ToSql` with something that implements `Params`. The
178 /// usage of this looks like `rusqlite::params_from_iter(something)`.
179 ///
180 /// A lot of the considerations here are similar either way, so you should see
181 /// the [`ParamsFromIter`] documentation for more info / examples.
182 pub trait Params: Sealed {
183 // XXX not public api, might not need to expose.
184 //
185 // Binds the parameters to the statement. It is unlikely calling this
186 // explicitly will do what you want. Please use `Statement::query` or
187 // similar directly.
188 //
189 // For now, just hide the function in the docs...
190 #[doc(hidden)]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>191 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()>;
192 }
193
194 // Explicitly impl for empty array. Critically, for `conn.execute([])` to be
195 // unambiguous, this must be the *only* implementation for an empty array. This
196 // avoids `NO_PARAMS` being a necessary part of the API.
197 //
198 // This sadly prevents `impl<T: ToSql, const N: usize> Params for [T; N]`, which
199 // forces people to use `params![...]` or `rusqlite::params_from_iter` for long
200 // homogenous lists of parameters. This is not that big of a deal, but is
201 // unfortunate, especially because I mostly did it because I wanted a simple
202 // syntax for no-params that didnt require importing -- the empty tuple fits
203 // that nicely, but I didn't think of it until much later.
204 //
205 // Admittedly, if we did have the generic impl, then we *wouldn't* support the
206 // empty array literal as a parameter, since the `T` there would fail to be
207 // inferred. The error message here would probably be quite bad, and so on
208 // further thought, probably would end up causing *more* surprises, not less.
209 impl Sealed for [&(dyn ToSql + Send + Sync); 0] {}
210 impl Params for [&(dyn ToSql + Send + Sync); 0] {
211 #[inline]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>212 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
213 stmt.ensure_parameter_count(0)
214 }
215 }
216
217 impl Sealed for &[&dyn ToSql] {}
218 impl Params for &[&dyn ToSql] {
219 #[inline]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>220 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
221 stmt.bind_parameters(self)
222 }
223 }
224
225 impl Sealed for &[(&str, &dyn ToSql)] {}
226 impl Params for &[(&str, &dyn ToSql)] {
227 #[inline]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>228 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
229 stmt.bind_parameters_named(self)
230 }
231 }
232
233 // Manual impls for the empty and singleton tuple, although the rest are covered
234 // by macros.
235 impl Sealed for () {}
236 impl Params for () {
237 #[inline]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>238 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
239 stmt.ensure_parameter_count(0)
240 }
241 }
242
243 // I'm pretty sure you could tweak the `single_tuple_impl` to accept this.
244 impl<T: ToSql> Sealed for (T,) {}
245 impl<T: ToSql> Params for (T,) {
246 #[inline]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>247 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
248 stmt.ensure_parameter_count(1)?;
249 stmt.raw_bind_parameter(1, self.0)?;
250 Ok(())
251 }
252 }
253
254 macro_rules! single_tuple_impl {
255 ($count:literal : $(($field:tt $ftype:ident)),* $(,)?) => {
256 impl<$($ftype,)*> Sealed for ($($ftype,)*) where $($ftype: ToSql,)* {}
257 impl<$($ftype,)*> Params for ($($ftype,)*) where $($ftype: ToSql,)* {
258 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
259 stmt.ensure_parameter_count($count)?;
260 $({
261 debug_assert!($field < $count);
262 stmt.raw_bind_parameter($field + 1, self.$field)?;
263 })+
264 Ok(())
265 }
266 }
267 }
268 }
269
270 // We use a the macro for the rest, but don't bother with trying to implement it
271 // in a single invocation (it's possible to do, but my attempts were almost the
272 // same amount of code as just writing it out this way, and much more dense --
273 // it is a more complicated case than the TryFrom macro we have for row->tuple).
274 //
275 // Note that going up to 16 (rather than the 12 that the impls in the stdlib
276 // usually support) is just because we did the same in the `TryFrom<Row>` impl.
277 // I didn't catch that then, but there's no reason to remove it, and it seems
278 // nice to be consistent here; this way putting data in the database and getting
279 // data out of the database are more symmetric in a (mostly superficial) sense.
280 single_tuple_impl!(2: (0 A), (1 B));
281 single_tuple_impl!(3: (0 A), (1 B), (2 C));
282 single_tuple_impl!(4: (0 A), (1 B), (2 C), (3 D));
283 single_tuple_impl!(5: (0 A), (1 B), (2 C), (3 D), (4 E));
284 single_tuple_impl!(6: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F));
285 single_tuple_impl!(7: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G));
286 single_tuple_impl!(8: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H));
287 single_tuple_impl!(9: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I));
288 single_tuple_impl!(10: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J));
289 single_tuple_impl!(11: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J), (10 K));
290 single_tuple_impl!(12: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J), (10 K), (11 L));
291 single_tuple_impl!(13: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J), (10 K), (11 L), (12 M));
292 single_tuple_impl!(14: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J), (10 K), (11 L), (12 M), (13 N));
293 single_tuple_impl!(15: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J), (10 K), (11 L), (12 M), (13 N), (14 O));
294 single_tuple_impl!(16: (0 A), (1 B), (2 C), (3 D), (4 E), (5 F), (6 G), (7 H), (8 I), (9 J), (10 K), (11 L), (12 M), (13 N), (14 O), (15 P));
295
296 macro_rules! impl_for_array_ref {
297 ($($N:literal)+) => {$(
298 // These are already generic, and there's a shedload of them, so lets
299 // avoid the compile time hit from making them all inline for now.
300 impl<T: ToSql + ?Sized> Sealed for &[&T; $N] {}
301 impl<T: ToSql + ?Sized> Params for &[&T; $N] {
302 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
303 stmt.bind_parameters(self)
304 }
305 }
306 impl<T: ToSql + ?Sized> Sealed for &[(&str, &T); $N] {}
307 impl<T: ToSql + ?Sized> Params for &[(&str, &T); $N] {
308 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
309 stmt.bind_parameters_named(self)
310 }
311 }
312 impl<T: ToSql> Sealed for [T; $N] {}
313 impl<T: ToSql> Params for [T; $N] {
314 #[inline]
315 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
316 stmt.bind_parameters(&self)
317 }
318 }
319 )+};
320 }
321
322 // Following libstd/libcore's (old) lead, implement this for arrays up to `[_;
323 // 32]`. Note `[_; 0]` is intentionally omitted for coherence reasons, see the
324 // note above the impl of `[&dyn ToSql; 0]` for more information.
325 //
326 // Note that this unfortunately means we can't use const generics here, but I
327 // don't really think it matters -- users who hit that can use `params!` anyway.
328 impl_for_array_ref!(
329 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
330 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
331 );
332
333 /// Adapter type which allows any iterator over [`ToSql`] values to implement
334 /// [`Params`].
335 ///
336 /// This struct is created by the [`params_from_iter`] function.
337 ///
338 /// This can be useful if you have something like an `&[String]` (of unknown
339 /// length), and you want to use them with an API that wants something
340 /// implementing `Params`. This way, you can avoid having to allocate storage
341 /// for something like a `&[&dyn ToSql]`.
342 ///
343 /// This essentially is only ever actually needed when dynamically generating
344 /// SQL — static SQL (by definition) has the number of parameters known
345 /// statically. As dynamically generating SQL is itself pretty advanced, this
346 /// API is itself for advanced use cases (See "Realistic use case" in the
347 /// examples).
348 ///
349 /// # Example
350 ///
351 /// ## Basic usage
352 ///
353 /// ```rust,no_run
354 /// use rusqlite::{params_from_iter, Connection, Result};
355 /// use std::collections::BTreeSet;
356 ///
357 /// fn query(conn: &Connection, ids: &BTreeSet<String>) -> Result<()> {
358 /// assert_eq!(ids.len(), 3, "Unrealistic sample code");
359 ///
360 /// let mut stmt = conn.prepare("SELECT * FROM users WHERE id IN (?, ?, ?)")?;
361 /// let _rows = stmt.query(params_from_iter(ids.iter()))?;
362 ///
363 /// // use _rows...
364 /// Ok(())
365 /// }
366 /// ```
367 ///
368 /// ## Realistic use case
369 ///
370 /// Here's how you'd use `ParamsFromIter` to call [`Statement::exists`] with a
371 /// dynamic number of parameters.
372 ///
373 /// ```rust,no_run
374 /// use rusqlite::{Connection, Result};
375 ///
376 /// pub fn any_active_users(conn: &Connection, usernames: &[String]) -> Result<bool> {
377 /// if usernames.is_empty() {
378 /// return Ok(false);
379 /// }
380 ///
381 /// // Note: `repeat_vars` never returns anything attacker-controlled, so
382 /// // it's fine to use it in a dynamically-built SQL string.
383 /// let vars = repeat_vars(usernames.len());
384 ///
385 /// let sql = format!(
386 /// // In practice this would probably be better as an `EXISTS` query.
387 /// "SELECT 1 FROM user WHERE is_active AND name IN ({}) LIMIT 1",
388 /// vars,
389 /// );
390 /// let mut stmt = conn.prepare(&sql)?;
391 /// stmt.exists(rusqlite::params_from_iter(usernames))
392 /// }
393 ///
394 /// // Helper function to return a comma-separated sequence of `?`.
395 /// // - `repeat_vars(0) => panic!(...)`
396 /// // - `repeat_vars(1) => "?"`
397 /// // - `repeat_vars(2) => "?,?"`
398 /// // - `repeat_vars(3) => "?,?,?"`
399 /// // - ...
400 /// fn repeat_vars(count: usize) -> String {
401 /// assert_ne!(count, 0);
402 /// let mut s = "?,".repeat(count);
403 /// // Remove trailing comma
404 /// s.pop();
405 /// s
406 /// }
407 /// ```
408 ///
409 /// That is fairly complex, and even so would need even more work to be fully
410 /// production-ready:
411 ///
412 /// - production code should ensure `usernames` isn't so large that it will
413 /// surpass [`conn.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER)`][limits]),
414 /// chunking if too large. (Note that the limits api requires rusqlite to have
415 /// the "limits" feature).
416 ///
417 /// - `repeat_vars` can be implemented in a way that avoids needing to allocate
418 /// a String.
419 ///
420 /// - Etc...
421 ///
422 /// [limits]: crate::Connection::limit
423 ///
424 /// This complexity reflects the fact that `ParamsFromIter` is mainly intended
425 /// for advanced use cases — most of the time you should know how many
426 /// parameters you have statically (and if you don't, you're either doing
427 /// something tricky, or should take a moment to think about the design).
428 #[derive(Clone, Debug)]
429 pub struct ParamsFromIter<I>(I);
430
431 /// Constructor function for a [`ParamsFromIter`]. See its documentation for
432 /// more.
433 #[inline]
params_from_iter<I>(iter: I) -> ParamsFromIter<I> where I: IntoIterator, I::Item: ToSql,434 pub fn params_from_iter<I>(iter: I) -> ParamsFromIter<I>
435 where
436 I: IntoIterator,
437 I::Item: ToSql,
438 {
439 ParamsFromIter(iter)
440 }
441
442 impl<I> Sealed for ParamsFromIter<I>
443 where
444 I: IntoIterator,
445 I::Item: ToSql,
446 {
447 }
448
449 impl<I> Params for ParamsFromIter<I>
450 where
451 I: IntoIterator,
452 I::Item: ToSql,
453 {
454 #[inline]
__bind_in(self, stmt: &mut Statement<'_>) -> Result<()>455 fn __bind_in(self, stmt: &mut Statement<'_>) -> Result<()> {
456 stmt.bind_parameters(self.0)
457 }
458 }
459