diesel/query_builder/
bind_collector.rs

1//! Types related to managing bind parameters during query construction.
2
3use crate::backend::Backend;
4use crate::result::Error::SerializationError;
5use crate::result::QueryResult;
6use crate::serialize::{IsNull, Output, ToSql};
7use crate::sql_types::{HasSqlType, TypeMetadata};
8
9#[doc(inline)]
10#[diesel_derives::__diesel_public_if(
11    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
12)]
13pub(crate) use self::private::ByteWrapper;
14
15/// A type which manages serializing bind parameters during query construction.
16///
17/// The only reason you would ever need to interact with this trait is if you
18/// are adding support for a new backend to Diesel. Plugins which are extending
19/// the query builder will use [`AstPass::push_bind_param`] instead.
20///
21/// [`AstPass::push_bind_param`]: crate::query_builder::AstPass::push_bind_param()
22pub trait BindCollector<'a, DB: TypeMetadata>: Sized {
23    /// The internal buffer type used by this bind collector
24    type Buffer;
25
26    /// Serializes the given bind value, and collects the result.
27    fn push_bound_value<T, U>(
28        &mut self,
29        bind: &'a U,
30        metadata_lookup: &mut DB::MetadataLookup,
31    ) -> QueryResult<()>
32    where
33        DB: Backend + HasSqlType<T>,
34        U: ToSql<T, DB> + ?Sized + 'a;
35
36    /// Push a null value with the given type information onto the bind collector
37    // For backward compatibility reasons we provide a default implementation
38    // but custom backends that want to support `#[derive(MultiConnection)]`
39    // need to provide a customized implementation of this function
40    #[diesel_derives::__diesel_public_if(
41        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
42    )]
43    fn push_null_value(&mut self, _metadata: DB::TypeMetadata) -> QueryResult<()> {
44        Ok(())
45    }
46}
47
48/// A movable version of the bind collector which allows it to be extracted, moved and refilled.
49///
50/// This is mostly useful in async context where bind data needs to be moved across threads.
51#[diesel_derives::__diesel_public_if(
52    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
53)]
54pub trait MoveableBindCollector<DB: TypeMetadata> {
55    /// The movable bind data of this bind collector
56    type BindData: Send + 'static;
57
58    /// Builds a movable version of the bind collector
59    fn moveable(&self) -> Self::BindData;
60
61    /// Refill the bind collector with its bind data
62    fn append_bind_data(&mut self, from: &Self::BindData);
63}
64
65#[derive(Debug)]
66/// A bind collector used by backends which transmit bind parameters as an
67/// opaque blob of bytes.
68///
69/// For most backends, this is the concrete implementation of `BindCollector`
70/// that should be used.
71#[diesel_derives::__diesel_public_if(
72    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes",
73    public_fields(metadata, binds)
74)]
75pub struct RawBytesBindCollector<DB: Backend + TypeMetadata> {
76    /// The metadata associated with each bind parameter.
77    ///
78    /// This vec is guaranteed to be the same length as `binds`.
79    pub(crate) metadata: Vec<DB::TypeMetadata>,
80    /// The serialized bytes for each bind parameter.
81    ///
82    /// This vec is guaranteed to be the same length as `metadata`.
83    pub(crate) binds: Vec<Option<Vec<u8>>>,
84}
85
86impl<DB: Backend + TypeMetadata> Default for RawBytesBindCollector<DB> {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92#[allow(clippy::new_without_default)]
93impl<DB: Backend + TypeMetadata> RawBytesBindCollector<DB> {
94    /// Construct an empty `RawBytesBindCollector`
95    pub fn new() -> Self {
96        RawBytesBindCollector {
97            metadata: Vec::new(),
98            binds: Vec::new(),
99        }
100    }
101
102    pub(crate) fn reborrow_buffer<'a: 'b, 'b>(b: &'b mut ByteWrapper<'a>) -> ByteWrapper<'b> {
103        ByteWrapper(b.0)
104    }
105}
106
107impl<'a, DB> BindCollector<'a, DB> for RawBytesBindCollector<DB>
108where
109    for<'b> DB: Backend<BindCollector<'b> = Self> + TypeMetadata,
110{
111    type Buffer = ByteWrapper<'a>;
112
113    fn push_bound_value<T, U>(
114        &mut self,
115        bind: &U,
116        metadata_lookup: &mut DB::MetadataLookup,
117    ) -> QueryResult<()>
118    where
119        DB: HasSqlType<T>,
120        U: ToSql<T, DB> + ?Sized,
121    {
122        let mut bytes = Vec::new();
123        let is_null = {
124            let mut to_sql_output = Output::new(ByteWrapper(&mut bytes), metadata_lookup);
125            bind.to_sql(&mut to_sql_output)
126                .map_err(SerializationError)?
127        };
128        let metadata = <DB as HasSqlType<T>>::metadata(metadata_lookup);
129        match is_null {
130            IsNull::No => self.binds.push(Some(bytes)),
131            IsNull::Yes => self.binds.push(None),
132        }
133        self.metadata.push(metadata);
134        Ok(())
135    }
136
137    fn push_null_value(&mut self, metadata: DB::TypeMetadata) -> QueryResult<()> {
138        self.metadata.push(metadata);
139        self.binds.push(None);
140        Ok(())
141    }
142}
143
144impl<DB> MoveableBindCollector<DB> for RawBytesBindCollector<DB>
145where
146    for<'a> DB: Backend<BindCollector<'a> = Self> + TypeMetadata + 'static,
147    <DB as TypeMetadata>::TypeMetadata: Clone + Send,
148{
149    type BindData = Self;
150
151    fn moveable(&self) -> Self::BindData {
152        RawBytesBindCollector {
153            binds: self.binds.clone(),
154            metadata: self.metadata.clone(),
155        }
156    }
157
158    fn append_bind_data(&mut self, from: &Self::BindData) {
159        self.binds.extend(from.binds.iter().cloned());
160        self.metadata.extend(from.metadata.clone());
161    }
162}
163
164// This is private for now as we may want to add `Into` impls for the wrapper type
165// later on
166mod private {
167    /// A type wrapper for raw bytes
168    #[derive(Debug)]
169    pub struct ByteWrapper<'a>(pub(crate) &'a mut Vec<u8>);
170}