use super::ValuesClause; use crate::backend::{sql_dialect, Backend, SqlDialect}; use crate::insertable::CanInsertInSingleQuery; use crate::query_builder::{AstPass, QueryFragment, QueryId}; use crate::QueryResult; use std::marker::PhantomData; /// This type represents a batch insert clause, which allows /// to insert multiple rows at once. /// /// Custom backends can specialize the [`QueryFragment`] /// implementation via [`SqlDialect::BatchInsertSupport`] /// or provide fully custom [`ExecuteDsl`](crate::query_dsl::methods::ExecuteDsl) /// and [`LoadQuery`](crate::query_dsl::methods::LoadQuery) implementations #[cfg_attr( feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes", cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes") )] #[derive(Debug)] pub struct BatchInsert { /// List of values that should be inserted pub values: V, _marker: PhantomData<(QId, Tab)>, } impl BatchInsert { pub(crate) fn new(values: V) -> Self { Self { values, _marker: PhantomData, } } } impl QueryId for BatchInsert { type QueryId = QId; const HAS_STATIC_QUERY_ID: bool = STABLE_QUERY_ID; } impl CanInsertInSingleQuery for BatchInsert where T: CanInsertInSingleQuery, DB: Backend+ SqlDialect { fn rows_to_insert(&self) -> Option { self.values.rows_to_insert() } } impl CanInsertInSingleQuery for [T; N] where DB: Backend+ SqlDialect { fn rows_to_insert(&self) -> Option { Some(N) } } impl CanInsertInSingleQuery for Box<[T; N]> where DB: Backend+ SqlDialect { fn rows_to_insert(&self) -> Option { Some(N) } } impl CanInsertInSingleQuery for [T] where DB: Backend+ SqlDialect { fn rows_to_insert(&self) -> Option { Some(self.len()) } } impl CanInsertInSingleQuery for Vec where DB: Backend+ SqlDialect, { fn rows_to_insert(&self) -> Option { Some(self.len()) } } impl QueryFragment for BatchInsert where DB: Backend, Self: QueryFragment, { fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> { >::walk_ast(self, pass) } } impl QueryFragment for BatchInsert>, Tab, QId, HAS_STATIC_QUERY_ID> where DB: Backend + SqlDialect< BatchInsertSupport = sql_dialect::batch_insert_support::PostgresLikeBatchInsertSupport, >, DB::InsertWithDefaultKeyword: sql_dialect::default_keyword_for_insert::SupportsDefaultKeyword, ValuesClause: QueryFragment, V: QueryFragment, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { if !HAS_STATIC_QUERY_ID { out.unsafe_to_cache_prepared(); } let mut values = self.values.iter(); if let Some(value) = values.next() { value.walk_ast(out.reborrow())?; } for value in values { out.push_sql(", ("); value.values.walk_ast(out.reborrow())?; out.push_sql(")"); } Ok(()) } }