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 push_prepared_insert_spill_row(
50    buffer: &mut crate::SpillBuffer,
51    schema: &RowSchema,
52    prepared: PreparedInsertSpillRow,
53) -> Result<(), SQLError> {
54    buffer
55        .push(crate::Batch::from_physical_rows(
56            schema.clone(),
57            vec![encode_prepared_insert_spill_row(prepared)],
58        ))
59        .map_err(crate::physical::physical_exec_error)?;
60    Ok(())
61}
62
63pub fn decode_prepared_insert_spill_row(
64    row: OwnedPhysicalRow,
65) -> Result<PreparedInsertSpillRow, SQLError> {
66    if row.schema.physical_width() != INSERT_SPILL_WIDTH {
67        return Err(SQLError::Internal(format!(
68            "INSERT prepared spill row has {} fields, expected {INSERT_SPILL_WIDTH}",
69            row.schema.physical_width()
70        )));
71    }
72    let Some(Value::Map(mut fields)) = row.physical_value_at(0).cloned() else {
73        return Err(SQLError::Internal(
74            "INSERT prepared spill row payload is not a map".into(),
75        ));
76    };
77    match fields.remove("version") {
78        Some(Value::Int(INSERT_SPILL_CODEC_VERSION)) => {}
79        Some(Value::Int(version)) => {
80            return Err(SQLError::Internal(format!(
81                "INSERT prepared spill row has unsupported codec version {version}"
82            )))
83        }
84        _ => {
85            return Err(SQLError::Internal(
86                "INSERT prepared spill row has no valid codec version".into(),
87            ))
88        }
89    }
90    let target_table = match fields.remove("target_table") {
91        Some(Value::Str(table)) => table,
92        _ => {
93            return Err(SQLError::Internal(
94                "INSERT prepared spill row has no target table".into(),
95            ))
96        }
97    };
98    let document = match fields.remove("document") {
99        Some(Value::Map(document)) => document,
100        _ => {
101            return Err(SQLError::Internal(
102                "INSERT prepared spill row has no document".into(),
103            ))
104        }
105    };
106    let conflict =
107        decode_prepared_insert_conflict(fields.remove("conflict").ok_or_else(|| {
108            SQLError::Internal("INSERT prepared spill row has no conflict action".into())
109        })?)?;
110    if let Some(field) = fields.keys().next() {
111        return Err(SQLError::Internal(format!(
112            "INSERT prepared spill row has unknown field `{field}`"
113        )));
114    }
115    Ok(PreparedInsertSpillRow {
116        target_table,
117        document,
118        conflict,
119    })
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    fn prepared() -> PreparedInsertSpillRow {
127        PreparedInsertSpillRow {
128            target_table: "public.items".into(),
129            document: BTreeMap::from([("id".into(), Value::Int(7))]),
130            conflict: PreparedInsertConflict::Insert {
131                doc_id: 7,
132                supplied: true,
133            },
134        }
135    }
136
137    #[test]
138    fn prepared_insert_spill_codec_round_trips() {
139        let expected = prepared();
140        let row = OwnedPhysicalRow::new(
141            prepared_insert_spill_schema(),
142            encode_prepared_insert_spill_row(expected.clone()),
143        );
144        assert_eq!(decode_prepared_insert_spill_row(row).unwrap(), expected);
145    }
146
147    #[test]
148    fn prepared_insert_spill_codec_rejects_version_width_and_unknown_fields() {
149        let wide = OwnedPhysicalRow::new(
150            RowSchema::with_internal_relation_types(
151                uqa_sql::ast::InternalRelationId::allocate(),
152                vec![None, None],
153            ),
154            PhysicalRow::from_values(vec![Value::Null, Value::Null]),
155        );
156        assert!(decode_prepared_insert_spill_row(wide).is_err());
157
158        let encoded = OwnedPhysicalRow::new(
159            prepared_insert_spill_schema(),
160            encode_prepared_insert_spill_row(prepared()),
161        );
162        let mut wrong_version = match encoded.physical_value_at(0) {
163            Some(Value::Map(fields)) => fields.clone(),
164            _ => unreachable!(),
165        };
166        wrong_version.insert("version".into(), Value::Int(INSERT_SPILL_CODEC_VERSION + 1));
167        let wrong_version = OwnedPhysicalRow::new(
168            prepared_insert_spill_schema(),
169            PhysicalRow::from_values(vec![Value::Map(wrong_version)]),
170        );
171        assert!(decode_prepared_insert_spill_row(wrong_version).is_err());
172
173        let encoded = OwnedPhysicalRow::new(
174            prepared_insert_spill_schema(),
175            encode_prepared_insert_spill_row(prepared()),
176        );
177        let mut unknown_field = match encoded.physical_value_at(0) {
178            Some(Value::Map(fields)) => fields.clone(),
179            _ => unreachable!(),
180        };
181        unknown_field.insert("unexpected".into(), Value::Null);
182        let unknown_field = OwnedPhysicalRow::new(
183            prepared_insert_spill_schema(),
184            PhysicalRow::from_values(vec![Value::Map(unknown_field)]),
185        );
186        assert!(decode_prepared_insert_spill_row(unknown_field).is_err());
187    }
188}