1use super::{corrupt, inline, word, Produced, ProductionControl, ProductionVec, SQLError, Value};
10use crate::catalog::type_metadata::builtin_scalar_type;
11use uqa_core::ArrayValue;
12
13pub struct ArrayShape {
15 dimensions: [usize; 6],
16 bounds: [i32; 6],
17 count: usize,
18}
19
20impl ArrayShape {
21 pub(super) fn read(bytes: &[u8]) -> Result<Self, SQLError> {
22 let count = integer(bytes, 0)?;
23 if !(0..=6).contains(&count) {
24 return Err(corrupt("invalid array dimensions"));
25 }
26 let count = count as usize;
27 let mut shape = Self {
28 dimensions: [0; 6],
29 bounds: [0; 6],
30 count,
31 };
32 for index in 0..count {
33 shape.dimensions[index] = usize::try_from(integer(bytes, 12 + index * 4)?)
34 .map_err(|_| corrupt("invalid array dimensions"))?;
35 shape.bounds[index] = integer(bytes, 12 + count * 4 + index * 4)?;
36 }
37 Ok(shape)
38 }
39
40 pub fn dimensions(&self) -> &[usize] {
41 &self.dimensions[..self.count]
42 }
43 pub fn lower_bounds(&self) -> &[i32] {
44 &self.bounds[..self.count]
45 }
46}
47
48pub(super) fn read(
49 bytes: &[u8],
50 catalog: Option<&dyn crate::expr::SQLValueCatalog>,
51 control: &ProductionControl<'_>,
52) -> Result<Produced<Value>, SQLError> {
53 let (array, memory) = read_array(bytes, catalog, control)?.into_parts();
54 Ok(control.finish(Value::Array(array), memory)?)
55}
56
57pub(super) fn read_legacy_vector(
58 bytes: &[u8],
59 kind: uqa_core::LegacyVectorKind,
60 control: &ProductionControl<'_>,
61) -> Result<Produced<Value>, SQLError> {
62 let element = match kind {
63 uqa_core::LegacyVectorKind::SmallInteger => &crate::ColumnType::SmallInteger,
64 uqa_core::LegacyVectorKind::Oid => &crate::ColumnType::Oid,
65 };
66 let oid = crate::catalog::type_metadata::pg_type_oid(element) as u32;
67 let invalid = || SQLError::Routine {
68 sqlstate: "42804".into(),
69 message: format!("array is not a valid {}", kind.type_name()),
70 };
71 if ArrayShape::read(bytes)?.dimensions().len() > 1
72 || integer(bytes, 4)? != 0
73 || integer(bytes, 8)? as u32 != oid
74 {
75 return Err(invalid());
76 }
77 let array = read_array(bytes, None, control)?;
78 let vector = uqa_core::LegacyVectorValue::try_from_array_with_control(kind, array, control)?
79 .ok_or_else(invalid)?;
80 let (vector, memory) = vector.into_parts();
81 Ok(control.finish(Value::LegacyVector(vector), memory)?)
82}
83
84fn read_array(
85 bytes: &[u8],
86 catalog: Option<&dyn crate::expr::SQLValueCatalog>,
87 control: &ProductionControl<'_>,
88) -> Result<Produced<ArrayValue>, SQLError> {
89 let shape = ArrayShape::read(bytes)?;
90 let dimensions = shape.dimensions();
91 let ndim = dimensions.len();
92 let dataoffset = integer(bytes, 4)?;
93 let oid = integer(bytes, 8)? as u32;
94 let resolved;
95 let element = if let Some(element) = builtin_scalar_type(oid) {
96 element
97 } else {
98 resolved = catalog
99 .map(|catalog| catalog.value_type_by_oid_with_control(oid, control))
100 .transpose()?
101 .flatten()
102 .ok_or_else(|| SQLError::Routine {
103 sqlstate: "XX000".into(),
104 message: format!("cache lookup failed for type {oid}"),
105 })?;
106 &resolved
107 };
108 let mut bounds = ProductionVec::new(*control);
109 let mut count = usize::from(ndim != 0);
110 for (dimension, bound) in dimensions.iter().zip(shape.lower_bounds()) {
111 count = count
112 .checked_mul(*dimension)
113 .ok_or_else(|| corrupt("invalid array dimensions"))?;
114 bounds.push_copy(*bound)?;
115 }
116 let bitmap_start = 12 + ndim * 8;
117 let bitmap = if dataoffset == 0 {
118 None
119 } else {
120 Some(
121 bytes
122 .get(
123 bitmap_start
124 ..bitmap_start
125 .checked_add(count.div_ceil(8))
126 .ok_or_else(|| corrupt("invalid array dimensions"))?,
127 )
128 .ok_or_else(|| corrupt("invalid array null bitmap"))?,
129 )
130 };
131 let offset = if dataoffset == 0 {
132 inline::align(bitmap_start + 4, b'd')?
133 } else {
134 usize::try_from(dataoffset).map_err(|_| corrupt("invalid array data offset"))?
135 }
136 .checked_sub(4)
137 .filter(|offset| *offset >= bitmap_start && *offset <= bytes.len())
138 .ok_or_else(|| corrupt("invalid array data offset"))?;
139 let mut reader = Elements {
140 bytes,
141 bitmap,
142 index: 0,
143 offset,
144 element,
145 catalog,
146 control: *control,
147 };
148 let values = reader.dimension(dimensions)?;
149 let array = ArrayValue::with_lower_bounds_with_control(values, bounds.finish()?, control)?
150 .ok_or_else(|| corrupt("invalid array dimensions"))?;
151 let (array, memory) = array.into_parts();
152 Ok(control.finish(array.with_element_type_oid(Some(oid)), memory)?)
153}
154
155struct Elements<'a, 'c> {
156 bytes: &'a [u8],
157 bitmap: Option<&'a [u8]>,
158 index: usize,
159 offset: usize,
160 element: &'a crate::ColumnType,
161 catalog: Option<&'a dyn crate::expr::SQLValueCatalog>,
162 control: ProductionControl<'c>,
163}
164
165impl Elements<'_, '_> {
166 fn dimension(&mut self, dimensions: &[usize]) -> Result<Produced<Vec<Value>>, SQLError> {
167 let mut values = ProductionVec::new(self.control);
168 let Some((length, nested)) = dimensions.split_first() else {
169 return Ok(values.finish()?);
170 };
171 values.reserve(*length)?;
172 for _ in 0..*length {
173 self.control.check()?;
174 let value = if nested.is_empty() {
175 self.element()?
176 } else {
177 let (values, memory) = self.dimension(nested)?.into_parts();
178 self.control.finish(Value::List(values), memory)?
179 };
180 values.push_produced(value)?;
181 }
182 Ok(values.finish()?)
183 }
184
185 fn element(&mut self) -> Result<Produced<Value>, SQLError> {
186 let null = self
187 .bitmap
188 .is_some_and(|bitmap| bitmap[self.index / 8] & (1 << (self.index % 8)) == 0);
189 self.index += 1;
190 if null {
191 return Ok(self
192 .control
193 .finish(Value::Null, self.control.empty_reservation())?);
194 }
195 inline::read(
196 self.bytes,
197 &mut self.offset,
198 4,
199 self.element,
200 self.catalog,
201 &self.control,
202 )
203 }
204}
205
206fn integer(bytes: &[u8], offset: usize) -> Result<i32, SQLError> {
207 word(bytes.get(offset..).unwrap_or_default())
208 .map(|value| value as i32)
209 .ok_or_else(|| corrupt("invalid array header"))
210}