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(oid))
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 .retain_external_with_control(control)?;
107 &resolved
108 };
109 let mut bounds = ProductionVec::new(*control);
110 let mut count = usize::from(ndim != 0);
111 for (dimension, bound) in dimensions.iter().zip(shape.lower_bounds()) {
112 count = count
113 .checked_mul(*dimension)
114 .ok_or_else(|| corrupt("invalid array dimensions"))?;
115 bounds.push_copy(*bound)?;
116 }
117 let bitmap_start = 12 + ndim * 8;
118 let bitmap = if dataoffset == 0 {
119 None
120 } else {
121 Some(
122 bytes
123 .get(
124 bitmap_start
125 ..bitmap_start
126 .checked_add(count.div_ceil(8))
127 .ok_or_else(|| corrupt("invalid array dimensions"))?,
128 )
129 .ok_or_else(|| corrupt("invalid array null bitmap"))?,
130 )
131 };
132 let offset = if dataoffset == 0 {
133 inline::align(bitmap_start + 4, b'd')?
134 } else {
135 usize::try_from(dataoffset).map_err(|_| corrupt("invalid array data offset"))?
136 }
137 .checked_sub(4)
138 .filter(|offset| *offset >= bitmap_start && *offset <= bytes.len())
139 .ok_or_else(|| corrupt("invalid array data offset"))?;
140 let mut reader = Elements {
141 bytes,
142 bitmap,
143 index: 0,
144 offset,
145 element,
146 catalog,
147 control: *control,
148 };
149 let values = reader.dimension(dimensions)?;
150 let array = ArrayValue::with_lower_bounds_with_control(values, bounds.finish()?, control)?
151 .ok_or_else(|| corrupt("invalid array dimensions"))?;
152 let (array, memory) = array.into_parts();
153 Ok(control.finish(array.with_element_type_oid(Some(oid)), memory)?)
154}
155
156struct Elements<'a, 'c> {
157 bytes: &'a [u8],
158 bitmap: Option<&'a [u8]>,
159 index: usize,
160 offset: usize,
161 element: &'a crate::ColumnType,
162 catalog: Option<&'a dyn crate::expr::SQLValueCatalog>,
163 control: ProductionControl<'c>,
164}
165
166impl Elements<'_, '_> {
167 fn dimension(&mut self, dimensions: &[usize]) -> Result<Produced<Vec<Value>>, SQLError> {
168 let mut values = ProductionVec::new(self.control);
169 let Some((length, nested)) = dimensions.split_first() else {
170 return Ok(values.finish()?);
171 };
172 values.reserve(*length)?;
173 for _ in 0..*length {
174 self.control.check()?;
175 let value = if nested.is_empty() {
176 self.element()?
177 } else {
178 let (values, memory) = self.dimension(nested)?.into_parts();
179 self.control.finish(Value::List(values), memory)?
180 };
181 values.push_produced(value)?;
182 }
183 Ok(values.finish()?)
184 }
185
186 fn element(&mut self) -> Result<Produced<Value>, SQLError> {
187 let null = self
188 .bitmap
189 .is_some_and(|bitmap| bitmap[self.index / 8] & (1 << (self.index % 8)) == 0);
190 self.index += 1;
191 if null {
192 return Ok(self
193 .control
194 .finish(Value::Null, self.control.empty_reservation())?);
195 }
196 inline::read(
197 self.bytes,
198 &mut self.offset,
199 4,
200 self.element,
201 self.catalog,
202 &self.control,
203 )
204 }
205}
206
207fn integer(bytes: &[u8], offset: usize) -> Result<i32, SQLError> {
208 word(bytes.get(offset..).unwrap_or_default())
209 .map(|value| value as i32)
210 .ok_or_else(|| corrupt("invalid array header"))
211}