use std::marker::PhantomData; use crate::backend::{sql_dialect, Backend, DieselReserveSpecialization, SqlDialect}; use crate::expression::grouped::Grouped; use crate::expression::{AppearsOnTable, Expression}; use crate::query_builder::{ AstPass, BatchInsert, InsertStatement, NoFromClause, QueryFragment, QueryId, UndecoratedInsertRecord, ValuesClause, }; use crate::query_source::{Column, Table}; use crate::result::QueryResult; /// Represents that a structure can be used to insert a new row into the /// database. This is automatically implemented for `&[T]` and `&Vec` for /// inserting more than one record. /// /// This trait can be [derived](derive@Insertable) pub trait Insertable { /// The `VALUES` clause to insert these records /// /// The types used here are generally internal to Diesel. /// Implementations of this trait should use the `Values` /// type of other `Insertable` types. /// For example ` as Insertable>::Values`. type Values; /// Construct `Self::Values` /// /// Implementations of this trait typically call `.values` /// on other `Insertable` types. fn values(self) -> Self::Values; /// Insert `self` into a given table. /// /// `foo.insert_into(table)` is identical to `insert_into(table).values(foo)`. /// However, when inserting from a select statement, /// this form is generally preferred. /// /// # Example /// /// ```rust /// # include!("doctest_setup.rs"); /// # /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::{posts, users}; /// # let conn = &mut establish_connection(); /// # diesel::delete(posts::table).execute(conn)?; /// users::table /// .select((users::name.concat("'s First Post"), users::id)) /// .insert_into(posts::table) /// .into_columns((posts::title, posts::user_id)) /// .execute(conn)?; /// /// let inserted_posts = posts::table.select(posts::title).load::(conn)?; /// let expected = vec!["Sean's First Post", "Tess's First Post"]; /// assert_eq!(expected, inserted_posts); /// # Ok(()) /// # } /// ``` fn insert_into(self, table: T) -> InsertStatement where T: Table, Self: Sized, { crate::insert_into(table).values(self) } } #[doc(inline)] pub use diesel_derives::Insertable; pub trait CanInsertInSingleQuery { /// How many rows will this query insert? /// /// This function should only return `None` when the query is valid on all /// backends, regardless of how many rows get inserted. fn rows_to_insert(&self) -> Option; } impl CanInsertInSingleQuery for &T where T: ?Sized + CanInsertInSingleQuery, DB: Backend, { fn rows_to_insert(&self) -> Option { (*self).rows_to_insert() } } impl CanInsertInSingleQuery for ColumnInsertValue where DB: Backend, { fn rows_to_insert(&self) -> Option { Some(1) } } impl CanInsertInSingleQuery for DefaultableColumnInsertValue where DB: Backend, V: CanInsertInSingleQuery, { fn rows_to_insert(&self) -> Option { Some(1) } } pub trait InsertValues: QueryFragment { fn column_names(&self, out: AstPass<'_, '_, DB>) -> QueryResult<()>; } #[derive(Debug, Copy, Clone, QueryId)] #[doc(hidden)] pub struct ColumnInsertValue { pub(crate) expr: Expr, p: PhantomData, } impl ColumnInsertValue { pub(crate) fn new(expr: Expr) -> Self { Self { expr, p: PhantomData, } } } #[derive(Debug, Default, Copy, Clone)] #[doc(hidden)] pub enum DefaultableColumnInsertValue { Expression(T), #[default] Default, } impl QueryId for DefaultableColumnInsertValue { type QueryId = (); const HAS_STATIC_QUERY_ID: bool = false; } impl InsertValues for DefaultableColumnInsertValue> where DB: Backend + SqlDialect, Col: Column, Expr: Expression + AppearsOnTable, Self: QueryFragment, { fn column_names(&self, mut out: AstPass<'_, '_, DB>) -> QueryResult<()> { out.push_identifier(Col::NAME)?; Ok(()) } } impl InsertValues for ColumnInsertValue where DB: Backend, Col: Column, Expr: Expression + AppearsOnTable, Self: QueryFragment, { fn column_names(&self, mut out: AstPass<'_, '_, DB>) -> QueryResult<()> { out.push_identifier(Col::NAME)?; Ok(()) } } impl QueryFragment for DefaultableColumnInsertValue where DB: Backend, Self: QueryFragment, { fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> { >::walk_ast(self, pass) } } impl QueryFragment for DefaultableColumnInsertValue where DB: Backend + SqlDialect, Expr: QueryFragment, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.unsafe_to_cache_prepared(); if let Self::Expression(ref inner) = *self { inner.walk_ast(out.reborrow())?; } else { out.push_sql("DEFAULT"); } Ok(()) } } impl QueryFragment for ColumnInsertValue where DB: Backend + DieselReserveSpecialization, Expr: QueryFragment, { fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> { self.expr.walk_ast(pass) } } #[cfg(feature = "sqlite")] impl InsertValues for DefaultableColumnInsertValue> where Col: Column, Expr: Expression + AppearsOnTable, Self: QueryFragment, { fn column_names(&self, mut out: AstPass<'_, '_, crate::sqlite::Sqlite>) -> QueryResult<()> { if let Self::Expression(..) = *self { out.push_identifier(Col::NAME)?; } Ok(()) } } #[cfg(feature = "sqlite")] impl QueryFragment< crate::sqlite::Sqlite, crate::backend::sql_dialect::default_keyword_for_insert::DoesNotSupportDefaultKeyword, > for DefaultableColumnInsertValue> where Expr: QueryFragment, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, crate::sqlite::Sqlite>) -> QueryResult<()> { if let Self::Expression(ref inner) = *self { inner.walk_ast(out.reborrow())?; } Ok(()) } } impl<'a, T, Tab> Insertable for &'a [T] where &'a T: UndecoratedInsertRecord + Insertable, { type Values = BatchInsert>::Values>, Tab, (), false>; fn values(self) -> Self::Values { let values = self.iter().map(Insertable::values).collect::>(); BatchInsert::new(values) } } impl<'a, T, Tab> Insertable for &'a Vec where &'a [T]: Insertable, { type Values = <&'a [T] as Insertable>::Values; fn values(self) -> Self::Values { (&**self).values() } } impl Insertable for Vec where T: Insertable + UndecoratedInsertRecord, { type Values = BatchInsert, Tab, (), false>; fn values(self) -> Self::Values { let values = self.into_iter().map(Insertable::values).collect::>(); BatchInsert::new(values) } } impl Insertable for [T; N] where T: Insertable, { type Values = BatchInsert, Tab, [T::Values; N], true>; fn values(self) -> Self::Values { let values = self.into_iter().map(Insertable::values).collect::>(); BatchInsert::new(values) } } impl<'a, T, Tab, const N: usize> Insertable for &'a [T; N] where T: Insertable, &'a T: Insertable, { // We can reuse the query id for [T; N] here as this // compiles down to the same query type Values = BatchInsert>::Values>, Tab, [T::Values; N], true>; fn values(self) -> Self::Values { let values = self.iter().map(Insertable::values).collect(); BatchInsert::new(values) } } impl Insertable for Box<[T; N]> where T: Insertable, { // We can reuse the query id for [T; N] here as this // compiles down to the same query type Values = BatchInsert, Tab, [T::Values; N], true>; fn values(self) -> Self::Values { let v = Vec::from(self as Box<[T]>); let values = v.into_iter().map(Insertable::values).collect::>(); BatchInsert::new(values) } } mod private { // This helper exists to differentiate between // Insertable implementations for tuples and for single values #[allow(missing_debug_implementations)] pub struct InsertableOptionHelper( pub(crate) Option, pub(crate) std::marker::PhantomData, ); } pub(crate) use self::private::InsertableOptionHelper; impl Insertable for Option where T: Insertable>, InsertableOptionHelper: Insertable, { type Values = as Insertable>::Values; fn values(self) -> Self::Values { InsertableOptionHelper(self, PhantomData).values() } } impl Insertable for InsertableOptionHelper> where T: Insertable, Tab>>, { type Values = ValuesClause>, Tab>; fn values(self) -> Self::Values { ValuesClause::new( self.0 .map(|v| DefaultableColumnInsertValue::Expression(Insertable::values(v).values)) .unwrap_or_default(), ) } } impl<'a, T, Tab> Insertable for &'a Option where Option<&'a T>: Insertable, { type Values = as Insertable>::Values; fn values(self) -> Self::Values { self.as_ref().values() } } impl Insertable for Grouped> where crate::expression::operators::Eq: Insertable, { type Values = as Insertable>::Values; fn values(self) -> Self::Values { self.0.values() } } impl<'a, L, R, Tab> Insertable for &'a Grouped> where &'a crate::expression::operators::Eq: Insertable, { type Values = <&'a crate::expression::operators::Eq as Insertable>::Values; fn values(self) -> Self::Values { self.0.values() } }