uqa_sql/result/
serialization.rs1use crate::{
10 expr::{EngineHook, EngineValueCatalog},
11 ColumnType, SQLError,
12};
13use uqa_core::{
14 memory::{Produced, ProductionControl, ProductionVec},
15 Value,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ResultFormat {
20 Text,
21 Binary,
22}
23
24pub fn encode_postgres_row_with_control<'v>(
26 fields: impl ExactSizeIterator<Item = (Option<&'v Value>, Option<&'v ColumnType>)> + Clone,
27 format: ResultFormat,
28 engine: Option<&dyn EngineHook>,
29 control: &ProductionControl<'_>,
30) -> Result<Produced<Vec<u8>>, SQLError> {
31 control.check()?;
32 if format == ResultFormat::Binary {
33 for (_, ty) in fields.clone() {
34 control.check()?;
35 super::binary::validate_type(ty.unwrap_or(&ColumnType::Text), control)?;
36 }
37 }
38 let mut output = ProductionVec::new(*control);
39 output.extend_from_slice(
40 &u16::try_from(fields.len())
41 .map_err(|_| super::binary::size_error())?
42 .to_be_bytes(),
43 )?;
44 let catalog = engine.map(EngineValueCatalog);
45 let catalog = catalog
46 .as_ref()
47 .map(|catalog| catalog as &dyn crate::expr::SQLValueCatalog);
48 for (value, ty) in fields {
49 control.check()?;
50 let ty = ty.unwrap_or(&ColumnType::Text);
51 let Some(value) = value.filter(|value| !matches!(value, Value::Null)) else {
52 output.extend_from_slice(&(-1_i32).to_be_bytes())?;
53 continue;
54 };
55 let text;
56 let binary;
57 let bytes = match format {
58 ResultFormat::Text => {
59 text = super::format_postgres_text_with_control(value, ty, engine, control)?;
60 text.as_bytes()
61 }
62 ResultFormat::Binary => {
63 binary = super::format_postgres_binary_with_catalog_and_control(
64 value, ty, catalog, control,
65 )?;
66 &binary
67 }
68 };
69 output.extend_from_slice(
70 &i32::try_from(bytes.len())
71 .map_err(|_| super::binary::size_error())?
72 .to_be_bytes(),
73 )?;
74 output.extend_from_slice(bytes)?;
75 }
76 Ok(output.finish()?)
77}