Add many Models to Self
(mut self, models: I)
| 171 | |
| 172 | /// Add many Models to Self |
| 173 | pub fn add_many<M, I>(mut self, models: I) -> Self |
| 174 | where |
| 175 | M: IntoActiveModel<A>, |
| 176 | I: IntoIterator<Item = M>, |
| 177 | { |
| 178 | let mut columns: Vec<_> = <A::Entity as EntityTrait>::Column::iter() |
| 179 | .map(|_| None) |
| 180 | .collect(); |
| 181 | let mut null_value: Vec<Option<Value>> = |
| 182 | std::iter::repeat(None).take(columns.len()).collect(); |
| 183 | let mut all_values: Vec<Vec<SimpleExpr>> = Vec::new(); |
| 184 | |
| 185 | for model in models.into_iter() { |
| 186 | let mut am: A = model.into_active_model(); |
| 187 | self.primary_key = |
| 188 | if !<<A::Entity as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::auto_increment() { |
| 189 | am.get_primary_key_value() |
| 190 | } else { |
| 191 | None |
| 192 | }; |
| 193 | let mut values = Vec::with_capacity(columns.len()); |
| 194 | for (idx, col) in <A::Entity as EntityTrait>::Column::iter().enumerate() { |
| 195 | let av = am.take(col); |
| 196 | match av { |
| 197 | ActiveValue::Set(value) | ActiveValue::Unchanged(value) => { |
| 198 | columns[idx] = Some(col); // mark the column as used |
| 199 | null_value[idx] = Some(value.as_null()); // store the null value with the correct type |
| 200 | values.push(col.save_as(Expr::val(value))); // same as add() above |
| 201 | } |
| 202 | ActiveValue::NotSet => { |
| 203 | values.push(SimpleExpr::Keyword(Keyword::Null)); // indicate a missing value |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | all_values.push(values); |
| 208 | } |
| 209 | |
| 210 | if !all_values.is_empty() { |
| 211 | // filter only used column |
| 212 | self.query.columns(columns.iter().cloned().flatten()); |
| 213 | |
| 214 | // flag used column |
| 215 | self.columns = columns.iter().map(Option::is_some).collect(); |
| 216 | } |
| 217 | |
| 218 | for values in all_values { |
| 219 | // since we've aligned the column set, this never panics |
| 220 | self.query |
| 221 | .values_panic(values.into_iter().enumerate().filter_map(|(i, v)| { |
| 222 | if columns[i].is_some() { |
| 223 | // only if the column is used |
| 224 | if !matches!(v, SimpleExpr::Keyword(Keyword::Null)) { |
| 225 | // use the value expression |
| 226 | Some(v) |
| 227 | } else { |
| 228 | // use null as standin, which must be Some |
| 229 | null_value[i].clone().map(SimpleExpr::Value) |
| 230 | } |
no test coverage detected