Skip to main content

uqa_execution/mutation/
rows.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Construct physical mutation rows, including generated values and tuple identity columns.
8
9pub mod context;
10use crate::{ColumnIdentity, OwnedPhysicalRow, PhysicalRow, RowSchema};
11use context::MutationRowContext;
12use std::collections::BTreeSet;
13use uqa_core::{DocId, Value};
14use uqa_sql::{
15    semantics::{doc_id_value, DOC_ID_COLUMN, TABLE_OID_COLUMN, XMIN_COLUMN},
16    ColumnType, SQLError,
17};
18use uqa_storage::document_store::Document;
19fn dml_storage_error(action: &str, error: impl std::fmt::Display) -> SQLError {
20    SQLError::Internal(format!("{action} failed in storage backend: {error}"))
21}
22
23pub fn is_virtual_document_id_column(
24    column: &str,
25    definitions: &[uqa_sql::ast::ColumnDef],
26) -> bool {
27    column == DOC_ID_COLUMN
28        && !definitions
29            .iter()
30            .any(|definition| definition.name == DOC_ID_COLUMN)
31}
32
33/// The value of an integer primary-key column in a row image: the stored value, or, for an image that lacks the column, the key its identity names. An identity no key names says nothing of the key.
34pub fn integer_key_value(
35    document: &Document,
36    column: &str,
37    doc_id: Option<DocId>,
38) -> Result<Value, SQLError> {
39    if let Some(value) = document.get(column) {
40        return Ok(value.clone());
41    }
42    doc_id
43        .filter(|doc_id| uqa_sql::semantics::key_identity::is_key_document_id(*doc_id))
44        .map_or(Ok(Value::Null), doc_id_value)
45}
46
47pub fn target_row(
48    context: MutationRowContext<'_>,
49    table: &str,
50    qualifier: &str,
51    doc_id: DocId,
52    document: &Document,
53) -> Result<OwnedPhysicalRow, SQLError> {
54    target_row_for_storage(context, table, table, qualifier, doc_id, document)
55}
56
57pub fn target_row_for_storage(
58    context: MutationRowContext<'_>,
59    table: &str,
60    storage_table: &str,
61    qualifier: &str,
62    doc_id: DocId,
63    document: &Document,
64) -> Result<OwnedPhysicalRow, SQLError> {
65    target_row_for_storage_optional(
66        context,
67        table,
68        Some(storage_table),
69        qualifier,
70        Some(doc_id),
71        document,
72        None,
73    )
74}
75
76pub fn target_row_for_storage_optional(
77    context: MutationRowContext<'_>,
78    table: &str,
79    storage_table: Option<&str>,
80    qualifier: &str,
81    doc_id: Option<DocId>,
82    document: &Document,
83    selected_columns: Option<&BTreeSet<String>>,
84) -> Result<OwnedPhysicalRow, SQLError> {
85    let metadata = match (storage_table, doc_id) {
86        (Some(storage_table), Some(doc_id)) => context
87            .tuples
88            .document_metadata(storage_table, doc_id)?
89            .unwrap_or_default(),
90        _ => uqa_storage::DocumentMetadata::default(),
91    };
92    target_row_for_storage_optional_with_metadata(
93        context,
94        table,
95        storage_table,
96        qualifier,
97        doc_id,
98        document,
99        selected_columns,
100        metadata,
101    )
102}
103
104pub fn existing_tuple_metadata(
105    context: MutationRowContext<'_>,
106    table: &str,
107    doc_id: DocId,
108) -> Result<uqa_storage::DocumentMetadata, SQLError> {
109    context
110        .tuples
111        .document_metadata(table, doc_id)?
112        .ok_or_else(|| {
113            SQLError::Internal(format!(
114                "document `{table}` row {doc_id} has no tuple metadata"
115            ))
116        })
117}
118
119pub fn new_tuple_metadata(
120    context: MutationRowContext<'_>,
121) -> Result<uqa_storage::DocumentMetadata, SQLError> {
122    Ok(uqa_storage::DocumentMetadata::with_tuple_xmin(
123        context.tuples.tuple_version_xid()?,
124    ))
125}
126
127#[expect(
128    clippy::too_many_arguments,
129    reason = "keeps mutation identity and tuple metadata explicit"
130)]
131pub fn target_row_for_storage_optional_with_metadata(
132    context: MutationRowContext<'_>,
133    table: &str,
134    storage_table: Option<&str>,
135    qualifier: &str,
136    doc_id: Option<DocId>,
137    document: &Document,
138    selected_columns: Option<&BTreeSet<String>>,
139    metadata: uqa_storage::DocumentMetadata,
140) -> Result<OwnedPhysicalRow, SQLError> {
141    let definitions = context
142        .relations
143        .column_definitions(table)
144        .map_err(|error| dml_storage_error("DML row schema lookup", error))?
145        .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?;
146    let mut materialized = document.clone();
147    if let Some(selected_columns) = selected_columns {
148        crate::query::generated::materialize_selected_virtual_generated_columns(
149            &definitions,
150            &mut materialized,
151            selected_columns,
152        )?;
153    } else {
154        crate::query::generated::materialize_virtual_generated_columns(
155            &definitions,
156            &mut materialized,
157        )?;
158    }
159    let mut columns = if definitions.is_empty() {
160        materialized
161            .keys()
162            .filter(|column| column.as_str() != XMIN_COLUMN)
163            .cloned()
164            .collect::<Vec<_>>()
165    } else {
166        definitions
167            .iter()
168            .map(|definition| definition.name.clone())
169            .collect::<Vec<_>>()
170    };
171    let mut types = columns
172        .iter()
173        .map(|column| {
174            definitions
175                .iter()
176                .find(|definition| definition.name == *column)
177                .map(|definition| definition.ty.clone())
178        })
179        .collect::<Vec<_>>();
180    if !columns.iter().any(|column| column == DOC_ID_COLUMN) {
181        columns.push(DOC_ID_COLUMN.into());
182        types.push(Some(ColumnType::BigInteger));
183    }
184    columns.push(TABLE_OID_COLUMN.into());
185    types.push(Some(ColumnType::Oid));
186    columns.push(XMIN_COLUMN.into());
187    types.push(Some(ColumnType::Xid));
188    let values = columns
189        .iter()
190        .map(|column| {
191            if is_virtual_document_id_column(column, &definitions) {
192                doc_id.map_or(Ok(Value::Null), doc_id_value)
193            } else if definitions.iter().any(|definition| {
194                definition.name == *column && definition.primary_key && definition.ty.is_integer()
195            }) {
196                integer_key_value(&materialized, column, doc_id)
197            } else if column == TABLE_OID_COLUMN {
198                storage_table.map_or(Ok(Value::Null), |storage_table| {
199                    Ok(Value::Int(
200                        context.tuples.table_relation_oid(storage_table)?,
201                    ))
202                })
203            } else if column == XMIN_COLUMN {
204                Ok(crate::query::document_projection::project_document_column(
205                    &materialized,
206                    metadata,
207                    column,
208                    &definitions,
209                ))
210            } else {
211                Ok(materialized.get(column).cloned().unwrap_or(Value::Null))
212            }
213        })
214        .collect::<Result<Vec<_>, _>>()?;
215    Ok(OwnedPhysicalRow::new(
216        RowSchema::with_qualified_types(qualifier, columns, types),
217        PhysicalRow::from_values(values),
218    ))
219}
220
221pub fn new_target_row_for_storage(
222    context: MutationRowContext<'_>,
223    table: &str,
224    storage_table: &str,
225    qualifier: &str,
226    doc_id: DocId,
227    document: &Document,
228) -> Result<OwnedPhysicalRow, SQLError> {
229    target_row_for_storage_optional_with_metadata(
230        context,
231        table,
232        Some(storage_table),
233        qualifier,
234        Some(doc_id),
235        document,
236        None,
237        uqa_storage::DocumentMetadata::with_tuple_xmin(context.tuples.tuple_version_xid()?),
238    )
239}
240
241pub fn null_target_row(
242    context: MutationRowContext<'_>,
243    table: &str,
244    qualifier: &str,
245) -> Result<OwnedPhysicalRow, SQLError> {
246    let schema =
247        uqa_sql::semantics::mutation_rows::null_target_schema(context.relations, table, qualifier)?;
248    let row = PhysicalRow::nulls(schema.physical_width());
249    Ok(OwnedPhysicalRow::new(schema, row))
250}
251
252pub fn join_rows(left: &OwnedPhysicalRow, right: &OwnedPhysicalRow) -> OwnedPhysicalRow {
253    OwnedPhysicalRow::new(
254        RowSchema::join(&left.schema, &right.schema, std::iter::empty()),
255        PhysicalRow::concat(&left.row, &right.row),
256    )
257}
258
259pub fn append_hidden_qualified_row(
260    base: &OwnedPhysicalRow,
261    qualifier: &str,
262    columns: &[String],
263    types: &[Option<ColumnType>],
264    values: Vec<Value>,
265) -> OwnedPhysicalRow {
266    let hidden_types = columns
267        .iter()
268        .enumerate()
269        .map(|(position, _)| types.get(position).cloned().flatten())
270        .collect::<Vec<_>>();
271    let schema = RowSchema::append_hidden_typed(&base.schema, &hidden_types);
272    let offset = base.schema.physical_width();
273    let aliases = columns
274        .iter()
275        .enumerate()
276        .map(|(position, column)| {
277            (
278                ColumnIdentity::qualified(qualifier, column),
279                offset + position,
280                hidden_types[position].clone(),
281            )
282        })
283        .collect::<Vec<_>>();
284    OwnedPhysicalRow::new(
285        RowSchema::with_physical_identity_aliases(&schema, &aliases),
286        base.row.clone().append_values(values),
287    )
288}