1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use super::{IntoExpr, IntoScope, IntoStatement, List, Path, Statement};
use crate::schema::Model;
use std::{fmt, marker::PhantomData};
use toasty_core::stmt;
/// A typed handle to a model association (relation).
///
/// `Association` represents a link between a source model and a target model,
/// such as a has-many or belongs-to relation. It wraps an untyped
/// [`stmt::Association`](toasty_core::stmt::Association) and carries a type `T`
/// that encodes the **returning type** — what executing the association query
/// produces:
///
/// - `Association<List<M>>` — a has-many relation, returns `Vec<M>`.
/// - `Association<M>` — a has-one or belongs-to relation, returns `M`.
///
/// Associations are constructed by generated code (see [`many`](Association::many),
/// [`many_via_one`](Association::many_via_one), and [`one`](Association::one)).
/// They implement [`IntoStatement`] so they can be passed directly to
/// [`Db::exec`](crate::Db::exec).
pub struct Association<T> {
pub(crate) untyped: stmt::Association,
_p: PhantomData<T>,
}
impl<T> Association<T> {
/// Borrow the underlying untyped association.
pub fn untyped(&self) -> &stmt::Association {
&self.untyped
}
/// Construct a typed association from a raw untyped one. Used by
/// generated code that re-types an association after carrying it through
/// an untyped storage slot.
#[doc(hidden)]
pub fn from_untyped(untyped: stmt::Association) -> Self {
Self {
untyped,
_p: PhantomData,
}
}
/// Construct an association from `source` following `path`, without
/// requiring the returning type `T` to be a model.
///
/// Used by generated `#[has_many(via = …)]` navigation methods, whose
/// terminal may be a scalar (`Path<S, List<String>>`). The [`many`](Self::many) /
/// [`one`](Self::one) constructors bound the element on [`Model`]; this one
/// only bounds the *source* model `S`, so it works for both relation- and
/// scalar-terminal vias.
///
/// # Panics
///
/// Panics if the root of `path` does not match the model id of `S`.
#[doc(hidden)]
pub fn from_source_and_path<S: Model>(source: super::Query<List<S>>, path: Path<S, T>) -> Self {
assert_eq!(path.untyped.root.as_model_unwrap(), S::id());
Self {
untyped: stmt::Association {
source: Box::new(source.untyped),
path: path.untyped,
},
_p: PhantomData,
}
}
}
impl<M: Model> Association<List<M>> {
/// Create a has-many association from `source` following `path`.
///
/// # Panics
///
/// Panics if the root of `path` does not match the model id of `T`.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// # #[derive(Debug, toasty::Model)]
/// # struct Todo {
/// # #[key]
/// # id: i64,
/// # user_id: i64,
/// # title: String,
/// # }
/// use toasty::stmt::{Association, List, Query};
/// use toasty::schema::Model;
///
/// let source = Query::<List<User>>::all().filter(User::fields().id().eq(1));
/// let path = User::path_field::<List<Todo>>(2);
/// let _assoc = Association::many(source, path);
/// ```
pub fn many<T: Model>(source: super::Query<List<T>>, path: Path<T, List<M>>) -> Self {
assert_eq!(path.untyped.root.as_model_unwrap(), T::id());
Self {
untyped: stmt::Association {
source: Box::new(source.untyped),
path: path.untyped,
},
_p: PhantomData,
}
}
/// Create a has-many association through a singular (has-one / belongs-to)
/// path. Because the source is a query that may match multiple rows, the
/// result is still a list.
///
/// # Panics
///
/// Panics if the root of `path` does not match the model id of `T`.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// # #[derive(Debug, toasty::Model)]
/// # struct Todo {
/// # #[key]
/// # id: i64,
/// # user_id: i64,
/// # title: String,
/// # }
/// use toasty::stmt::{Association, List, Query};
/// use toasty::schema::Model;
///
/// let source = Query::<List<Todo>>::all();
/// let path = Todo::path_field::<User>(1);
/// let _assoc: Association<List<User>> = Association::many_via_one(source, path);
/// ```
pub fn many_via_one<T: Model>(source: super::Query<List<T>>, path: Path<T, M>) -> Self {
assert_eq!(path.untyped.root.as_model_unwrap(), T::id());
Self {
untyped: stmt::Association {
source: Box::new(source.untyped),
path: path.untyped,
},
_p: PhantomData,
}
}
/// Insert an associated record into this has-many relation.
///
/// Converts the association into an update statement that adds `expr` to
/// the relation's field on the source model.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// # #[derive(Debug, toasty::Model)]
/// # struct Todo {
/// # #[key]
/// # id: i64,
/// # user_id: i64,
/// # title: String,
/// # }
/// use toasty::stmt::{Association, Expr, List, Query};
/// use toasty::schema::Model;
///
/// let source = Query::<List<User>>::all().filter(User::fields().id().eq(1));
/// let path = User::path_field::<List<Todo>>(2);
/// let assoc = Association::many(source, path);
///
/// let todo_expr = Expr::<Todo>::from_untyped(
/// toasty_core::stmt::Value::from(42_i64),
/// );
/// let _stmt = assoc.insert(todo_expr);
/// ```
pub fn insert(self, expr: impl IntoExpr<M>) -> Statement<()> {
let [index] = self.untyped.path.projection.as_slice() else {
todo!()
};
let mut stmt = self.untyped.source.update();
stmt.assignments.insert(*index, expr.into_expr().untyped);
Statement {
untyped: stmt.into(),
_p: PhantomData,
}
}
/// Remove an associated record from this has-many relation.
///
/// Converts the association into an update statement that removes `expr`
/// from the relation's field on the source model.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// # #[derive(Debug, toasty::Model)]
/// # struct Todo {
/// # #[key]
/// # id: i64,
/// # user_id: i64,
/// # title: String,
/// # }
/// use toasty::stmt::{Association, Expr, List, Query};
/// use toasty::schema::Model;
///
/// let source = Query::<List<User>>::all().filter(User::fields().id().eq(1));
/// let path = User::path_field::<List<Todo>>(2);
/// let assoc = Association::many(source, path);
///
/// // Remove a todo by its expression
/// let todo_expr = Expr::<Todo>::from_untyped(
/// toasty_core::stmt::Value::from(42_i64),
/// );
/// let _stmt = assoc.remove(todo_expr);
/// ```
pub fn remove(self, expr: impl IntoExpr<M>) -> Statement<()> {
let [index] = self.untyped.path.projection.as_slice() else {
todo!()
};
let mut stmt = self.untyped.source.update();
stmt.assignments.remove(*index, expr.into_expr().untyped);
Statement {
untyped: stmt.into(),
_p: PhantomData,
}
}
/// Append a single field step to this association's path, retargeting it
/// to `NewTarget`. Used by macro-generated chain methods on the `Many`
/// struct — `field_index` must identify a relation field on `M`.
#[doc(hidden)]
pub fn chain_field<NewTarget>(mut self, field_index: usize) -> Association<List<NewTarget>> {
self.untyped.path.projection.push(field_index);
Association {
untyped: self.untyped,
_p: PhantomData,
}
}
}
impl<T: Model> IntoStatement for Association<List<T>> {
type Returning = List<T>;
fn into_statement(self) -> Statement<List<T>> {
let query = stmt::Query::builder(stmt::SourceModel {
id: T::id(),
via: Some(self.untyped),
})
.build();
Statement::from_untyped_stmt(query.into())
}
}
impl<M: Model> IntoScope<M> for Association<List<M>> {
fn into_scope(self) -> Statement<List<M>> {
self.into_statement()
}
}
impl<M: Model> Association<M> {
/// Create a has-one or belongs-to association from `source` following
/// `path`.
///
/// # Panics
///
/// Panics if the root of `path` does not match the model id of `T`.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// # #[derive(Debug, toasty::Model)]
/// # struct Todo {
/// # #[key]
/// # id: i64,
/// # user_id: i64,
/// # title: String,
/// # }
/// use toasty::stmt::{Association, List, Query};
/// use toasty::schema::Model;
///
/// let source = Query::<List<Todo>>::all().filter(Todo::fields().id().eq(1));
/// let path = Todo::path_field::<User>(1);
/// let _assoc = Association::one(source, path);
/// ```
pub fn one<T: Model>(source: super::Query<List<T>>, path: Path<T, M>) -> Self {
assert_eq!(path.untyped.root.as_model_unwrap(), T::id());
Self {
untyped: stmt::Association {
source: Box::new(source.untyped),
path: path.untyped,
},
_p: PhantomData,
}
}
}
impl<T: Model> IntoStatement for Association<T> {
type Returning = List<T>;
fn into_statement(self) -> Statement<List<T>> {
let query = stmt::Query::builder(stmt::SourceModel {
id: T::id(),
via: Some(self.untyped),
})
.build();
Statement::from_untyped_stmt(query.into())
}
}
impl<M: Model> IntoScope<M> for Association<M> {
fn into_scope(self) -> Statement<List<M>> {
self.into_statement()
}
}
impl<M> fmt::Debug for Association<M> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.untyped.fmt(fmt)
}
}