Skip to main content

sql_builder/query/insert/
conflict.rs

1use super::*;
2
3impl InsertStatement {
4    /// ON CONFLICT expression
5    ///
6    /// # Examples
7    ///
8    /// - [`OnConflict::update_columns`]: Update column value of existing row with inserting value
9    pub fn on_conflict(&mut self, on_conflict: OnConflict) -> &mut Self {
10        self.on_conflict = Some(on_conflict);
11        self
12    }
13
14    /// Whether the statement says what to do on a conflict.
15    pub fn has_on_conflict(&self) -> bool {
16        self.on_conflict.is_some()
17    }
18
19    /// RETURNING expressions.
20    ///
21    /// # Examples
22    ///
23    /// ```
24    /// use sql_builder::*;
25    ///
26    /// let query = Query::insert()
27    ///     .into_table("glyph")
28    ///     .columns(["image"])
29    ///     .values_panic(["12A".into()])
30    ///     .returning(Query::returning().columns(["id"]))
31    ///     .take();
32    ///
33    /// assert_eq!(
34    ///     query.to_string(MariaDbDialect).unwrap(),
35    ///     "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING `id`"
36    /// );
37    /// assert_eq!(
38    ///     query.to_string(PostgresQueryBuilder).unwrap(),
39    ///     r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING "id""#
40    /// );
41    /// assert_eq!(
42    ///     query.to_string(SqliteQueryBuilder).unwrap(),
43    ///     r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING "id""#
44    /// );
45    /// ```
46    pub fn returning(&mut self, returning: ReturningClause) -> &mut Self {
47        self.returning = Some(returning);
48        self
49    }
50
51    /// RETURNING expressions for a column.
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use sql_builder::*;
57    ///
58    /// let query = Query::insert()
59    ///     .into_table("glyph")
60    ///     .columns(["image"])
61    ///     .values_panic(["12A".into()])
62    ///     .returning_col("id")
63    ///     .take();
64    ///
65    /// assert_eq!(
66    ///     query.to_string(MariaDbDialect).unwrap(),
67    ///     "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING `id`"
68    /// );
69    /// assert_eq!(
70    ///     query.to_string(PostgresQueryBuilder).unwrap(),
71    ///     r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING "id""#
72    /// );
73    /// assert_eq!(
74    ///     query.to_string(SqliteQueryBuilder).unwrap(),
75    ///     r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING "id""#
76    /// );
77    /// ```
78    pub fn returning_col<C>(&mut self, col: C) -> &mut Self
79    where
80        C: IntoColumnRef,
81    {
82        self.returning(ReturningClause::Columns(vec![col.into_column_ref()]))
83    }
84
85    /// RETURNING expressions all columns.
86    ///
87    /// # Examples
88    ///
89    /// ```
90    /// use sql_builder::*;
91    ///
92    /// let query = Query::insert()
93    ///     .into_table("glyph")
94    ///     .columns(["image"])
95    ///     .values_panic(["12A".into()])
96    ///     .returning_all()
97    ///     .take();
98    ///
99    /// assert_eq!(
100    ///     query.to_string(MariaDbDialect).unwrap(),
101    ///     "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING *"
102    /// );
103    /// assert_eq!(
104    ///     query.to_string(PostgresQueryBuilder).unwrap(),
105    ///     r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING *"#
106    /// );
107    /// assert_eq!(
108    ///     query.to_string(SqliteQueryBuilder).unwrap(),
109    ///     r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING *"#
110    /// );
111    /// ```
112    pub fn returning_all(&mut self) -> &mut Self {
113        self.returning(ReturningClause::All)
114    }
115
116    /// Create a [WithQuery] by specifying a [WithClause] to execute this query with.
117    ///
118    /// MySQL and MariaDB have no `WITH` before an `INSERT`, so this is a
119    /// [`RenderError`](crate::RenderError) there; give the `INSERT`'s
120    /// [`SelectStatement`] the `WITH` clause instead
121    /// ([`SelectStatement::with_cte`]).
122    ///
123    /// # Examples
124    ///
125    /// ```
126    /// use sql_builder::{*, IntoCondition, IntoIden};
127    ///
128    /// let select = SelectStatement::new()
129    ///         .columns(["id", "image", "aspect"])
130    ///         .from("glyph")
131    ///         .take();
132    ///     let cte = CommonTableExpression::new()
133    ///         .query(select)
134    ///         .column("id")
135    ///         .column("image")
136    ///         .column("aspect")
137    ///         .table_name("cte")
138    ///         .to_owned();
139    ///     let with_clause = WithClause::new().cte(cte).to_owned();
140    ///     let select = SelectStatement::new()
141    ///         .columns(["id", "image", "aspect"])
142    ///         .from("cte")
143    ///         .take();
144    ///     let mut insert = Query::insert();
145    ///     insert
146    ///         .into_table("glyph")
147    ///         .columns(["id", "image", "aspect"])
148    ///         .select_from(select)
149    ///         .unwrap();
150    ///     let query = insert.with(with_clause);
151    ///
152    /// // MySQL and MariaDB refuse it.
153    /// assert!(query.to_string(MysqlQueryBuilder).is_err());
154    /// assert_eq!(
155    ///     query.to_string(PostgresQueryBuilder).unwrap(),
156    ///     r#"WITH "cte" ("id", "image", "aspect") AS (SELECT "id", "image", "aspect" FROM "glyph") INSERT INTO "glyph" ("id", "image", "aspect") SELECT "id", "image", "aspect" FROM "cte""#
157    /// );
158    /// assert_eq!(
159    ///     query.to_string(SqliteQueryBuilder).unwrap(),
160    ///     r#"WITH "cte" ("id", "image", "aspect") AS (SELECT "id", "image", "aspect" FROM "glyph") INSERT INTO "glyph" ("id", "image", "aspect") SELECT "id", "image", "aspect" FROM "cte""#
161    /// );
162    /// ```
163    pub fn with(self, clause: WithClause) -> WithQuery {
164        clause.query(self)
165    }
166
167    /// Create a Common Table Expression by specifying a [CommonTableExpression][crate::CommonTableExpression]
168    /// or [WithClause] to execute this query with.
169    ///
170    /// MySQL and MariaDB have no `WITH` before an `INSERT`, so this is a
171    /// [`RenderError`](crate::RenderError) there; give the `INSERT`'s
172    /// [`SelectStatement`] the `WITH` clause instead
173    /// ([`SelectStatement::with_cte`]).
174    ///
175    /// # Examples
176    ///
177    /// ```
178    /// use sql_builder::{*, IntoCondition, IntoIden};
179    ///
180    /// let select = SelectStatement::new()
181    ///         .columns(["id", "image", "aspect"])
182    ///         .from("glyph")
183    ///         .take();
184    ///     let cte = CommonTableExpression::new()
185    ///         .query(select)
186    ///         .column("id")
187    ///         .column("image")
188    ///         .column("aspect")
189    ///         .table_name("cte")
190    ///         .to_owned();
191    ///     let with_clause = WithClause::new().cte(cte).to_owned();
192    ///     let select = SelectStatement::new()
193    ///         .columns(["id", "image", "aspect"])
194    ///         .from("cte")
195    ///         .take();
196    ///     let mut query = Query::insert();
197    ///     query
198    ///         .with_cte(with_clause)
199    ///         .into_table("glyph")
200    ///         .columns(["id", "image", "aspect"])
201    ///         .select_from(select)
202    ///         .unwrap();
203    ///
204    /// // MySQL and MariaDB refuse it.
205    /// assert!(query.to_string(MysqlQueryBuilder).is_err());
206    /// assert_eq!(
207    ///     query.to_string(PostgresQueryBuilder).unwrap(),
208    ///     r#"WITH "cte" ("id", "image", "aspect") AS (SELECT "id", "image", "aspect" FROM "glyph") INSERT INTO "glyph" ("id", "image", "aspect") SELECT "id", "image", "aspect" FROM "cte""#
209    /// );
210    /// assert_eq!(
211    ///     query.to_string(SqliteQueryBuilder).unwrap(),
212    ///     r#"WITH "cte" ("id", "image", "aspect") AS (SELECT "id", "image", "aspect" FROM "glyph") INSERT INTO "glyph" ("id", "image", "aspect") SELECT "id", "image", "aspect" FROM "cte""#
213    /// );
214    /// ```
215    pub fn with_cte<C: Into<WithClause>>(&mut self, clause: C) -> &mut Self {
216        self.with = Some(clause.into());
217        self
218    }
219
220    /// Insert with default values if columns and values are not supplied.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// use sql_builder::*;
226    ///
227    /// // Insert default
228    /// let query = Query::insert()
229    ///     .into_table("glyph")
230    ///     .or_default_values()
231    ///     .take();
232    ///
233    /// assert_eq!(
234    ///     query.to_string(MysqlQueryBuilder).unwrap(),
235    ///     r#"INSERT INTO `glyph` VALUES ()"#
236    /// );
237    /// assert_eq!(
238    ///     query.to_string(PostgresQueryBuilder).unwrap(),
239    ///     r#"INSERT INTO "glyph" VALUES (DEFAULT)"#
240    /// );
241    /// assert_eq!(
242    ///     query.to_string(SqliteQueryBuilder).unwrap(),
243    ///     r#"INSERT INTO "glyph" DEFAULT VALUES"#
244    /// );
245    ///
246    /// // Ordinary insert as columns and values are supplied
247    /// let query = Query::insert()
248    ///     .into_table("glyph")
249    ///     .or_default_values()
250    ///     .columns(["image"])
251    ///     .values_panic(["ABC".into()])
252    ///     .take();
253    ///
254    /// assert_eq!(
255    ///     query.to_string(MysqlQueryBuilder).unwrap(),
256    ///     r#"INSERT INTO `glyph` (`image`) VALUES ('ABC')"#
257    /// );
258    /// assert_eq!(
259    ///     query.to_string(PostgresQueryBuilder).unwrap(),
260    ///     r#"INSERT INTO "glyph" ("image") VALUES ('ABC')"#
261    /// );
262    /// assert_eq!(
263    ///     query.to_string(SqliteQueryBuilder).unwrap(),
264    ///     r#"INSERT INTO "glyph" ("image") VALUES ('ABC')"#
265    /// );
266    /// ```
267    pub fn or_default_values(&mut self) -> &mut Self {
268        self.default_values = Some(1);
269        self
270    }
271
272    /// Insert multiple rows with default values if columns and values are not supplied.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use sql_builder::*;
278    ///
279    /// // Insert default
280    /// let query = Query::insert()
281    ///     .into_table("glyph")
282    ///     .or_default_values_many(3)
283    ///     .take();
284    ///
285    /// assert_eq!(
286    ///     query.to_string(MysqlQueryBuilder).unwrap(),
287    ///     r#"INSERT INTO `glyph` VALUES (), (), ()"#
288    /// );
289    /// assert_eq!(
290    ///     query.to_string(PostgresQueryBuilder).unwrap(),
291    ///     r#"INSERT INTO "glyph" VALUES (DEFAULT), (DEFAULT), (DEFAULT)"#
292    /// );
293    /// assert_eq!(
294    ///     query.to_string(SqliteQueryBuilder).unwrap(),
295    ///     r#"INSERT INTO "glyph" (rowid) VALUES (NULL), (NULL), (NULL)"#
296    /// );
297    ///
298    /// // Ordinary insert as columns and values are supplied
299    /// let query = Query::insert()
300    ///     .into_table("glyph")
301    ///     .or_default_values_many(3)
302    ///     .columns(["image"])
303    ///     .values_panic(["ABC".into()])
304    ///     .take();
305    ///
306    /// assert_eq!(
307    ///     query.to_string(MysqlQueryBuilder).unwrap(),
308    ///     r#"INSERT INTO `glyph` (`image`) VALUES ('ABC')"#
309    /// );
310    /// assert_eq!(
311    ///     query.to_string(PostgresQueryBuilder).unwrap(),
312    ///     r#"INSERT INTO "glyph" ("image") VALUES ('ABC')"#
313    /// );
314    /// assert_eq!(
315    ///     query.to_string(SqliteQueryBuilder).unwrap(),
316    ///     r#"INSERT INTO "glyph" ("image") VALUES ('ABC')"#
317    /// );
318    /// ```
319    pub fn or_default_values_many(&mut self, num_rows: usize) -> &mut Self {
320        self.default_values = Some(num_rows);
321        self
322    }
323}