diesel/
insertable.rs

1use std::marker::PhantomData;
2
3use crate::backend::{sql_dialect, Backend, DieselReserveSpecialization, SqlDialect};
4use crate::expression::grouped::Grouped;
5use crate::expression::{AppearsOnTable, Expression};
6use crate::query_builder::{
7    AstPass, BatchInsert, InsertStatement, NoFromClause, QueryFragment, QueryId,
8    UndecoratedInsertRecord, ValuesClause,
9};
10use crate::query_source::{Column, Table};
11use crate::result::QueryResult;
12
13/// Represents that a structure can be used to insert a new row into the
14/// database. This is automatically implemented for `&[T]` and `&Vec<T>` for
15/// inserting more than one record.
16///
17/// This trait can be [derived](derive@Insertable)
18pub trait Insertable<T> {
19    /// The `VALUES` clause to insert these records
20    ///
21    /// The types used here are generally internal to Diesel.
22    /// Implementations of this trait should use the `Values`
23    /// type of other `Insertable` types.
24    /// For example `<diesel::dsl::Eq<column, &str> as Insertable<table>>::Values`.
25    type Values;
26
27    /// Construct `Self::Values`
28    ///
29    /// Implementations of this trait typically call `.values`
30    /// on other `Insertable` types.
31    fn values(self) -> Self::Values;
32
33    /// Insert `self` into a given table.
34    ///
35    /// `foo.insert_into(table)` is identical to `insert_into(table).values(foo)`.
36    /// However, when inserting from a select statement,
37    /// this form is generally preferred.
38    ///
39    /// # Example
40    ///
41    /// ```rust
42    /// # include!("doctest_setup.rs");
43    /// #
44    /// # fn main() {
45    /// #     run_test().unwrap();
46    /// # }
47    /// #
48    /// # fn run_test() -> QueryResult<()> {
49    /// #     use schema::{posts, users};
50    /// #     let conn = &mut establish_connection();
51    /// #     diesel::delete(posts::table).execute(conn)?;
52    /// users::table
53    ///     .select((
54    ///         users::name.concat("'s First Post"),
55    ///         users::id,
56    ///     ))
57    ///     .insert_into(posts::table)
58    ///     .into_columns((posts::title, posts::user_id))
59    ///     .execute(conn)?;
60    ///
61    /// let inserted_posts = posts::table
62    ///     .select(posts::title)
63    ///     .load::<String>(conn)?;
64    /// let expected = vec!["Sean's First Post", "Tess's First Post"];
65    /// assert_eq!(expected, inserted_posts);
66    /// #     Ok(())
67    /// # }
68    /// ```
69    fn insert_into(self, table: T) -> InsertStatement<T, Self::Values>
70    where
71        T: Table,
72        Self: Sized,
73    {
74        crate::insert_into(table).values(self)
75    }
76}
77
78#[doc(inline)]
79pub use diesel_derives::Insertable;
80
81pub trait CanInsertInSingleQuery<DB: Backend> {
82    /// How many rows will this query insert?
83    ///
84    /// This function should only return `None` when the query is valid on all
85    /// backends, regardless of how many rows get inserted.
86    fn rows_to_insert(&self) -> Option<usize>;
87}
88
89impl<T, DB> CanInsertInSingleQuery<DB> for &T
90where
91    T: ?Sized + CanInsertInSingleQuery<DB>,
92    DB: Backend,
93{
94    fn rows_to_insert(&self) -> Option<usize> {
95        (*self).rows_to_insert()
96    }
97}
98
99impl<T, U, DB> CanInsertInSingleQuery<DB> for ColumnInsertValue<T, U>
100where
101    DB: Backend,
102{
103    fn rows_to_insert(&self) -> Option<usize> {
104        Some(1)
105    }
106}
107
108impl<V, DB> CanInsertInSingleQuery<DB> for DefaultableColumnInsertValue<V>
109where
110    DB: Backend,
111    V: CanInsertInSingleQuery<DB>,
112{
113    fn rows_to_insert(&self) -> Option<usize> {
114        Some(1)
115    }
116}
117
118pub trait InsertValues<DB: Backend, T: Table>: QueryFragment<DB> {
119    fn column_names(&self, out: AstPass<'_, '_, DB>) -> QueryResult<()>;
120}
121
122#[derive(Debug, Copy, Clone, QueryId)]
123#[doc(hidden)]
124pub struct ColumnInsertValue<Col, Expr> {
125    pub(crate) expr: Expr,
126    p: PhantomData<Col>,
127}
128
129impl<Col, Expr> ColumnInsertValue<Col, Expr> {
130    pub(crate) fn new(expr: Expr) -> Self {
131        Self {
132            expr,
133            p: PhantomData,
134        }
135    }
136}
137
138#[derive(Debug, Default, Copy, Clone)]
139#[doc(hidden)]
140pub enum DefaultableColumnInsertValue<T> {
141    Expression(T),
142    #[default]
143    Default,
144}
145
146impl<T> QueryId for DefaultableColumnInsertValue<T> {
147    type QueryId = ();
148    const HAS_STATIC_QUERY_ID: bool = false;
149}
150
151impl<Col, Expr, DB> InsertValues<DB, Col::Table>
152    for DefaultableColumnInsertValue<ColumnInsertValue<Col, Expr>>
153where
154    DB: Backend + SqlDialect<InsertWithDefaultKeyword = sql_dialect::default_keyword_for_insert::IsoSqlDefaultKeyword>,
155    Col: Column,
156    Expr: Expression<SqlType = Col::SqlType> + AppearsOnTable<NoFromClause>,
157    Self: QueryFragment<DB>,
158{
159    fn column_names(&self, mut out: AstPass<'_, '_, DB>) -> QueryResult<()> {
160        out.push_identifier(Col::NAME)?;
161        Ok(())
162    }
163}
164
165impl<Col, Expr, DB> InsertValues<DB, Col::Table> for ColumnInsertValue<Col, Expr>
166where
167    DB: Backend,
168    Col: Column,
169    Expr: Expression<SqlType = Col::SqlType> + AppearsOnTable<NoFromClause>,
170    Self: QueryFragment<DB>,
171{
172    fn column_names(&self, mut out: AstPass<'_, '_, DB>) -> QueryResult<()> {
173        out.push_identifier(Col::NAME)?;
174        Ok(())
175    }
176}
177
178impl<Expr, DB> QueryFragment<DB> for DefaultableColumnInsertValue<Expr>
179where
180    DB: Backend,
181    Self: QueryFragment<DB, DB::InsertWithDefaultKeyword>,
182{
183    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
184        <Self as QueryFragment<DB, DB::InsertWithDefaultKeyword>>::walk_ast(self, pass)
185    }
186}
187
188impl<Expr, DB> QueryFragment<DB, sql_dialect::default_keyword_for_insert::IsoSqlDefaultKeyword> for DefaultableColumnInsertValue<Expr>
189where
190    DB: Backend + SqlDialect<InsertWithDefaultKeyword = sql_dialect::default_keyword_for_insert::IsoSqlDefaultKeyword>,
191    Expr: QueryFragment<DB>,
192{
193    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
194        out.unsafe_to_cache_prepared();
195        if let Self::Expression(ref inner) = *self {
196            inner.walk_ast(out.reborrow())?;
197        } else {
198            out.push_sql("DEFAULT");
199        }
200        Ok(())
201    }
202}
203
204impl<Col, Expr, DB> QueryFragment<DB> for ColumnInsertValue<Col, Expr>
205where
206    DB: Backend + DieselReserveSpecialization,
207    Expr: QueryFragment<DB>,
208{
209    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
210        self.expr.walk_ast(pass)
211    }
212}
213
214#[cfg(feature = "sqlite")]
215impl<Col, Expr> InsertValues<crate::sqlite::Sqlite, Col::Table>
216    for DefaultableColumnInsertValue<ColumnInsertValue<Col, Expr>>
217where
218    Col: Column,
219    Expr: Expression<SqlType = Col::SqlType> + AppearsOnTable<NoFromClause>,
220    Self: QueryFragment<crate::sqlite::Sqlite>,
221{
222    fn column_names(&self, mut out: AstPass<'_, '_, crate::sqlite::Sqlite>) -> QueryResult<()> {
223        if let Self::Expression(..) = *self {
224            out.push_identifier(Col::NAME)?;
225        }
226        Ok(())
227    }
228}
229
230#[cfg(feature = "sqlite")]
231impl<Col, Expr>
232    QueryFragment<
233        crate::sqlite::Sqlite,
234        crate::backend::sql_dialect::default_keyword_for_insert::DoesNotSupportDefaultKeyword,
235    > for DefaultableColumnInsertValue<ColumnInsertValue<Col, Expr>>
236where
237    Expr: QueryFragment<crate::sqlite::Sqlite>,
238{
239    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, crate::sqlite::Sqlite>) -> QueryResult<()> {
240        if let Self::Expression(ref inner) = *self {
241            inner.walk_ast(out.reborrow())?;
242        }
243        Ok(())
244    }
245}
246
247impl<'a, T, Tab> Insertable<Tab> for &'a [T]
248where
249    &'a T: UndecoratedInsertRecord<Tab> + Insertable<Tab>,
250{
251    type Values = BatchInsert<Vec<<&'a T as Insertable<Tab>>::Values>, Tab, (), false>;
252
253    fn values(self) -> Self::Values {
254        let values = self.iter().map(Insertable::values).collect::<Vec<_>>();
255        BatchInsert::new(values)
256    }
257}
258
259impl<'a, T, Tab> Insertable<Tab> for &'a Vec<T>
260where
261    &'a [T]: Insertable<Tab>,
262{
263    type Values = <&'a [T] as Insertable<Tab>>::Values;
264
265    fn values(self) -> Self::Values {
266        (&**self).values()
267    }
268}
269
270impl<T, Tab> Insertable<Tab> for Vec<T>
271where
272    T: Insertable<Tab> + UndecoratedInsertRecord<Tab>,
273{
274    type Values = BatchInsert<Vec<T::Values>, Tab, (), false>;
275
276    fn values(self) -> Self::Values {
277        let values = self.into_iter().map(Insertable::values).collect::<Vec<_>>();
278        BatchInsert::new(values)
279    }
280}
281
282impl<T, Tab, const N: usize> Insertable<Tab> for [T; N]
283where
284    T: Insertable<Tab>,
285{
286    type Values = BatchInsert<Vec<T::Values>, Tab, [T::Values; N], true>;
287
288    fn values(self) -> Self::Values {
289        let values = self.into_iter().map(Insertable::values).collect::<Vec<_>>();
290        BatchInsert::new(values)
291    }
292}
293
294impl<'a, T, Tab, const N: usize> Insertable<Tab> for &'a [T; N]
295where
296    T: Insertable<Tab>,
297    &'a T: Insertable<Tab>,
298{
299    // We can reuse the query id for [T; N] here as this
300    // compiles down to the same query
301    type Values = BatchInsert<Vec<<&'a T as Insertable<Tab>>::Values>, Tab, [T::Values; N], true>;
302
303    fn values(self) -> Self::Values {
304        let values = self.iter().map(Insertable::values).collect();
305        BatchInsert::new(values)
306    }
307}
308
309impl<T, Tab, const N: usize> Insertable<Tab> for Box<[T; N]>
310where
311    T: Insertable<Tab>,
312{
313    // We can reuse the query id for [T; N] here as this
314    // compiles down to the same query
315    type Values = BatchInsert<Vec<T::Values>, Tab, [T::Values; N], true>;
316
317    fn values(self) -> Self::Values {
318        let v = Vec::from(self as Box<[T]>);
319        let values = v.into_iter().map(Insertable::values).collect::<Vec<_>>();
320        BatchInsert::new(values)
321    }
322}
323
324mod private {
325    // This helper exists to differentiate between
326    // Insertable implementations for tuples and for single values
327    #[allow(missing_debug_implementations)]
328    pub struct InsertableOptionHelper<T, V>(
329        pub(crate) Option<T>,
330        pub(crate) std::marker::PhantomData<V>,
331    );
332}
333
334pub(crate) use self::private::InsertableOptionHelper;
335
336impl<T, Tab, V> Insertable<Tab> for Option<T>
337where
338    T: Insertable<Tab, Values = ValuesClause<V, Tab>>,
339    InsertableOptionHelper<T, V>: Insertable<Tab>,
340{
341    type Values = <InsertableOptionHelper<T, V> as Insertable<Tab>>::Values;
342
343    fn values(self) -> Self::Values {
344        InsertableOptionHelper(self, PhantomData).values()
345    }
346}
347
348impl<T, Tab, Expr, Col> Insertable<Tab> for InsertableOptionHelper<T, ColumnInsertValue<Col, Expr>>
349where
350    T: Insertable<Tab, Values = ValuesClause<ColumnInsertValue<Col, Expr>, Tab>>,
351{
352    type Values = ValuesClause<DefaultableColumnInsertValue<ColumnInsertValue<Col, Expr>>, Tab>;
353
354    fn values(self) -> Self::Values {
355        ValuesClause::new(
356            self.0
357                .map(|v| DefaultableColumnInsertValue::Expression(Insertable::values(v).values))
358                .unwrap_or_default(),
359        )
360    }
361}
362
363impl<'a, T, Tab> Insertable<Tab> for &'a Option<T>
364where
365    Option<&'a T>: Insertable<Tab>,
366{
367    type Values = <Option<&'a T> as Insertable<Tab>>::Values;
368
369    fn values(self) -> Self::Values {
370        self.as_ref().values()
371    }
372}
373
374impl<L, R, Tab> Insertable<Tab> for Grouped<crate::expression::operators::Eq<L, R>>
375where
376    crate::expression::operators::Eq<L, R>: Insertable<Tab>,
377{
378    type Values = <crate::expression::operators::Eq<L, R> as Insertable<Tab>>::Values;
379
380    fn values(self) -> Self::Values {
381        self.0.values()
382    }
383}
384
385impl<'a, L, R, Tab> Insertable<Tab> for &'a Grouped<crate::expression::operators::Eq<L, R>>
386where
387    &'a crate::expression::operators::Eq<L, R>: Insertable<Tab>,
388{
389    type Values = <&'a crate::expression::operators::Eq<L, R> as Insertable<Tab>>::Values;
390
391    fn values(self) -> Self::Values {
392        self.0.values()
393    }
394}