Skip to main content

diesel/query_builder/insert_statement/
mod.rs

1pub(crate) mod batch_insert;
2mod column_list;
3mod insert_from_select;
4
5pub(crate) use self::batch_insert::BatchInsert;
6pub(crate) use self::column_list::ColumnList;
7pub(crate) use self::insert_from_select::InsertFromSelect;
8pub(crate) use self::private::Insert;
9pub use self::private::{InsertOrIgnore, Replace};#[diesel_derives::__diesel_public_if(
10    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
11)]
12pub(crate) use self::private::{InsertOrIgnore, Replace};
13
14use crate::backend::{DieselReserveSpecialization, SqlDialect, sql_dialect};
15use crate::expression::grouped::Grouped;
16use crate::expression::operators::Eq;
17use crate::expression::{Expression, NonAggregate, SelectableExpression};
18use crate::query_builder::returning::{
19    InsertStmtKind, NoReturningClause, ReturningClause, ReturningQuerySource,
20};
21use crate::query_builder::*;
22use crate::query_dsl::RunQueryDslSupport;
23use crate::query_source::{Column, Table};
24use crate::{QuerySource, insertable::*};
25use core::marker::PhantomData;
26
27pub(crate) use self::private::InsertAutoTypeHelper;
28
29#[cfg(feature = "__sqlite-shared")]
30mod insert_with_default_for_sqlite;
31
32/// The structure returned by [`insert_into`].
33///
34/// The provided methods [`values`] and [`default_values`] will insert
35/// data into the targeted table.
36///
37/// [`insert_into`]: crate::insert_into()
38/// [`values`]: IncompleteInsertStatement::values()
39/// [`default_values`]: IncompleteInsertStatement::default_values()
40#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug, Op: ::core::fmt::Debug>
    ::core::fmt::Debug for IncompleteInsertStatement<T, Op> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "IncompleteInsertStatement target operator", &self.target,
            &&self.operator)
    }
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone,
    Op: ::core::clone::Clone> ::core::clone::Clone for
    IncompleteInsertStatement<T, Op> {
    #[inline]
    fn clone(&self) -> Self {
        IncompleteInsertStatement {
            target: ::core::clone::Clone::clone(&self.target),
            operator: ::core::clone::Clone::clone(&self.operator),
        }
    }
}Clone, #[automatically_derived]impl<T: ::core::marker::Copy,
    Op: ::core::marker::Copy> ::core::marker::Copy for
    IncompleteInsertStatement<T, Op> {
}Copy)]
41#[must_use = "Queries are only executed when calling `load`, `get_result` or similar."]
42pub struct IncompleteInsertStatement<T, Op = Insert> {
43    target: T,
44    operator: Op,
45}
46
47/// Represents the return type of [`diesel::insert_or_ignore_into`](crate::insert_or_ignore_into)
48pub type IncompleteInsertOrIgnoreStatement<T> = IncompleteInsertStatement<T, InsertOrIgnore>;
49
50/// Represents a complete `INSERT OR IGNORE` statement.
51pub type InsertOrIgnoreStatement<T, U, Ret = NoReturningClause> =
52    InsertStatement<T, U, InsertOrIgnore, Ret>;
53
54/// Represents the return type of [`diesel::replace_into`](crate::replace_into)
55pub type IncompleteReplaceStatement<T> = IncompleteInsertStatement<T, Replace>;
56
57/// Represents a complete `INSERT OR REPLACE` statement.
58pub type ReplaceStatement<T, U, Ret = NoReturningClause> = InsertStatement<T, U, Replace, Ret>;
59
60impl<T, Op> IncompleteInsertStatement<T, Op>
61where
62    T: QuerySource,
63{
64    pub(crate) fn new(target: T, operator: Op) -> Self {
65        IncompleteInsertStatement { target, operator }
66    }
67
68    /// Inserts `DEFAULT VALUES` into the targeted table.
69    ///
70    /// ```rust
71    /// # include!("../../doctest_setup.rs");
72    /// #
73    /// # table! {
74    /// #     users (name) {
75    /// #         name -> Text,
76    /// #         hair_color -> Text,
77    /// #     }
78    /// # }
79    /// #
80    /// # // Reading the query result requires reading memory allocated by the
81    /// # // native sqlite library, which miri cannot track provenance for.
82    /// # #[cfg(miri)]
83    /// # fn main() {}
84    /// # #[cfg(not(miri))]
85    /// # fn main() {
86    /// #     run_test();
87    /// # }
88    /// #
89    /// # fn run_test() -> QueryResult<()> {
90    /// #     use diesel::insert_into;
91    /// #     use self::users::dsl::*;
92    /// #     let connection = &mut connection_no_data();
93    /// diesel::sql_query(
94    ///     "CREATE TABLE users (
95    ///     name VARCHAR(255) NOT NULL DEFAULT 'Sean',
96    ///     hair_color VARCHAR(255) NOT NULL DEFAULT 'Green'
97    /// )",
98    /// )
99    /// .execute(connection)?;
100    ///
101    /// insert_into(users)
102    ///     .default_values()
103    ///     .execute(connection)
104    ///     .unwrap();
105    /// let inserted_user = users.first(connection)?;
106    /// let expected_data = (String::from("Sean"), String::from("Green"));
107    ///
108    /// assert_eq!(expected_data, inserted_user);
109    /// #     Ok(())
110    /// # }
111    /// ```
112    pub fn default_values(self) -> InsertStatement<T, DefaultValues, Op> {
113        self.values(DefaultValues)
114    }
115
116    /// Inserts the given values into the table passed to `insert_into`.
117    ///
118    /// See the documentation of [`insert_into`] for
119    /// usage examples.
120    ///
121    /// This method can sometimes produce extremely opaque error messages due to
122    /// limitations of the Rust language. If you receive an error about
123    /// "overflow evaluating requirement" as a result of calling this method,
124    /// you may need an `&` in front of the argument to this method.
125    ///
126    /// `#[derive(Insertable)]` usually generates implementations for both owned
127    /// and borrowed records, but `#[diesel(serialize_as)]` consumes the field
128    /// value via `.into()`. In that case, only the owned form implements
129    /// `Insertable`, so call `.values(record)` instead of `.values(&record)`.
130    ///
131    /// [`insert_into`]: crate::insert_into()
132    pub fn values<U>(self, records: U) -> InsertStatement<T, U::Values, Op>
133    where
134        U: Insertable<T>,
135    {
136        InsertStatement::new(
137            self.target,
138            records.values(),
139            self.operator,
140            NoReturningClause,
141        )
142    }
143}
144
145/// A fully constructed insert statement.
146///
147/// The parameters of this struct represent:
148///
149/// - `T`: The table we are inserting into
150/// - `U`: The data being inserted
151/// - `Op`: The operation being performed. The specific types used to represent
152///   this are private, but correspond to SQL such as `INSERT` or `REPLACE`.
153///   You can safely rely on the default type representing `INSERT`
154/// - `Ret`: The `RETURNING` clause of the query. The specific types used to
155///   represent this are private. You can safely rely on the default type
156///   representing a query without a `RETURNING` clause.
157#[doc = " A fully constructed insert statement."]
#[doc = ""]
#[doc = " The parameters of this struct represent:"]
#[doc = ""]
#[doc = " - `T`: The table we are inserting into"]
#[doc = " - `U`: The data being inserted"]
#[doc =
" - `Op`: The operation being performed. The specific types used to represent"]
#[doc =
"   this are private, but correspond to SQL such as `INSERT` or `REPLACE`."]
#[doc = "   You can safely rely on the default type representing `INSERT`"]
#[doc =
" - `Ret`: The `RETURNING` clause of the query. The specific types used to"]
#[doc =
"   represent this are private. You can safely rely on the default type"]
#[doc = "   representing a query without a `RETURNING` clause."]
#[must_use =
"Queries are only executed when calling `load`, `get_result` or similar."]
#[non_exhaustive]
pub struct InsertStatement<T: QuerySource, U, Op = Insert, Ret =
    NoReturningClause> {
    #[doc = " The operator used by this InsertStatement"]
    #[doc = ""]
    #[doc = " Corresponds to either `Insert` or `Replace`"]
    pub operator: Op,
    #[doc = " The table we are inserting into"]
    pub target: T,
    #[doc = " The data which should be inserted"]
    pub records: U,
    #[doc = " An optional returning clause"]
    pub returning: Ret,
    into_clause: T::FromClause,
}#[diesel_derives::__diesel_public_if(
158    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes",
159    public_fields(operator, target, records, returning)
160)]
161#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug + QuerySource,
    U: ::core::fmt::Debug, Op: ::core::fmt::Debug, Ret: ::core::fmt::Debug>
    ::core::fmt::Debug for InsertStatement<T, U, Op, Ret> where
    T::FromClause: ::core::fmt::Debug {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "InsertStatement operator target records returning into_clause",
            &self.operator, &self.target, &self.records, &self.returning,
            &&self.into_clause)
    }
}Debug, #[automatically_derived]impl<T: ::core::marker::Copy + QuerySource,
    U: ::core::marker::Copy, Op: ::core::marker::Copy,
    Ret: ::core::marker::Copy> ::core::marker::Copy for
    InsertStatement<T, U, Op, Ret> where T::FromClause: ::core::marker::Copy {
}Copy, #[automatically_derived]impl<T: ::core::clone::Clone + QuerySource,
    U: ::core::clone::Clone, Op: ::core::clone::Clone,
    Ret: ::core::clone::Clone> ::core::clone::Clone for
    InsertStatement<T, U, Op, Ret> where T::FromClause: ::core::clone::Clone {
    #[inline]
    fn clone(&self) -> Self {
        InsertStatement {
            operator: ::core::clone::Clone::clone(&self.operator),
            target: ::core::clone::Clone::clone(&self.target),
            records: ::core::clone::Clone::clone(&self.records),
            returning: ::core::clone::Clone::clone(&self.returning),
            into_clause: ::core::clone::Clone::clone(&self.into_clause),
        }
    }
}Clone)]
162#[must_use = "Queries are only executed when calling `load`, `get_result` or similar."]
163pub struct InsertStatement<T: QuerySource, U, Op = Insert, Ret = NoReturningClause> {
164    /// The operator used by this InsertStatement
165    ///
166    /// Corresponds to either `Insert` or `Replace`
167    operator: Op,
168    /// The table we are inserting into
169    target: T,
170    /// The data which should be inserted
171    records: U,
172    /// An optional returning clause
173    returning: Ret,
174    into_clause: T::FromClause,
175}
176
177impl<T, U, Op, Ret> QueryId for InsertStatement<T, U, Op, Ret>
178where
179    T: QuerySource + QueryId + 'static,
180    U: QueryId,
181    Op: QueryId,
182    Ret: QueryId,
183{
184    type QueryId = InsertStatement<T, U::QueryId, Op::QueryId, Ret::QueryId>;
185
186    const HAS_STATIC_QUERY_ID: bool = T::HAS_STATIC_QUERY_ID
187        && U::HAS_STATIC_QUERY_ID
188        && Op::HAS_STATIC_QUERY_ID
189        && Ret::HAS_STATIC_QUERY_ID;
190}
191
192impl<T: QuerySource, U, Op, Ret> InsertStatement<T, U, Op, Ret> {
193    /// Create a new InsertStatement instance
194    #[doc = " Create a new InsertStatement instance"]
pub fn new(target: T, records: U, operator: Op, returning: Ret) -> Self {
    InsertStatement {
        into_clause: target.from_clause(),
        operator,
        target,
        records,
        returning,
    }
}#[diesel_derives::__diesel_public_if(
195        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
196    )]
197    pub(crate) fn new(target: T, records: U, operator: Op, returning: Ret) -> Self {
198        InsertStatement {
199            into_clause: target.from_clause(),
200            operator,
201            target,
202            records,
203            returning,
204        }
205    }
206
207    pub(crate) fn replace_values<F, V>(self, f: F) -> InsertStatement<T, V, Op, Ret>
208    where
209        F: FnOnce(U) -> V,
210    {
211        InsertStatement::new(self.target, f(self.records), self.operator, self.returning)
212    }
213}
214
215impl<T: QuerySource, U, C, Op, Ret> InsertStatement<T, InsertFromSelect<U, C>, Op, Ret> {
216    /// Set the column list when inserting from a select statement
217    ///
218    /// See the documentation for [`insert_into`] for usage examples.
219    ///
220    /// [`insert_into`]: crate::insert_into()
221    pub fn into_columns<C2>(
222        self,
223        columns: C2,
224    ) -> InsertStatement<T, InsertFromSelect<U, C2>, Op, Ret>
225    where
226        C2: ColumnList<Table = T> + Expression,
227        U: Query<SqlType = C2::SqlType>,
228    {
229        InsertStatement::new(
230            self.target,
231            self.records.with_columns(columns),
232            self.operator,
233            self.returning,
234        )
235    }
236}
237
238// This is a separate free standing function
239// so that the debug impl for sqlite can use it with
240// slightly adjusted types
241pub(super) fn walk_ast_intern<'b, T, U, Op, Ret, DB>(
242    mut out: AstPass<'_, 'b, DB>,
243    records: &'b U,
244    into_clause: &'b T::FromClause,
245    operator: &'b Op,
246    returning: &'b Ret,
247) -> QueryResult<()>
248where
249    DB: Backend + DieselReserveSpecialization,
250    T: Table,
251    T::FromClause: QueryFragment<DB>,
252    U: QueryFragment<DB> + CanInsertInSingleQuery<DB>,
253    Op: QueryFragment<DB>,
254    Ret: QueryFragment<DB>,
255{
256    if records.rows_to_insert() == Some(0) {
257        out.push_sql("SELECT 1 FROM ");
258        into_clause.walk_ast(out.reborrow())?;
259        out.push_sql(" WHERE 1=0");
260        return Ok(());
261    }
262
263    operator.walk_ast(out.reborrow())?;
264    out.push_sql(" INTO ");
265    into_clause.walk_ast(out.reborrow())?;
266    out.push_sql(" ");
267    records.walk_ast(out.reborrow())?;
268    returning.walk_ast(out.reborrow())?;
269    Ok(())
270}
271
272impl<T, U, Op, Ret, DB> QueryFragment<DB> for InsertStatement<T, U, Op, Ret>
273where
274    DB: Backend + DieselReserveSpecialization,
275    T: Table,
276    T::FromClause: QueryFragment<DB>,
277    U: QueryFragment<DB> + CanInsertInSingleQuery<DB>,
278    Op: QueryFragment<DB>,
279    Ret: QueryFragment<DB>,
280{
281    fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
282        walk_ast_intern::<T, U, Op, Ret, DB>(
283            out,
284            &self.records,
285            &self.into_clause,
286            &self.operator,
287            &self.returning,
288        )
289    }
290}
291
292impl<T, U, Op> AsQuery for InsertStatement<T, U, Op, NoReturningClause>
293where
294    T: Table,
295    U: InsertStmtKind,
296    InsertStatement<T, U, Op, ReturningClause<T::AllColumns>>: Query,
297    T::AllColumns: SelectableExpression<ReturningQuerySource<U::StmtKind, T>>,
298{
299    type SqlType = <Self::Query as Query>::SqlType;
300    type Query = InsertStatement<T, U, Op, ReturningClause<T::AllColumns>>;
301
302    fn as_query(self) -> Self::Query {
303        self.returning(T::all_columns())
304    }
305}
306
307impl<T, U, Op, Ret> Query for InsertStatement<T, U, Op, ReturningClause<Ret>>
308where
309    T: QuerySource,
310    U: InsertStmtKind,
311    Ret: SelectableExpression<ReturningQuerySource<U::StmtKind, T>> + NonAggregate,
312{
313    type SqlType = <Ret as Expression>::SqlType;
314}
315
316impl<T: QuerySource, U, Op, Ret> RunQueryDslSupport for InsertStatement<T, U, Op, Ret> {}
317
318impl<T: QuerySource, U, Op> InsertStatement<T, U, Op> {
319    /// Specify what expression is returned after execution of the `insert`.
320    /// # Examples
321    ///
322    /// ### Inserting records:
323    ///
324    /// ```rust
325    /// # include!("../../doctest_setup.rs");
326    /// #
327    /// # #[cfg(feature = "postgres")]
328    /// # fn main() {
329    /// #     use schema::users::dsl::*;
330    /// #     let connection = &mut establish_connection();
331    /// let inserted_names = diesel::insert_into(users)
332    ///     .values(&vec![name.eq("Timmy"), name.eq("Jimmy")])
333    ///     .returning(name)
334    ///     .get_results(connection)
335    ///     .unwrap();
336    /// // Note that the returned order is not guaranteed to be preserved
337    /// assert_eq!(inserted_names.len(), 2);
338    /// assert!(inserted_names.contains(&"Timmy".to_string()));
339    /// assert!(inserted_names.contains(&"Jimmy".to_string()));
340    /// # }
341    /// # #[cfg(not(feature = "postgres"))]
342    /// # fn main() {}
343    /// ```
344    pub fn returning<E>(self, returns: E) -> InsertStatement<T, U, Op, ReturningClause<E>>
345    where
346        InsertStatement<T, U, Op, ReturningClause<E>>: Query,
347    {
348        InsertStatement::new(
349            self.target,
350            self.records,
351            self.operator,
352            ReturningClause(returns),
353        )
354    }
355}
356
357/// Marker trait to indicate that no additional operations have been added
358/// to a record for insert.
359///
360/// This is used to prevent things like
361/// `.on_conflict_do_nothing().on_conflict_do_nothing()`
362/// from compiling.
363#[cfg_attr(
364    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes",
365    cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")
366)]
367pub trait UndecoratedInsertRecord<Table> {}
368
369impl<T, Tab> UndecoratedInsertRecord<Tab> for &T where T: ?Sized + UndecoratedInsertRecord<Tab> {}
370
371impl<T, U> UndecoratedInsertRecord<T::Table> for ColumnInsertValue<T, U> where T: Column {}
372
373impl<T, U> UndecoratedInsertRecord<T::Table>
374    for DefaultableColumnInsertValue<ColumnInsertValue<T, U>>
375where
376    T: Column,
377{
378}
379
380impl<T, Table> UndecoratedInsertRecord<Table> for [T] where T: UndecoratedInsertRecord<Table> {}
381
382impl<T, Table, QId, const STATIC_QUERY_ID: bool> UndecoratedInsertRecord<Table>
383    for BatchInsert<T, Table, QId, STATIC_QUERY_ID>
384where
385    T: UndecoratedInsertRecord<Table>,
386{
387}
388
389impl<T, Table> UndecoratedInsertRecord<Table> for Vec<T> where [T]: UndecoratedInsertRecord<Table> {}
390
391impl<Lhs, Rhs> UndecoratedInsertRecord<Lhs::Table> for Eq<Lhs, Rhs> where Lhs: Column {}
392
393impl<Lhs, Rhs, Tab> UndecoratedInsertRecord<Tab> for Option<Eq<Lhs, Rhs>> where
394    Eq<Lhs, Rhs>: UndecoratedInsertRecord<Tab>
395{
396}
397
398impl<Lhs, Rhs> UndecoratedInsertRecord<Lhs::Table> for Grouped<Eq<Lhs, Rhs>> where Lhs: Column {}
399
400impl<Lhs, Rhs, Tab> UndecoratedInsertRecord<Tab> for Option<Grouped<Eq<Lhs, Rhs>>> where
401    Eq<Lhs, Rhs>: UndecoratedInsertRecord<Tab>
402{
403}
404
405impl<T, Table> UndecoratedInsertRecord<Table> for ValuesClause<T, Table> where
406    T: UndecoratedInsertRecord<Table>
407{
408}
409
410#[derive(#[automatically_derived]impl ::core::fmt::Debug for DefaultValues {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "DefaultValues")
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DefaultValues {
}
#[automatically_derived]impl ::core::clone::Clone for DefaultValues {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DefaultValues { }Copy, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for DefaultValues {
            type QueryId = DefaultValues<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId)]
411#[doc(hidden)]
412pub struct DefaultValues;
413
414impl<DB: Backend> CanInsertInSingleQuery<DB> for DefaultValues {
415    fn rows_to_insert(&self) -> Option<usize> {
416        Some(1)
417    }
418}
419
420impl<Tab> Insertable<Tab> for DefaultValues {
421    type Values = DefaultValues;
422
423    fn values(self) -> Self::Values {
424        self
425    }
426}
427
428impl<Tab> Insertable<Tab> for &DefaultValues {
429    type Values = DefaultValues;
430
431    fn values(self) -> Self::Values {
432        *self
433    }
434}
435
436/// Insert values that produce exactly one row: a single record's values,
437/// [`default_values`](crate::query_builder::IncompleteInsertStatement::default_values), or an upsert wrapping
438/// either. Batch inserts and `INSERT ... SELECT` do not qualify.
439#[diagnostic::on_unimplemented(
440    message = "`{Self}` may insert zero or several rows",
441    note = "the database client reports one generated id per statement, \
442            so this operation supports only single-row inserts"
443)]
444#[cfg(any(feature = "mysql_backend", feature = "mariadb_backend"))]
445pub trait SingleRowInsertValues<Tab> {}
446
447#[cfg(any(feature = "mysql_backend", feature = "mariadb_backend"))]
448impl<V, Tab> SingleRowInsertValues<Tab> for ValuesClause<V, Tab> {}
449
450#[cfg(any(feature = "mysql_backend", feature = "mariadb_backend"))]
451impl<Tab> SingleRowInsertValues<Tab> for DefaultValues {}
452
453#[cfg(any(feature = "mysql_backend", feature = "mariadb_backend"))]
454impl<V, Tab, Target, Action, WhereClause> SingleRowInsertValues<Tab>
455    for crate::query_builder::upsert::on_conflict_clause::OnConflictValues<
456        V,
457        Target,
458        Action,
459        WhereClause,
460    >
461where
462    V: SingleRowInsertValues<Tab>,
463{
464}
465
466impl<DB> QueryFragment<DB> for DefaultValues
467where
468    DB: Backend,
469    Self: QueryFragment<DB, DB::DefaultValueClauseForInsert>,
470{
471    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
472        <Self as QueryFragment<DB, DB::DefaultValueClauseForInsert>>::walk_ast(self, pass)
473    }
474}
475
476impl<DB> QueryFragment<DB, sql_dialect::default_value_clause::AnsiDefaultValueClause>
477    for DefaultValues
478where
479    DB: Backend
480        + SqlDialect<
481            DefaultValueClauseForInsert = sql_dialect::default_value_clause::AnsiDefaultValueClause,
482        >,
483{
484    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
485        out.push_sql("DEFAULT VALUES");
486        Ok(())
487    }
488}
489
490/// This type represents a values clause used as part of insert statements
491///
492/// Diesel exposes this type for third party backends so that
493/// they can implement batch insert support
494#[cfg_attr(
495    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes",
496    cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")
497)]
498#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug, Tab: ::core::fmt::Debug>
    ::core::fmt::Debug for ValuesClause<T, Tab> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ValuesClause values _marker", &self.values, &&self._marker)
    }
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone,
    Tab: ::core::clone::Clone> ::core::clone::Clone for ValuesClause<T, Tab> {
    #[inline]
    fn clone(&self) -> Self {
        ValuesClause {
            values: ::core::clone::Clone::clone(&self.values),
            _marker: ::core::clone::Clone::clone(&self._marker),
        }
    }
}Clone, #[automatically_derived]impl<T: ::core::marker::Copy,
    Tab: ::core::marker::Copy> ::core::marker::Copy for ValuesClause<T, Tab> {
}Copy, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl<T: diesel::query_builder::QueryId,
            Tab: diesel::query_builder::QueryId>
            diesel::query_builder::QueryId for ValuesClause<T, Tab> {
            type QueryId =
                ValuesClause<<T as diesel::query_builder::QueryId>::QueryId,
                <Tab as diesel::query_builder::QueryId>::QueryId>;
            const HAS_STATIC_QUERY_ID: bool =
                <T as diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID &&
                        <Tab as diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID
                    && true;
            const IS_WINDOW_FUNCTION: bool =
                <T as diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION ||
                        <Tab as diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION
                    || false;
        }
    };QueryId)]
499pub struct ValuesClause<T, Tab> {
500    /// Values to insert
501    pub values: T,
502    _marker: PhantomData<Tab>,
503}
504
505impl<T: Default, Tab> Default for ValuesClause<T, Tab> {
506    fn default() -> Self {
507        Self::new(T::default())
508    }
509}
510
511impl<T, Tab> ValuesClause<T, Tab> {
512    pub(crate) fn new(values: T) -> Self {
513        Self {
514            values,
515            _marker: PhantomData,
516        }
517    }
518}
519
520impl<T, Tab, DB> CanInsertInSingleQuery<DB> for ValuesClause<T, Tab>
521where
522    DB: Backend,
523    T: CanInsertInSingleQuery<DB>,
524{
525    fn rows_to_insert(&self) -> Option<usize> {
526        self.values.rows_to_insert()
527    }
528}
529
530impl<T, Tab, DB> QueryFragment<DB> for ValuesClause<T, Tab>
531where
532    DB: Backend,
533    Tab: Table,
534    T: InsertValues<DB, Tab>,
535    DefaultValues: QueryFragment<DB>,
536{
537    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
538        if self.values.is_noop(out.backend())? {
539            DefaultValues.walk_ast(out)?;
540        } else {
541            out.push_sql("(");
542            self.values.column_names(out.reborrow())?;
543            out.push_sql(") VALUES (");
544            self.values.walk_ast(out.reborrow())?;
545            out.push_sql(")");
546        }
547        Ok(())
548    }
549}
550
551mod private {
552    use super::InsertStatement;
553    use crate::QueryResult;
554    use crate::QuerySource;
555    use crate::backend::{Backend, DieselReserveSpecialization};
556    use crate::query_builder::{AstPass, QueryFragment, QueryId};
557
558    #[derive(#[automatically_derived]impl ::core::fmt::Debug for Insert {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "Insert")
    }
}Debug, #[automatically_derived]impl ::core::marker::Copy for Insert { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Insert {
}
#[automatically_derived]impl ::core::clone::Clone for Insert {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for Insert {
            type QueryId = Insert<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId)]
559    pub struct Insert;
560
561    impl<DB> QueryFragment<DB> for Insert
562    where
563        DB: Backend + DieselReserveSpecialization,
564    {
565        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
566            out.push_sql("INSERT");
567            Ok(())
568        }
569    }
570
571    /// A marker type for insert or ignore statements
572    #[derive(#[automatically_derived]impl ::core::fmt::Debug for InsertOrIgnore {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "InsertOrIgnore")
    }
}Debug, #[automatically_derived]impl ::core::marker::Copy for InsertOrIgnore { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for InsertOrIgnore {
}
#[automatically_derived]impl ::core::clone::Clone for InsertOrIgnore {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for InsertOrIgnore {
            type QueryId = InsertOrIgnore<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId)]
573    pub struct InsertOrIgnore;
574
575    #[cfg(feature = "__sqlite-shared")]
576    impl QueryFragment<crate::sqlite::Sqlite> for InsertOrIgnore {
577        fn walk_ast<'b>(
578            &'b self,
579            mut out: AstPass<'_, 'b, crate::sqlite::Sqlite>,
580        ) -> QueryResult<()> {
581            out.push_sql("INSERT OR IGNORE");
582            Ok(())
583        }
584    }
585
586    #[cfg(any(feature = "mysql_backend", feature = "mariadb_backend"))]
587    #[diagnostic::do_not_recommend]
588    impl<DB: crate::mysql_like::MysqlLikeBackend> QueryFragment<DB> for InsertOrIgnore {
589        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
590            out.push_sql("INSERT IGNORE");
591            Ok(())
592        }
593    }
594
595    /// A marker type for replace statements
596    #[derive(#[automatically_derived]impl ::core::fmt::Debug for Replace {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "Replace")
    }
}Debug, #[automatically_derived]impl ::core::marker::Copy for Replace { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Replace {
}
#[automatically_derived]impl ::core::clone::Clone for Replace {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for Replace {
            type QueryId = Replace<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId)]
597    pub struct Replace;
598
599    #[cfg(feature = "__sqlite-shared")]
600    impl QueryFragment<crate::sqlite::Sqlite> for Replace {
601        fn walk_ast<'b>(
602            &'b self,
603            mut out: AstPass<'_, 'b, crate::sqlite::Sqlite>,
604        ) -> QueryResult<()> {
605            out.push_sql("REPLACE");
606            Ok(())
607        }
608    }
609
610    #[cfg(any(feature = "mysql_backend", feature = "mariadb_backend"))]
611    #[diagnostic::do_not_recommend]
612    impl<DB: crate::mysql_like::MysqlLikeBackend> QueryFragment<DB> for Replace {
613        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
614            out.push_sql("REPLACE");
615            Ok(())
616        }
617    }
618
619    // otherwise rustc complains at a different location that this trait is more private than the other item that uses it
620    #[allow(unreachable_pub)]
621    pub trait InsertAutoTypeHelper {
622        type Table;
623        type Op;
624        type Values;
625        type Ret;
626    }
627
628    impl<T, Op> InsertAutoTypeHelper for crate::query_builder::IncompleteInsertStatement<T, Op> {
629        type Table = T;
630        type Op = Op;
631        type Values = ();
632        type Ret = crate::query_builder::returning::NoReturningClause;
633    }
634
635    impl<T, U, Op, Ret> InsertAutoTypeHelper for InsertStatement<T, U, Op, Ret>
636    where
637        T: QuerySource,
638    {
639        type Table = T;
640        type Op = Op;
641        type Values = U;
642        type Ret = Ret;
643    }
644}