toasty/stmt/update.rs
1use super::Query;
2use crate::{
3 Executor, Result,
4 schema::{Load, Model},
5};
6use std::{fmt, marker::PhantomData};
7use toasty_core::stmt;
8
9/// A typed update statement.
10///
11/// `Update` modifies records matching a selection (typically derived from a
12/// [`Query`]). Field assignments are added with [`set`](Update::set),
13/// [`insert`](Update::insert), and [`remove`](Update::remove).
14///
15/// The type parameter `T` is the **returning type** — it determines what
16/// `exec()` produces, not which model is being updated. For example,
17/// `Update<User>` returns the updated `User` (single-row update), while
18/// `Update<List<User>>` returns the updated records as `Vec<User>`.
19///
20/// Generated update-builders wrap this type and expose typed setter methods.
21/// You rarely construct `Update` by hand.
22///
23/// By default, an update returns the changed records. Call
24/// [`set_returning_none`](Update::set_returning_none) to suppress this.
25pub struct Update<T> {
26 pub(crate) untyped: stmt::Update,
27 _p: PhantomData<T>,
28}
29
30// Methods available on all Update<M> regardless of M
31impl<T> Update<T> {
32 /// Create a new update statement from the given query selection.
33 ///
34 /// All records matched by `selection` will be updated. By default the
35 /// update returns the changed records (`Returning::Changed`).
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// # #[derive(Debug, toasty::Model)]
41 /// # struct User {
42 /// # #[key]
43 /// # id: i64,
44 /// # name: String,
45 /// # }
46 /// use toasty::stmt::{List, Query, Update};
47 ///
48 /// let update = Update::<List<User>>::new(Query::<List<User>>::all());
49 /// ```
50 pub fn new(selection: Query<T>) -> Self {
51 let mut stmt = selection.untyped.update();
52 stmt.returning = Some(stmt::Returning::Changed);
53
54 Self {
55 untyped: stmt,
56 _p: PhantomData,
57 }
58 }
59
60 /// Wrap a raw untyped [`stmt::Update`](toasty_core::stmt::Update).
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// # #[derive(Debug, toasty::Model)]
66 /// # struct User {
67 /// # #[key]
68 /// # id: i64,
69 /// # name: String,
70 /// # }
71 /// use toasty::stmt::{List, Query, Update};
72 ///
73 /// // Round-trip through an untyped update
74 /// let update = Update::<List<User>>::new(Query::<List<User>>::all());
75 /// let raw = update.into_untyped();
76 /// ```
77 pub const fn from_untyped(untyped: stmt::Update) -> Self {
78 Self {
79 untyped,
80 _p: PhantomData,
81 }
82 }
83
84 /// Get a mutable reference to the underlying untyped update.
85 ///
86 /// # Examples
87 ///
88 /// ```
89 /// # #[derive(Debug, toasty::Model)]
90 /// # struct User {
91 /// # #[key]
92 /// # id: i64,
93 /// # name: String,
94 /// # }
95 /// use toasty::stmt::{List, Query, Update};
96 ///
97 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
98 /// let raw = update.as_untyped_mut();
99 /// // Inspect or modify the raw update
100 /// assert!(raw.returning.is_some());
101 /// ```
102 pub fn as_untyped_mut(&mut self) -> &mut stmt::Update {
103 &mut self.untyped
104 }
105
106 /// Replace all field assignments with `assignments`.
107 ///
108 /// # Examples
109 ///
110 /// ```
111 /// # #[derive(Debug, toasty::Model)]
112 /// # struct User {
113 /// # #[key]
114 /// # id: i64,
115 /// # name: String,
116 /// # }
117 /// use toasty::stmt::{List, Query, Update};
118 ///
119 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
120 /// update.set_assignments(toasty_core::stmt::Assignments::default());
121 /// ```
122 pub fn set_assignments(&mut self, assignments: stmt::Assignments) {
123 self.untyped.assignments = assignments;
124 }
125
126 /// Assign a value to a field.
127 ///
128 /// `field` identifies which field to update and `expr` is the new value.
129 ///
130 /// # Examples
131 ///
132 /// ```
133 /// # #[derive(Debug, toasty::Model)]
134 /// # struct User {
135 /// # #[key]
136 /// # id: i64,
137 /// # name: String,
138 /// # }
139 /// use toasty::stmt::{List, Query, Update};
140 ///
141 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
142 /// // Set field at index 1 (name) to "Bob"
143 /// update.set(1, toasty_core::stmt::Value::from("Bob"));
144 /// ```
145 pub fn set(&mut self, field: impl Into<stmt::Projection>, expr: impl Into<stmt::Expr>) {
146 self.untyped.assignments.set(field, expr);
147 }
148
149 /// Append a value to a collection field (e.g., a has-many relation).
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// # #[derive(Debug, toasty::Model)]
155 /// # struct User {
156 /// # #[key]
157 /// # id: i64,
158 /// # name: String,
159 /// # }
160 /// use toasty::stmt::{List, Query, Update};
161 ///
162 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
163 /// update.insert(1, toasty_core::stmt::Value::from("new_tag"));
164 /// ```
165 pub fn insert(&mut self, field: impl Into<stmt::Projection>, expr: impl Into<stmt::Expr>) {
166 self.untyped.assignments.insert(field, expr);
167 }
168
169 /// Remove a value from a collection field.
170 ///
171 /// # Examples
172 ///
173 /// ```
174 /// # #[derive(Debug, toasty::Model)]
175 /// # struct User {
176 /// # #[key]
177 /// # id: i64,
178 /// # name: String,
179 /// # }
180 /// use toasty::stmt::{List, Query, Update};
181 ///
182 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
183 /// update.remove(1, toasty_core::stmt::Value::from("old_tag"));
184 /// ```
185 pub fn remove(&mut self, field: impl Into<stmt::Projection>, expr: impl Into<stmt::Expr>) {
186 self.untyped.assignments.remove(field, expr);
187 }
188
189 /// Don't return anything.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// # #[derive(Debug, toasty::Model)]
195 /// # struct User {
196 /// # #[key]
197 /// # id: i64,
198 /// # name: String,
199 /// # }
200 /// use toasty::stmt::{List, Query, Update};
201 ///
202 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
203 /// update.set_returning_none();
204 /// ```
205 pub fn set_returning_none(&mut self) {
206 self.untyped.returning = None;
207 }
208
209 /// Consume this typed update and return the untyped core statement.
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// # #[derive(Debug, toasty::Model)]
215 /// # struct User {
216 /// # #[key]
217 /// # id: i64,
218 /// # name: String,
219 /// # }
220 /// use toasty::stmt::{List, Query, Update};
221 ///
222 /// let update = Update::<List<User>>::new(Query::<List<User>>::all());
223 /// let _raw = update.into_untyped();
224 /// ```
225 pub fn into_untyped(self) -> stmt::Statement {
226 self.untyped.into()
227 }
228}
229
230impl<T: Load> Update<T> {
231 /// Execute this update statement against the given executor.
232 ///
233 /// Returns the updated records unless
234 /// [`set_returning_none`](Update::set_returning_none) was called.
235 ///
236 /// # Examples
237 ///
238 /// ```
239 /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
240 /// # #[derive(Debug, toasty::Model)]
241 /// # struct User {
242 /// # #[key]
243 /// # id: i64,
244 /// # name: String,
245 /// # }
246 /// # let driver = toasty_driver_sqlite::Sqlite::in_memory();
247 /// # let mut db = toasty::Db::builder().models(toasty::models!(User)).build(driver).await.unwrap();
248 /// # db.push_schema().await.unwrap();
249 /// use toasty::stmt::{List, Query, Update};
250 ///
251 /// let mut update = Update::<List<User>>::new(Query::<List<User>>::all());
252 /// update.set(1, toasty_core::stmt::Value::from("Bob"));
253 /// let _users: Vec<User> = update.exec(&mut db).await.unwrap();
254 /// # });
255 /// ```
256 pub async fn exec(self, executor: &mut dyn Executor) -> Result<T::Output> {
257 executor.exec(self.into()).await
258 }
259}
260
261impl<M> Clone for Update<M> {
262 fn clone(&self) -> Self {
263 Self {
264 untyped: self.untyped.clone(),
265 _p: PhantomData,
266 }
267 }
268}
269
270impl<M: Model> Default for Update<M> {
271 fn default() -> Self {
272 Self {
273 untyped: stmt::Update {
274 target: stmt::UpdateTarget::Model(M::id()),
275 assignments: stmt::Assignments::default(),
276 filter: stmt::Filter::new(stmt::Expr::from(false)),
277 condition: stmt::Condition::default(),
278 returning: Some(stmt::Returning::Changed),
279 },
280 _p: PhantomData,
281 }
282 }
283}
284
285impl<M> AsRef<stmt::Update> for Update<M> {
286 fn as_ref(&self) -> &stmt::Update {
287 &self.untyped
288 }
289}
290
291impl<M> AsMut<stmt::Update> for Update<M> {
292 fn as_mut(&mut self) -> &mut stmt::Update {
293 &mut self.untyped
294 }
295}
296
297impl<M> fmt::Debug for Update<M> {
298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299 self.untyped.fmt(f)
300 }
301}