quaint_forked/ast/
update.rs

1use crate::ast::*;
2use std::borrow::Cow;
3
4/// A builder for an `UPDATE` statement.
5#[derive(Debug, PartialEq, Clone)]
6pub struct Update<'a> {
7    pub(crate) table: Table<'a>,
8    pub(crate) columns: Vec<Column<'a>>,
9    pub(crate) values: Vec<Expression<'a>>,
10    pub(crate) conditions: Option<ConditionTree<'a>>,
11    pub(crate) comment: Option<Cow<'a, str>>,
12}
13
14impl<'a> From<Update<'a>> for Query<'a> {
15    fn from(update: Update<'a>) -> Self {
16        Query::Update(Box::new(update))
17    }
18}
19
20impl<'a> Update<'a> {
21    /// Creates the basis for an `UPDATE` statement to the given table.
22    pub fn table<T>(table: T) -> Self
23    where
24        T: Into<Table<'a>>,
25    {
26        Self {
27            table: table.into(),
28            columns: Vec::new(),
29            values: Vec::new(),
30            conditions: None,
31            comment: None,
32        }
33    }
34
35    /// Add another column value assignment to the query
36    ///
37    /// ```rust
38    /// # use quaint::{ast::*, visitor::{Visitor, Sqlite}};
39    /// # fn main() -> Result<(), quaint::error::Error> {
40    /// let query = Update::table("users").set("foo", 10).set("bar", false);
41    /// let (sql, params) = Sqlite::build(query)?;
42    ///
43    /// assert_eq!("UPDATE `users` SET `foo` = ?, `bar` = ?", sql);
44    ///
45    /// assert_eq!(
46    ///     vec![
47    ///         Value::from(10),
48    ///         Value::from(false),
49    ///     ],
50    ///     params,
51    /// );
52    /// # Ok(())
53    /// # }
54    /// ```
55    pub fn set<K, V>(mut self, column: K, value: V) -> Update<'a>
56    where
57        K: Into<Column<'a>>,
58        V: Into<Expression<'a>>,
59    {
60        self.columns.push(column.into());
61        self.values.push(value.into());
62
63        self
64    }
65
66    /// Adds a comment to the update.
67    ///
68    /// ```rust
69    /// # use quaint::{ast::*, visitor::{Visitor, Sqlite}};
70    /// # fn main() -> Result<(), quaint::error::Error> {
71    /// let query = Update::table("users").set("foo", 10).comment("trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2'");
72    /// let (sql, _) = Sqlite::build(query)?;
73    ///
74    /// assert_eq!("UPDATE `users` SET `foo` = ? /* trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2' */", sql);
75    /// # Ok(())
76    /// # }
77    /// ```
78    pub fn comment<C: Into<Cow<'a, str>>>(mut self, comment: C) -> Self {
79        self.comment = Some(comment.into());
80        self
81    }
82
83    /// Adds `WHERE` conditions to the query. See
84    /// [Comparable](trait.Comparable.html#required-methods) for more examples.
85    ///
86    /// ```rust
87    /// # use quaint::{ast::*, visitor::{Visitor, Sqlite}};
88    /// # fn main() -> Result<(), quaint::error::Error> {
89    /// let query = Update::table("users").set("foo", 1).so_that("bar".equals(false));
90    /// let (sql, params) = Sqlite::build(query)?;
91    ///
92    /// assert_eq!("UPDATE `users` SET `foo` = ? WHERE `bar` = ?", sql);
93    ///
94    /// assert_eq!(
95    ///     vec![
96    ///         Value::from(1),
97    ///         Value::from(false),
98    ///     ],
99    ///     params,
100    /// );
101    /// # Ok(())
102    /// # }
103    /// ```
104    ///
105    /// We can also use a nested `SELECT` in the conditions.
106    ///
107    /// ```rust
108    /// # use quaint::{ast::*, visitor::{Visitor, Sqlite}};
109    /// # fn main() -> Result<(), quaint::error::Error> {
110    /// let select = Select::from_table("bars").column("id").so_that("uniq_val".equals(3));
111    /// let query = Update::table("users").set("foo", 1).so_that("bar".equals(select));
112    /// let (sql, params) = Sqlite::build(query)?;
113    ///
114    /// assert_eq!(
115    ///     "UPDATE `users` SET `foo` = ? WHERE `bar` = (SELECT `id` FROM `bars` WHERE `uniq_val` = ?)",
116    ///     sql
117    /// );
118    ///
119    /// assert_eq!(
120    ///     vec![
121    ///         Value::from(1),
122    ///         Value::from(3),
123    ///     ],
124    ///     params,
125    /// );
126    /// # Ok(())
127    /// # }
128    /// ```
129    pub fn so_that<T>(mut self, conditions: T) -> Self
130    where
131        T: Into<ConditionTree<'a>>,
132    {
133        self.conditions = Some(conditions.into());
134        self
135    }
136}