Skip to content

Commit

Permalink
post_answer関数で複数回答のbulk insertをできるようにする
Browse files Browse the repository at this point in the history
  • Loading branch information
rito528 committed Oct 9, 2023
1 parent 06a7935 commit f506d1a
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 40 deletions.
17 changes: 15 additions & 2 deletions server/infra/entities/src/answers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub form_id: i32,
#[sea_orm(column_type = "Binary(BlobSize::Blob(Some(16)))")]
pub user: Vec<u8>,
pub user: i32,
pub title: String,
pub time_stamp: DateTimeUtc,
}
Expand All @@ -26,6 +25,14 @@ pub enum Relation {
FormMetaData,
#[sea_orm(has_many = "super::real_answers::Entity")]
RealAnswers,
#[sea_orm(
belongs_to = "super::users::Entity",
from = "Column::User",
to = "super::users::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
Users,
}

impl Related<super::form_meta_data::Entity> for Entity {
Expand All @@ -40,4 +47,10 @@ impl Related<super::real_answers::Entity> for Entity {
}
}

impl Related<super::users::Entity> for Entity {
fn to() -> RelationDef {
Relation::Users.def()
}
}

impl ActiveModelBehavior for ActiveModel {}
18 changes: 18 additions & 0 deletions server/infra/entities/src/form_meta_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ pub struct Model {
pub title: String,
pub description: Option<String>,
pub created_at: DateTimeUtc,
pub created_by: i32,
pub updated_at: DateTimeUtc,
pub updated_by: i32,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
Expand All @@ -25,6 +27,22 @@ pub enum Relation {
FormWebhooks,
#[sea_orm(has_many = "super::response_period::Entity")]
ResponsePeriod,
#[sea_orm(
belongs_to = "super::users::Entity",
from = "Column::CreatedBy",
to = "super::users::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
Users2,
#[sea_orm(
belongs_to = "super::users::Entity",
from = "Column::UpdatedBy",
to = "super::users::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
Users1,
}

impl Related<super::answers::Entity> for Entity {
Expand Down
3 changes: 1 addition & 2 deletions server/infra/entities/src/form_questions.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.1
use sea_orm::entity::prelude::*;

use super::sea_orm_active_enums::QuestionType;
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "form_questions")]
Expand Down
1 change: 1 addition & 0 deletions server/infra/entities/src/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ pub mod form_webhooks;
pub mod real_answers;
pub mod response_period;
pub mod sea_orm_active_enums;
pub mod users;
15 changes: 9 additions & 6 deletions server/infra/entities/src/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.1
pub use super::{
answers::Entity as Answers, default_answer_titles::Entity as DefaultAnswerTitles,
form_choices::Entity as FormChoices, form_meta_data::Entity as FormMetaData,
form_questions::Entity as FormQuestions, form_webhooks::Entity as FormWebhooks,
real_answers::Entity as RealAnswers, response_period::Entity as ResponsePeriod,
};
pub use super::answers::Entity as Answers;
pub use super::default_answer_titles::Entity as DefaultAnswerTitles;
pub use super::form_choices::Entity as FormChoices;
pub use super::form_meta_data::Entity as FormMetaData;
pub use super::form_questions::Entity as FormQuestions;
pub use super::form_webhooks::Entity as FormWebhooks;
pub use super::real_answers::Entity as RealAnswers;
pub use super::response_period::Entity as ResponsePeriod;
pub use super::users::Entity as Users;
27 changes: 27 additions & 0 deletions server/infra/entities/src/users.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.1
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "users")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(column_type = "Binary(BlobSize::Blob(Some(16)))")]
pub uuid: Vec<u8>,
pub name: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::answers::Entity")]
Answers,
}

impl Related<super::answers::Entity> for Entity {
fn to() -> RelationDef {
Relation::Answers.def()
}
}

impl ActiveModelBehavior for ActiveModel {}
65 changes: 35 additions & 30 deletions server/infra/resource/src/database/form.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use async_trait::async_trait;
use chrono::Utc;
use domain::form::models::{
Answer, DefaultAnswerTitle, FormDescription, FormId, FormQuestionUpdateSchema, FormTitle,
DefaultAnswerTitle, FormDescription, FormId, FormQuestionUpdateSchema, FormTitle,
FormUpdateTargets, OffsetAndLimit, PostedAnswers,
};
use entities::{
Expand All @@ -19,11 +18,11 @@ use itertools::Itertools;
use num_traits::cast::FromPrimitive;
use regex::Regex;
use sea_orm::{
prelude::Uuid,
sea_query::{Expr, SimpleExpr},
ActiveEnum, ActiveModelTrait, ActiveValue,
ActiveValue::Set,
ColumnTrait, EntityTrait, ModelTrait, QueryFilter, QueryOrder, QuerySelect,
ColumnTrait, ConnectionTrait, DatabaseBackend, EntityTrait, ModelTrait, QueryFilter,
QueryOrder, QuerySelect, Statement,
};

use crate::{
Expand All @@ -44,7 +43,9 @@ impl FormDatabase for ConnectionPool {
title: Set(title.title().to_owned()),
description: Set(description.to_owned()),
created_at: Default::default(),
created_by: Set(1),
updated_at: Default::default(),
updated_by: Set(1),
}
.insert(&self.pool)
.await?
Expand Down Expand Up @@ -405,36 +406,39 @@ impl FormDatabase for ConnectionPool {
},
);

let id = answers::ActiveModel {
id: Default::default(),
form_id: Set(answer.form_id.to_owned()),
user: Set(answer.uuid.to_owned().as_ref().to_vec()),
title: Set(embed_title),
time_stamp: Set(Utc::now()),
}
.insert(&self.pool)
.await?
.id;
let id = self.pool.execute(Statement::from_sql_and_values(
DatabaseBackend::MySql,
"INSERT INTO answers (form_id, user, title) VALUES (?, (SELECT id FROM users WHERE uuid = UUID_TO_BIN(?)), ?)",
[answer.form_id.to_owned().into(), answer.uuid.to_string().into(), embed_title.into()])
)
.await?
.last_insert_id();

let real_answer_models = answer
let params = answer
.answers
.into_iter()
.map(
|Answer {
question_id,
answer,
..
}| real_answers::ActiveModel {
id: Default::default(),
answer_id: Set(id),
question_id: Set(question_id.into()),
answer: Set(answer),
},
)
.map(|answer| {
vec![
id.to_string(),
answer.question_id.to_string(),
answer.answer,
]
})
.collect_vec();

RealAnswers::insert_many(real_answer_models)
.exec(&self.pool)
self.pool
.execute(Statement::from_sql_and_values(
DatabaseBackend::MySql,
format!(
"INSERT INTO real_answers (answer_id, question_id, answer) VALUES {}",
vec!["(?, ?, ?)"; params.len()].iter().join(", ")
),
params
.iter()
.flatten()
.map(|value| value.into())
.collect_vec(),
))
.await?;

Ok(())
Expand Down Expand Up @@ -466,7 +470,8 @@ impl FormDatabase for ConnectionPool {
.collect_vec();

Ok(PostedAnswersDto {
uuid: Uuid::from_slice(answer.user.as_slice())?,
// uuid: Uuid::from_slice(answer.user.as_slice())?,
uuid: todo!(),
timestamp: answer.time_stamp,
form_id: answer.form_id,
title: Some(answer.title),
Expand Down

0 comments on commit f506d1a

Please sign in to comment.