Skip to main content

uqa_execution/mutation/merge/
returning.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! MERGE `RETURNING` row construction and projection.
8
9use crate::mutation::output::MutationOutput;
10use crate::mutation::{
11    returning::{
12        dml_returning_result_with_projections, returning_row_context, returning_value_context,
13        DmlReturningShape, ReturningExecutionContext, ReturningValueProjectionRow,
14    },
15    row_images::MutationRowImages,
16};
17use crate::query::{relational::project_row::build_projection_physical_row_with_ctes, CteScope};
18use uqa_core::Value;
19use uqa_sql::semantics::merge::{
20    expanded_merge_returning_projections, merge_returning_source_schema,
21};
22use uqa_sql::{
23    plan::{MergePlan, ProjectionPlan},
24    SQLError, SQLParam,
25};
26
27#[derive(Clone)]
28pub struct MergeReturningRow<'a> {
29    pub target_table: &'a str,
30    pub target_qual: &'a str,
31    pub images: MutationRowImages<'a>,
32    pub returning_aliases: &'a uqa_sql::ast::ReturningAliases,
33    pub source_row: &'a crate::OwnedPhysicalRow,
34    pub source_schema: &'a crate::RowSchema,
35    pub source_relation: uqa_sql::ast::InternalRelationId,
36    pub action: &'a str,
37}
38
39pub struct ViewMergeReturningRow<'a> {
40    pub table: &'a str,
41    pub target_qualifier: &'a str,
42    pub current: &'a [Value],
43    pub old: Option<&'a [Value]>,
44    pub new: Option<&'a [Value]>,
45    pub returning_aliases: &'a uqa_sql::ast::ReturningAliases,
46    pub source_row: &'a crate::OwnedPhysicalRow,
47    pub source_schema: &'a crate::RowSchema,
48    pub source_relation: uqa_sql::ast::InternalRelationId,
49    pub action: &'a str,
50}
51
52pub struct ViewMergeReturningResult<'a, S: Clone + 'static> {
53    pub stmt: &'a MergePlan,
54    pub source_schema: &'a crate::RowSchema,
55    pub source_relation: uqa_sql::ast::InternalRelationId,
56    pub params: &'a [SQLParam],
57    pub ctes: &'a CteScope<S>,
58    pub rows: crate::mutation::returning::ReturningRows,
59    pub affected: u64,
60}
61
62pub fn build_merge_returning_row<S: Clone + 'static>(
63    context: &ReturningExecutionContext<'_, S>,
64    input: MergeReturningRow<'_>,
65    returning: &[ProjectionPlan],
66    params: &[SQLParam],
67    ctes: &CteScope<S>,
68) -> Result<crate::OwnedPhysicalRow, SQLError> {
69    let row = merge_returning_context(context, input.clone())?;
70    let projections = expanded_merge_returning_projections(
71        context.catalog,
72        input.target_table,
73        input.target_qual,
74        input.returning_aliases,
75        input.source_schema,
76        input.source_relation,
77        returning,
78    )?;
79    let snapshot_scope = ctes.returning_statement_snapshot_scope_with_control(
80        &context
81            .relational
82            .expressions
83            .production_resources()?
84            .control(),
85    )?;
86    build_projection_physical_row_with_ctes(
87        context.relational,
88        &row,
89        &projections,
90        params,
91        &snapshot_scope,
92    )
93}
94
95fn merge_returning_context<S: Clone + 'static>(
96    context: &ReturningExecutionContext<'_, S>,
97    input: MergeReturningRow<'_>,
98) -> Result<crate::OwnedPhysicalRow, SQLError> {
99    let row = returning_row_context(
100        *context,
101        input.target_table,
102        input.target_qual,
103        input.images,
104        input.returning_aliases,
105    )?;
106    append_merge_returning_metadata(
107        row,
108        input.source_row,
109        input.source_schema,
110        input.source_relation,
111        input.action,
112    )
113}
114
115fn append_merge_returning_metadata(
116    mut row: crate::OwnedPhysicalRow,
117    source_row: &crate::OwnedPhysicalRow,
118    source_schema: &crate::RowSchema,
119    source_relation: uqa_sql::ast::InternalRelationId,
120    action: &str,
121) -> Result<crate::OwnedPhysicalRow, SQLError> {
122    row.schema = crate::RowSchema::append_internal_typed(
123        &row.schema,
124        &[(
125            uqa_sql::semantics::merge_action_attribute(),
126            Some(uqa_sql::ast::ColumnType::Text),
127        )],
128    );
129    row.row = row.row.append_values(vec![Value::Str(action.into())]);
130    let aliases = source_schema
131        .columns()
132        .iter()
133        .enumerate()
134        .map(|(position, _)| {
135            let slot = source_row.schema.physical_slot(position).ok_or_else(|| {
136                SQLError::Internal(format!(
137                    "MERGE RETURNING source lost physical column {position}"
138                ))
139            })?;
140            Ok((
141                source_relation.column(position),
142                slot,
143                source_schema.column_type(position).cloned(),
144            ))
145        })
146        .collect::<Result<Vec<_>, SQLError>>()?;
147    let source_schema =
148        crate::RowSchema::with_physical_internal_aliases(&source_row.schema, &aliases);
149    row = crate::OwnedPhysicalRow::new(
150        crate::RowSchema::join(&row.schema, &source_schema, std::iter::empty()),
151        crate::PhysicalRow::concat(&row.row, &source_row.row),
152    );
153    Ok(row)
154}
155
156pub fn build_view_merge_returning_row<S: Clone + 'static>(
157    context: &ReturningExecutionContext<'_, S>,
158    input: ViewMergeReturningRow<'_>,
159    returning: &[ProjectionPlan],
160    params: &[SQLParam],
161    ctes: &CteScope<S>,
162) -> Result<crate::OwnedPhysicalRow, SQLError> {
163    let target = returning_value_context(
164        *context,
165        ReturningValueProjectionRow {
166            table: input.table,
167            target_qualifier: input.target_qualifier,
168            current: input.current,
169            old: input.old,
170            new: input.new,
171            aliases: input.returning_aliases,
172            context: None,
173        },
174    )?;
175    let row = append_merge_returning_metadata(
176        target,
177        input.source_row,
178        input.source_schema,
179        input.source_relation,
180        input.action,
181    )?;
182    let projections = expanded_merge_returning_projections(
183        context.catalog,
184        input.table,
185        input.target_qualifier,
186        input.returning_aliases,
187        input.source_schema,
188        input.source_relation,
189        returning,
190    )?;
191    let snapshot_scope = ctes.returning_statement_snapshot_scope_with_control(
192        &context
193            .relational
194            .expressions
195            .production_resources()?
196            .control(),
197    )?;
198    build_projection_physical_row_with_ctes(
199        context.relational,
200        &row,
201        &projections,
202        params,
203        &snapshot_scope,
204    )
205}
206
207pub fn finish_view_merge_returning<S: Clone + 'static>(
208    context: &ReturningExecutionContext<'_, S>,
209    input: ViewMergeReturningResult<'_, S>,
210) -> Result<MutationOutput, SQLError> {
211    let ViewMergeReturningResult {
212        stmt,
213        source_schema,
214        source_relation,
215        params,
216        ctes,
217        rows,
218        affected,
219    } = input;
220    if stmt.returning.is_empty() {
221        return Ok(MutationOutput::from_affected(affected));
222    }
223    let projections = expanded_merge_returning_projections(
224        context.catalog,
225        &stmt.target,
226        &stmt.target_qualifier,
227        &stmt.returning_aliases,
228        source_schema,
229        source_relation,
230        &stmt.returning,
231    )?;
232    let returning_source_schema = merge_returning_source_schema(source_schema, source_relation);
233    dml_returning_result_with_projections(
234        *context,
235        DmlReturningShape {
236            table: &stmt.target,
237            target_qualifier: &stmt.target_qualifier,
238            aliases: &stmt.returning_aliases,
239            returning: &stmt.returning,
240            params,
241            ctes,
242            supplemental_schema: Some(&returning_source_schema),
243        },
244        &projections,
245        rows,
246        affected,
247    )
248}