Skip to main content

sql_builder/query/
on_conflict.rs

1use crate::{ConditionHolder, DynIden, Expr, IntoCondition, IntoIden};
2
3#[derive(Debug, Clone, Default, PartialEq)]
4pub struct OnConflict {
5    pub(crate) targets: OnConflictTarget,
6    pub(crate) target_where: ConditionHolder,
7    pub(crate) action: Option<OnConflictAction>,
8    pub(crate) action_where: ConditionHolder,
9}
10
11/// Represents ON CONFLICT (upsert) targets
12///
13/// Targets can be a list of columns or expressions, even mixed, or just a
14/// single constraint name.
15#[derive(Debug, Clone, PartialEq)]
16pub enum OnConflictTarget {
17    /// List of column names or expressions
18    Identifiers(Vec<OnConflictIdentifier>),
19    /// A constraint name
20    Constraint(String),
21}
22
23/// Represents either a column or an expression in the conflict targets
24#[derive(Debug, Clone, PartialEq)]
25pub enum OnConflictIdentifier {
26    /// A column
27    Column(DynIden),
28    /// An expression `(LOWER(column), ...)`
29    Expr(Expr),
30}
31
32/// Represents ON CONFLICT (upsert) actions
33#[derive(Debug, Clone, PartialEq)]
34pub enum OnConflictAction {
35    /// Do nothing
36    DoNothing(Vec<DynIden>),
37    /// Update column value of existing row
38    Update(Vec<OnConflictUpdate>),
39}
40
41/// Represents strategies to update column in ON CONFLICT (upsert) actions
42#[derive(Debug, Clone, PartialEq)]
43pub enum OnConflictUpdate {
44    /// Update column value of existing row with inserting value
45    Column(DynIden),
46    /// Update column value of existing row with expression
47    Expr(DynIden, Expr),
48}
49
50impl Default for OnConflictTarget {
51    fn default() -> Self {
52        OnConflictTarget::Identifiers(vec![])
53    }
54}
55
56impl OnConflict {
57    /// Create a ON CONFLICT expression without target column,
58    /// a special method designed for MySQL
59    pub fn new() -> Self {
60        Default::default()
61    }
62
63    /// Set ON CONFLICT target column
64    pub fn column<C>(column: C) -> Self
65    where
66        C: IntoIden,
67    {
68        Self::columns([column])
69    }
70
71    /// Set ON CONFLICT target columns
72    pub fn columns<I, C>(columns: I) -> Self
73    where
74        C: IntoIden,
75        I: IntoIterator<Item = C>,
76    {
77        Self {
78            targets: OnConflictTarget::Identifiers(
79                columns
80                    .into_iter()
81                    .map(|c| OnConflictIdentifier::Column(c.into_iden()))
82                    .collect(),
83            ),
84            target_where: ConditionHolder::new(),
85            action: None,
86            action_where: ConditionHolder::new(),
87        }
88    }
89
90    /// Set ON CONSTRAINT target constraint name
91    pub fn constraint(constraint: &str) -> Self {
92        Self {
93            targets: OnConflictTarget::Constraint(constraint.to_owned()),
94            target_where: ConditionHolder::new(),
95            action: None,
96            action_where: ConditionHolder::new(),
97        }
98    }
99
100    /// Set ON CONFLICT target expression
101    ///
102    /// # Examples
103    ///
104    /// ```
105    /// use sql_builder::*;
106    ///
107    /// let query = Query::insert()
108    ///     .into_table("glyph")
109    ///     .columns(["aspect", "image"])
110    ///     .values_panic(["abcd".into(), 3.1415.into()])
111    ///     .on_conflict(
112    ///         OnConflict::new()
113    ///             .expr(Expr::col("id"))
114    ///             .update_column("aspect")
115    ///             .value("image", Expr::val(1).add(2))
116    ///             .to_owned(),
117    ///     )
118    ///     .to_owned();
119    ///
120    /// assert_eq!(
121    ///     query.to_string(MysqlQueryBuilder).unwrap(),
122    ///     [
123    ///         r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
124    ///         r#"VALUES ('abcd', 3.1415)"#,
125    ///         r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = 1 + 2"#,
126    ///     ]
127    ///     .join(" ")
128    /// );
129    /// assert_eq!(
130    ///     query.to_string(PostgresQueryBuilder).unwrap(),
131    ///     [
132    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
133    ///         r#"VALUES ('abcd', 3.1415)"#,
134    ///         r#"ON CONFLICT ("id") DO UPDATE SET "aspect" = "excluded"."aspect", "image" = 1 + 2"#,
135    ///     ]
136    ///     .join(" ")
137    /// );
138    /// assert_eq!(
139    ///     query.to_string(SqliteQueryBuilder).unwrap(),
140    ///     [
141    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
142    ///         r#"VALUES ('abcd', 3.1415)"#,
143    ///         r#"ON CONFLICT ("id") DO UPDATE SET "aspect" = "excluded"."aspect", "image" = 1 + 2"#,
144    ///     ]
145    ///     .join(" ")
146    /// );
147    /// ```
148    pub fn expr<T>(&mut self, expr: T) -> &mut Self
149    where
150        T: Into<Expr>,
151    {
152        Self::exprs(self, [expr])
153    }
154
155    /// Set multiple target expressions for ON CONFLICT. See [`OnConflict::expr`]
156    pub fn exprs<I, T>(&mut self, exprs: I) -> &mut Self
157    where
158        T: Into<Expr>,
159        I: IntoIterator<Item = T>,
160    {
161        let es = exprs
162            .into_iter()
163            .map(|e| OnConflictIdentifier::Expr(e.into()));
164
165        match self.targets {
166            OnConflictTarget::Identifiers(ref mut ids) => {
167                ids.extend(es);
168            }
169            OnConflictTarget::Constraint(_) => {
170                self.targets = OnConflictTarget::Identifiers(es.collect())
171            }
172        }
173
174        self
175    }
176
177    /// Set ON CONFLICT do nothing.
178    ///
179    /// MySQL has no such clause and refuses to render it: use
180    /// [`Self::do_nothing_on()`] and name the primary key columns there.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use sql_builder::*;
186    ///
187    /// let query = Query::insert()
188    ///     .into_table("glyph")
189    ///     .columns(["aspect", "image"])
190    ///     .values_panic(["abcd".into(), 3.1415.into()])
191    ///     .on_conflict(
192    ///         OnConflict::columns(["id", "aspect"])
193    ///             .do_nothing()
194    ///             .to_owned(),
195    ///     )
196    ///     .to_owned();
197    ///
198    /// assert!(query.to_string(MysqlQueryBuilder).is_err());
199    /// assert_eq!(
200    ///     query.to_string(PostgresQueryBuilder).unwrap(),
201    ///     [
202    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
203    ///         r#"VALUES ('abcd', 3.1415)"#,
204    ///         r#"ON CONFLICT ("id", "aspect") DO NOTHING"#,
205    ///     ]
206    ///     .join(" ")
207    /// );
208    /// assert_eq!(
209    ///     query.to_string(SqliteQueryBuilder).unwrap(),
210    ///     [
211    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
212    ///         r#"VALUES ('abcd', 3.1415)"#,
213    ///         r#"ON CONFLICT ("id", "aspect") DO NOTHING"#,
214    ///     ]
215    ///     .join(" ")
216    /// );
217    /// ```
218    pub fn do_nothing(&mut self) -> &mut Self {
219        self.action = Some(OnConflictAction::DoNothing(vec![]));
220        self
221    }
222
223    /// Set ON CONFLICT do nothing, but with MySQL specific polyfill.
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use sql_builder::*;
229    ///
230    /// let query = Query::insert()
231    ///     .into_table("glyph")
232    ///     .columns(["aspect", "image"])
233    ///     .values_panic(["abcd".into(), 3.1415.into()])
234    ///     .on_conflict(
235    ///         OnConflict::columns(["id", "aspect"])
236    ///             .do_nothing_on(["id"])
237    ///             .to_owned(),
238    ///     )
239    ///     .to_owned();
240    ///
241    /// assert_eq!(
242    ///     query.to_string(MysqlQueryBuilder).unwrap(),
243    ///     [
244    ///         r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
245    ///         r#"VALUES ('abcd', 3.1415)"#,
246    ///         r#"ON DUPLICATE KEY UPDATE `id` = `id`"#,
247    ///     ]
248    ///     .join(" ")
249    /// );
250    /// assert_eq!(
251    ///     query.to_string(PostgresQueryBuilder).unwrap(),
252    ///     [
253    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
254    ///         r#"VALUES ('abcd', 3.1415)"#,
255    ///         r#"ON CONFLICT ("id", "aspect") DO NOTHING"#,
256    ///     ]
257    ///     .join(" ")
258    /// );
259    /// assert_eq!(
260    ///     query.to_string(SqliteQueryBuilder).unwrap(),
261    ///     [
262    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
263    ///         r#"VALUES ('abcd', 3.1415)"#,
264    ///         r#"ON CONFLICT ("id", "aspect") DO NOTHING"#,
265    ///     ]
266    ///     .join(" ")
267    /// );
268    /// ```
269    pub fn do_nothing_on<C, I>(&mut self, pk_cols: I) -> &mut Self
270    where
271        C: IntoIden,
272        I: IntoIterator<Item = C>,
273    {
274        self.action = Some(OnConflictAction::DoNothing(
275            pk_cols.into_iter().map(IntoIden::into_iden).collect(),
276        ));
277        self
278    }
279
280    /// Set ON CONFLICT update column
281    ///
282    /// # Examples
283    ///
284    /// ```
285    /// use sql_builder::*;
286    ///
287    /// let query = Query::insert()
288    ///     .into_table("glyph")
289    ///     .columns(["aspect", "image"])
290    ///     .values_panic([
291    ///         "abcd".into(),
292    ///         3.1415.into(),
293    ///     ])
294    ///     .on_conflict(
295    ///         OnConflict::columns(["id", "aspect"])
296    ///             .update_column("aspect")
297    ///             .value("image", Expr::val(1).add(2))
298    ///             .to_owned()
299    ///     )
300    ///     .to_owned();
301    ///
302    /// assert_eq!(
303    ///     query.to_string(MysqlQueryBuilder).unwrap(),
304    ///     [
305    ///         r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
306    ///         r#"VALUES ('abcd', 3.1415)"#,
307    ///         r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = 1 + 2"#,
308    ///     ]
309    ///     .join(" ")
310    /// );
311    /// assert_eq!(
312    ///     query.to_string(PostgresQueryBuilder).unwrap(),
313    ///     [
314    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
315    ///         r#"VALUES ('abcd', 3.1415)"#,
316    ///         r#"ON CONFLICT ("id", "aspect") DO UPDATE SET "aspect" = "excluded"."aspect", "image" = 1 + 2"#,
317    ///     ]
318    ///     .join(" ")
319    /// );
320    /// assert_eq!(
321    ///     query.to_string(SqliteQueryBuilder).unwrap(),
322    ///     [
323    ///         r#"INSERT INTO "glyph" ("aspect", "image")"#,
324    ///         r#"VALUES ('abcd', 3.1415)"#,
325    ///         r#"ON CONFLICT ("id", "aspect") DO UPDATE SET "aspect" = "excluded"."aspect", "image" = 1 + 2"#,
326    ///     ]
327    ///     .join(" ")
328    /// );
329    /// ```
330    pub fn update_column<C>(&mut self, column: C) -> &mut Self
331    where
332        C: IntoIden,
333    {
334        self.update_columns([column])
335    }
336
337    /// Set ON CONFLICT update columns
338    ///
339    /// # Examples
340    ///
341    /// ```
342    /// use sql_builder::*;
343    ///
344    /// let query = Query::insert()
345    ///     .into_table("glyph")
346    ///     .columns(["aspect", "image"])
347    ///     .values_panic([
348    ///         2.into(),
349    ///         3.into(),
350    ///     ])
351    ///     .on_conflict(
352    ///         OnConflict::column("id")
353    ///             .update_columns(["aspect", "image"])
354    ///             .to_owned(),
355    ///     )
356    ///     .to_owned();
357    ///
358    /// assert_eq!(
359    ///     query.to_string(MysqlQueryBuilder).unwrap(),
360    ///     r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2, 3) ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = VALUES(`image`)"#
361    /// );
362    /// assert_eq!(
363    ///     query.to_string(PostgresQueryBuilder).unwrap(),
364    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") DO UPDATE SET "aspect" = "excluded"."aspect", "image" = "excluded"."image""#
365    /// );
366    /// assert_eq!(
367    ///     query.to_string(SqliteQueryBuilder).unwrap(),
368    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") DO UPDATE SET "aspect" = "excluded"."aspect", "image" = "excluded"."image""#
369    /// );
370    /// ```
371    pub fn update_columns<C, I>(&mut self, columns: I) -> &mut Self
372    where
373        C: IntoIden,
374        I: IntoIterator<Item = C>,
375    {
376        self.add_updates(
377            columns
378                .into_iter()
379                .map(|x| OnConflictUpdate::Column(IntoIden::into_iden(x)))
380                .collect(),
381        )
382    }
383
384    /// Set ON CONFLICT update exprs. Append to current list of expressions.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use sql_builder::*;
390    ///
391    /// let query = Query::insert()
392    ///     .into_table("glyph")
393    ///     .columns(["aspect", "image"])
394    ///     .values_panic([
395    ///         2.into(),
396    ///         3.into(),
397    ///     ])
398    ///     .on_conflict(
399    ///         OnConflict::column("id")
400    ///             .values([("image", Expr::val(1).add(2))])
401    ///             .to_owned()
402    ///     )
403    ///     .to_owned();
404    ///
405    /// assert_eq!(
406    ///     query.to_string(MysqlQueryBuilder).unwrap(),
407    ///     r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2, 3) ON DUPLICATE KEY UPDATE `image` = 1 + 2"#
408    /// );
409    /// assert_eq!(
410    ///     query.to_string(PostgresQueryBuilder).unwrap(),
411    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") DO UPDATE SET "image" = 1 + 2"#
412    /// );
413    /// assert_eq!(
414    ///     query.to_string(SqliteQueryBuilder).unwrap(),
415    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") DO UPDATE SET "image" = 1 + 2"#
416    /// );
417    /// ```
418    pub fn values<C, I>(&mut self, values: I) -> &mut Self
419    where
420        C: IntoIden,
421        I: IntoIterator<Item = (C, Expr)>,
422    {
423        self.add_updates(
424            values
425                .into_iter()
426                .map(|(c, e)| OnConflictUpdate::Expr(c.into_iden(), e))
427                .collect(),
428        )
429    }
430
431    fn add_updates(&mut self, mut updates: Vec<OnConflictUpdate>) -> &mut Self {
432        match &mut self.action {
433            Some(OnConflictAction::Update(v)) => v.append(&mut updates),
434            Some(OnConflictAction::DoNothing(_)) | None => {
435                self.action = Some(OnConflictAction::Update(updates));
436            }
437        }
438        self
439    }
440
441    /// Set ON CONFLICT update value
442    pub fn value<C, T>(&mut self, col: C, value: T) -> &mut Self
443    where
444        C: IntoIden,
445        T: Into<Expr>,
446    {
447        self.values([(col, value.into())])
448    }
449
450    /// Set target WHERE
451    ///
452    /// # Examples
453    ///
454    /// ```
455    /// use sql_builder::*;
456    ///
457    /// let query = Query::insert()
458    ///     .into_table("glyph")
459    ///     .columns(["aspect", "image"])
460    ///     .values_panic([
461    ///         2.into(),
462    ///         3.into(),
463    ///     ])
464    ///     .on_conflict(
465    ///         OnConflict::column("id")
466    ///             .value("image", Expr::val(1).add(2))
467    ///             .target_and_where(Expr::col(("glyph", "aspect")).is_null())
468    ///             .to_owned()
469    ///     )
470    ///     .to_owned();
471    ///
472    /// assert_eq!(
473    ///     query.to_string(MysqlQueryBuilder).unwrap(),
474    ///     r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2, 3) ON DUPLICATE KEY UPDATE `image` = 1 + 2"#
475    /// );
476    /// assert_eq!(
477    ///     query.to_string(PostgresQueryBuilder).unwrap(),
478    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") WHERE "glyph"."aspect" IS NULL DO UPDATE SET "image" = 1 + 2"#
479    /// );
480    /// assert_eq!(
481    ///     query.to_string(SqliteQueryBuilder).unwrap(),
482    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") WHERE "glyph"."aspect" IS NULL DO UPDATE SET "image" = 1 + 2"#
483    /// );
484    /// ```
485    pub fn target_and_where(&mut self, other: Expr) -> &mut Self {
486        self.target_cond_where(other)
487    }
488
489    /// Set target WHERE
490    pub fn target_and_where_option(&mut self, other: Option<Expr>) -> &mut Self {
491        if let Some(other) = other {
492            self.target_cond_where(other);
493        }
494        self
495    }
496
497    /// Set target WHERE
498    pub fn target_cond_where<C>(&mut self, condition: C) -> &mut Self
499    where
500        C: IntoCondition,
501    {
502        self.target_where.add_condition(condition.into_condition());
503        self
504    }
505
506    /// Set action WHERE
507    ///
508    /// MySQL's `ON DUPLICATE KEY UPDATE` takes no condition, so it refuses to
509    /// render one.
510    ///
511    /// # Examples
512    ///
513    /// ```
514    /// use sql_builder::*;
515    ///
516    /// let query = Query::insert()
517    ///     .into_table("glyph")
518    ///     .columns(["aspect", "image"])
519    ///     .values_panic([
520    ///         2.into(),
521    ///         3.into(),
522    ///     ])
523    ///     .on_conflict(
524    ///         OnConflict::column("id")
525    ///             .value("image", Expr::val(1).add(2))
526    ///             .action_and_where(Expr::col(("glyph", "aspect")).is_null())
527    ///             .to_owned()
528    ///     )
529    ///     .to_owned();
530    ///
531    /// assert!(query.to_string(MysqlQueryBuilder).is_err());
532    /// assert_eq!(
533    ///     query.to_string(PostgresQueryBuilder).unwrap(),
534    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") DO UPDATE SET "image" = 1 + 2 WHERE "glyph"."aspect" IS NULL"#
535    /// );
536    /// assert_eq!(
537    ///     query.to_string(SqliteQueryBuilder).unwrap(),
538    ///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, 3) ON CONFLICT ("id") DO UPDATE SET "image" = 1 + 2 WHERE "glyph"."aspect" IS NULL"#
539    /// );
540    /// ```
541    pub fn action_and_where(&mut self, other: Expr) -> &mut Self {
542        self.action_cond_where(other)
543    }
544
545    /// Set action WHERE
546    pub fn action_and_where_option(&mut self, other: Option<Expr>) -> &mut Self {
547        if let Some(other) = other {
548            self.action_cond_where(other);
549        }
550        self
551    }
552
553    /// Set action WHERE
554    pub fn action_cond_where<C>(&mut self, condition: C) -> &mut Self
555    where
556        C: IntoCondition,
557    {
558        self.action_where.add_condition(condition.into_condition());
559        self
560    }
561}