Skip to main content

uqa_execution/mutation/rules/
returning.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Physical capture and outer projection of a rule action's RETURNING rows.
8use super::RuleRows;
9use crate::mutation::output::MutationOutput;
10use crate::{
11    mutation::returning::{
12        build_returning_value_row, dml_returning_result, DmlReturningShape,
13        ReturningExecutionContext, ReturningRows, ReturningValueProjectionRow,
14    },
15    OwnedPhysicalRow, PhysicalRow, RowSchema,
16};
17use uqa_core::Value;
18use uqa_sql::SQLError;
19
20pub struct RuleReturningResult {
21    images: ReturningRows,
22    width: usize,
23    source_rows: Option<RuleRows>,
24    affected_rows: u64,
25}
26
27impl RuleReturningResult {
28    pub fn empty() -> Self {
29        Self {
30            images: ReturningRows::default(),
31            width: 0,
32            source_rows: None,
33            affected_rows: 0,
34        }
35    }
36
37    pub fn project<S: Clone + 'static>(
38        self,
39        context: ReturningExecutionContext<'_, S>,
40        shape: DmlReturningShape<'_, S>,
41    ) -> Result<MutationOutput, SQLError> {
42        let mut rows = ReturningRows::new(context.relational.runtime)?;
43        for image in self.images.into_rows()? {
44            let image = image?;
45            let values = image.row.into_physical_values();
46            let source = source_index(&values, self.width * 3, self.source_rows.as_ref())?
47                .map(|index| {
48                    self.source_rows
49                        .as_ref()
50                        .expect("validated source owner")
51                        .get(index)
52                })
53                .transpose()?;
54            rows.push(build_returning_value_row(
55                context,
56                ReturningValueProjectionRow {
57                    table: shape.table,
58                    target_qualifier: shape.target_qualifier,
59                    current: &values[..self.width],
60                    old: Some(&values[self.width..self.width * 2]),
61                    new: Some(&values[self.width * 2..self.width * 3]),
62                    aliases: shape.aliases,
63                    context: source.as_ref().and_then(|source| source.context.as_ref()),
64                },
65                shape.returning,
66                shape.params,
67                shape.ctes,
68            )?)?;
69        }
70        dml_returning_result(context, shape, rows, self.affected_rows)
71    }
72}
73
74pub fn capture_rule_returning_result(
75    mut images: ReturningRows,
76    assignment: &dyn uqa_sql::assignment::AssignmentContext,
77    result: MutationOutput,
78    columns: &[uqa_sql::ast::ColumnDef],
79    source_rows: Option<RuleRows>,
80) -> Result<RuleReturningResult, SQLError> {
81    let width = columns.len();
82    let image_width = width.saturating_mul(3);
83    let expected_width = image_width + usize::from(source_rows.is_some());
84    if result.schema.len() != expected_width {
85        return Err(SQLError::Internal(format!(
86            "rewrite-rule RETURNING provider produced {} columns, expected {}",
87            result.schema.len(),
88            expected_width
89        )));
90    }
91    let schema = RowSchema::new(result.schema.columns().to_vec());
92    let affected_rows = result.affected_rows;
93    for batch in result.into_batches() {
94        let batch = batch?;
95        for row in batch.rows {
96            let row = OwnedPhysicalRow::new(batch.schema.clone(), row);
97            let row = row.view();
98            let mut values = Vec::with_capacity(expected_width);
99            for offset in [0, width, width * 2] {
100                for (position, column) in columns.iter().enumerate() {
101                    let value = row.value_at(offset + position).cloned().ok_or_else(|| {
102                        SQLError::Internal(
103                            "rewrite-rule RETURNING provider lost a positional value".into(),
104                        )
105                    })?;
106                    values.push(uqa_sql::assignment::conversion::coerce_assignment_value(
107                        assignment,
108                        value,
109                        &column.ty,
110                        batch.schema.column_type(offset + position),
111                    )?);
112                }
113            }
114            if source_rows.is_some() {
115                values.push(row.value_at(image_width).cloned().ok_or_else(|| {
116                    SQLError::Internal(
117                        "rewrite-rule RETURNING provider lost its source index".into(),
118                    )
119                })?);
120            }
121            source_index(&values, image_width, source_rows.as_ref())?;
122            images.push(OwnedPhysicalRow::new(
123                schema.clone(),
124                PhysicalRow::from_values(values),
125            ))?;
126        }
127    }
128    Ok(RuleReturningResult {
129        images,
130        width,
131        source_rows,
132        affected_rows,
133    })
134}
135
136fn source_index(
137    values: &[Value],
138    image_width: usize,
139    source_rows: Option<&RuleRows>,
140) -> Result<Option<usize>, SQLError> {
141    let Some(source_rows) = source_rows else {
142        return Ok(None);
143    };
144    let source_index = match values.get(image_width) {
145        Some(Value::Int(index)) if *index >= 0 => usize::try_from(*index).map_err(|_| {
146            SQLError::Internal("rewrite-rule RETURNING source index exceeds usize".into())
147        })?,
148        Some(value) => {
149            return Err(SQLError::Internal(format!(
150                "rewrite-rule RETURNING source index is not a non-negative integer: {value:?}"
151            )))
152        }
153        None => {
154            return Err(SQLError::Internal(
155                "rewrite-rule RETURNING provider lost its source index".into(),
156            ))
157        }
158    };
159    (source_index < source_rows.len())
160        .then_some(Some(source_index))
161        .ok_or_else(|| {
162            SQLError::Internal(
163                "rewrite-rule RETURNING source index is outside the event row set".into(),
164            )
165        })
166}
167
168#[cfg(test)]
169mod tests;