use crate::{ error::*, ActiveModelTrait, DatabaseConnection, DbBackend, EntityTrait, Insert, PrimaryKeyTrait, Statement, TryFromU64, }; use sea_query::{FromValueTuple, InsertStatement, ValueTuple}; use std::{future::Future, marker::PhantomData}; #[derive(Debug)] pub struct Inserter where A: ActiveModelTrait, { primary_key: Option, query: InsertStatement, model: PhantomData, } #[derive(Debug)] pub struct InsertResult where A: ActiveModelTrait, { pub last_insert_id: <<::Entity as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType, } impl Insert where A: ActiveModelTrait, { #[allow(unused_mut)] pub fn exec<'a>( self, db: &'a DatabaseConnection, ) -> impl Future, DbErr>> + 'a where A: 'a, { // so that self is dropped before entering await let mut query = self.query; if db.get_database_backend() == DbBackend::Postgres { use crate::{sea_query::Query, Iterable}; if ::PrimaryKey::iter().count() > 0 { query.returning( Query::select() .columns(::PrimaryKey::iter()) .take(), ); } } Inserter::::new(self.primary_key, query).exec(db) } } impl Inserter where A: ActiveModelTrait, { pub fn new(primary_key: Option, query: InsertStatement) -> Self { Self { primary_key, query, model: PhantomData, } } pub fn exec<'a>( self, db: &'a DatabaseConnection, ) -> impl Future, DbErr>> + 'a where A: 'a, { let builder = db.get_database_backend(); exec_insert(self.primary_key, builder.build(&self.query), db) } } // Only Statement impl Send async fn exec_insert( primary_key: Option, statement: Statement, db: &DatabaseConnection, ) -> Result, DbErr> where A: ActiveModelTrait, { type PrimaryKey = <::Entity as EntityTrait>::PrimaryKey; type ValueTypeOf = as PrimaryKeyTrait>::ValueType; let last_insert_id_opt = match db.get_database_backend() { DbBackend::Postgres => { use crate::{sea_query::Iden, Iterable}; let cols = PrimaryKey::::iter() .map(|col| col.to_string()) .collect::>(); let res = db.query_one(statement).await?.unwrap(); res.try_get_many("", cols.as_ref()).ok() } _ => { let last_insert_id = db.execute(statement).await?.last_insert_id(); ValueTypeOf::::try_from_u64(last_insert_id).ok() } }; let last_insert_id = match last_insert_id_opt { Some(last_insert_id) => last_insert_id, None => match primary_key { Some(value_tuple) => FromValueTuple::from_value_tuple(value_tuple), None => return Err(DbErr::Exec("Fail to unpack last_insert_id".to_owned())), }, }; Ok(InsertResult { last_insert_id }) }