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