Skip to main content

uqa_execution/mutation/insert/
codec.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Typed codec for streaming INSERT preparation spill rows.
8
9use std::collections::BTreeMap;
10
11use crate::{OwnedPhysicalRow, PhysicalRow, RowSchema};
12use uqa_core::Value;
13use uqa_sql::SQLError;
14use uqa_storage::document_store::Document;
15
16use crate::mutation::prepared::{
17    decode_prepared_insert_conflict, encode_prepared_insert_conflict, PreparedInsertConflict,
18};
19
20const INSERT_SPILL_CODEC_VERSION: i64 = 1;
21const INSERT_SPILL_WIDTH: usize = 1;
22
23#[derive(Debug, Clone, PartialEq)]
24pub struct PreparedInsertSpillRow {
25    pub target_table: String,
26    pub document: Document,
27    pub conflict: PreparedInsertConflict,
28}
29
30pub fn prepared_insert_spill_schema() -> RowSchema {
31    RowSchema::with_internal_relation_types(
32        uqa_sql::ast::InternalRelationId::allocate(),
33        vec![None],
34    )
35}
36
37pub fn encode_prepared_insert_spill_row(prepared: PreparedInsertSpillRow) -> PhysicalRow {
38    PhysicalRow::from_values(vec![Value::Map(BTreeMap::from([
39        ("version".into(), Value::Int(INSERT_SPILL_CODEC_VERSION)),
40        ("target_table".into(), Value::Str(prepared.target_table)),
41        ("document".into(), Value::Map(prepared.document)),
42        (
43            "conflict".into(),
44            encode_prepared_insert_conflict(prepared.conflict),
45        ),
46    ]))])
47}
48
49pub fn decode_prepared_insert_spill_row(
50    row: OwnedPhysicalRow,
51) -> Result<PreparedInsertSpillRow, SQLError> {
52    if row.schema.physical_width() != INSERT_SPILL_WIDTH {
53        return Err(SQLError::Internal(format!(
54            "INSERT prepared spill row has {} fields, expected {INSERT_SPILL_WIDTH}",
55            row.schema.physical_width()
56        )));
57    }
58    let Some(Value::Map(mut fields)) = row.physical_value_at(0).cloned() else {
59        return Err(SQLError::Internal(
60            "INSERT prepared spill row payload is not a map".into(),
61        ));
62    };
63    match fields.remove("version") {
64        Some(Value::Int(INSERT_SPILL_CODEC_VERSION)) => {}
65        Some(Value::Int(version)) => {
66            return Err(SQLError::Internal(format!(
67                "INSERT prepared spill row has unsupported codec version {version}"
68            )))
69        }
70        _ => {
71            return Err(SQLError::Internal(
72                "INSERT prepared spill row has no valid codec version".into(),
73            ))
74        }
75    }
76    let target_table = match fields.remove("target_table") {
77        Some(Value::Str(table)) => table,
78        _ => {
79            return Err(SQLError::Internal(
80                "INSERT prepared spill row has no target table".into(),
81            ))
82        }
83    };
84    let document = match fields.remove("document") {
85        Some(Value::Map(document)) => document,
86        _ => {
87            return Err(SQLError::Internal(
88                "INSERT prepared spill row has no document".into(),
89            ))
90        }
91    };
92    let conflict =
93        decode_prepared_insert_conflict(fields.remove("conflict").ok_or_else(|| {
94            SQLError::Internal("INSERT prepared spill row has no conflict action".into())
95        })?)?;
96    if let Some(field) = fields.keys().next() {
97        return Err(SQLError::Internal(format!(
98            "INSERT prepared spill row has unknown field `{field}`"
99        )));
100    }
101    Ok(PreparedInsertSpillRow {
102        target_table,
103        document,
104        conflict,
105    })
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn prepared() -> PreparedInsertSpillRow {
113        PreparedInsertSpillRow {
114            target_table: "public.items".into(),
115            document: BTreeMap::from([("id".into(), Value::Int(7))]),
116            conflict: PreparedInsertConflict::Insert {
117                doc_id: 7,
118                supplied: true,
119            },
120        }
121    }
122
123    #[test]
124    fn prepared_insert_spill_codec_round_trips() {
125        let expected = prepared();
126        let row = OwnedPhysicalRow::new(
127            prepared_insert_spill_schema(),
128            encode_prepared_insert_spill_row(expected.clone()),
129        );
130        assert_eq!(decode_prepared_insert_spill_row(row).unwrap(), expected);
131    }
132
133    #[test]
134    fn prepared_insert_spill_codec_rejects_version_width_and_unknown_fields() {
135        let wide = OwnedPhysicalRow::new(
136            RowSchema::with_internal_relation_types(
137                uqa_sql::ast::InternalRelationId::allocate(),
138                vec![None, None],
139            ),
140            PhysicalRow::from_values(vec![Value::Null, Value::Null]),
141        );
142        assert!(decode_prepared_insert_spill_row(wide).is_err());
143
144        let encoded = OwnedPhysicalRow::new(
145            prepared_insert_spill_schema(),
146            encode_prepared_insert_spill_row(prepared()),
147        );
148        let mut wrong_version = match encoded.physical_value_at(0) {
149            Some(Value::Map(fields)) => fields.clone(),
150            _ => unreachable!(),
151        };
152        wrong_version.insert("version".into(), Value::Int(INSERT_SPILL_CODEC_VERSION + 1));
153        let wrong_version = OwnedPhysicalRow::new(
154            prepared_insert_spill_schema(),
155            PhysicalRow::from_values(vec![Value::Map(wrong_version)]),
156        );
157        assert!(decode_prepared_insert_spill_row(wrong_version).is_err());
158
159        let encoded = OwnedPhysicalRow::new(
160            prepared_insert_spill_schema(),
161            encode_prepared_insert_spill_row(prepared()),
162        );
163        let mut unknown_field = match encoded.physical_value_at(0) {
164            Some(Value::Map(fields)) => fields.clone(),
165            _ => unreachable!(),
166        };
167        unknown_field.insert("unexpected".into(), Value::Null);
168        let unknown_field = OwnedPhysicalRow::new(
169            prepared_insert_spill_schema(),
170            PhysicalRow::from_values(vec![Value::Map(unknown_field)]),
171        );
172        assert!(decode_prepared_insert_spill_row(unknown_field).is_err());
173    }
174}