Skip to main content

uqa_execution/mutation/
prepared.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Typed prepared rewrite/delete trees and their private spill codec.
8
9use std::collections::BTreeMap;
10
11use super::candidate::PhysicalDocumentIdentity;
12use uqa_core::{DocId, Value};
13use uqa_sql::SQLError;
14use uqa_storage::document_store::Document;
15
16const PREPARED_MUTATION_CODEC_VERSION: i64 = 4;
17
18#[derive(Debug, Clone, PartialEq)]
19pub struct PreparedDocumentRewrite {
20    pub table: String,
21    pub doc_id: DocId,
22    pub destination: Option<(String, DocId)>,
23    /// The table the `UPDATE` named for a row it moves to another partition, whose triggers fire for the referenced keys the row held.
24    pub moved_through: Option<String>,
25    /// The identity within its own table the row moves to because its integer primary key changed, decided once when the rewrite is prepared so that every later stage moves it to the same one.
26    pub relocation: Option<DocId>,
27    pub partition_move_delete: Option<Box<PreparedDocumentDelete>>,
28    pub old_document: Document,
29    pub new_document: Document,
30    pub capture_partition_move_update_transition: bool,
31    /// The referential action that prepared the rewrite, if one did.
32    pub referential_action: Option<Box<ReferentialRewrite>>,
33}
34
35impl PreparedDocumentRewrite {
36    pub fn is_partition_move_delete(&self) -> bool {
37        self.partition_move_delete.is_some()
38    }
39
40    /// The columns the referential action that prepared the rewrite sets, which select its `UPDATE OF` triggers.
41    pub fn referential_columns(&self) -> Option<&[String]> {
42        self.referential_action
43            .as_deref()
44            .map(|action| action.columns.as_slice())
45    }
46}
47
48/// The referential action of a foreign key that rewrites a row of its table, which `PostgreSQL` performs as a statement of its own.
49#[derive(Debug, Clone, PartialEq)]
50pub struct ReferentialRewrite {
51    /// The table of the foreign key, which the action's statement names.
52    pub relation: String,
53    /// The columns the action sets.
54    pub columns: Vec<String>,
55}
56
57#[derive(Debug, Clone, PartialEq)]
58pub struct PreparedDocumentDelete {
59    pub table: String,
60    pub doc_id: DocId,
61    pub document: Document,
62}
63
64#[derive(Debug, Clone, PartialEq)]
65pub struct PreparedDocumentInsert {
66    pub table: String,
67    pub doc_id: DocId,
68    pub document: Document,
69}
70
71#[derive(Debug, Clone, PartialEq)]
72pub enum PreparedMutationAction {
73    Insert(PreparedDocumentInsert),
74    Rewrite(PreparedDocumentRewrite),
75    Delete(PreparedDocumentDelete),
76}
77
78impl PreparedMutationAction {
79    /// The rows the action writes: the row it inserts or deletes, or the row it rewrites with the identity a moved row takes.
80    pub fn written_rows(&self) -> Vec<PhysicalDocumentIdentity> {
81        let identity = |table: &str, doc_id: DocId| PhysicalDocumentIdentity {
82            table: table.to_string(),
83            doc_id,
84        };
85        match self {
86            Self::Insert(insert) => vec![identity(&insert.table, insert.doc_id)],
87            Self::Delete(delete) => vec![identity(&delete.table, delete.doc_id)],
88            Self::Rewrite(rewrite) => std::iter::once(identity(&rewrite.table, rewrite.doc_id))
89                .chain(
90                    rewrite
91                        .destination
92                        .as_ref()
93                        .map(|(table, doc_id)| identity(table, *doc_id)),
94                )
95                .chain(
96                    rewrite
97                        .relocation
98                        .map(|doc_id| identity(&rewrite.table, doc_id)),
99                )
100                .collect(),
101        }
102    }
103}
104
105#[derive(Debug, Clone, PartialEq)]
106pub enum PreparedInsertConflict {
107    Unresolved,
108    Insert { doc_id: DocId, supplied: bool },
109    Skip,
110    Updated(PreparedDocumentRewrite),
111}
112
113pub fn encode_prepared_doc_id(doc_id: DocId) -> Value {
114    Value::Bytes(doc_id.to_be_bytes().to_vec())
115}
116
117pub fn decode_prepared_doc_id(value: Value, context: &str) -> Result<DocId, SQLError> {
118    let Value::Bytes(bytes) = value else {
119        return Err(SQLError::Internal(format!(
120            "{context} has a non-binary document id"
121        )));
122    };
123    let bytes: [u8; std::mem::size_of::<DocId>()] = bytes
124        .try_into()
125        .map_err(|_| SQLError::Internal(format!("{context} has an invalid document id width")))?;
126    Ok(DocId::from_be_bytes(bytes))
127}
128
129fn take_codec_version(fields: &mut BTreeMap<String, Value>, context: &str) -> Result<(), SQLError> {
130    match fields.remove("version") {
131        Some(Value::Int(PREPARED_MUTATION_CODEC_VERSION)) => Ok(()),
132        Some(Value::Int(version)) => Err(SQLError::Internal(format!(
133            "{context} has unsupported codec version {version}"
134        ))),
135        _ => Err(SQLError::Internal(format!(
136            "{context} has no valid codec version"
137        ))),
138    }
139}
140
141fn reject_unknown_fields(fields: &BTreeMap<String, Value>, context: &str) -> Result<(), SQLError> {
142    if fields.is_empty() {
143        return Ok(());
144    }
145    Err(SQLError::Internal(format!(
146        "{context} has unknown field `{}`",
147        fields.keys().next().expect("non-empty map")
148    )))
149}
150
151pub fn encode_prepared_document_rewrite(prepared: PreparedDocumentRewrite) -> Value {
152    Value::Map(BTreeMap::from([
153        (
154            "version".into(),
155            Value::Int(PREPARED_MUTATION_CODEC_VERSION),
156        ),
157        ("table".into(), Value::Str(prepared.table)),
158        ("doc_id".into(), encode_prepared_doc_id(prepared.doc_id)),
159        (
160            "destination".into(),
161            prepared.destination.map_or(Value::Null, |(table, doc_id)| {
162                Value::Map(BTreeMap::from([
163                    ("table".into(), Value::Str(table)),
164                    ("doc_id".into(), encode_prepared_doc_id(doc_id)),
165                ]))
166            }),
167        ),
168        (
169            "moved_through".into(),
170            prepared.moved_through.map_or(Value::Null, Value::Str),
171        ),
172        (
173            "relocation".into(),
174            prepared
175                .relocation
176                .map_or(Value::Null, encode_prepared_doc_id),
177        ),
178        (
179            "partition_move_delete".into(),
180            prepared
181                .partition_move_delete
182                .map_or(Value::Null, |delete| {
183                    encode_prepared_document_delete(*delete)
184                }),
185        ),
186        ("old".into(), Value::Map(prepared.old_document)),
187        ("new".into(), Value::Map(prepared.new_document)),
188        (
189            "capture_partition_move_update_transition".into(),
190            Value::Bool(prepared.capture_partition_move_update_transition),
191        ),
192        (
193            "referential_action".into(),
194            prepared.referential_action.map_or(Value::Null, |action| {
195                Value::Map(BTreeMap::from([
196                    ("relation".into(), Value::Str(action.relation)),
197                    (
198                        "columns".into(),
199                        Value::List(action.columns.into_iter().map(Value::Str).collect()),
200                    ),
201                ]))
202            }),
203        ),
204    ]))
205}
206
207#[expect(clippy::too_many_lines, reason = "preserves DML lock and event order")]
208pub fn decode_prepared_document_rewrite(value: Value) -> Result<PreparedDocumentRewrite, SQLError> {
209    let Value::Map(mut fields) = value else {
210        return Err(SQLError::Internal(
211            "prepared rewrite spill payload is not a map".into(),
212        ));
213    };
214    take_codec_version(&mut fields, "prepared rewrite spill payload")?;
215    let table = match fields.remove("table") {
216        Some(Value::Str(table)) => table,
217        _ => {
218            return Err(SQLError::Internal(
219                "prepared rewrite spill payload has no table".into(),
220            ))
221        }
222    };
223    let doc_id = decode_prepared_doc_id(
224        fields.remove("doc_id").ok_or_else(|| {
225            SQLError::Internal("prepared rewrite spill payload has no document id".into())
226        })?,
227        "prepared rewrite spill payload",
228    )?;
229    let destination = match fields.remove("destination") {
230        Some(Value::Null) | None => None,
231        Some(Value::Map(mut destination)) => {
232            let table = match destination.remove("table") {
233                Some(Value::Str(table)) => table,
234                _ => {
235                    return Err(SQLError::Internal(
236                        "prepared rewrite destination has no table".into(),
237                    ))
238                }
239            };
240            let doc_id = decode_prepared_doc_id(
241                destination.remove("doc_id").ok_or_else(|| {
242                    SQLError::Internal("prepared rewrite destination has no document id".into())
243                })?,
244                "prepared rewrite destination",
245            )?;
246            reject_unknown_fields(&destination, "prepared rewrite destination")?;
247            Some((table, doc_id))
248        }
249        Some(_) => {
250            return Err(SQLError::Internal(
251                "prepared rewrite destination is not a map".into(),
252            ))
253        }
254    };
255    let moved_through = match fields.remove("moved_through") {
256        Some(Value::Null) => None,
257        Some(Value::Str(table)) => Some(table),
258        _ => {
259            return Err(SQLError::Internal(
260                "prepared rewrite spill payload has no moved-through relation".into(),
261            ))
262        }
263    };
264    let relocation = match fields.remove("relocation") {
265        Some(Value::Null) => None,
266        Some(doc_id) => Some(decode_prepared_doc_id(
267            doc_id,
268            "prepared rewrite relocation",
269        )?),
270        None => {
271            return Err(SQLError::Internal(
272                "prepared rewrite spill payload has no relocation".into(),
273            ))
274        }
275    };
276    let partition_move_delete = match fields.remove("partition_move_delete") {
277        Some(Value::Null) | None => None,
278        Some(delete) => Some(Box::new(decode_prepared_document_delete(delete)?)),
279    };
280    let old_document = match fields.remove("old") {
281        Some(Value::Map(document)) => document,
282        _ => {
283            return Err(SQLError::Internal(
284                "prepared rewrite spill payload has no old document".into(),
285            ))
286        }
287    };
288    let new_document = match fields.remove("new") {
289        Some(Value::Map(document)) => document,
290        _ => {
291            return Err(SQLError::Internal(
292                "prepared rewrite spill payload has no new document".into(),
293            ))
294        }
295    };
296    let capture_partition_move_update_transition = match fields
297        .remove("capture_partition_move_update_transition")
298    {
299        Some(Value::Bool(capture)) => capture,
300        _ => {
301            return Err(SQLError::Internal(
302                "prepared rewrite spill payload has no partition movement transition mode".into(),
303            ))
304        }
305    };
306    let referential_action = match fields.remove("referential_action") {
307        Some(Value::Null) => None,
308        Some(action) => Some(Box::new(decode_referential_rewrite(action)?)),
309        None => {
310            return Err(SQLError::Internal(
311                "prepared rewrite spill payload has no referential action".into(),
312            ))
313        }
314    };
315    reject_unknown_fields(&fields, "prepared rewrite spill payload")?;
316    Ok(PreparedDocumentRewrite {
317        table,
318        doc_id,
319        destination,
320        moved_through,
321        relocation,
322        partition_move_delete,
323        old_document,
324        new_document,
325        capture_partition_move_update_transition,
326        referential_action,
327    })
328}
329
330fn decode_referential_rewrite(value: Value) -> Result<ReferentialRewrite, SQLError> {
331    let Value::Map(mut fields) = value else {
332        return Err(SQLError::Internal(
333            "prepared rewrite referential action is not a map".into(),
334        ));
335    };
336    let relation = match fields.remove("relation") {
337        Some(Value::Str(relation)) => relation,
338        _ => {
339            return Err(SQLError::Internal(
340                "prepared rewrite referential action has no relation".into(),
341            ))
342        }
343    };
344    let columns = match fields.remove("columns") {
345        Some(Value::List(columns)) => columns
346            .into_iter()
347            .map(|column| match column {
348                Value::Str(column) => Ok(column),
349                _ => Err(SQLError::Internal(
350                    "prepared rewrite referential action has a non-text column".into(),
351                )),
352            })
353            .collect::<Result<Vec<_>, _>>()?,
354        _ => {
355            return Err(SQLError::Internal(
356                "prepared rewrite referential action has no column list".into(),
357            ))
358        }
359    };
360    reject_unknown_fields(&fields, "prepared rewrite referential action")?;
361    Ok(ReferentialRewrite { relation, columns })
362}
363
364pub fn encode_prepared_document_delete(prepared: PreparedDocumentDelete) -> Value {
365    Value::Map(BTreeMap::from([
366        (
367            "version".into(),
368            Value::Int(PREPARED_MUTATION_CODEC_VERSION),
369        ),
370        ("table".into(), Value::Str(prepared.table)),
371        ("doc_id".into(), encode_prepared_doc_id(prepared.doc_id)),
372        ("document".into(), Value::Map(prepared.document)),
373    ]))
374}
375
376pub fn decode_prepared_document_delete(value: Value) -> Result<PreparedDocumentDelete, SQLError> {
377    let Value::Map(mut fields) = value else {
378        return Err(SQLError::Internal(
379            "prepared delete spill payload is not a map".into(),
380        ));
381    };
382    take_codec_version(&mut fields, "prepared delete spill payload")?;
383    let table = match fields.remove("table") {
384        Some(Value::Str(table)) => table,
385        _ => {
386            return Err(SQLError::Internal(
387                "prepared delete spill payload has no table".into(),
388            ))
389        }
390    };
391    let doc_id = decode_prepared_doc_id(
392        fields.remove("doc_id").ok_or_else(|| {
393            SQLError::Internal("prepared delete spill payload has no document id".into())
394        })?,
395        "prepared delete spill payload",
396    )?;
397    let document = match fields.remove("document") {
398        Some(Value::Map(document)) => document,
399        _ => {
400            return Err(SQLError::Internal(
401                "prepared delete spill payload has no document".into(),
402            ))
403        }
404    };
405    reject_unknown_fields(&fields, "prepared delete spill payload")?;
406    Ok(PreparedDocumentDelete {
407        table,
408        doc_id,
409        document,
410    })
411}
412
413pub fn encode_prepared_insert_conflict(prepared: PreparedInsertConflict) -> Value {
414    let mut fields = BTreeMap::from([(
415        "version".into(),
416        Value::Int(PREPARED_MUTATION_CODEC_VERSION),
417    )]);
418    match prepared {
419        PreparedInsertConflict::Unresolved => {
420            fields.insert("kind".into(), Value::Str("unresolved".into()));
421        }
422        PreparedInsertConflict::Insert { doc_id, supplied } => {
423            fields.insert("kind".into(), Value::Str("insert".into()));
424            fields.insert("doc_id".into(), encode_prepared_doc_id(doc_id));
425            fields.insert("supplied".into(), Value::Bool(supplied));
426        }
427        PreparedInsertConflict::Skip => {
428            fields.insert("kind".into(), Value::Str("skip".into()));
429        }
430        PreparedInsertConflict::Updated(rewrite) => {
431            fields.insert("kind".into(), Value::Str("updated".into()));
432            fields.insert("rewrite".into(), encode_prepared_document_rewrite(rewrite));
433        }
434    }
435    Value::Map(fields)
436}
437
438pub fn decode_prepared_insert_conflict(value: Value) -> Result<PreparedInsertConflict, SQLError> {
439    let Value::Map(mut fields) = value else {
440        return Err(SQLError::Internal(
441            "prepared INSERT conflict payload is not a map".into(),
442        ));
443    };
444    take_codec_version(&mut fields, "prepared INSERT conflict payload")?;
445    let kind = match fields.remove("kind") {
446        Some(Value::Str(kind)) => kind,
447        _ => {
448            return Err(SQLError::Internal(
449                "prepared INSERT conflict payload has no kind".into(),
450            ))
451        }
452    };
453    let prepared = match kind.as_str() {
454        "unresolved" => PreparedInsertConflict::Unresolved,
455        "insert" => PreparedInsertConflict::Insert {
456            doc_id: decode_prepared_doc_id(
457                fields.remove("doc_id").ok_or_else(|| {
458                    SQLError::Internal("prepared INSERT payload has no document identity".into())
459                })?,
460                "prepared INSERT action",
461            )?,
462            supplied: match fields.remove("supplied") {
463                Some(Value::Bool(supplied)) => supplied,
464                _ => {
465                    return Err(SQLError::Internal(
466                        "prepared INSERT payload has no supplied-id flag".into(),
467                    ))
468                }
469            },
470        },
471        "skip" => PreparedInsertConflict::Skip,
472        "updated" => PreparedInsertConflict::Updated(decode_prepared_document_rewrite(
473            fields.remove("rewrite").ok_or_else(|| {
474                SQLError::Internal("prepared INSERT conflict payload has no rewrite plan".into())
475            })?,
476        )?),
477        _ => {
478            return Err(SQLError::Internal(format!(
479                "prepared INSERT conflict payload has unknown kind `{kind}`"
480            )))
481        }
482    };
483    reject_unknown_fields(&fields, "prepared INSERT conflict payload")?;
484    Ok(prepared)
485}
486
487pub fn encode_prepared_mutation_action(action: PreparedMutationAction) -> Value {
488    let (kind, plan) = match action {
489        PreparedMutationAction::Insert(insert) => (
490            "insert",
491            Value::Map(BTreeMap::from([
492                ("table".into(), Value::Str(insert.table)),
493                ("doc_id".into(), encode_prepared_doc_id(insert.doc_id)),
494                ("document".into(), Value::Map(insert.document)),
495            ])),
496        ),
497        PreparedMutationAction::Rewrite(rewrite) => {
498            ("rewrite", encode_prepared_document_rewrite(rewrite))
499        }
500        PreparedMutationAction::Delete(delete) => {
501            ("delete", encode_prepared_document_delete(delete))
502        }
503    };
504    Value::Map(BTreeMap::from([
505        (
506            "version".into(),
507            Value::Int(PREPARED_MUTATION_CODEC_VERSION),
508        ),
509        ("kind".into(), Value::Str(kind.into())),
510        ("plan".into(), plan),
511    ]))
512}
513
514pub fn decode_prepared_mutation_action(value: Value) -> Result<PreparedMutationAction, SQLError> {
515    let Value::Map(mut fields) = value else {
516        return Err(SQLError::Internal(
517            "prepared mutation action payload is not a map".into(),
518        ));
519    };
520    take_codec_version(&mut fields, "prepared mutation action payload")?;
521    let kind = match fields.remove("kind") {
522        Some(Value::Str(kind)) => kind,
523        _ => {
524            return Err(SQLError::Internal(
525                "prepared mutation action payload has no kind".into(),
526            ))
527        }
528    };
529    let plan = fields
530        .remove("plan")
531        .ok_or_else(|| SQLError::Internal("prepared mutation action payload has no plan".into()))?;
532    reject_unknown_fields(&fields, "prepared mutation action payload")?;
533    match kind.as_str() {
534        "insert" => {
535            let Value::Map(mut fields) = plan else {
536                return Err(SQLError::Internal(
537                    "prepared insert action plan is not a map".into(),
538                ));
539            };
540            let table = match fields.remove("table") {
541                Some(Value::Str(table)) => table,
542                _ => {
543                    return Err(SQLError::Internal(
544                        "prepared insert action plan has no table".into(),
545                    ))
546                }
547            };
548            let doc_id = decode_prepared_doc_id(
549                fields.remove("doc_id").ok_or_else(|| {
550                    SQLError::Internal("prepared insert action plan has no document id".into())
551                })?,
552                "prepared insert action plan",
553            )?;
554            let document = match fields.remove("document") {
555                Some(Value::Map(document)) => document,
556                _ => {
557                    return Err(SQLError::Internal(
558                        "prepared insert action plan has no document".into(),
559                    ))
560                }
561            };
562            reject_unknown_fields(&fields, "prepared insert action plan")?;
563            Ok(PreparedMutationAction::Insert(PreparedDocumentInsert {
564                table,
565                doc_id,
566                document,
567            }))
568        }
569        "rewrite" => Ok(PreparedMutationAction::Rewrite(
570            decode_prepared_document_rewrite(plan)?,
571        )),
572        "delete" => Ok(PreparedMutationAction::Delete(
573            decode_prepared_document_delete(plan)?,
574        )),
575        _ => Err(SQLError::Internal(format!(
576            "prepared mutation action payload has unknown kind `{kind}`"
577        ))),
578    }
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584
585    fn document(key: &str, value: i64) -> Document {
586        BTreeMap::from([(key.to_string(), Value::Int(value))])
587    }
588
589    fn rewrite() -> PreparedDocumentRewrite {
590        PreparedDocumentRewrite {
591            table: "public.source".into(),
592            doc_id: 7,
593            destination: Some(("public.destination".into(), 9)),
594            moved_through: Some("public.root".into()),
595            relocation: None,
596            partition_move_delete: Some(Box::new(PreparedDocumentDelete {
597                table: "public.source".into(),
598                doc_id: 7,
599                document: document("id", 7),
600            })),
601            old_document: document("value", 1),
602            new_document: document("value", 2),
603            capture_partition_move_update_transition: true,
604            referential_action: None,
605        }
606    }
607
608    fn referential_rewrite() -> PreparedDocumentRewrite {
609        PreparedDocumentRewrite {
610            table: "public.child".into(),
611            doc_id: 11,
612            destination: None,
613            moved_through: None,
614            relocation: Some(1 << 62),
615            partition_move_delete: None,
616            old_document: document("parent", 7),
617            new_document: document("parent", 9),
618            capture_partition_move_update_transition: false,
619            referential_action: Some(Box::new(ReferentialRewrite {
620                relation: "public.child".into(),
621                columns: vec!["parent".into(), "status".into()],
622            })),
623        }
624    }
625
626    #[test]
627    fn prepared_rewrite_and_delete_codec_round_trip() {
628        for expected in [rewrite(), referential_rewrite()] {
629            let actual = decode_prepared_document_rewrite(encode_prepared_document_rewrite(
630                expected.clone(),
631            ))
632            .unwrap();
633            assert_eq!(actual, expected);
634        }
635        let expected_delete = PreparedDocumentDelete {
636            table: "public.parent".into(),
637            doc_id: 3,
638            document: document("id", 3),
639        };
640        let actual_delete = decode_prepared_document_delete(encode_prepared_document_delete(
641            expected_delete.clone(),
642        ))
643        .unwrap();
644        assert_eq!(actual_delete, expected_delete);
645    }
646
647    #[test]
648    fn prepared_codec_rejects_version_width_and_unknown_fields() {
649        for version in [
650            PREPARED_MUTATION_CODEC_VERSION - 1,
651            PREPARED_MUTATION_CODEC_VERSION + 1,
652        ] {
653            let mut wrong_version = match encode_prepared_document_rewrite(rewrite()) {
654                Value::Map(fields) => fields,
655                _ => unreachable!(),
656            };
657            wrong_version.insert("version".into(), Value::Int(version));
658            assert!(decode_prepared_document_rewrite(Value::Map(wrong_version)).is_err());
659        }
660
661        assert!(decode_prepared_doc_id(Value::Bytes(vec![0; 3]), "test identity").is_err());
662
663        let mut unknown_field = match encode_prepared_document_delete(PreparedDocumentDelete {
664            table: "public.items".into(),
665            doc_id: 1,
666            document: document("id", 1),
667        }) {
668            Value::Map(fields) => fields,
669            _ => unreachable!(),
670        };
671        unknown_field.insert("unexpected".into(), Value::Null);
672        assert!(decode_prepared_document_delete(Value::Map(unknown_field)).is_err());
673
674        for invalid in [
675            Value::Int(1),
676            Value::Map(BTreeMap::from([(
677                "columns".into(),
678                Value::List(vec![Value::Str("parent".into())]),
679            )])),
680            Value::Map(BTreeMap::from([
681                ("relation".into(), Value::Str("public.child".into())),
682                ("columns".into(), Value::List(vec![Value::Int(1)])),
683            ])),
684        ] {
685            let mut invalid_action = match encode_prepared_document_rewrite(referential_rewrite()) {
686                Value::Map(fields) => fields,
687                _ => unreachable!(),
688            };
689            invalid_action.insert("referential_action".into(), invalid);
690            assert!(decode_prepared_document_rewrite(Value::Map(invalid_action)).is_err());
691        }
692    }
693
694    #[test]
695    fn prepared_insert_conflict_codec_round_trips_every_action() {
696        for expected in [
697            PreparedInsertConflict::Unresolved,
698            PreparedInsertConflict::Insert {
699                doc_id: 23,
700                supplied: true,
701            },
702            PreparedInsertConflict::Skip,
703            PreparedInsertConflict::Updated(rewrite()),
704        ] {
705            let actual =
706                decode_prepared_insert_conflict(encode_prepared_insert_conflict(expected.clone()))
707                    .unwrap();
708            assert_eq!(actual, expected);
709        }
710    }
711
712    #[test]
713    fn prepared_insert_conflict_codec_rejects_malformed_payloads() {
714        assert!(decode_prepared_insert_conflict(Value::Str("skip".into())).is_err());
715
716        let mut missing_width =
717            match encode_prepared_insert_conflict(PreparedInsertConflict::Insert {
718                doc_id: 23,
719                supplied: false,
720            }) {
721                Value::Map(fields) => fields,
722                _ => unreachable!(),
723            };
724        missing_width.insert("doc_id".into(), Value::Bytes(vec![0; 3]));
725        assert!(decode_prepared_insert_conflict(Value::Map(missing_width)).is_err());
726
727        let mut unknown_field = match encode_prepared_insert_conflict(PreparedInsertConflict::Skip)
728        {
729            Value::Map(fields) => fields,
730            _ => unreachable!(),
731        };
732        unknown_field.insert("unexpected".into(), Value::Null);
733        assert!(decode_prepared_insert_conflict(Value::Map(unknown_field)).is_err());
734    }
735
736    #[test]
737    fn prepared_mutation_action_codec_round_trips_every_action() {
738        for expected in [
739            PreparedMutationAction::Insert(PreparedDocumentInsert {
740                table: "public.items".into(),
741                doc_id: 29,
742                document: document("id", 29),
743            }),
744            PreparedMutationAction::Rewrite(rewrite()),
745            PreparedMutationAction::Delete(PreparedDocumentDelete {
746                table: "public.items".into(),
747                doc_id: 31,
748                document: document("id", 31),
749            }),
750        ] {
751            let actual =
752                decode_prepared_mutation_action(encode_prepared_mutation_action(expected.clone()))
753                    .unwrap();
754            assert_eq!(actual, expected);
755        }
756    }
757}