1use std::borrow::Cow;
59
60use chrono::{DateTime, Utc};
61
62use crate::column::{Assignment, Column, ColumnName, IntoQuery};
63use crate::driver::InsertOutcome;
64use crate::error::{OrmError, Result};
65use crate::exec::{Access, Executor, SqlTarget, Target};
66use crate::ir::{DeleteIr, Expr, InsertIr, OnConflict, TableRef};
67use crate::model::{KeyKind, Model, PrimaryKey};
68use crate::query::{Builder, TableBuilder};
69use crate::row::{Row, decode_error};
70use crate::sql::{Dialect, Statement, render_truncate, render_update_from};
71use crate::value::{Field, Value};
72
73#[derive(Clone, Debug)]
88#[non_exhaustive]
89pub enum ConflictUpdate {
90 All,
93 Column(Cow<'static, str>),
95 Set(Assignment),
98}
99
100impl From<&str> for ConflictUpdate {
101 fn from(column: &str) -> Self {
102 ConflictUpdate::Column(Cow::Owned(column.to_owned()))
103 }
104}
105
106impl From<String> for ConflictUpdate {
107 fn from(column: String) -> Self {
108 ConflictUpdate::Column(Cow::Owned(column))
109 }
110}
111
112impl<M, T> From<Column<M, T>> for ConflictUpdate {
113 fn from(column: Column<M, T>) -> Self {
114 ConflictUpdate::Column(Cow::Owned(column.column_name().into_owned()))
115 }
116}
117
118impl<M, T> From<&Column<M, T>> for ConflictUpdate {
119 fn from(column: &Column<M, T>) -> Self {
120 ConflictUpdate::Column(Cow::Owned(column.column_name().into_owned()))
121 }
122}
123
124impl From<Assignment> for ConflictUpdate {
125 fn from(assignment: Assignment) -> Self {
126 ConflictUpdate::Set(assignment)
127 }
128}
129
130struct Rows {
137 columns: Vec<Cow<'static, str>>,
138 values: Vec<Vec<Expr>>,
139}
140
141impl Rows {
142 fn collect<R, C, V>(table: &str, rows: impl IntoIterator<Item = R>) -> Result<Rows>
145 where
146 R: IntoIterator<Item = (C, V)>,
147 C: Into<Cow<'static, str>>,
148 V: Into<Value>,
149 {
150 let mut columns: Vec<Cow<'static, str>> = Vec::new();
151 let mut values: Vec<Vec<Expr>> = Vec::new();
152 for (index, row) in rows.into_iter().enumerate() {
153 let pairs: Vec<(Cow<'static, str>, Value)> = row
154 .into_iter()
155 .map(|(column, value)| (column.into(), value.into()))
156 .collect();
157 if index == 0 {
158 columns = pairs.iter().map(|(column, _)| column.clone()).collect();
159 }
160 if pairs.len() != columns.len() {
161 return Err(OrmError::invalid(format!(
162 "row {} of an insert into `{table}` has {} columns, the first has {}",
163 index + 1,
164 pairs.len(),
165 columns.len()
166 )));
167 }
168 let mut ordered = Vec::with_capacity(columns.len());
169 for column in &columns {
170 let value = pairs
171 .iter()
172 .find(|(name, _)| name == column)
173 .map(|(_, value)| value.clone())
174 .ok_or_else(|| {
175 OrmError::invalid(format!(
176 "row {} of an insert into `{table}` has no `{column}` column",
177 index + 1
178 ))
179 })?;
180 ordered.push(Expr::Value(value));
181 }
182 values.push(ordered);
183 }
184 Ok(Rows { columns, values })
185 }
186}
187
188fn bound_values(expr: &Expr) -> usize {
190 match expr {
191 Expr::Value(_) => 1,
192 Expr::Raw { values, .. } => values.len(),
193 Expr::Function { args, .. } => args.iter().map(bound_values).sum(),
194 Expr::Arithmetic { left, right, .. } => bound_values(left) + bound_values(right),
195 Expr::Aggregate { arg, .. } => arg.as_deref().map_or(0, bound_values),
196 Expr::Column(_) | Expr::All { .. } | Expr::Excluded { .. } => 0,
197 _ => 1,
198 }
199}
200
201fn split(mut insert: InsertIr, dialect: Option<Dialect>) -> Vec<InsertIr> {
204 if insert.select.is_some() || insert.rows.len() <= 1 {
205 return vec![insert];
206 }
207 if insert.columns.is_empty() {
208 let count = insert.rows.len();
210 insert.rows = vec![Vec::new()];
211 return vec![insert; count];
212 }
213 let Some(dialect) = dialect else {
214 return vec![insert];
215 };
216 let reserved: usize = match &insert.on_conflict {
217 Some(OnConflict::Update { sets, .. }) => {
218 sets.iter().map(|(_, expr)| bound_values(expr)).sum()
219 }
220 _ => 0,
221 };
222 let per_row = insert
223 .rows
224 .iter()
225 .map(|row| row.iter().map(bound_values).sum::<usize>())
226 .max()
227 .unwrap_or(0)
228 .max(1);
229 let budget = dialect.max_bind_values().saturating_sub(reserved);
230 let rows_per_statement = (budget / per_row).max(1);
231 if insert.rows.len() <= rows_per_statement {
232 return vec![insert];
233 }
234 let rows = std::mem::take(&mut insert.rows);
235 rows.chunks(rows_per_statement)
236 .map(|part| InsertIr {
237 rows: part.to_vec(),
238 ..insert.clone()
239 })
240 .collect()
241}
242
243async fn run_inserts(target: &Target<'_>, inserts: Vec<InsertIr>) -> Result<InsertOutcome> {
246 if inserts.len() <= 1 {
247 return match inserts.first() {
248 Some(insert) => target.insert(insert).await,
249 None => Ok(InsertOutcome::default()),
250 };
251 }
252 match target.begin_atomic().await? {
253 Some(tx) => {
254 let nested = target.on_transaction(&tx);
255 let result = run_each(&nested, &inserts).await;
256 drop(nested);
257 finish(tx, result).await
258 }
259 None => run_each(target, &inserts).await,
260 }
261}
262
263async fn run_each(target: &Target<'_>, inserts: &[InsertIr]) -> Result<InsertOutcome> {
264 let mut total = InsertOutcome::default();
265 for insert in inserts {
266 let outcome = target.insert(insert).await?;
267 total.rows_affected += outcome.rows_affected;
268 total.returned.extend(outcome.returned);
269 if total.last_insert_id.is_none() {
270 total.last_insert_id = outcome.last_insert_id;
271 }
272 }
273 Ok(total)
274}
275
276async fn finish<T>(tx: crate::exec::OwnTransaction, result: Result<T>) -> Result<T> {
278 match result {
279 Ok(value) => {
280 tx.commit().await?;
281 Ok(value)
282 }
283 Err(error) => {
284 if let Err(rollback) = tx.rollback().await {
285 tracing::warn!(target: "navree_orm", error = %rollback, "rolling back a bulk write failed");
286 }
287 Err(error)
288 }
289 }
290}
291
292fn conflict_sets(
297 columns: &[Cow<'static, str>],
298 unique_by: &[Cow<'static, str>],
299 skipped: &[&str],
300 update: Vec<ConflictUpdate>,
301) -> Result<Vec<(Cow<'static, str>, Expr)>> {
302 let mut sets: Vec<(Cow<'static, str>, Expr)> = Vec::new();
303 let mut put = |column: Cow<'static, str>, expr: Expr| match sets
304 .iter_mut()
305 .find(|(existing, _)| *existing == column)
306 {
307 Some(existing) => existing.1 = expr,
308 None => sets.push((column, expr)),
309 };
310 for item in update {
311 match item {
312 ConflictUpdate::All => {
313 for column in columns {
314 if !unique_by.contains(column) && !skipped.contains(&column.as_ref()) {
315 put(column.clone(), Expr::excluded(column.clone()));
316 }
317 }
318 }
319 ConflictUpdate::Column(column) => put(column.clone(), Expr::excluded(column)),
320 ConflictUpdate::Set(assignment) => {
321 let (column, expr) = assignment.into_set().map_err(OrmError::invalid)?;
322 put(column, expr);
323 }
324 }
325 }
326 Ok(sets)
327}
328
329fn upsert_conflict(
332 unique_by: Vec<Cow<'static, str>>,
333 sets: Vec<(Cow<'static, str>, Expr)>,
334) -> OnConflict {
335 if sets.is_empty() {
336 OnConflict::Ignore { target: unique_by }
337 } else {
338 OnConflict::Update {
339 target: unique_by,
340 sets,
341 }
342 }
343}
344
345fn sql_only<'t, 'a>(target: &'t Target<'a>, feature: &str) -> Result<&'t SqlTarget<'a>> {
348 match target {
349 Target::Sql(sql) => Ok(sql),
350 Target::Document(_) => Err(OrmError::unsupported(
351 feature.to_owned(),
352 target.context().database(),
353 )),
354 }
355}
356
357fn returned_key<K: Field>(outcome: &InsertOutcome, table: &str, column: &str) -> Result<K> {
359 if let Some(row) = outcome.returned.first() {
360 return row
361 .field::<K>(column)
362 .map_err(|error| decode_error(table.to_owned(), column, K::type_name(), &error));
363 }
364 match outcome.last_insert_id {
365 Some(id) if outcome.rows_affected > 0 => K::from_value(Value::U64(id))
366 .map_err(|error| decode_error(table.to_owned(), column, K::type_name(), &error)),
367 _ => Err(OrmError::invalid(format!(
368 "the database did not return the `{column}` of the row inserted into `{table}`"
369 ))),
370 }
371}
372
373async fn truncate_table(target: &Target<'_>, table: &str, cascade: bool) -> Result<()> {
375 let sql = match target {
376 Target::Sql(sql) => sql,
377 Target::Document(_) => {
378 target
379 .delete(&DeleteIr {
380 table: TableRef::new(table.to_owned()),
381 wheres: Vec::new(),
382 })
383 .await?;
384 return Ok(());
385 }
386 };
387 let dialect = sql.dialect();
388 let statements = render_truncate(table, cascade, dialect);
389 if dialect != Dialect::Sqlite {
390 for statement in &statements {
391 sql.execute(statement).await?;
392 }
393 return Ok(());
394 }
395 let has_sequences = sql
398 .query_one(&Statement {
399 sql: "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_sequence'"
400 .to_owned(),
401 values: Vec::new(),
402 dialect,
403 })
404 .await?
405 .is_some();
406 let statements: Vec<&Statement> = statements
407 .iter()
408 .filter(|statement| has_sequences || !statement.sql.contains("sqlite_sequence"))
409 .collect();
410 match target.begin_atomic().await? {
411 Some(tx) => {
412 let nested = target.on_transaction(&tx);
413 let result = async {
414 let nested_sql = sql_only(&nested, "truncate")?;
415 for statement in &statements {
416 nested_sql.execute(statement).await?;
417 }
418 Ok(())
419 }
420 .await;
421 drop(nested);
422 finish(tx, result).await
423 }
424 None => {
425 for statement in statements {
426 sql.execute(statement).await?;
427 }
428 Ok(())
429 }
430 }
431}
432
433impl TableBuilder {
438 fn insert_table(&self, what: &str) -> Result<Cow<'static, str>> {
440 let ir = self.ir();
441 ir.check()?;
442 if ir.table.subquery.is_some() {
443 return Err(OrmError::invalid(format!(
444 "cannot {what} into the subquery `{}`; name a table",
445 ir.table.qualifier()
446 )));
447 }
448 Ok(ir.table.name.clone())
449 }
450
451 async fn run_insert<E: Executor + ?Sized>(
453 exec: &E,
454 route: crate::Route<'_>,
455 insert: InsertIr,
456 ) -> Result<InsertOutcome> {
457 let target = exec.target_routed(Access::Write, route).await?;
458 let parts = split(insert, target.dialect());
459 run_inserts(&target, parts).await
460 }
461
462 pub async fn insert<E, R, C, V>(
476 self,
477 exec: &E,
478 rows: impl IntoIterator<Item = R>,
479 ) -> Result<u64>
480 where
481 E: Executor + ?Sized,
482 R: IntoIterator<Item = (C, V)>,
483 C: Into<Cow<'static, str>>,
484 V: Into<Value>,
485 {
486 let table = self.insert_table("insert")?;
487 let rows = Rows::collect(&table, rows)?;
488 if rows.values.is_empty() {
489 return Ok(0);
490 }
491 let insert = InsertIr::new(table, rows.columns, rows.values);
492 Ok(Self::run_insert(exec, self.route(), insert)
493 .await?
494 .rows_affected)
495 }
496
497 pub async fn insert_get_id<K: Field>(
508 self,
509 exec: &(impl Executor + ?Sized),
510 row: impl IntoIterator<Item = (impl Into<Cow<'static, str>>, impl Into<Value>)>,
511 ) -> Result<K> {
512 self.insert_get_key(exec, row, "id").await
513 }
514
515 pub async fn insert_get_key<K: Field>(
518 self,
519 exec: &(impl Executor + ?Sized),
520 row: impl IntoIterator<Item = (impl Into<Cow<'static, str>>, impl Into<Value>)>,
521 column: &str,
522 ) -> Result<K> {
523 let table = self.insert_table("insert")?;
524 let rows = Rows::collect(&table, [row])?;
525 let insert = InsertIr::new(table.clone(), rows.columns, rows.values)
526 .returning(vec![Cow::Owned(column.to_owned())]);
527 let outcome = Self::run_insert(exec, self.route(), insert).await?;
528 returned_key(&outcome, &table, column)
529 }
530
531 pub async fn insert_or_ignore<E, R, C, V>(
537 self,
538 exec: &E,
539 rows: impl IntoIterator<Item = R>,
540 ) -> Result<u64>
541 where
542 E: Executor + ?Sized,
543 R: IntoIterator<Item = (C, V)>,
544 C: Into<Cow<'static, str>>,
545 V: Into<Value>,
546 {
547 let table = self.insert_table("insert")?;
548 let rows = Rows::collect(&table, rows)?;
549 if rows.values.is_empty() {
550 return Ok(0);
551 }
552 let insert = InsertIr::new(table, rows.columns, rows.values)
553 .on_conflict(OnConflict::Ignore { target: Vec::new() });
554 Ok(Self::run_insert(exec, self.route(), insert)
555 .await?
556 .rows_affected)
557 }
558
559 pub async fn insert_or_ignore_returning<E, R, C, V>(
574 self,
575 exec: &E,
576 rows: impl IntoIterator<Item = R>,
577 returning: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
578 unique_by: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
579 ) -> Result<Vec<Row>>
580 where
581 E: Executor + ?Sized,
582 R: IntoIterator<Item = (C, V)>,
583 C: Into<Cow<'static, str>>,
584 V: Into<Value>,
585 {
586 let table = self.insert_table("insert")?;
587 let returning: Vec<Cow<'static, str>> = returning.into_iter().map(Into::into).collect();
588 if returning.is_empty() {
589 return Err(OrmError::invalid(format!(
590 "insert_or_ignore_returning into `{table}` names no column to return"
591 )));
592 }
593 let rows = Rows::collect(&table, rows)?;
594 if rows.values.is_empty() {
595 return Ok(Vec::new());
596 }
597 let target = exec.target_routed(Access::Write, self.route()).await?;
598 if target.dialect() == Some(Dialect::MySql) {
599 return Err(OrmError::unsupported(
600 "returning the rows of an insert (MySQL has no RETURNING; use insert_or_ignore, then select the rows)",
601 "MySQL",
602 ));
603 }
604 let insert = InsertIr::new(table, rows.columns, rows.values)
605 .returning(returning)
606 .on_conflict(OnConflict::Ignore {
607 target: unique_by.into_iter().map(Into::into).collect(),
608 });
609 let parts = split(insert, target.dialect());
610 Ok(run_inserts(&target, parts).await?.returned)
611 }
612
613 pub async fn insert_using<E: Executor + ?Sized>(
625 self,
626 exec: &E,
627 columns: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
628 query: impl IntoQuery,
629 ) -> Result<u64> {
630 let table = self.insert_table("insert")?;
631 let mut insert = InsertIr::new(
632 table,
633 columns.into_iter().map(Into::into).collect(),
634 Vec::new(),
635 );
636 insert.select = Some(Box::new(query.into_query()));
637 Ok(Self::run_insert(exec, self.route(), insert)
638 .await?
639 .rows_affected)
640 }
641
642 pub async fn insert_or_ignore_using<E: Executor + ?Sized>(
645 self,
646 exec: &E,
647 columns: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
648 query: impl IntoQuery,
649 ) -> Result<u64> {
650 let table = self.insert_table("insert")?;
651 let mut insert = InsertIr::new(
652 table,
653 columns.into_iter().map(Into::into).collect(),
654 Vec::new(),
655 )
656 .on_conflict(OnConflict::Ignore { target: Vec::new() });
657 insert.select = Some(Box::new(query.into_query()));
658 Ok(Self::run_insert(exec, self.route(), insert)
659 .await?
660 .rows_affected)
661 }
662
663 pub async fn upsert<E, R, C, V, U>(
684 self,
685 exec: &E,
686 rows: impl IntoIterator<Item = R>,
687 unique_by: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
688 update: impl IntoIterator<Item = U>,
689 ) -> Result<u64>
690 where
691 E: Executor + ?Sized,
692 R: IntoIterator<Item = (C, V)>,
693 C: Into<Cow<'static, str>>,
694 V: Into<Value>,
695 U: Into<ConflictUpdate>,
696 {
697 let table = self.insert_table("upsert")?;
698 let unique_by: Vec<Cow<'static, str>> = unique_by.into_iter().map(Into::into).collect();
699 if unique_by.is_empty() {
700 return Err(OrmError::invalid(format!(
701 "an upsert into `{table}` needs the unique columns its rows conflict on"
702 )));
703 }
704 let rows = Rows::collect(&table, rows)?;
705 if rows.values.is_empty() {
706 return Ok(0);
707 }
708 let update: Vec<ConflictUpdate> = update.into_iter().map(Into::into).collect();
709 let sets = conflict_sets(&rows.columns, &unique_by, &[], update)?;
710 let insert = InsertIr::new(table, rows.columns, rows.values)
711 .on_conflict(upsert_conflict(unique_by, sets));
712 Ok(Self::run_insert(exec, self.route(), insert)
713 .await?
714 .rows_affected)
715 }
716
717 pub async fn update_or_insert<E, F, I>(
737 self,
738 exec: &E,
739 attributes: impl IntoIterator<Item = Assignment>,
740 values: F,
741 ) -> Result<bool>
742 where
743 E: Executor + ?Sized,
744 F: FnOnce(bool) -> I,
745 I: IntoIterator<Item = Assignment>,
746 {
747 let table = self.insert_table("insert")?;
748 let attributes: Vec<Assignment> = attributes.into_iter().collect();
749 let query = attributes.iter().fold(self, |query, attribute| {
750 query.where_(attribute.to_filter(None))
751 });
752 let target = exec.target_routed(Access::Write, query.route()).await?;
754 let exists = target.exists(query.ir()).await?;
755 let values: Vec<Assignment> = values(exists).into_iter().collect();
756 if exists {
757 if values.is_empty() {
758 return Ok(true);
759 }
760 let sets = values
761 .into_iter()
762 .map(|assignment| assignment.into_set().map_err(OrmError::invalid))
763 .collect::<Result<Vec<_>>>()?;
764 let (table, wheres) = query.write_target("update", target.dialect())?;
765 let changed = target
766 .update(&crate::ir::UpdateIr {
767 table,
768 sets,
769 wheres,
770 })
771 .await?;
772 return Ok(changed > 0);
773 }
774 let mut row: Vec<(Cow<'static, str>, Value)> = Vec::new();
775 for assignment in attributes.into_iter().chain(values) {
776 let column = Cow::Owned(assignment.column().to_owned());
777 let value = assignment.assigned_value().cloned().ok_or_else(|| {
778 OrmError::invalid(format!(
779 "update_or_insert into `{table}` needs a value for `{column}`, not an expression"
780 ))
781 })?;
782 match row.iter_mut().find(|(existing, _)| *existing == column) {
783 Some(existing) => existing.1 = value,
784 None => row.push((column, value)),
785 }
786 }
787 let rows = Rows::collect(&table, [row])?;
788 let insert = InsertIr::new(table, rows.columns, rows.values);
789 let outcome = target.insert(&insert).await?;
790 Ok(outcome.rows_affected > 0)
791 }
792
793 pub async fn update_from<E: Executor + ?Sized>(
810 self,
811 exec: &E,
812 assignments: impl IntoIterator<Item = Assignment>,
813 ) -> Result<u64> {
814 let sets = assignments
815 .into_iter()
816 .map(|assignment| assignment.into_set().map_err(OrmError::invalid))
817 .collect::<Result<Vec<_>>>()?;
818 let target = exec.target_routed(Access::Write, self.route()).await?;
819 update_from_on(&target, self.into_ir(), sets).await
820 }
821
822 pub async fn truncate<E: Executor + ?Sized>(self, exec: &E) -> Result<()> {
825 let table = self.insert_table("truncate")?;
826 let target = exec.target_routed(Access::Write, self.route()).await?;
827 truncate_table(&target, &table, false).await
828 }
829
830 pub async fn truncate_cascade<E: Executor + ?Sized>(self, exec: &E) -> Result<()> {
833 let table = self.insert_table("truncate")?;
834 let target = exec.target_routed(Access::Write, self.route()).await?;
835 if target.dialect() != Some(Dialect::Postgres) {
836 return Err(OrmError::unsupported(
837 "TRUNCATE … CASCADE",
838 target.context().database(),
839 ));
840 }
841 truncate_table(&target, &table, true).await
842 }
843}
844
845async fn update_from_on(
847 target: &Target<'_>,
848 query: crate::ir::QueryIr,
849 sets: Vec<(Cow<'static, str>, Expr)>,
850) -> Result<u64> {
851 query.check()?;
852 let sql = sql_only(target, "update_from")?;
853 if query.limit.is_some()
854 || query.offset.is_some()
855 || !query.groups.is_empty()
856 || !query.unions.is_empty()
857 {
858 return Err(OrmError::invalid(format!(
859 "update_from on `{}` takes joins and conditions only (no limit, offset, groups or unions)",
860 query.table.qualifier()
861 )));
862 }
863 let statement = render_update_from(
864 &query.table,
865 &sets,
866 &query.joins,
867 &query.wheres,
868 sql.syntax(),
869 )?;
870 Ok(sql.execute(&statement).await?.rows_affected)
871}
872
873fn fill<M: Model>(models: impl IntoIterator<Item = M>, now: DateTime<Utc>) -> Result<Vec<M>> {
880 let meta = M::meta();
881 let mut filled = Vec::new();
882 for mut model in models {
883 if model.key().is_empty() {
884 match meta.key_kind() {
885 KeyKind::Increments => {}
886 KeyKind::Manual => {
887 return Err(OrmError::MissingKey {
888 model: Cow::Borrowed(meta.name()),
889 column: meta.key_column(),
890 });
891 }
892 kind => {
893 let key = M::Key::generate(kind).ok_or_else(|| {
894 OrmError::invalid(format!(
895 "{}'s key type {kind:?} cannot be generated for its key field of type {}",
896 meta.name(),
897 M::Key::type_name()
898 ))
899 })?;
900 model.set_key(key);
901 }
902 }
903 }
904 for column in [meta.created_at(), meta.updated_at()].into_iter().flatten() {
905 if model.timestamp_is_empty(column) {
906 model.touch_timestamp(column, now)?;
907 }
908 }
909 filled.push(model);
910 }
911 Ok(filled)
912}
913
914type InsertGroup = (Vec<Cow<'static, str>>, Vec<Vec<Expr>>);
916
917fn model_inserts<M: Model>(models: &[M]) -> Result<Vec<InsertIr>> {
921 let meta = M::meta();
922 let mut without_key: Option<InsertGroup> = None;
923 let mut with_key: Option<InsertGroup> = None;
924 for model in models {
925 let skip_key = meta.key_kind() == KeyKind::Increments && model.key().is_empty();
926 let (columns, row): (Vec<Cow<'static, str>>, Vec<Expr>) = model
927 .values()?
928 .into_iter()
929 .filter(|(column, _)| !(skip_key && *column == meta.key_column()))
930 .map(|(column, value)| (Cow::Borrowed(column), Expr::Value(value)))
931 .unzip();
932 let group = if skip_key {
933 &mut without_key
934 } else {
935 &mut with_key
936 };
937 group
938 .get_or_insert_with(|| (columns, Vec::new()))
939 .1
940 .push(row);
941 }
942 Ok([without_key, with_key]
943 .into_iter()
944 .flatten()
945 .map(|(columns, rows)| InsertIr::new(meta.table(), columns, rows))
946 .collect())
947}
948
949impl<M: Model> Builder<M> {
950 async fn insert_models<E: Executor + ?Sized>(
953 exec: &E,
954 route: crate::Route<'_>,
955 models: Option<Vec<M>>,
956 fill_models: bool,
957 on_conflict: impl Fn(&[Cow<'static, str>]) -> Result<Option<OnConflict>>,
958 ) -> Result<u64> {
959 let Some(models) = models.filter(|models| !models.is_empty()) else {
960 return Ok(0);
961 };
962 let target = exec.target_routed(Access::Write, route).await?;
963 let models = if fill_models {
964 fill(models, target.context().now().await)?
965 } else {
966 models
967 };
968 let mut parts = Vec::new();
969 for mut insert in model_inserts(&models)? {
970 insert.on_conflict = on_conflict(&insert.columns)?;
971 parts.extend(split(insert, target.dialect()));
972 }
973 Ok(run_inserts(&target, parts).await?.rows_affected)
974 }
975
976 pub async fn insert<E: Executor + ?Sized>(
983 self,
984 exec: &E,
985 models: impl IntoIterator<Item = M>,
986 ) -> Result<u64> {
987 Self::insert_models(
988 exec,
989 self.route(),
990 Some(models.into_iter().collect()),
991 false,
992 |_| Ok(None),
993 )
994 .await
995 }
996
997 pub async fn insert_or_ignore<E: Executor + ?Sized>(
1000 self,
1001 exec: &E,
1002 models: impl IntoIterator<Item = M>,
1003 ) -> Result<u64> {
1004 Self::insert_models(
1005 exec,
1006 self.route(),
1007 Some(models.into_iter().collect()),
1008 false,
1009 |_| Ok(Some(OnConflict::Ignore { target: Vec::new() })),
1010 )
1011 .await
1012 }
1013
1014 pub async fn fill_for_insert<E: Executor + ?Sized>(
1019 self,
1020 exec: &E,
1021 models: impl IntoIterator<Item = M>,
1022 ) -> Result<Vec<M>> {
1023 let target = exec.target_routed(Access::Read, self.route()).await?;
1024 fill(models, target.context().now().await)
1025 }
1026
1027 pub async fn fill_and_insert<E: Executor + ?Sized>(
1040 self,
1041 exec: &E,
1042 models: impl IntoIterator<Item = M>,
1043 ) -> Result<u64> {
1044 Self::insert_models(
1045 exec,
1046 self.route(),
1047 Some(models.into_iter().collect()),
1048 true,
1049 |_| Ok(None),
1050 )
1051 .await
1052 }
1053
1054 pub async fn fill_and_insert_or_ignore<E: Executor + ?Sized>(
1057 self,
1058 exec: &E,
1059 models: impl IntoIterator<Item = M>,
1060 ) -> Result<u64> {
1061 Self::insert_models(
1062 exec,
1063 self.route(),
1064 Some(models.into_iter().collect()),
1065 true,
1066 |_| Ok(Some(OnConflict::Ignore { target: Vec::new() })),
1067 )
1068 .await
1069 }
1070
1071 pub async fn fill_and_insert_get_id<E: Executor + ?Sized>(
1074 self,
1075 exec: &E,
1076 model: M,
1077 ) -> Result<M::Key> {
1078 let meta = M::meta();
1079 let target = exec.target_routed(Access::Write, self.route()).await?;
1080 let mut filled = fill([model], target.context().now().await)?;
1081 let model = filled.remove(0);
1082 let assigned = meta.key_kind() == KeyKind::Increments && model.key().is_empty();
1083 let mut inserts = model_inserts(std::slice::from_ref(&model))?;
1084 let mut insert = inserts.remove(0);
1085 if assigned {
1086 insert.returning = vec![Cow::Borrowed(meta.key_column())];
1087 }
1088 let outcome = target.insert(&insert).await?;
1089 if assigned {
1090 let key: Value = returned_key(&outcome, meta.table(), meta.key_column())?;
1091 return M::Key::from_value(key).map_err(|error| {
1092 decode_error(meta.name(), meta.key_column(), M::Key::type_name(), &error)
1093 });
1094 }
1095 Ok(model.key())
1096 }
1097
1098 pub async fn upsert<E, U>(
1113 self,
1114 exec: &E,
1115 models: impl IntoIterator<Item = M>,
1116 unique_by: impl IntoIterator<Item = impl ColumnName>,
1117 update: impl IntoIterator<Item = U>,
1118 ) -> Result<u64>
1119 where
1120 E: Executor + ?Sized,
1121 U: Into<ConflictUpdate>,
1122 {
1123 let meta = M::meta();
1124 let unique_by: Vec<Cow<'static, str>> = unique_by
1125 .into_iter()
1126 .map(|column| Cow::Owned(column.column_name().into_owned()))
1127 .collect();
1128 if unique_by.is_empty() {
1129 return Err(OrmError::invalid(format!(
1130 "an upsert of {} needs the unique columns its rows conflict on",
1131 meta.name()
1132 )));
1133 }
1134 let update: Vec<ConflictUpdate> = update.into_iter().map(Into::into).collect();
1135 let mut skipped = vec![meta.key_column()];
1136 skipped.extend(meta.created_at());
1137 Self::insert_models(
1138 exec,
1139 self.route(),
1140 Some(models.into_iter().collect()),
1141 true,
1142 |columns| {
1143 if update.is_empty() {
1144 return Ok(Some(OnConflict::Ignore {
1145 target: unique_by.clone(),
1146 }));
1147 }
1148 let mut sets = conflict_sets(columns, &unique_by, &skipped, update.clone())?;
1149 if let Some(updated_at) = meta.updated_at()
1150 && !sets.iter().any(|(column, _)| column == updated_at)
1151 && columns.iter().any(|column| column == updated_at)
1152 {
1153 sets.push((Cow::Borrowed(updated_at), Expr::excluded(updated_at)));
1154 }
1155 Ok(Some(upsert_conflict(unique_by.clone(), sets)))
1156 },
1157 )
1158 .await
1159 }
1160
1161 pub async fn update_from<E: Executor + ?Sized>(
1166 self,
1167 exec: &E,
1168 assignments: impl IntoIterator<Item = Assignment>,
1169 ) -> Result<u64> {
1170 let target = exec.target_routed(Access::Write, self.route()).await?;
1171 let now = target.context().now().await;
1172 let sets = Self::sets(now, assignments)?;
1173 let mut ir = self.apply_global_scopes().ir;
1174 ir.table = TableRef::new(M::meta().table());
1175 update_from_on(&target, ir, sets).await
1176 }
1177
1178 pub async fn truncate<E: Executor + ?Sized>(self, exec: &E) -> Result<()> {
1181 let target = exec.target_routed(Access::Write, self.route()).await?;
1182 truncate_table(&target, M::meta().table(), false).await
1183 }
1184}
1185
1186impl<M: Model> crate::record::Record<M> {
1187 pub async fn save_or_ignore<E: Executor + ?Sized>(&mut self, exec: &E) -> Result<bool> {
1203 self.save_or_ignore_on(exec, Vec::<&str>::new()).await
1204 }
1205
1206 pub async fn save_or_ignore_on<E: Executor + ?Sized, C: ColumnName>(
1210 &mut self,
1211 exec: &E,
1212 columns: impl IntoIterator<Item = C>,
1213 ) -> Result<bool> {
1214 if self.exists() {
1215 return Err(OrmError::invalid(format!(
1216 "save_or_ignore inserts new records; this {} is stored already (use save)",
1217 M::meta().name()
1218 )));
1219 }
1220 let target_columns = columns
1221 .into_iter()
1222 .map(|column| Cow::Owned(column.column_name().into_owned()))
1223 .collect();
1224 let target = exec
1225 .target_routed(Access::Write, crate::query::model_route::<M>())
1226 .await?;
1227 crate::persist::save_new(
1228 &target,
1229 self,
1230 Some(OnConflict::Ignore {
1231 target: target_columns,
1232 }),
1233 )
1234 .await
1235 }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240 use super::*;
1241
1242 fn insert_of(rows: usize, columns: usize) -> InsertIr {
1243 InsertIr::new(
1244 "t",
1245 (0..columns).map(|c| Cow::Owned(format!("c{c}"))).collect(),
1246 (0..rows)
1247 .map(|_| (0..columns).map(|_| Expr::val(1)).collect())
1248 .collect(),
1249 )
1250 }
1251
1252 #[test]
1253 fn inserts_split_under_the_bind_limit() {
1254 let parts = split(insert_of(10_000, 4), Some(Dialect::Sqlite));
1255 assert_eq!(parts.len(), 2, "32,766 / 4 = 8,191 rows per statement");
1256 assert_eq!(parts[0].rows.len(), 8_191);
1257 assert_eq!(parts[1].rows.len(), 1_809);
1258 assert_eq!(
1259 split(insert_of(10_000, 4), Some(Dialect::Postgres)).len(),
1260 1
1261 );
1262 assert_eq!(split(insert_of(10_000, 4), None).len(), 1);
1263 let defaults = split(insert_of(3, 0), Some(Dialect::Postgres));
1264 assert_eq!(defaults.len(), 3, "DEFAULT VALUES inserts one row each");
1265 }
1266
1267 #[test]
1268 fn conflict_updates_resolve_against_the_columns() {
1269 let columns = vec![
1270 Cow::Borrowed("id"),
1271 Cow::Borrowed("name"),
1272 Cow::Borrowed("color"),
1273 ];
1274 let sets = conflict_sets(
1275 &columns,
1276 &[Cow::Borrowed("name")],
1277 &["id"],
1278 vec![ConflictUpdate::All, "name".into()],
1279 )
1280 .unwrap();
1281 let names: Vec<&str> = sets.iter().map(|(c, _)| c.as_ref()).collect();
1282 assert_eq!(names, ["color", "name"]);
1283 }
1284}