sqlx_core/
arguments.rs

1//! Types and traits for passing arguments to SQL queries.
2
3use crate::database::Database;
4use crate::encode::Encode;
5use crate::error::BoxDynError;
6use crate::types::Type;
7use std::fmt::{self, Write};
8
9/// A tuple of arguments to be sent to the database.
10// This lint is designed for general collections, but `Arguments` is not meant to be as such.
11#[allow(clippy::len_without_is_empty)]
12pub trait Arguments<'q>: Send + Sized + Default {
13    type Database: Database;
14
15    /// Reserves the capacity for at least `additional` more values (of `size` total bytes) to
16    /// be added to the arguments without a reallocation.
17    fn reserve(&mut self, additional: usize, size: usize);
18
19    /// Add the value to the end of the arguments.
20    fn add<T>(&mut self, value: T) -> Result<(), BoxDynError>
21    where
22        T: 'q + Encode<'q, Self::Database> + Type<Self::Database>;
23
24    /// The number of arguments that were already added.
25    fn len(&self) -> usize;
26
27    fn format_placeholder<W: Write>(&self, writer: &mut W) -> fmt::Result {
28        writer.write_str("?")
29    }
30}
31
32pub trait IntoArguments<'q, DB: Database>: Sized + Send {
33    fn into_arguments(self) -> <DB as Database>::Arguments<'q>;
34}
35
36// NOTE: required due to lack of lazy normalization
37#[macro_export]
38macro_rules! impl_into_arguments_for_arguments {
39    ($Arguments:path) => {
40        impl<'q>
41            $crate::arguments::IntoArguments<
42                'q,
43                <$Arguments as $crate::arguments::Arguments<'q>>::Database,
44            > for $Arguments
45        {
46            fn into_arguments(self) -> $Arguments {
47                self
48            }
49        }
50    };
51}
52
53/// used by the query macros to prevent supernumerary `.bind()` calls
54pub struct ImmutableArguments<'q, DB: Database>(pub <DB as Database>::Arguments<'q>);
55
56impl<'q, DB: Database> IntoArguments<'q, DB> for ImmutableArguments<'q, DB> {
57    fn into_arguments(self) -> <DB as Database>::Arguments<'q> {
58        self.0
59    }
60}
61
62// TODO: Impl `IntoArguments` for &[&dyn Encode]
63// TODO: Impl `IntoArguments` for (impl Encode, ...) x16