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    /// # Examples
229    ///
230    /// ```
231    /// use sql_builder::*;
232    ///
233    /// let query = Query::update()
234    ///     .table("glyph")
235    ///     .value("aspect", 2.1345)
236    ///     .value("image", "235m")
237    ///     .returning(Query::returning().columns(["id"]))
238    ///     .to_owned();
239    ///
240    /// assert_eq!(
241    ///     query.to_string(MariaDbDialect).unwrap(),
242    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' RETURNING `id`"#
243    /// );
244    /// assert_eq!(
245    ///     query.to_string(PostgresQueryBuilder).unwrap(),
246    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
247    /// );
248    /// assert_eq!(
249    ///     query.to_string(SqliteQueryBuilder).unwrap(),
250    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
251    /// );
252    /// ```
253    pub fn returning(&mut self, returning: ReturningClause) -> &mut Self {
254        self.returning = Some(returning);
255        self
256    }
257
258    /// RETURNING expressions for a column.
259    ///
260    /// # Examples
261    ///
262    /// ```
263    /// use sql_builder::*;
264    ///
265    /// let query = Query::update()
266    ///     .table("glyph")
267    ///     .value("aspect", 2.1345)
268    ///     .value("image", "235m")
269    ///     .returning_col("id")
270    ///     .to_owned();
271    ///
272    /// assert_eq!(
273    ///     query.to_string(MariaDbDialect).unwrap(),
274    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' RETURNING `id`"#
275    /// );
276    /// assert_eq!(
277    ///     query.to_string(PostgresQueryBuilder).unwrap(),
278    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
279    /// );
280    /// assert_eq!(
281    ///     query.to_string(SqliteQueryBuilder).unwrap(),
282    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING "id""#
283    /// );
284    /// ```
285    pub fn returning_col<C>(&mut self, col: C) -> &mut Self
286    where
287        C: IntoColumnRef,
288    {
289        self.returning(ReturningClause::Columns(vec![col.into_column_ref()]))
290    }
291
292    /// RETURNING expressions all columns.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use sql_builder::*;
298    ///
299    /// let query = Query::update()
300    ///     .table("glyph")
301    ///     .value("aspect", 2.1345)
302    ///     .value("image", "235m")
303    ///     .returning_all()
304    ///     .to_owned();
305    ///
306    /// assert_eq!(
307    ///     query.to_string(MariaDbDialect).unwrap(),
308    ///     r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' RETURNING *"#
309    /// );
310    /// assert_eq!(
311    ///     query.to_string(PostgresQueryBuilder).unwrap(),
312    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING *"#
313    /// );
314    /// assert_eq!(
315    ///     query.to_string(SqliteQueryBuilder).unwrap(),
316    ///     r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' RETURNING *"#
317    /// );
318    /// ```
319    pub fn returning_all(&mut self) -> &mut Self {
320        self.returning(ReturningClause::All)
321    }
322
323    /// Create a [WithQuery] by specifying a [WithClause] to execute this query with.
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// use sql_builder::{IntoCondition, IntoIden, *};
329    ///
330    /// let select = SelectStatement::new()
331    ///         .columns(["id"])
332    ///         .from("glyph")
333    ///         .and_where(Expr::col("image").like("0%"))
334    ///         .to_owned();
335    ///     let cte = CommonTableExpression::new()
336    ///         .query(select)
337    ///         .column("id")
338    ///         .table_name("cte")
339    ///         .to_owned();
340    ///     let with_clause = WithClause::new().cte(cte).to_owned();
341    ///     let update = UpdateStatement::new()
342    ///         .table("glyph")
343    ///         .and_where(Expr::col("id").in_subquery(SelectStatement::new().column("id").from("cte").to_owned()))
344    ///         .value("aspect", Expr::cust("60 * 24 * 24"))
345    ///         .to_owned();
346    ///     let query = update.with(with_clause);
347    ///
348    /// assert_eq!(
349    ///     query.to_string(MysqlQueryBuilder).unwrap(),
350    ///     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`)"#
351    /// );
352    /// assert_eq!(
353    ///     query.to_string(PostgresQueryBuilder).unwrap(),
354    ///     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")"#
355    /// );
356    /// assert_eq!(
357    ///     query.to_string(SqliteQueryBuilder).unwrap(),
358    ///     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")"#
359    /// );
360    /// ```
361    pub fn with(self, clause: WithClause) -> WithQuery {
362        clause.query(self)
363    }
364
365    /// Create a Common Table Expression by specifying a [CommonTableExpression][crate::CommonTableExpression]
366    /// or [WithClause] to execute this query with.
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// use sql_builder::{IntoCondition, IntoIden, *};
372    ///
373    /// let select = SelectStatement::new()
374    ///         .columns(["id"])
375    ///         .from("glyph")
376    ///         .and_where(Expr::col("image").like("0%"))
377    ///         .to_owned();
378    ///     let cte = CommonTableExpression::new()
379    ///         .query(select)
380    ///         .column("id")
381    ///         .table_name("cte")
382    ///         .to_owned();
383    ///     let with_clause = WithClause::new().cte(cte).to_owned();
384    ///     let query = UpdateStatement::new()
385    ///         .table("glyph")
386    ///         .and_where(Expr::col("id").in_subquery(SelectStatement::new().column("id").from("cte").to_owned()))
387    ///         .value("aspect", Expr::cust("60 * 24 * 24"))
388    ///         .with_cte(with_clause)
389    ///         .to_owned();
390    ///
391    /// assert_eq!(
392    ///     query.to_string(MysqlQueryBuilder).unwrap(),
393    ///     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`)"#
394    /// );
395    /// assert_eq!(
396    ///     query.to_string(PostgresQueryBuilder).unwrap(),
397    ///     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")"#
398    /// );
399    /// assert_eq!(
400    ///     query.to_string(SqliteQueryBuilder).unwrap(),
401    ///     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")"#
402    /// );
403    /// ```
404    pub fn with_cte<C: Into<WithClause>>(&mut self, clause: C) -> &mut Self {
405        self.with = Some(clause.into());
406        self
407    }
408}
409
410query_statement_builder!(UpdateStatement, statements::prepare_update_statement);
411
412impl From<UpdateStatement> for QueryStatement {
413    fn from(s: UpdateStatement) -> Self {
414        Self::Update(s)
415    }
416}
417
418impl From<UpdateStatement> for SubQueryStatement {
419    fn from(s: UpdateStatement) -> Self {
420        Self::UpdateStatement(s)
421    }
422}
423
424query_statement_writer!(UpdateStatement);
425ordered_statement!(UpdateStatement, orders);
426conditional_statement!(UpdateStatement);