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
use super::{Expr, IntoScope, List};
use crate::schema::Model;
use std::{fmt, marker::PhantomData};
use toasty_core::stmt;
/// A typed insert statement for model `M`.
///
/// `Insert` represents one or more records to be created. Generated
/// create-builders (e.g., `User::create()`) produce `Insert` values under the
/// hood.
///
/// The type parameter `M` is the **returning type** — `exec()` produces the
/// newly created `M` instance(s). For inserts, the returning type always
/// matches the model being inserted.
///
/// Field values are set with [`set`](Insert::set). Collection fields can be
/// extended with [`insert_all`](Insert::insert_all).
pub struct Insert<M> {
pub(crate) untyped: stmt::Insert,
_p: PhantomData<M>,
}
impl<M: Model> Insert<M> {
/// Create an insert statement with a single blank record.
///
/// Fields marked `#[auto]` are set to [`Expr::Default`](toasty_core::stmt::Expr::Default)
/// (the database generates the value). All other fields are initialized to
/// `NULL`. The caller must fill in required fields with [`set`](Insert::set)
/// before executing; the blank record is not guaranteed to be valid on its
/// own.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// use toasty::stmt::Insert;
///
/// let mut insert = Insert::<User>::blank_single();
/// // Fill in the required fields
/// insert.set(0, toasty_core::stmt::Value::from(1_i64));
/// insert.set(1, toasty_core::stmt::Value::from("Alice"));
/// ```
pub fn blank_single() -> Self {
Self {
untyped: stmt::Insert {
target: stmt::InsertTarget::Model(M::id()),
source: stmt::Query::new_single(vec![
stmt::ExprRecord::from_vec(
M::schema()
.as_root_unwrap()
.fields
.iter()
.map(|field| match field.auto() {
Some(_) => stmt::Expr::Default,
None => stmt::Expr::Value(stmt::Value::Null),
})
.collect(),
)
.into(),
]),
upsert: None,
returning: Some(stmt::Returning::Model { include: vec![] }),
},
_p: PhantomData,
}
}
/// Set the scope of the insert.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// use toasty::stmt::Insert;
///
/// let mut insert = Insert::<User>::blank_single();
/// // Scope the insert to all users (used by association inserts)
/// insert.set_scope(User::all());
/// ```
pub fn set_scope<S>(&mut self, scope: S)
where
S: IntoScope<M>,
{
self.untyped.target =
stmt::InsertTarget::Scope(Box::new(scope.into_scope().into_untyped_query()));
}
/// Set the value of the field at `field` index in the current record.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// use toasty::stmt::Insert;
///
/// let mut insert = Insert::<User>::blank_single();
/// insert.set(0, toasty_core::stmt::Value::from(1_i64));
/// insert.set(1, toasty_core::stmt::Value::from("Alice"));
/// ```
pub fn set(&mut self, field: usize, expr: impl Into<stmt::Expr>) {
*self.expr_mut(field) = expr.into();
}
/// Merge a list expression into the list field at `field` index,
/// extending any existing list.
///
/// If the field is currently `NULL`, it is replaced with `expr`. If both
/// are lists, the items from `expr` are appended to the existing list.
///
/// # Examples
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// # #[key]
/// # id: i64,
/// # name: String,
/// # }
/// use toasty::stmt::Insert;
///
/// let mut insert = Insert::<User>::blank_single();
/// let list = toasty_core::stmt::Expr::list([
/// toasty_core::stmt::Expr::Value(toasty_core::stmt::Value::from("a")),
/// toasty_core::stmt::Expr::Value(toasty_core::stmt::Value::from("b")),
/// ]);
/// insert.insert_all(1, list);
/// ```
pub fn insert_all(&mut self, field: usize, expr: impl Into<stmt::Expr>) {
let target = self.expr_mut(field);
let incoming = expr.into();
match target {
stmt::Expr::Value(stmt::Value::Null) => {
*target = incoming;
}
stmt::Expr::List(existing) => {
if let stmt::Expr::List(incoming_list) = incoming {
existing.items.extend(incoming_list.items);
} else {
existing.items.push(incoming);
}
}
_ => todo!("existing={target:#?}; expr={:#?}", incoming),
}
}
pub(crate) fn merge(&mut self, stmt: Self) {
self.untyped.merge(stmt.untyped);
}
fn expr_mut(&mut self, field: usize) -> &mut stmt::Expr {
&mut self.current_mut()[field]
}
/// Returns the current record being updated
fn current_mut(&mut self) -> &mut stmt::ExprRecord {
let values = self.untyped.source.body.as_values_mut_unwrap();
values.rows.last_mut().unwrap().as_record_mut_unwrap()
}
/// Convert this insert into a list expression.
///
/// The resulting [`Expr<List<M>>`] wraps the insert as a sub-statement,
/// which can be used as the right-hand side of an association
/// [`insert`](Association::insert) call or embedded in other expressions.
///
pub(crate) fn into_list_expr(self) -> Expr<List<M>> {
Expr::from_untyped(stmt::Expr::Stmt(self.untyped.into()))
}
}
impl<M> Clone for Insert<M> {
fn clone(&self) -> Self {
Self {
untyped: self.untyped.clone(),
_p: PhantomData,
}
}
}
impl<M> From<Insert<M>> for stmt::Expr {
fn from(value: Insert<M>) -> Self {
Self::stmt(value.untyped)
}
}
impl<M> fmt::Debug for Insert<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.untyped.fmt(f)
}
}