Skip to main content

uqa_execution/mutation/
output.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Completed mutation output remains bounded until a public caller requests owned SQL rows.
8
9use super::returning::{ReturningBatchReader, ReturningRows};
10use crate::{
11    physical::{physical_exec_error, ExecError, ExecResult},
12    Batch, OwnedPhysicalRow, PhysicalOperator, RowSchema,
13};
14use std::collections::BTreeSet;
15use uqa_sql::{SQLError, SQLResult};
16
17pub struct MutationOutput {
18    pub schema: RowSchema,
19    pub affected_rows: u64,
20    rows: Option<ReturningBatchReader>,
21    row_count: usize,
22}
23
24impl MutationOutput {
25    pub fn from_affected(affected_rows: u64) -> Self {
26        Self {
27            schema: RowSchema::new(Vec::new()),
28            affected_rows,
29            rows: None,
30            row_count: 0,
31        }
32    }
33
34    pub(crate) fn from_returning(
35        schema: RowSchema,
36        rows: ReturningRows,
37        affected_rows: u64,
38    ) -> Result<Self, SQLError> {
39        if !schema.is_identity_layout()
40            || schema.physical_width() != schema.len()
41            || rows
42                .schema()
43                .is_some_and(|source| source.columns() != schema.columns())
44        {
45            return Err(SQLError::Internal(
46                "RETURNING values do not match their bound output columns".into(),
47            ));
48        }
49        let row_count = rows.len();
50        Ok(Self {
51            schema,
52            affected_rows,
53            rows: Some(rows.into_batches()?),
54            row_count,
55        })
56    }
57
58    pub fn row_count(&self) -> usize {
59        self.row_count
60    }
61
62    pub fn into_batches(self) -> MutationBatches {
63        MutationBatches {
64            schema: self.schema,
65            rows: self.rows,
66        }
67    }
68
69    pub fn into_operator(self) -> Box<dyn PhysicalOperator> {
70        Box::new(MutationScan {
71            count: self.row_count,
72            batches: self.into_batches(),
73            opened: false,
74        })
75    }
76
77    pub fn into_sql_result(self) -> Result<SQLResult, SQLError> {
78        let schema = self.schema.clone();
79        let affected = self.affected_rows;
80        let preserve_positions =
81            schema.columns().iter().collect::<BTreeSet<_>>().len() != schema.len();
82        let mut named_rows = Vec::with_capacity(self.row_count);
83        let mut positional_rows = preserve_positions.then(|| Vec::with_capacity(self.row_count));
84        for batch in self.into_batches() {
85            let batch = batch?;
86            for row in batch.rows {
87                let row = OwnedPhysicalRow::new(batch.schema.clone(), row);
88                if let Some(positional_rows) = positional_rows.as_mut() {
89                    positional_rows
90                        .push(row.view().iter().map(|(_, value)| value.clone()).collect());
91                }
92                named_rows.push(row.into_result_row());
93            }
94        }
95        let mut result =
96            SQLResult::from_schema_rows_with_positions(schema, named_rows, positional_rows);
97        result.affected_rows = affected;
98        Ok(result)
99    }
100}
101
102pub struct MutationBatches {
103    schema: RowSchema,
104    rows: Option<ReturningBatchReader>,
105}
106
107impl Iterator for MutationBatches {
108    type Item = Result<Batch, SQLError>;
109
110    fn next(&mut self) -> Option<Self::Item> {
111        self.rows.as_mut()?.next().map(|batch| {
112            let mut batch = batch.map_err(physical_exec_error)?;
113            // The producer retained dense positional values; final binding owns the public types, collations and record descriptors.
114            batch.schema = self.schema.clone();
115            Ok(batch)
116        })
117    }
118}
119
120struct MutationScan {
121    count: usize,
122    batches: MutationBatches,
123    opened: bool,
124}
125
126impl PhysicalOperator for MutationScan {
127    fn row_schema(&self) -> &RowSchema {
128        &self.batches.schema
129    }
130    fn estimated_cardinality(&self) -> Option<u64> {
131        u64::try_from(self.count).ok()
132    }
133    fn open(&mut self) -> ExecResult<()> {
134        if self.opened {
135            return Err(ExecError::Other(
136                "mutation output cannot be reopened".into(),
137            ));
138        }
139        self.opened = true;
140        Ok(())
141    }
142    fn next(&mut self) -> ExecResult<Option<Batch>> {
143        self.batches.next().transpose().map_err(ExecError::from)
144    }
145    fn close(&mut self) -> ExecResult<()> {
146        self.batches.rows = None;
147        Ok(())
148    }
149}