Skip to main content

sql_builder/query/
update.rs

1mod getters;
2
3use crate::{
4    ConditionHolder, DynIden, Expr, IntoColumnRef, IntoIden, IntoTableRef, OrderExpr,
5    QueryStatement, ReturningClause, SubQueryStatement, TableRef, Value, WithClause, WithQuery,
6    conditional_statement, ordered_statement, query_statement_builder, query_statement_writer,
7    statements,
8};
9
10/// Update existing rows in the table
11///
12/// # Examples
13///
14/// ```
15/// use sql_builder::*;
16///
17/// let query = Query::update()
18///     .table("glyph")
19///     .values([("aspect", 1.23.into()), ("image", "123".into())])
20///     .and_where(Expr::col("id").eq(1))
21///     .to_owned();
22///
23/// assert_eq!(
24///     query.to_string(MysqlQueryBuilder).unwrap(),
25///     r#"UPDATE `glyph` SET `aspect` = 1.23, `image` = '123' WHERE `id` = 1"#
26/// );
27/// assert_eq!(
28///     query.to_string(PostgresQueryBuilder).unwrap(),
29///     r#"UPDATE "glyph" SET "aspect" = 1.23, "image" = '123' WHERE "id" = 1"#
30/// );
31/// assert_eq!(
32///     query.to_string(SqliteQueryBuilder).unwrap(),
33///     r#"UPDATE "glyph" SET "aspect" = 1.23, "image" = '123' WHERE "id" = 1"#
34/// );
35/// ```
36#[derive(Default, Debug, Clone, PartialEq)]
37pub struct UpdateStatement {
38    pub(crate) table: Option<Box<TableRef>>,
39    pub(crate) from: Vec<TableRef>,
40    pub(crate) values: Vec<(DynIden, Box<Expr>)>,
41    pub(crate) r#where: ConditionHolder,
42    pub(crate) orders: Vec<OrderExpr>,
43    pub(crate) limit: Option<Value>,
44    pub(crate) returning: Option<ReturningClause>,
45    pub(crate) with: Option<WithClause>,
46}
47
48impl UpdateStatement {
49    /// Construct a new [`UpdateStatement`]
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    pub fn take(&mut self) -> Self {
55        Self {
56            table: self.table.take(),
57            from: std::mem::take(&mut self.from),
58            values: std::mem::take(&mut self.values),
59            r#where: std::mem::take(&mut self.r#where),
60            orders: std::mem::take(&mut self.orders),
61            limit: self.limit.take(),
62            returning: self.returning.take(),
63            with: self.with.take(),
64        }
65    }
66
67    /// Specify which table to update; see [`UpdateStatement::values`] for an
68    /// example.
69    #[allow(clippy::wrong_self_convention)]
70    pub fn table<T>(&mut self, tbl_ref: T) -> &mut Self
71    where
72        T: IntoTableRef,
73    {
74        self.table = Some(Box::new(tbl_ref.into_table_ref()));
75        self
76    }
77
78    /// Update using data from another table (`UPDATE .. FROM ..`).
79    ///
80    /// # MySQL Notes
81    ///
82    /// MySQL has no `UPDATE .. FROM`: it gets `UPDATE .. JOIN .. ON <where>`.
83    ///
84    /// # Examples
85    ///
86    /// ```
87    /// use sql_builder::*;
88    ///
89    /// let query = Query::update()
90    ///     .table("glyph")
91    ///     .value("tokens", Expr::column(("character", "character")))
92    ///     .from("character")
93    ///     .cond_where(
94    ///         Expr::col(("glyph", "image"))
95    ///             .eq(Expr::col(("character", "user_data"))),
96    ///     )
97    ///     .to_owned();
98    ///
99    /// assert_eq!(
100    ///     query.to_string(MysqlQueryBuilder).unwrap(),
101    ///     "UPDATE `glyph` JOIN `character` ON `glyph`.`image` = `character`.`user_data` SET `glyph`.`tokens` = `character`.`character`"
102    /// );
103    /// assert_eq!(
104    ///     query.to_string(PostgresQueryBuilder).unwrap(),
105    ///     r#"UPDATE "glyph" SET "tokens" = "character"."character" FROM "character" WHERE "glyph"."image" = "character"."user_data""#
106    /// );
107    /// assert_eq!(
108    ///     query.to_string(SqliteQueryBuilder).unwrap(),
109    ///     r#"UPDATE "glyph" SET "tokens" = "character"."character" FROM "character" WHERE "glyph"."image" = "character"."user_data""#
110    /// );
111    /// ```
112    pub fn from<R>(&mut self, tbl_ref: R) -> &mut Self
113    where
114        R: IntoTableRef,
115    {
116        self.from_from(tbl_ref.into_table_ref())
117    }
118
119    #[allow(clippy::wrong_self_convention)]
120    fn from_from(&mut self, select: TableRef) -> &mut Self {
121        self.from.push(select);
122        self
123    }
124
125    /// Update column values. To set multiple column-value pairs at once.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use sql_builder::*;
131    ///
132    /// let query = Query::update()
133    ///     .table("glyph")
134    ///     .values([
135    ///         ("aspect", 2.1345.into()),
136    ///         ("image", "235m".into()),
137    ///     ])
138    ///     .to_owned();
139    ///
140    /// assert_eq!(
141    ///     query.to_string(MysqlQueryBuilder).unwrap(),
142    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m'"#
143    /// );
144    /// assert_eq!(
145    ///     query.to_string(PostgresQueryBuilder).unwrap(),
146    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m'"#
147    /// );
148    /// assert_eq!(
149    ///     query.to_string(SqliteQueryBuilder).unwrap(),
150    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m'"#
151    /// );
152    /// ```
153    pub fn values<T, I>(&mut self, values: I) -> &mut Self
154    where
155        T: IntoIden,
156        I: IntoIterator<Item = (T, Expr)>,
157    {
158        for (k, v) in values.into_iter() {
159            self.values.push((k.into_iden(), Box::new(v)));
160        }
161        self
162    }
163
164    /// Update column value by [`Expr`].
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use sql_builder::*;
170    ///
171    /// let query = Query::update()
172    ///     .table("glyph")
173    ///     .value("aspect", Expr::cust("60 * 24 * 24"))
174    ///     .values([
175    ///         ("image", "24B0E11951B03B07F8300FD003983F03F0780060".into()),
176    ///     ])
177    ///     .to_owned();
178    ///
179    /// assert_eq!(
180    ///     query.to_string(MysqlQueryBuilder).unwrap(),
181    ///     r#"UPDATE `glyph` SET `aspect` = 60 * 24 * 24, `image` = '24B0E11951B03B07F8300FD003983F03F0780060'"#
182    /// );
183    /// assert_eq!(
184    ///     query.to_string(PostgresQueryBuilder).unwrap(),
185    ///     r#"UPDATE "glyph" SET "aspect" = 60 * 24 * 24, "image" = '24B0E11951B03B07F8300FD003983F03F0780060'"#
186    /// );
187    /// assert_eq!(
188    ///     query.to_string(SqliteQueryBuilder).unwrap(),
189    ///     r#"UPDATE "glyph" SET "aspect" = 60 * 24 * 24, "image" = '24B0E11951B03B07F8300FD003983F03F0780060'"#
190    /// );
191    ///
192    /// let query = Query::update()
193    ///     .table("glyph")
194    ///     .value("aspect", Expr::value(Value::Int(None)))
195    ///     .to_owned();
196    ///
197    /// assert_eq!(
198    ///     query.to_string(MysqlQueryBuilder).unwrap(),
199    ///     r#"UPDATE `glyph` SET `aspect` = NULL"#
200    /// );
201    /// assert_eq!(
202    ///     query.to_string(PostgresQueryBuilder).unwrap(),
203    ///     r#"UPDATE "glyph" SET "aspect" = NULL"#
204    /// );
205    /// assert_eq!(
206    ///     query.to_string(SqliteQueryBuilder).unwrap(),
207    ///     r#"UPDATE "glyph" SET "aspect" = NULL"#
208    /// );
209    /// ```
210    pub fn value<C, T>(&mut self, col: C, value: T) -> &mut Self
211    where
212        C: IntoIden,
213        T: Into<Expr>,
214    {
215        self.values.push((col.into_iden(), Box::new(value.into())));
216        self
217    }
218
219    /// Limit number of updated rows. PostgreSQL refuses to render a limit or an
220    /// order on an `UPDATE`.
221    pub fn limit(&mut self, limit: u64) -> &mut Self {
222        self.limit = Some(limit.into());
223        self
224    }
225
226    /// RETURNING expressions.
227    ///
228    /// MySQL has no `RETURNING`. MariaDB has it on an `UPDATE` from 13.0 and
229    /// for one table only, so one that joins [`from`](Self::from) tables is a
230    /// [`RenderError`](crate::RenderError); the builder does not know the
231    /// server's version, and an earlier MariaDB refuses the statement.
232    ///
233    /// # Examples
234    ///
235    /// ```
236    /// use sql_builder::*;
237    ///
238    /// let query = Query::update()
239    ///     .table("glyph")
240    ///     .value("aspect", 2.1345)
241    ///     .value("image", "235m")
242    ///     .returning(Query::returning().columns(["id"]))
243    ///     .to_owned();
244    ///
245    /// assert_eq!(
246    ///     query.to_string(MariaDbDialect).unwrap(),
247    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' RETURNING `id`"#
248    /// );
249    /// assert_eq!(
250    ///     query.to_string(PostgresQueryBuilder).unwrap(),
251    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
252    /// );
253    /// assert_eq!(
254    ///     query.to_string(SqliteQueryBuilder).unwrap(),
255    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
256    /// );
257    /// ```
258    pub fn returning(&mut self, returning: ReturningClause) -> &mut Self {
259        self.returning = Some(returning);
260        self
261    }
262
263    /// RETURNING expressions for a column.
264    ///
265    /// Where it renders: see [`returning`](Self::returning).
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use sql_builder::*;
271    ///
272    /// let query = Query::update()
273    ///     .table("glyph")
274    ///     .value("aspect", 2.1345)
275    ///     .value("image", "235m")
276    ///     .returning_col("id")
277    ///     .to_owned();
278    ///
279    /// assert_eq!(
280    ///     query.to_string(MariaDbDialect).unwrap(),
281    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' RETURNING `id`"#
282    /// );
283    /// assert_eq!(
284    ///     query.to_string(PostgresQueryBuilder).unwrap(),
285    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
286    /// );
287    /// assert_eq!(
288    ///     query.to_string(SqliteQueryBuilder).unwrap(),
289    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
290    /// );
291    /// ```
292    pub fn returning_col<C>(&mut self, col: C) -> &mut Self
293    where
294        C: IntoColumnRef,
295    {
296        self.returning(ReturningClause::Columns(vec![col.into_column_ref()]))
297    }
298
299    /// RETURNING expressions all columns.
300    ///
301    /// Where it renders: see [`returning`](Self::returning).
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use sql_builder::*;
307    ///
308    /// let query = Query::update()
309    ///     .table("glyph")
310    ///     .value("aspect", 2.1345)
311    ///     .value("image", "235m")
312    ///     .returning_all()
313    ///     .to_owned();
314    ///
315    /// assert_eq!(
316    ///     query.to_string(MariaDbDialect).unwrap(),
317    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' RETURNING *"#
318    /// );
319    /// assert_eq!(
320    ///     query.to_string(PostgresQueryBuilder).unwrap(),
321    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING *"#
322    /// );
323    /// assert_eq!(
324    ///     query.to_string(SqliteQueryBuilder).unwrap(),
325    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING *"#
326    /// );
327    /// ```
328    pub fn returning_all(&mut self) -> &mut Self {
329        self.returning(ReturningClause::All)
330    }
331
332    /// Create a [WithQuery] by specifying a [WithClause] to execute this query with.
333    ///
334    /// # Examples
335    ///
336    /// ```
337    /// use sql_builder::{IntoCondition, IntoIden, *};
338    ///
339    /// let select = SelectStatement::new()
340    ///         .columns(["id"])
341    ///         .from("glyph")
342    ///         .and_where(Expr::col("image").like("0%"))
343    ///         .to_owned();
344    ///     let cte = CommonTableExpression::new()
345    ///         .query(select)
346    ///         .column("id")
347    ///         .table_name("cte")
348    ///         .to_owned();
349    ///     let with_clause = WithClause::new().cte(cte).to_owned();
350    ///     let update = UpdateStatement::new()
351    ///         .table("glyph")
352    ///         .and_where(Expr::col("id").in_subquery(SelectStatement::new().column("id").from("cte").to_owned()))
353    ///         .value("aspect", Expr::cust("60 * 24 * 24"))
354    ///         .to_owned();
355    ///     let query = update.with(with_clause);
356    ///
357    /// assert_eq!(
358    ///     query.to_string(MysqlQueryBuilder).unwrap(),
359    ///     r#"WITH `cte` (`id`) AS (SELECT `id` FROM `glyph` WHERE `image` LIKE '0%') UPDATE `glyph` SET `aspect` = 60 * 24 * 24 WHERE `id` IN (SELECT `id` FROM `cte`)"#
360    /// );
361    /// assert_eq!(
362    ///     query.to_string(PostgresQueryBuilder).unwrap(),
363    ///     r#"WITH "cte" ("id") AS (SELECT "id" FROM "glyph" WHERE "image" LIKE '0%') UPDATE "glyph" SET "aspect" = 60 * 24 * 24 WHERE "id" IN (SELECT "id" FROM "cte")"#
364    /// );
365    /// assert_eq!(
366    ///     query.to_string(SqliteQueryBuilder).unwrap(),
367    ///     r#"WITH "cte" ("id") AS (SELECT "id" FROM "glyph" WHERE "image" LIKE '0%') UPDATE "glyph" SET "aspect" = 60 * 24 * 24 WHERE "id" IN (SELECT "id" FROM "cte")"#
368    /// );
369    /// ```
370    pub fn with(self, clause: WithClause) -> WithQuery {
371        clause.query(self)
372    }
373
374    /// Create a Common Table Expression by specifying a [CommonTableExpression][crate::CommonTableExpression]
375    /// or [WithClause] to execute this query with.
376    ///
377    /// # Examples
378    ///
379    /// ```
380    /// use sql_builder::{IntoCondition, IntoIden, *};
381    ///
382    /// let select = SelectStatement::new()
383    ///         .columns(["id"])
384    ///         .from("glyph")
385    ///         .and_where(Expr::col("image").like("0%"))
386    ///         .to_owned();
387    ///     let cte = CommonTableExpression::new()
388    ///         .query(select)
389    ///         .column("id")
390    ///         .table_name("cte")
391    ///         .to_owned();
392    ///     let with_clause = WithClause::new().cte(cte).to_owned();
393    ///     let query = UpdateStatement::new()
394    ///         .table("glyph")
395    ///         .and_where(Expr::col("id").in_subquery(SelectStatement::new().column("id").from("cte").to_owned()))
396    ///         .value("aspect", Expr::cust("60 * 24 * 24"))
397    ///         .with_cte(with_clause)
398    ///         .to_owned();
399    ///
400    /// assert_eq!(
401    ///     query.to_string(MysqlQueryBuilder).unwrap(),
402    ///     r#"WITH `cte` (`id`) AS (SELECT `id` FROM `glyph` WHERE `image` LIKE '0%') UPDATE `glyph` SET `aspect` = 60 * 24 * 24 WHERE `id` IN (SELECT `id` FROM `cte`)"#
403    /// );
404    /// assert_eq!(
405    ///     query.to_string(PostgresQueryBuilder).unwrap(),
406    ///     r#"WITH "cte" ("id") AS (SELECT "id" FROM "glyph" WHERE "image" LIKE '0%') UPDATE "glyph" SET "aspect" = 60 * 24 * 24 WHERE "id" IN (SELECT "id" FROM "cte")"#
407    /// );
408    /// assert_eq!(
409    ///     query.to_string(SqliteQueryBuilder).unwrap(),
410    ///     r#"WITH "cte" ("id") AS (SELECT "id" FROM "glyph" WHERE "image" LIKE '0%') UPDATE "glyph" SET "aspect" = 60 * 24 * 24 WHERE "id" IN (SELECT "id" FROM "cte")"#
411    /// );
412    /// ```
413    pub fn with_cte<C: Into<WithClause>>(&mut self, clause: C) -> &mut Self {
414        self.with = Some(clause.into());
415        self
416    }
417}
418
419query_statement_builder!(UpdateStatement, statements::prepare_update_statement);
420
421impl From<UpdateStatement> for QueryStatement {
422    fn from(s: UpdateStatement) -> Self {
423        Self::Update(s)
424    }
425}
426
427impl From<UpdateStatement> for SubQueryStatement {
428    fn from(s: UpdateStatement) -> Self {
429        Self::UpdateStatement(s)
430    }
431}
432
433query_statement_writer!(UpdateStatement);
434ordered_statement!(UpdateStatement, orders);
435conditional_statement!(UpdateStatement);