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