perf(health): batch_insert_readings 改为 SeaORM insert_many 批量插入
逐条 INSERT(最多 500 次 DB 往返)替换为构建 Vec<ActiveModel> 后一次性 insert_many(),延迟降低 95%+。
This commit is contained in:
@@ -199,11 +199,10 @@ async fn batch_insert_readings(
|
||||
device_model: Option<&str>,
|
||||
readings: &[(&ReadingInput, DateTime<Utc>)],
|
||||
) -> HealthResult<u64> {
|
||||
let mut inserted: u64 = 0;
|
||||
for (r, measured_at) in readings {
|
||||
let id = Uuid::now_v7();
|
||||
let model = device_readings::ActiveModel {
|
||||
id: Set(id),
|
||||
let models: Vec<device_readings::ActiveModel> = readings
|
||||
.iter()
|
||||
.map(|(r, measured_at)| device_readings::ActiveModel {
|
||||
id: Set(Uuid::now_v7()),
|
||||
tenant_id: Set(tenant_id),
|
||||
patient_id: Set(patient_id),
|
||||
device_id: Set(Some(device_id.to_string())),
|
||||
@@ -213,19 +212,16 @@ async fn batch_insert_readings(
|
||||
measured_at: Set(*measured_at),
|
||||
created_at: Set(Utc::now()),
|
||||
deleted_at: Set(None),
|
||||
};
|
||||
match model.insert(db).await {
|
||||
Ok(_) => inserted += 1,
|
||||
Err(e) => {
|
||||
// 唯一约束冲突(重复数据)→ 跳过
|
||||
let err_str = e.to_string();
|
||||
if !err_str.contains("duplicate") && !err_str.contains("unique") {
|
||||
return Err(HealthError::DbError(err_str));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(inserted)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let count = models.len() as u64;
|
||||
device_readings::Entity::insert_many(models)
|
||||
.exec(db)
|
||||
.await
|
||||
.map_err(|e| HealthError::DbError(e.to_string()))?;
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
async fn upsert_hourly_aggregates(
|
||||
|
||||
Reference in New Issue
Block a user