Skip to main content

navree_orm/query/
bulk.rs

1//! Bulk writes: multi-row inserts, inserts that skip conflicting rows or
2//! read a generated key back, `INSERT … SELECT`, upserts,
3//! update-or-insert, `UPDATE … FROM` and truncation, on table queries
4//! ([`TableBuilder`]) and on models ([`Builder`]).
5//!
6//! | Method | Writes | Returns |
7//! |---|---|---|
8//! | `insert` | `INSERT INTO t (..) VALUES (..), (..)` | rows inserted |
9//! | `insert_get_id` | one row, reading its key back | the key |
10//! | `insert_or_ignore` | the rows that conflict with no unique index | rows inserted |
11//! | `insert_or_ignore_returning` | the same, reading columns of the inserted rows back | rows |
12//! | `insert_using`, `insert_or_ignore_using` | `INSERT INTO t (..) SELECT ..` | rows inserted |
13//! | `upsert` | new rows, and an update of the rows they conflict with | rows the database reports |
14//! | `update_or_insert` | an update of the matching rows, or a new row | whether a row was written |
15//! | `update_from` | `UPDATE t SET .. FROM joined ..` | rows updated |
16//! | `truncate` | every row, and the identity sequence | — |
17//! | models: `fill_and_insert` and friends | models with generated keys and timestamps, like `save` | as above |
18//!
19//! None of them runs lifecycle hooks or records change events: they write
20//! rows, not records (save records one by one when hooks or the audit trail
21//! matter). A multi-row insert is one statement, split into several when
22//! its values exceed the database's bind limit (65,535 values on
23//! PostgreSQL and MySQL, 32,766 on SQLite); the parts then run in one
24//! transaction (a savepoint inside a unit of work), so the insert stays
25//! all or nothing.
26//!
27//! Skipping conflicts is `ON CONFLICT DO NOTHING` on PostgreSQL and SQLite
28//! (only rows that conflict on a unique index are skipped; any other error
29//! fails the statement) and `INSERT IGNORE` on MySQL, which also turns
30//! other errors, such as a value too long for its column, into warnings.
31//! An upsert is `ON CONFLICT (unique columns) DO UPDATE` on PostgreSQL and
32//! SQLite and `ON DUPLICATE KEY UPDATE` on MySQL (which checks every unique
33//! index, whatever columns are named).
34//!
35//! ```no_run
36//! # use navree_orm::__doc_models::*;
37//! use navree_orm::ConflictUpdate;
38//!
39//! # async fn demo(db: Db, uow: Uow) -> Result<()> {
40//! // Tags by name: new ones are inserted, existing ones get the new color.
41//! let tags = vec![
42//!     Tag { name: "vip".into(), color: "gold".into(), ..Default::default() },
43//!     Tag { name: "churn-risk".into(), color: "red".into(), ..Default::default() },
44//! ];
45//! Tag::upsert(&uow, tags, [Tag::NAME], [Tag::COLOR]).await?;
46//!
47//! // Pivot rows, skipping the pairs that exist.
48//! table("deal_tag")
49//!     .insert_or_ignore(&uow, [[("deal_id", 1), ("tag_id", 2)], [("deal_id", 1), ("tag_id", 3)]])
50//!     .await?;
51//!
52//! // Every column but the key and created_at on conflict.
53//! let settings = vec![Setting { key: "theme".into(), value: "dark".into(), ..Default::default() }];
54//! Setting::upsert(&db, settings, [Setting::KEY], [ConflictUpdate::All]).await?;
55//! # Ok(()) }
56//! ```
57
58use 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/// What an [`upsert`](TableBuilder::upsert) sets on a row that already
74/// exists: a column (set to the value the row would have been inserted
75/// with), an assignment, or every inserted column.
76///
77/// ```
78/// use navree_orm::{ConflictUpdate, Expr, col};
79///
80/// let updates: Vec<ConflictUpdate> = vec![
81///     "color".into(),
82///     // Add to the stored count instead of replacing it.
83///     col("hits").set_expr(Expr::col("tags.hits").add(Expr::excluded("hits"))).into(),
84/// ];
85/// # let _ = updates;
86/// ```
87#[derive(Clone, Debug)]
88#[non_exhaustive]
89pub enum ConflictUpdate {
90    /// Every inserted column but the unique ones (and, for a model, its key
91    /// and creation timestamp).
92    All,
93    /// The column, set to the value the row would have been inserted with.
94    Column(Cow<'static, str>),
95    /// An assignment; [`Expr::excluded`] is the value the row would have
96    /// been inserted with.
97    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
130// ---------------------------------------------------------------------------
131// Rows and statements
132// ---------------------------------------------------------------------------
133
134/// Rows to insert: the first row's columns, and every row's values in that
135/// order.
136struct Rows {
137    columns: Vec<Cow<'static, str>>,
138    values: Vec<Vec<Expr>>,
139}
140
141impl Rows {
142    /// `rows` as `(column, value)` pairs, every row with the same columns
143    /// (in any order).
144    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
188/// How many values `expr` binds.
189fn 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
201/// `insert` as statements that each bind fewer values than `dialect`
202/// allows: its rows in consecutive parts.
203fn 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        // `DEFAULT VALUES` inserts one row per statement.
209        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
243/// Runs `inserts` on `target` as one whole: alone when there is one, else
244/// in a transaction (a savepoint inside one).
245async 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
276/// Commits `tx` after `result`, or rolls it back.
277async 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
292/// The `SET` list of an upsert of rows with `columns`, conflicting on
293/// `unique_by`: `update` resolved, later items replacing earlier ones for
294/// the same column. [`ConflictUpdate::All`] leaves out the unique columns
295/// and `skipped` ones.
296fn 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
329/// The insert handling conflicts on `unique_by` with `sets` (skipping the
330/// conflicting rows when there is nothing to set).
331fn 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
345/// The SQL target of `target`, or the error a document store answers
346/// `feature` with.
347fn 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
357/// Reads key column `column` of an insert's outcome as `K`.
358fn 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
373/// Empties `table` on `target` (see [`render_truncate`]).
374async 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    // SQLite keeps AUTOINCREMENT counters in `sqlite_sequence`, which exists
396    // once a table declares one.
397    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
433// ---------------------------------------------------------------------------
434// Table queries
435// ---------------------------------------------------------------------------
436
437impl TableBuilder {
438    /// The table an insert writes to (a subquery cannot be written).
439    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    /// Runs `insert` (split under the bind limit) where `exec` writes.
452    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    /// Inserts `rows` (each a list of `(column, value)` pairs, every row
463    /// with the same columns) in one statement, split under the database's
464    /// bind limit; returns how many were inserted. No statement runs for an
465    /// empty list.
466    ///
467    /// ```no_run
468    /// # use navree_orm::__doc_models::*;
469    /// # async fn demo(uow: Uow, deal: Uuid, tag: i64) -> Result<()> {
470    /// table("deal_tag")
471    ///     .insert(&uow, [[("deal_id", Value::from(deal)), ("tag_id", Value::from(tag))]])
472    ///     .await?;
473    /// # Ok(()) }
474    /// ```
475    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    /// Inserts one row and returns its `id` column, read back with
498    /// `RETURNING` on PostgreSQL and SQLite and from `LAST_INSERT_ID()` on
499    /// MySQL.
500    ///
501    /// ```no_run
502    /// # use navree_orm::__doc_models::*;
503    /// # async fn demo(db: Db) -> Result<()> {
504    /// let id: i64 = table("tags").insert_get_id(&db, [("name", "vip"), ("color", "gold")]).await?;
505    /// # Ok(()) }
506    /// ```
507    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    /// [`insert_get_id`](Self::insert_get_id) for a key column other than
516    /// `id`.
517    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    /// Inserts `rows`, skipping the ones that conflict with a unique index;
532    /// returns how many were inserted. PostgreSQL and SQLite skip only the
533    /// rows that conflict on a unique index (`ON CONFLICT DO NOTHING`, `OR
534    /// IGNORE`); MySQL's `INSERT IGNORE` also turns other errors, such as a
535    /// value too long for its column, into warnings.
536    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    /// Inserts `rows`, skipping the ones that conflict on the unique index
560    /// of `unique_by` (any unique index when empty), and returns the
561    /// `returning` columns of the rows inserted. PostgreSQL and SQLite
562    /// only: MySQL cannot return inserted rows (use
563    /// [`insert_or_ignore`](Self::insert_or_ignore), then select them).
564    ///
565    /// ```no_run
566    /// # use navree_orm::__doc_models::*;
567    /// # async fn demo(db: Db) -> Result<()> {
568    /// let created = table("tags")
569    ///     .insert_or_ignore_returning(&db, [[("name", "vip"), ("color", "gold")]], ["id", "name"], ["name"])
570    ///     .await?;
571    /// # Ok(()) }
572    /// ```
573    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    /// Inserts the rows `query` selects (`INSERT INTO table (columns)
614    /// SELECT ..`), one value per column; returns how many were inserted.
615    ///
616    /// ```no_run
617    /// # use navree_orm::__doc_models::*;
618    /// # async fn demo(db: Db) -> Result<()> {
619    /// let archived = table("archived_deals")
620    ///     .insert_using(&db, ["id", "title"], table("deals").select(["id", "title"]).where_(col("stage").eq("lost")))
621    ///     .await?;
622    /// # Ok(()) }
623    /// ```
624    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    /// [`insert_using`](Self::insert_using), skipping the rows that
643    /// conflict with a unique index.
644    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    /// Inserts `rows`; a row that conflicts on the unique index of
664    /// `unique_by` updates the existing row with `update` instead (an empty
665    /// `update` skips it). Returns the number of rows the database reports
666    /// (MySQL counts an updated row twice and an unchanged one not at all).
667    ///
668    /// ```no_run
669    /// # use navree_orm::__doc_models::*;
670    /// use navree_orm::{ConflictUpdate, Expr, col};
671    ///
672    /// # async fn demo(db: Db) -> Result<()> {
673    /// table("page_views")
674    ///     .upsert(
675    ///         &db,
676    ///         [[("path", Value::from("/pricing")), ("views", Value::from(1))]],
677    ///         ["path"],
678    ///         [col("views").set_expr(Expr::col("page_views.views").add(Expr::excluded("views")))],
679    ///     )
680    ///     .await?;
681    /// # Ok(()) }
682    /// ```
683    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    /// Updates the rows matching `attributes` with the assignments
718    /// `values` returns, or, when no row matches, inserts one with the
719    /// attributes and the values. `values` learns whether a row existed.
720    /// Returns whether a row was inserted or changed.
721    ///
722    /// ```no_run
723    /// # use navree_orm::__doc_models::*;
724    /// # async fn demo(db: Db) -> Result<()> {
725    /// table("settings")
726    ///     .update_or_insert(&db, [col("key").set("theme")], |exists| {
727    ///         let mut values = vec![col("value").set("dark")];
728    ///         if !exists {
729    ///             values.push(col("created_by").set("system"));
730    ///         }
731    ///         values
732    ///     })
733    ///     .await?;
734    /// # Ok(()) }
735    /// ```
736    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        // Read and write through the same connection (the unit of work's).
753        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    /// Updates the rows of the table joined to the query's joined tables:
794    /// PostgreSQL's (and SQLite's) `UPDATE table SET .. FROM joined ..
795    /// WHERE <join conditions> AND <conditions>`, MySQL's `UPDATE table
796    /// JOIN joined ON .. SET ..` (one joined table). Inner and cross joins
797    /// only; returns how many rows changed.
798    ///
799    /// ```no_run
800    /// # use navree_orm::__doc_models::*;
801    /// # async fn demo(db: Db) -> Result<()> {
802    /// table("deals")
803    ///     .join("companies", "companies.id", "=", "deals.company_id")
804    ///     .where_(col("companies.active").eq(false))
805    ///     .update_from(&db, [col("stage").set("lost")])
806    ///     .await?;
807    /// # Ok(()) }
808    /// ```
809    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    /// Empties the table and restarts its identity (see [`render_truncate`]
823    /// per database); on MySQL this commits the open transaction.
824    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    /// [`truncate`](Self::truncate) that also empties the tables whose
831    /// foreign keys reference this one (`CASCADE`, PostgreSQL only).
832    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
845/// `UPDATE … FROM` of `query`'s table, joins and conditions.
846async 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
873// ---------------------------------------------------------------------------
874// Models
875// ---------------------------------------------------------------------------
876
877/// `models` with empty keys generated and empty timestamps set to `now`,
878/// as [`Record::save`](crate::Record::save) would before inserting.
879fn 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
914/// The columns of an insert and its rows.
915type InsertGroup = (Vec<Cow<'static, str>>, Vec<Vec<Expr>>);
916
917/// The inserts of `models`' stored values (casts applied): one group per
918/// column list, as a key the database assigns is left out when it is
919/// empty.
920fn 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    /// Runs the inserts of `models` where `route` asks, each handling
951    /// conflicts with `on_conflict` (given the insert's columns).
952    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    /// Inserts `models` as they are, in one statement (split under the
977    /// bind limit): every column's stored value, casts applied, and no key
978    /// for a model whose key the database assigns and is empty. No hooks,
979    /// no change events, no generated keys or timestamps (see
980    /// [`fill_and_insert`](Self::fill_and_insert)). Returns how many rows
981    /// were inserted.
982    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    /// [`insert`](Self::insert), skipping the models that conflict with a
998    /// unique index.
999    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    /// `models` as [`fill_and_insert`](Self::fill_and_insert) would insert
1015    /// them: empty keys generated (UUID v7, UUID v4 or ULID by the key
1016    /// type) and empty timestamps set to now (the app's clock). Writes
1017    /// nothing.
1018    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    /// Inserts `models` the way [`Record::save`](crate::Record::save) would
1028    /// fill them (generated keys, timestamps, casts), in one statement and
1029    /// without hooks or change events. Returns how many rows were
1030    /// inserted.
1031    ///
1032    /// ```no_run
1033    /// # use navree_orm::__doc_models::*;
1034    /// # async fn demo(db: Db) -> Result<()> {
1035    /// let events = (0..1_000).map(|n| Event { name: format!("import-{n}"), ..Default::default() });
1036    /// Event::query().fill_and_insert(&db, events).await?; // UUID v7 keys and timestamps filled in
1037    /// # Ok(()) }
1038    /// ```
1039    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    /// [`fill_and_insert`](Self::fill_and_insert), skipping the models that
1055    /// conflict with a unique index.
1056    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    /// Inserts one model filled like [`fill_and_insert`](Self::fill_and_insert)
1072    /// and returns its key (read back when the database assigns it).
1073    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    /// Inserts `models` filled like [`fill_and_insert`](Self::fill_and_insert);
1099    /// a model that conflicts on the unique index of `unique_by` updates
1100    /// the stored row with `update` instead: the listed columns (or
1101    /// [`ConflictUpdate::All`]: every column but the key, `unique_by` and
1102    /// the creation timestamp), plus the update timestamp. An empty
1103    /// `update` skips conflicting models. Returns the number of rows the
1104    /// database reports.
1105    ///
1106    /// ```no_run
1107    /// # use navree_orm::__doc_models::*;
1108    /// # async fn demo(db: Db, tags: Vec<Tag>) -> Result<()> {
1109    /// Tag::query().upsert(&db, tags, [Tag::NAME], [Tag::COLOR]).await?;
1110    /// # Ok(()) }
1111    /// ```
1112    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    /// Updates the model's rows joined to the query's joined tables
1162    /// (`UPDATE … FROM`, see [`TableBuilder::update_from`]), setting the
1163    /// update timestamp too; returns how many rows changed. Global scopes
1164    /// apply; no hooks run.
1165    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    /// Empties the model's table and restarts its identity (no hooks; see
1179    /// [`TableBuilder::truncate`]).
1180    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    /// Inserts this new record unless it conflicts with a unique index of
1188    /// its table; returns whether it was inserted. The insert runs like
1189    /// [`save`](Self::save) (hooks, generated key, timestamps, change
1190    /// event), and nothing after `creating` runs when the row is skipped.
1191    /// A record that is stored already is refused: this only inserts.
1192    ///
1193    /// ```no_run
1194    /// # use navree_orm::__doc_models::*;
1195    /// # async fn demo(db: Db) -> Result<()> {
1196    /// let mut tag = Record::new(Tag { name: "vip".into(), color: "gold".into(), ..Default::default() });
1197    /// if !tag.save_or_ignore(&db).await? {
1198    ///     println!("a tag named vip exists already");
1199    /// }
1200    /// # Ok(()) }
1201    /// ```
1202    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    /// [`save_or_ignore`](Self::save_or_ignore), skipping only conflicts on
1207    /// the unique index of `columns` (another unique index still fails the
1208    /// insert; MySQL checks every unique index).
1209    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}