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
use super::*;
/// Editable single-row INSERT returned by [`insert()`].
///
/// Assignments stay editable through WITH, RETURNING and ON CONFLICT.
/// Batch, SELECT and DEFAULT VALUES select a complete body and return [`Insert`],
/// which has no additive row setters. Convert with `.into()` when a helper
/// needs a completed `Insert` or [`Stmt`].
#[derive(Clone, Debug)]
#[must_use]
pub struct InsertRow(pub(super) Insert);
impl InsertRow {
pub(super) fn new(target: impl Into<Source>) -> Self {
Self(Insert {
ctes: Vec::new(),
target: target.into(),
body: InsertBody::Values(Vec::new()),
conflict: None,
returning: Vec::new(),
})
}
/// Adds one column assignment. If the same database column was assigned
/// earlier, this assignment replaces the earlier value.
///
/// This makes it safe to layer server-owned values around a DTO mapping:
/// call `values(&dto)` for request-owned fields and use `set(...)` for
/// generated IDs, tenant IDs, status defaults, or explicit overrides.
#[inline]
pub fn set(mut self, assignment: Assignment) -> Self {
push_assignment(self.values_mut(), assignment);
self
}
/// Adds multiple column assignments. Later assignments for the same
/// database column replace earlier values.
pub fn set_many(mut self, assignments: impl IntoAssignments) -> Self {
extend_assignments(self.values_mut(), assignments.into_assignments());
self
}
/// Adds one assignment only when `condition` is true.
#[inline]
pub fn set_if(self, condition: bool, assignment: Assignment) -> Self {
if condition {
self.set(assignment)
} else {
self
}
}
/// Adds one assignment built from an optional value.
pub fn set_option<T>(self, value: Option<T>, f: impl FnOnce(T) -> Assignment) -> Self {
match value {
Some(value) => self.set(f(value)),
None => self,
}
}
/// Adds assignments produced by an [`Insertable`] DTO.
///
/// The assignments participate in the same replacement rules as `set`.
/// Call `values(&dto)` first, then `set(...)` for IDs, tenant fields, or
/// other values owned by the server.
pub fn values(mut self, values: impl Insertable) -> Self {
extend_assignments(self.values_mut(), values.insert_assignments());
self
}
/// Adds many [`Insertable`] DTO rows through `INSERT ... SELECT` over an
/// inline `VALUES` source.
///
/// Every row must produce the same insert fields in the same order. This is
/// usually true for DTOs without `#[rqb(skip_none)]`; if optional insert
/// fields can be omitted per row, normalize the input first or build an
/// explicit `values_source(...)`.
/// The row builder must not already contain single-row assignments.
///
/// For an upsert, use `do_update_excluded` or `set_excluded`: PostgreSQL
/// exposes incoming values as `EXCLUDED` in the conflict action.
pub fn values_many<I, R>(self, rows: I) -> Result<Insert>
where
I: IntoIterator<Item = R>,
R: Insertable,
{
if !matches!(&self.0.body, InsertBody::Values(assignments) if assignments.is_empty()) {
return Err(Error::InvalidInsertShape {
message: "batch insert cannot be combined with existing single-row assignments",
});
}
let mut columns = None::<Vec<Meta>>;
let mut values: Vec<Vec<ValueExpr>> = Vec::new();
for row in rows {
let assignments = normalized_assignments(row.insert_assignments());
if assignments.is_empty() {
return Err(Error::InvalidInsertShape {
message: "batch insert rows must contain at least one assignment",
});
}
match &columns {
Some(columns) if !same_batch_fields(columns, &assignments) => {
return Err(Error::InvalidInsertShape {
message: "batch insert rows must use the same fields in the same order",
});
}
Some(_) => {}
None => {
columns = Some(
assignments
.iter()
.map(|assignment| assignment.field)
.collect(),
);
}
}
values.push(
assignments
.into_iter()
.map(|assignment| match assignment.value {
// VALUES resolves all-NULL columns before target coercion.
AssignmentValue::Expr(ValueExpr::Null) => {
Ok(ValueExpr::Null.cast(assignment.field.pg))
}
AssignmentValue::Expr(expr) => Ok(expr),
AssignmentValue::Default => Err(Error::InvalidInsertShape {
message: "batch insert rows cannot use DEFAULT assignments",
}),
})
.collect::<Result<Vec<_>>>()?,
);
}
let Some(columns) = columns else {
return Err(Error::InvalidInsertShape {
message: "batch insert requires at least one row",
});
};
Ok(self.from_select_all(crate::values_source(values, "incoming", columns)))
}
/// Replaces the row body with an INSERT ... SELECT.
pub fn from_select(self, columns: impl IntoFieldMetas, select: Select) -> Insert {
self.0.from_select(columns, select)
}
/// Replaces the row body with all exposed source fields.
pub fn from_select_all(self, source: impl Into<Source>) -> Insert {
self.0.from_select_all(source)
}
/// Replaces the row body with PostgreSQL DEFAULT VALUES.
pub fn default_values(self) -> Insert {
self.0.default_values()
}
/// Validates the insert without rendering SQL.
pub fn validate(&self) -> Result<()> {
self.0.validate()
}
/// Validates and renders parameterized SQL without consuming the row builder.
pub fn build(&self) -> Result<crate::BuiltQuery> {
self.0.build()
}
pub(crate) fn check_returning(&self) -> Result<()> {
self.0.check_returning()
}
fn values_mut(&mut self) -> &mut Vec<Assignment> {
let InsertBody::Values(assignments) = &mut self.0.body else {
unreachable!("InsertRow only constructs and preserves the Values body")
};
assignments
}
}
impl From<InsertRow> for Insert {
fn from(row: InsertRow) -> Self {
row.0
}
}
impl Insert {
/// Uses a select statement as the insert source.
///
/// `columns` owns the complete target-column list for the insert-select
/// body. This keeps the AST from carrying pending target columns before a
/// select source exists.
pub fn from_select(mut self, columns: impl IntoFieldMetas, select: Select) -> Self {
self.body = InsertBody::Select {
columns: columns.into_field_metas(),
select: Box::new(select),
};
self
}
/// Uses every exposed field from `source` as both target columns and the
/// `INSERT ... SELECT` projection.
///
/// This is the compact path for bulk loads from `values_source(...)` or
/// staging sources whose exposed metadata already matches the insert target.
pub fn from_select_all(mut self, source: impl Into<Source>) -> Self {
let source = source.into();
let qualifier = source.explicit_alias().map(str::to_owned);
let mut columns = Vec::new();
let mut projection = Vec::new();
source.for_each_field(|field| {
push_column(&mut columns, *field);
projection.push(SelectItem {
expr: ValueExpr::field(*field, qualifier.clone()),
alias: None,
});
});
let mut select = Select::from(source);
select.projection = projection;
self.body = InsertBody::Select {
columns,
select: Box::new(select),
};
self
}
/// Uses PostgreSQL `DEFAULT VALUES` instead of explicit insert values.
///
/// This is for rows where every target column should be populated by its
/// database default or remain nullable. It can still be combined with
/// `RETURNING` and `ON CONFLICT`. A later `from_select(...)` or
/// `from_select_all(...)` explicitly replaces this body.
#[inline]
pub fn default_values(mut self) -> Self {
self.body = InsertBody::DefaultValues;
self
}
}
macro_rules! impl_insert_clauses {
($ty:ty $(, $field:tt)?) => {
impl $ty {
/// Adds a CTE to the insert statement.
#[inline]
pub fn with(mut self, cte: Cte) -> Self {
self $(.$field)?.ctes.push(cte);
self
}
/// Starts an `ON CONFLICT (columns...)` clause.
/// Completing a later conflict clause replaces the previous clause.
///
/// Use this for column/index targets. For a named database constraint, use
/// [`Insert::on_conflict_constraint`] with a generated constraint constant.
pub fn on_conflict(self, fields: impl ConflictFields) -> ColumnConflictBuilder<Self> {
let mut target_fields = Vec::with_capacity(fields.conflict_field_count());
fields.push_conflict_fields(&mut target_fields);
ColumnConflictBuilder {
insert: self,
fields: target_fields,
predicate: None,
}
}
/// Starts an `ON CONFLICT ON CONSTRAINT` clause.
/// Completing a later conflict clause replaces the previous clause.
///
/// Generated schema exposes unique constraint names under
/// `relation::constraints`.
pub fn on_conflict_constraint(
self,
constraint: impl Into<String>,
) -> ConstraintConflictBuilder<Self> {
ConstraintConflictBuilder {
insert: self,
constraint: constraint.into(),
}
}
/// Adds one or more fields to `RETURNING`.
///
/// Use a field for one returned column or tuple syntax for a small
/// heterogeneous field list: `.returning((users::ID, users::EMAIL))`.
pub fn returning(mut self, fields: impl IntoColumns) -> Self {
self $(.$field)?.returning.extend(fields.into_columns().items);
self
}
/// Adds an aliased expression to `RETURNING`.
pub fn returning_as(mut self, expr: impl Into<ValueExpr>, alias: impl Into<String>) -> Self {
self $(.$field)?.returning.push(SelectItem {
expr: expr.into(),
alias: Some(alias.into()),
});
self
}
/// Replaces `RETURNING` with every field exposed by the target source.
#[inline]
pub fn returning_all(mut self) -> Self {
self $(.$field)?.returning.clear();
push_returning_fields(&self $(.$field)?.target, &mut self $(.$field)?.returning);
self
}
}
};
}
impl_insert_clauses!(Insert);
impl_insert_clauses!(InsertRow, 0);
fn same_batch_fields(columns: &[Meta], assignments: &[Assignment]) -> bool {
columns.len() == assignments.len()
&& columns
.iter()
.zip(assignments)
.all(|(column, assignment)| column.db == assignment.field.db)
}