Skip to main content

diesel/query_builder/update_statement/
changeset.rs

1use super::{SetClause, batch_update::*};
2use crate::associations::HasTable;
3use crate::backend::DieselReserveSpecialization;
4use crate::expression::AppearsOnTable;
5use crate::expression::grouped::Grouped;
6use crate::expression::operators::Eq;
7use crate::query_builder::*;
8use crate::query_source::{Column, QuerySource};
9use crate::{Identifiable, Table};
10use alloc::borrow::ToOwned;
11
12/// Types which can be passed to
13/// [`update.set`](UpdateStatement::set()).
14///
15/// This trait can be [derived](derive@AsChangeset)
16pub trait AsChangeset {
17    /// The table which `Self::Changeset` will be updating
18    type Target: QuerySource;
19
20    /// The update statement this type represents
21    type Changeset;
22
23    /// Return the associated Update type. Defaults to Single row Updates.
24    #[doc(hidden)]
25    const SET_CLAUSE: SetClause = SetClause::Immediate;
26
27    /// Convert `self` into the actual update statement being executed
28    // This method is part of our public API
29    // we won't change it to just appease clippy
30    #[allow(clippy::wrong_self_convention)]
31    fn as_changeset(self) -> Self::Changeset;
32}
33
34// This is a false positive, we reexport it later
35#[allow(unreachable_pub)]
36#[doc(inline)]
37pub use diesel_derives::AsChangeset;
38
39impl<T: AsChangeset> AsChangeset for Option<T> {
40    type Target = T::Target;
41    type Changeset = Option<T::Changeset>;
42
43    fn as_changeset(self) -> Self::Changeset {
44        self.map(AsChangeset::as_changeset)
45    }
46}
47
48impl<'update, T> AsChangeset for &'update Option<T>
49where
50    &'update T: AsChangeset,
51{
52    type Target = <&'update T as AsChangeset>::Target;
53    type Changeset = Option<<&'update T as AsChangeset>::Changeset>;
54
55    fn as_changeset(self) -> Self::Changeset {
56        self.as_ref().map(AsChangeset::as_changeset)
57    }
58}
59
60impl<Left, Right> AsChangeset for Eq<Left, Right>
61where
62    Left: AssignmentTarget,
63    Right: AppearsOnTable<Left::Table>,
64{
65    type Target = Left::Table;
66    type Changeset = Assign<<Left as AssignmentTarget>::QueryAstNode, Right>;
67
68    fn as_changeset(self) -> Self::Changeset {
69        Assign {
70            target: self.left.into_target(),
71            expr: self.right,
72        }
73    }
74}
75
76impl<Left, Right> AsChangeset for Grouped<Eq<Left, Right>>
77where
78    Eq<Left, Right>: AsChangeset,
79{
80    type Target = <Eq<Left, Right> as AsChangeset>::Target;
81
82    type Changeset = <Eq<Left, Right> as AsChangeset>::Changeset;
83
84    fn as_changeset(self) -> Self::Changeset {
85        self.0.as_changeset()
86    }
87}
88
89#[derive(#[automatically_derived]
impl<Target: ::core::fmt::Debug, Expr: ::core::fmt::Debug> ::core::fmt::Debug
    for Assign<Target, Expr> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Assign",
            "target", &self.target, "expr", &&self.expr)
    }
}Debug, #[automatically_derived]
impl<Target: ::core::clone::Clone, Expr: ::core::clone::Clone>
    ::core::clone::Clone for Assign<Target, Expr> {
    #[inline]
    fn clone(&self) -> Assign<Target, Expr> {
        Assign {
            target: ::core::clone::Clone::clone(&self.target),
            expr: ::core::clone::Clone::clone(&self.expr),
        }
    }
}Clone, #[automatically_derived]
impl<Target: ::core::marker::Copy, Expr: ::core::marker::Copy>
    ::core::marker::Copy for Assign<Target, Expr> {
}Copy, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl<Target: diesel::query_builder::QueryId,
            Expr: diesel::query_builder::QueryId>
            diesel::query_builder::QueryId for Assign<Target, Expr> {
            type QueryId =
                Assign<<Target as diesel::query_builder::QueryId>::QueryId,
                <Expr as diesel::query_builder::QueryId>::QueryId>;
            const HAS_STATIC_QUERY_ID: bool =
                <Target as
                            diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID &&
                        <Expr as
                            diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID &&
                    true;
            const IS_WINDOW_FUNCTION: bool =
                <Target as diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION
                        ||
                        <Expr as diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION
                    || false;
        }
    };QueryId)]
90pub struct Assign<Target, Expr> {
91    pub(crate) target: Target,
92    expr: Expr,
93}
94
95impl<T, U, DB> QueryFragment<DB> for Assign<T, U>
96where
97    DB: Backend,
98    T: QueryFragment<DB>,
99    U: QueryFragment<DB>,
100{
101    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
102        QueryFragment::walk_ast(&self.target, out.reborrow())?;
103        out.push_sql(" = ");
104        QueryFragment::walk_ast(&self.expr, out.reborrow())
105    }
106}
107
108/// Represents the left hand side of an assignment expression for an
109/// assignment in [AsChangeset]. The vast majority of the time, this will
110/// be a [Column]. However, in certain database backends, it's possible to
111/// assign to an expression. For example, in Postgres, it's possible to
112/// "UPDATE TABLE SET array_column\[1\] = 'foo'".
113pub trait AssignmentTarget {
114    /// Table the assignment is to
115    type Table: Table;
116    /// A wrapper around a type to assign to (this wrapper should implement
117    /// [QueryFragment]).
118    type QueryAstNode;
119
120    /// Move this in to the AST node which should implement [QueryFragment].
121    fn into_target(self) -> Self::QueryAstNode;
122}
123
124/// Represents a `Column` as an `AssignmentTarget`. The vast majority of
125/// targets in an update statement will be `Column`s.
126#[derive(#[automatically_derived]
impl<C: ::core::fmt::Debug> ::core::fmt::Debug for ColumnWrapperForUpdate<C> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "ColumnWrapperForUpdate", &&self.0)
    }
}Debug, #[automatically_derived]
impl<C: ::core::clone::Clone> ::core::clone::Clone for
    ColumnWrapperForUpdate<C> {
    #[inline]
    fn clone(&self) -> ColumnWrapperForUpdate<C> {
        ColumnWrapperForUpdate(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]
impl<C: ::core::marker::Copy> ::core::marker::Copy for
    ColumnWrapperForUpdate<C> {
}Copy)]
127pub struct ColumnWrapperForUpdate<C>(pub C);
128
129impl<DB, C> QueryFragment<DB> for ColumnWrapperForUpdate<C>
130where
131    DB: Backend + DieselReserveSpecialization,
132    C: Column,
133{
134    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
135        out.push_identifier(C::NAME)
136    }
137}
138
139impl<C> AssignmentTarget for C
140where
141    C: Column,
142{
143    type Table = C::Table;
144    type QueryAstNode = ColumnWrapperForUpdate<C>;
145
146    fn into_target(self) -> Self::QueryAstNode {
147        ColumnWrapperForUpdate(self)
148    }
149}
150
151#[cfg(any(
152    feature = "__sqlite-shared",
153    feature = "postgres_backend",
154    feature = "mysql_backend"
155))]
156impl<C, T, DB> BatchValueHelper<DB> for Assign<ColumnWrapperForUpdate<C>, T>
157where
158    DB: Backend + DieselReserveSpecialization,
159    C: Column + QueryFragment<DB>,
160    T: QueryFragment<DB>,
161    Self: BatchAssignHelper<DB>,
162{
163    fn assign<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
164        self.batch_assign_identifier(out.reborrow())?;
165        out.push_sql(" = ");
166        out.push_identifier(BATCH_UPDATE_ALIAS)?;
167        out.push_sql(".");
168        out.push_identifier(C::NAME)?;
169        Ok(())
170    }
171
172    fn column_name<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
173        self.target.walk_ast(out)
174    }
175
176    fn bind_value<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
177        self.expr.walk_ast(out)
178    }
179}
180
181impl<'a, U, I, C, PK> AsChangeset for &'a [U]
182where
183    U: AsChangeset + HasTable<Table = U::Target>,
184    U::Target: Table<PrimaryKey = PK>,
185    &'a U: AsChangeset<Target = U::Target, Changeset = C> + Identifiable<Table = U::Target, Id = I>,
186{
187    type Target = U::Target;
188    type Changeset = BatchUpdate<I, C, PK, U::Target>;
189    const SET_CLAUSE: SetClause = SetClause::Delegated;
190
191    fn as_changeset(self) -> Self::Changeset {
192        let values = self
193            .iter()
194            .map(|value| (Identifiable::id(value), AsChangeset::as_changeset(value)))
195            .collect::<Vec<_>>();
196        BatchUpdate::new(values, U::table().primary_key())
197    }
198}
199
200impl<'a, U> AsChangeset for &'a Vec<U>
201where
202    U: AsChangeset,
203    &'a [U]: AsChangeset,
204{
205    type Target = U::Target;
206    type Changeset = <&'a [U] as AsChangeset>::Changeset;
207    const SET_CLAUSE: SetClause = <&'a [U] as AsChangeset>::SET_CLAUSE;
208
209    fn as_changeset(self) -> Self::Changeset {
210        (&**self).as_changeset()
211    }
212}
213
214impl<'a, U, const N: usize> AsChangeset for &'a [U; N]
215where
216    &'a [U]: AsChangeset,
217{
218    type Target = <&'a [U] as AsChangeset>::Target;
219    type Changeset = <&'a [U] as AsChangeset>::Changeset;
220    const SET_CLAUSE: SetClause = <&'a [U] as AsChangeset>::SET_CLAUSE;
221
222    fn as_changeset(self) -> Self::Changeset {
223        self.as_slice().as_changeset()
224    }
225}
226
227impl<U> AsChangeset for Vec<U>
228where
229    Box<[U]>: AsChangeset,
230{
231    type Target = <Box<[U]> as AsChangeset>::Target;
232    type Changeset = <Box<[U]> as AsChangeset>::Changeset;
233    const SET_CLAUSE: SetClause = <Box<[U]> as AsChangeset>::SET_CLAUSE;
234
235    fn as_changeset(self) -> Self::Changeset {
236        self.into_boxed_slice().as_changeset()
237    }
238}
239
240impl<U, const N: usize> AsChangeset for Box<[U; N]>
241where
242    Box<[U]>: AsChangeset,
243{
244    type Target = <Box<[U]> as AsChangeset>::Target;
245    type Changeset = <Box<[U]> as AsChangeset>::Changeset;
246    const SET_CLAUSE: SetClause = <Box<[U]> as AsChangeset>::SET_CLAUSE;
247
248    fn as_changeset(self) -> Self::Changeset {
249        (self as Box<[U]>).as_changeset()
250    }
251}
252
253impl<U, I, C, PK> AsChangeset for Box<[U]>
254where
255    U: AsChangeset<Changeset = C> + HasTable<Table = U::Target>,
256    U::Target: Table<PrimaryKey = PK>,
257    for<'a> &'a U: Identifiable<Id: IntoOwned<Owned = I>>,
258{
259    type Target = U::Target;
260    type Changeset = BatchUpdate<I, C, PK, U::Target>;
261    const SET_CLAUSE: SetClause = SetClause::Delegated;
262
263    fn as_changeset(self) -> Self::Changeset {
264        let values = self
265            .into_iter()
266            .map(|v| {
267                // this clone is not that great, but we do not have
268                // many other options. On the other hand the primary key
269                // is often cheap to clone, especially compared
270                // to sending an large set of updates to the DB, so it shouldn't
271                // matter that much
272                let id = v.id().into_owned();
273                let changes = v.as_changeset();
274                (id, changes)
275            })
276            .collect();
277        BatchUpdate::new(values, U::table().primary_key())
278    }
279}
280
281impl<U, I, C, PK, const N: usize> AsChangeset for [U; N]
282where
283    U: AsChangeset<Changeset = C> + HasTable<Table = U::Target>,
284    U::Target: Table<PrimaryKey = PK>,
285    for<'a> &'a U: Identifiable<Id: IntoOwned<Owned = I>>,
286{
287    type Target = U::Target;
288    type Changeset = BatchUpdate<I, C, PK, U::Target>;
289    const SET_CLAUSE: SetClause = SetClause::Delegated;
290
291    fn as_changeset(self) -> Self::Changeset {
292        let values = self
293            .into_iter()
294            .map(|v| {
295                // this clone is not that great, but we do not have
296                // many other options. On the other hand the primary key
297                // is often cheap to clone, especially compared
298                // to sending an large set of updates to the DB, so it shouldn't
299                // matter that much
300                let id = v.id().into_owned();
301                let changes = v.as_changeset();
302                (id, changes)
303            })
304            .collect();
305        BatchUpdate::new(values, U::table().primary_key())
306    }
307}
308
309pub(crate) trait IntoOwned {
310    type Owned;
311
312    fn into_owned(self) -> Self::Owned;
313}
314
315impl<T> IntoOwned for &T
316where
317    T: ToOwned,
318{
319    type Owned = T::Owned;
320
321    fn into_owned(self) -> Self::Owned {
322        (*self).to_owned()
323    }
324}