feat: update UpstreamCreateInfo conversion to include upstream targets
This commit is contained in:
@@ -2,7 +2,7 @@ use std::sync::Arc;
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelTrait, ColumnTrait, DatabaseConnection, DatabaseTransaction, EntityTrait,
|
||||
ModelTrait, QueryFilter, QuerySelect,
|
||||
ModelTrait, QueryFilter, QuerySelect, TransactionTrait,
|
||||
};
|
||||
|
||||
use database::generated::entities::{upstream, upstream_target};
|
||||
@@ -42,8 +42,40 @@ impl UpstreamService {
|
||||
create_info: UpstreamCreateInfo,
|
||||
tx: Option<&mut DatabaseTransaction>,
|
||||
) -> Result<UpstreamInfo, ServiceError> {
|
||||
let model: upstream::ActiveModel = create_info.into();
|
||||
let r = with_conn!(&*self.connection, tx, conn, { model.insert(*conn).await? });
|
||||
let (upstream_model, upstream_target_models): (
|
||||
upstream::ActiveModel,
|
||||
Vec<upstream_target::ActiveModel>,
|
||||
) = create_info.into();
|
||||
|
||||
// If a transaction was provided use it, otherwise create and own one here.
|
||||
let mut maybe_owned_tx: Option<DatabaseTransaction> = None;
|
||||
let tx_ref: Option<&mut DatabaseTransaction> = if let Some(tx) = tx {
|
||||
Some(tx)
|
||||
} else {
|
||||
maybe_owned_tx = Some(self.connection.begin().await?);
|
||||
maybe_owned_tx.as_mut()
|
||||
};
|
||||
|
||||
let r = with_conn!(&*self.connection, tx_ref, conn, {
|
||||
let created_upstream = upstream_model.insert(*conn).await?;
|
||||
let created_targets = upstream_target::Entity::insert_many(
|
||||
upstream_target_models
|
||||
.into_iter()
|
||||
.map(|mut model| {
|
||||
model.upstream_id = sea_orm::ActiveValue::Set(created_upstream.id);
|
||||
model
|
||||
})
|
||||
.collect::<Vec<upstream_target::ActiveModel>>(),
|
||||
)
|
||||
.exec_with_returning(*conn)
|
||||
.await?;
|
||||
(created_upstream, created_targets)
|
||||
});
|
||||
|
||||
// Commit only if we created the transaction here (we own it).
|
||||
if let Some(t) = maybe_owned_tx.take() {
|
||||
t.commit().await?;
|
||||
}
|
||||
Ok(r.into())
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user