Skip to main content

vortex_layout/layouts/struct_/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod reader;
5
6use std::sync::Arc;
7
8use reader::StructReader;
9use vortex_array::DeserializeMetadata;
10use vortex_array::EmptyMetadata;
11use vortex_array::dtype::DType;
12use vortex_array::dtype::Field;
13use vortex_array::dtype::FieldMask;
14use vortex_array::dtype::Nullability;
15use vortex_array::dtype::StructFields;
16use vortex_error::VortexExpect;
17use vortex_error::VortexResult;
18use vortex_error::vortex_bail;
19use vortex_error::vortex_ensure;
20use vortex_error::vortex_err;
21use vortex_session::SessionExt;
22use vortex_session::VortexSession;
23use vortex_session::registry::ReadContext;
24
25use crate::LayoutChildType;
26use crate::LayoutEncodingRef;
27use crate::LayoutId;
28use crate::LayoutReaderRef;
29use crate::LayoutRef;
30use crate::VTable;
31use crate::children::LayoutChildren;
32use crate::children::OwnedLayoutChildren;
33use crate::segments::SegmentId;
34use crate::segments::SegmentSource;
35use crate::vtable;
36
37vtable!(Struct);
38
39impl VTable for Struct {
40    type Layout = StructLayout;
41    type Encoding = StructLayoutEncoding;
42    type Metadata = EmptyMetadata;
43
44    fn id(_encoding: &Self::Encoding) -> LayoutId {
45        LayoutId::new_ref("vortex.struct")
46    }
47
48    fn encoding(_layout: &Self::Layout) -> LayoutEncodingRef {
49        LayoutEncodingRef::new_ref(StructLayoutEncoding.as_ref())
50    }
51
52    fn row_count(layout: &Self::Layout) -> u64 {
53        layout.row_count
54    }
55
56    fn dtype(layout: &Self::Layout) -> &DType {
57        &layout.dtype
58    }
59
60    fn metadata(_layout: &Self::Layout) -> Self::Metadata {
61        EmptyMetadata
62    }
63
64    fn segment_ids(_layout: &Self::Layout) -> Vec<SegmentId> {
65        vec![]
66    }
67
68    fn nchildren(layout: &Self::Layout) -> usize {
69        let validity_children = if layout.dtype.is_nullable() { 1 } else { 0 };
70        layout.struct_fields().nfields() + validity_children
71    }
72
73    fn child(layout: &Self::Layout, index: usize) -> VortexResult<LayoutRef> {
74        let schema_index = if layout.dtype.is_nullable() {
75            index.saturating_sub(1)
76        } else {
77            index
78        };
79
80        let child_dtype = if index == 0 && layout.dtype.is_nullable() {
81            DType::Bool(Nullability::NonNullable)
82        } else {
83            layout
84                .struct_fields()
85                .field_by_index(schema_index)
86                .ok_or_else(|| vortex_err!("Missing field {schema_index}"))?
87        };
88
89        layout.children.child(index, &child_dtype)
90    }
91
92    fn child_type(layout: &Self::Layout, idx: usize) -> LayoutChildType {
93        let schema_index = if layout.dtype.is_nullable() {
94            idx.saturating_sub(1)
95        } else {
96            idx
97        };
98
99        if idx == 0 && layout.dtype.is_nullable() {
100            LayoutChildType::Auxiliary("validity".into())
101        } else {
102            LayoutChildType::Field(
103                layout
104                    .struct_fields()
105                    .field_name(schema_index)
106                    .vortex_expect("Field index out of bounds")
107                    .clone(),
108            )
109        }
110    }
111
112    fn new_reader(
113        layout: &Self::Layout,
114        name: Arc<str>,
115        segment_source: Arc<dyn SegmentSource>,
116        session: &VortexSession,
117    ) -> VortexResult<LayoutReaderRef> {
118        Ok(Arc::new(StructReader::try_new(
119            layout.clone(),
120            name,
121            segment_source,
122            session.session(),
123        )?))
124    }
125
126    fn build(
127        _encoding: &Self::Encoding,
128        dtype: &DType,
129        row_count: u64,
130        _metadata: &<Self::Metadata as DeserializeMetadata>::Output,
131        _segment_ids: Vec<SegmentId>,
132        children: &dyn LayoutChildren,
133        _ctx: &ReadContext,
134    ) -> VortexResult<Self::Layout> {
135        let struct_dt = dtype
136            .as_struct_fields_opt()
137            .ok_or_else(|| vortex_err!("Expected struct dtype"))?;
138
139        let expected_children = struct_dt.nfields() + (dtype.is_nullable() as usize);
140        vortex_ensure!(
141            children.nchildren() == expected_children,
142            "Struct layout has {} children, but dtype has {} fields",
143            children.nchildren(),
144            struct_dt.nfields()
145        );
146
147        Ok(StructLayout {
148            row_count,
149            dtype: dtype.clone(),
150            children: children.to_arc(),
151        })
152    }
153
154    fn with_children(layout: &mut Self::Layout, children: Vec<LayoutRef>) -> VortexResult<()> {
155        let struct_dt = layout
156            .dtype
157            .as_struct_fields_opt()
158            .ok_or_else(|| vortex_err!("Expected struct dtype"))?;
159
160        let expected_children = struct_dt.nfields() + (layout.dtype.is_nullable() as usize);
161        vortex_ensure!(
162            children.len() == expected_children,
163            "StructLayout expects {} children, got {}",
164            expected_children,
165            children.len()
166        );
167
168        layout.children = OwnedLayoutChildren::layout_children(children);
169        Ok(())
170    }
171}
172
173#[derive(Debug)]
174pub struct StructLayoutEncoding;
175
176/// Decomposes a struct-typed column into one child per field, enabling columnar projection.
177///
178/// Queries that only need a subset of fields can skip reading the rest entirely.
179#[derive(Clone, Debug)]
180pub struct StructLayout {
181    row_count: u64,
182    dtype: DType,
183    children: Arc<dyn LayoutChildren>,
184}
185
186impl StructLayout {
187    pub fn new(row_count: u64, dtype: DType, children: Vec<LayoutRef>) -> Self {
188        Self {
189            row_count,
190            dtype,
191            children: OwnedLayoutChildren::layout_children(children),
192        }
193    }
194
195    pub fn struct_fields(&self) -> &StructFields {
196        self.dtype
197            .as_struct_fields_opt()
198            .vortex_expect("Struct layout dtype must be a struct")
199    }
200
201    #[inline]
202    pub fn row_count(&self) -> u64 {
203        self.row_count
204    }
205
206    #[inline]
207    pub fn children(&self) -> &Arc<dyn LayoutChildren> {
208        &self.children
209    }
210
211    pub fn matching_fields<F>(&self, field_mask: &[FieldMask], mut per_child: F) -> VortexResult<()>
212    where
213        F: FnMut(FieldMask, usize) -> VortexResult<()>,
214    {
215        // If the field mask contains an `All` fields, then enumerate all fields.
216        if field_mask.iter().any(|mask| mask.matches_all()) {
217            for idx in 0..self.struct_fields().nfields() {
218                per_child(FieldMask::All, idx)?;
219            }
220            return Ok(());
221        }
222
223        // Enumerate each field in the mask
224        for path in field_mask {
225            let Some(field) = path.starting_field()? else {
226                // skip fields not in mask
227                continue;
228            };
229            let Field::Name(field_name) = field else {
230                vortex_bail!("Expected field name, got {field:?}");
231            };
232            let idx = self
233                .struct_fields()
234                .find(field_name)
235                .ok_or_else(|| vortex_err!("Field not found: {field_name}"))?;
236
237            per_child(path.clone().step_into()?, idx)?;
238        }
239
240        Ok(())
241    }
242}