uqa-execution 0.5.0

Volcano physical operators with row-batch pipelines
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! INSERT conflict tuple locking, EXCLUDED projection and typed update preparation.
use super::{find_insert_conflict, CurrentInsertConflict, InsertConflictOverlay};
use crate::mutation::{
    assignment::MutationAssignmentTarget,
    candidate::{MutationLockTarget, PhysicalDocumentIdentity},
    constraints::lock_document_key_dependencies,
    errors::{dml_storage_error, missing_document_error},
    expressions::eval_mutation_expr,
    locking::{lock_mutation_target, MutationLockCleanup},
    prepared::PreparedInsertConflict,
    referential::{prepare_document_rewrite, reject_partition_rewrite, ReferentialContext},
    rows::{
        append_hidden_qualified_row as dml_append_hidden_qualified_row,
        target_row as dml_target_row,
    },
};
use crate::query::locking::context::update_lock_strength;
use crate::query::CteScope;
use uqa_core::{DocId, Value};
use uqa_sql::{
    plan::{ConflictActionPlan, ConflictPlan},
    SQLError, SQLParam,
};
use uqa_storage::document_store::Document;
pub struct InsertConflictPreparation<'a, S: Clone + 'static> {
    pub context: ReferentialContext<'a, S>,
    pub table: &'a str,
    pub target_qualifier: &'a str,
    pub on_conflict: &'a ConflictPlan,
    pub document: &'a Document,
    pub params: &'a [SQLParam],
    pub scope: &'a CteScope<S>,
}

fn on_conflict_cardinality_violation() -> SQLError {
    SQLError::Diagnostic {
        sqlstate: "21000".into(),
        message: "ON CONFLICT DO UPDATE command cannot affect row a second time".into(),
        detail: None,
        hint: Some(
            "Ensure that no rows proposed for insertion within the same command have duplicate constrained values."
                .into(),
        ),
    }
}

enum BuiltConflictUpdate {
    Skip,
    Update {
        old_document: Document,
        new_document: Document,
    },
}

#[expect(
    clippy::too_many_arguments,
    reason = "keeps DML row-image inputs aligned"
)]
fn build_conflict_update<S: Clone + 'static>(
    context: &ReferentialContext<'_, S>,
    table: &str,
    target_qualifier: &str,
    existing_id: DocId,
    document: &Document,
    assignments: &[uqa_sql::plan::AssignmentPlan],
    predicate: Option<&crate::ScalarExpr>,
    params: &[SQLParam],
    scope: &CteScope<S>,
) -> Result<BuiltConflictUpdate, SQLError> {
    let existing_doc = context
        .locking
        .rows
        .get_document_for_mutation(table, existing_id)?
        .ok_or_else(|| missing_document_error("INSERT ON CONFLICT", table, existing_id))?;
    let target_row = dml_target_row(
        context.assignment.rows,
        table,
        target_qualifier,
        existing_id,
        &existing_doc,
    )?;
    let conflict_row = conflict_evaluation_row(context, table, &target_row, document)?;
    if let Some(predicate) = predicate {
        let keep = eval_mutation_expr(
            context.assignment.expressions,
            scope,
            predicate,
            Some(&conflict_row),
            params,
        )?;
        if !uqa_sql::expr::truthy(&keep) {
            return Ok(BuiltConflictUpdate::Skip);
        }
    }
    let mut updated_doc = existing_doc.clone();
    for (position, assignment) in assignments.iter().enumerate() {
        let source = crate::mutation::assignment::AssignmentSource::evaluate(
            context.assignment,
            scope,
            assignment,
            Some(&conflict_row),
            params,
        )?;
        for (target_position, target) in assignment.target.targets().iter().enumerate() {
            let value = crate::mutation::assignment::eval_mutation_assignment_input(
                context.assignment,
                scope,
                MutationAssignmentTarget {
                    table,
                    target,
                    current: updated_doc.get(&target.column),
                    final_column_write: crate::mutation::assignment::final_column_write(
                        assignments,
                        position,
                        target_position,
                    ),
                    action: "INSERT ON CONFLICT DO UPDATE",
                    new_row: false,
                },
                source.input(assignment.target.source_position(target_position)),
                Some(&conflict_row),
                params,
            )?;
            if let Some(value) = value {
                updated_doc.insert(target.column.clone(), value);
            } else {
                updated_doc.remove(&target.column);
            }
        }
    }
    Ok(BuiltConflictUpdate::Update {
        old_document: existing_doc,
        new_document: updated_doc,
    })
}

/// Locks every currently visible ON CONFLICT dependency for an INSERT input set while the storage transaction is still a reader. DO NOTHING locks are retained only until writer promotion; DO UPDATE target locks keep their normal transaction lifetime. Once the single backend writer is held no concurrent transaction can create a new physical conflict and make the execution phase wait behind a tuple owner.
pub struct InsertConflictLocks {
    transient: MutationLockCleanup,
    overlay: Option<InsertConflictOverlay>,
}

impl InsertConflictLocks {
    pub fn new<S: Clone + 'static>(context: &ReferentialContext<'_, S>) -> Self {
        Self {
            transient: MutationLockCleanup::new(context.locking.session),
            overlay: None,
        }
    }

    pub fn lock_document<S: Clone + 'static>(
        &mut self,
        context: &ReferentialContext<'_, S>,
        table: &str,
        target_qualifier: &str,
        on_conflict: &ConflictPlan,
        document: &Document,
    ) -> Result<(), SQLError> {
        for _ in 0..=64 {
            let Some(existing) =
                find_insert_conflict(context.constraints, table, on_conflict, document)?
            else {
                return Ok(());
            };
            let (locked, recheck) = match &on_conflict.action {
                ConflictActionPlan::Nothing => (
                    existing.clone(),
                    self.transient.acquire(
                        context.locking.session,
                        &existing.table,
                        target_qualifier,
                        existing.doc_id,
                        uqa_sql::ast::LockStrength::ForKeyShare,
                    )?,
                ),
                ConflictActionPlan::Update { assignments, .. } => {
                    match lock_mutation_target(
                        context.locking.session,
                        &existing.table,
                        target_qualifier,
                        existing.doc_id,
                        update_lock_strength(
                            context.locking.catalog,
                            &existing.table,
                            &assignments
                                .iter()
                                .flat_map(|assignment| assignment.target.column_names())
                                .map(str::to_owned)
                                .collect::<Vec<_>>(),
                        ),
                    )? {
                        MutationLockTarget::Present { doc_id, recheck } => (
                            PhysicalDocumentIdentity {
                                table: existing.table,
                                doc_id,
                            },
                            recheck,
                        ),
                        MutationLockTarget::Deleted => {
                            context
                                .constraints
                                .transactions
                                .refresh_explicit_statement_snapshot()?;
                            continue;
                        }
                    }
                }
            };
            if recheck {
                context
                    .constraints
                    .transactions
                    .refresh_explicit_statement_snapshot()?;
            }
            if find_insert_conflict(context.constraints, table, on_conflict, document)?
                == Some(locked)
            {
                return Ok(());
            }
        }
        Err(SQLError::Internal(format!(
            "INSERT conflict lookup for `{table}` did not converge"
        )))
    }

    #[expect(clippy::too_many_lines, reason = "preserves DML lock and event order")]
    pub fn prepare_document<S: Clone + 'static>(
        &mut self,
        preparation: InsertConflictPreparation<'_, S>,
    ) -> Result<PreparedInsertConflict, SQLError> {
        let InsertConflictPreparation {
            context,
            table,
            target_qualifier,
            on_conflict,
            document,
            params,
            scope,
        } = preparation;
        let key_acquisitions =
            lock_document_key_dependencies(context.constraints, table, document, None)?;
        if self.overlay.is_none() {
            self.overlay = Some(InsertConflictOverlay::new(
                context.constraints,
                table,
                on_conflict,
            )?);
        }
        let current = self
            .overlay
            .as_ref()
            .ok_or_else(|| SQLError::Internal("INSERT conflict overlay is absent".into()))?
            .find(context.constraints, table, document)?;
        match current {
            None => {
                self.overlay
                    .as_mut()
                    .ok_or_else(|| SQLError::Internal("INSERT conflict overlay is absent".into()))?
                    .note_insert(context.constraints, table, document)?;
                return Ok(PreparedInsertConflict::Unresolved);
            }
            Some(CurrentInsertConflict::Overlay) => {
                self.transient.rollback(key_acquisitions);
                return match &on_conflict.action {
                    ConflictActionPlan::Nothing => Ok(PreparedInsertConflict::Skip),
                    ConflictActionPlan::Update { .. } => Err(on_conflict_cardinality_violation()),
                };
            }
            Some(CurrentInsertConflict::Base(_)) => {}
        }
        self.lock_document(&context, table, target_qualifier, on_conflict, document)?;
        let current = self
            .overlay
            .as_ref()
            .ok_or_else(|| SQLError::Internal("INSERT conflict overlay is absent".into()))?
            .find(context.constraints, table, document)?;
        let existing = match current {
            None => {
                self.overlay
                    .as_mut()
                    .ok_or_else(|| SQLError::Internal("INSERT conflict overlay is absent".into()))?
                    .note_insert(context.constraints, table, document)?;
                return Ok(PreparedInsertConflict::Unresolved);
            }
            Some(CurrentInsertConflict::Overlay) => {
                self.transient.rollback(key_acquisitions);
                return match &on_conflict.action {
                    ConflictActionPlan::Nothing => Ok(PreparedInsertConflict::Skip),
                    ConflictActionPlan::Update { .. } => Err(on_conflict_cardinality_violation()),
                };
            }
            Some(CurrentInsertConflict::Base(identity)) => identity,
        };
        self.transient.retain(key_acquisitions);
        let ConflictActionPlan::Update {
            assignments,
            predicate,
        } = &on_conflict.action
        else {
            return Ok(PreparedInsertConflict::Skip);
        };
        // Another command of the statement, or a statement its triggers or functions started, inserted or rewrote the conflicting row, whose version `PostgreSQL`'s `ExecOnConflictUpdate` finds invisible to the statement's command id.
        if scope.statement_wrote(&existing) || scope.statement_triggered_write(&existing) {
            return Err(on_conflict_cardinality_violation());
        }
        match build_conflict_update(
            &context,
            &existing.table,
            target_qualifier,
            existing.doc_id,
            document,
            assignments,
            predicate.as_deref(),
            params,
            scope,
        )? {
            BuiltConflictUpdate::Skip => Ok(PreparedInsertConflict::Skip),
            BuiltConflictUpdate::Update {
                old_document,
                mut new_document,
            } => {
                let updated_columns = assignments
                    .iter()
                    .flat_map(|assignment| assignment.target.column_names())
                    .map(str::to_owned)
                    .collect::<Vec<_>>();
                let Some(triggered_document) = crate::mutation::triggers::fire_before_row_triggers(
                    &context.triggers,
                    &existing.table,
                    uqa_sql::ast::TriggerEvent::Update,
                    existing.doc_id,
                    Some(&old_document),
                    Some(&new_document),
                    &updated_columns,
                )?
                else {
                    return Ok(PreparedInsertConflict::Skip);
                };
                new_document = triggered_document;
                let prepared = prepare_document_rewrite(
                    &context,
                    &existing.table,
                    &existing.table,
                    existing.doc_id,
                    old_document,
                    new_document,
                )?;
                reject_partition_rewrite(&context, &prepared, params)?;
                self.overlay
                    .as_mut()
                    .ok_or_else(|| SQLError::Internal("INSERT conflict overlay is absent".into()))?
                    .note_update(context.constraints, &existing, &prepared.new_document)?;
                Ok(PreparedInsertConflict::Updated(prepared))
            }
        }
    }
}

fn conflict_evaluation_row<S: Clone + 'static>(
    context: &ReferentialContext<'_, S>,
    table: &str,
    target_row: &crate::OwnedPhysicalRow,
    document: &Document,
) -> Result<crate::OwnedPhysicalRow, SQLError> {
    let definitions = context
        .constraints
        .catalog
        .try_describe_table(table)
        .map_err(|error| dml_storage_error("INSERT EXCLUDED schema", error))?
        .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?;
    let mut excluded_document = document.clone();
    crate::query::generated::materialize_virtual_generated_columns(
        &definitions,
        &mut excluded_document,
    )?;
    let excluded_columns = if definitions.is_empty() {
        excluded_document.keys().cloned().collect::<Vec<_>>()
    } else {
        definitions
            .iter()
            .map(|definition| definition.name.clone())
            .collect::<Vec<_>>()
    };
    let excluded_types = excluded_columns
        .iter()
        .map(|column| {
            definitions
                .iter()
                .find(|definition| definition.name == *column)
                .map(|definition| definition.ty.clone())
        })
        .collect::<Vec<_>>();
    let excluded_values = excluded_columns
        .iter()
        .map(|column| {
            excluded_document
                .get(column)
                .cloned()
                .unwrap_or(Value::Null)
        })
        .collect();
    Ok(dml_append_hidden_qualified_row(
        target_row,
        "excluded",
        &excluded_columns,
        &excluded_types,
        excluded_values,
    ))
}