lance_arrow/
schema.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! Extension to arrow schema

use arrow_schema::{ArrowError, DataType, Field, FieldRef, Schema};

pub enum Indentation {
    OneLine,
    MultiLine(u8),
}

impl Indentation {
    fn value(&self) -> String {
        match self {
            Self::OneLine => "".to_string(),
            Self::MultiLine(spaces) => " ".repeat(*spaces as usize),
        }
    }

    fn deepen(&self) -> Self {
        match self {
            Self::OneLine => Self::OneLine,
            Self::MultiLine(spaces) => Self::MultiLine(spaces + 2),
        }
    }
}

/// Extends the functionality of [arrow_schema::Field].
pub trait FieldExt {
    /// Create a compact string representation of the field
    ///
    /// This is intended for display purposes and not for serialization
    fn to_compact_string(&self, indent: Indentation) -> String;

    fn is_packed_struct(&self) -> bool;
}

impl FieldExt for Field {
    fn to_compact_string(&self, indent: Indentation) -> String {
        let mut result = format!("{}: ", self.name().clone());
        match self.data_type() {
            DataType::Struct(fields) => {
                result += "{";
                result += &indent.value();
                for (field_idx, field) in fields.iter().enumerate() {
                    result += field.to_compact_string(indent.deepen()).as_str();
                    if field_idx < fields.len() - 1 {
                        result += ",";
                    }
                    result += indent.value().as_str();
                }
                result += "}";
            }
            DataType::List(field)
            | DataType::LargeList(field)
            | DataType::ListView(field)
            | DataType::LargeListView(field) => {
                result += "[";
                result += field.to_compact_string(indent.deepen()).as_str();
                result += "]";
            }
            DataType::FixedSizeList(child, dimension) => {
                result += &format!(
                    "[{}; {}]",
                    child.to_compact_string(indent.deepen()),
                    dimension
                );
            }
            DataType::Dictionary(key_type, value_type) => {
                result += &value_type.to_string();
                result += "@";
                result += &key_type.to_string();
            }
            _ => {
                result += &self.data_type().to_string();
            }
        }
        if self.is_nullable() {
            result += "?";
        }
        result
    }

    // Check if field has metadata `packed` set to true, this check is case insensitive.
    fn is_packed_struct(&self) -> bool {
        let field_metadata = self.metadata();
        field_metadata
            .get("packed")
            .map(|v| v.to_lowercase() == "true")
            .unwrap_or(false)
    }
}

/// Extends the functionality of [arrow_schema::Schema].
pub trait SchemaExt {
    /// Create a new [`Schema`] with one extra field.
    fn try_with_column(&self, field: Field) -> std::result::Result<Schema, ArrowError>;

    fn try_with_column_at(
        &self,
        index: usize,
        field: Field,
    ) -> std::result::Result<Schema, ArrowError>;

    fn field_names(&self) -> Vec<&String>;

    fn without_column(&self, column_name: &str) -> Schema;

    /// Create a compact string representation of the schema
    ///
    /// This is intended for display purposes and not for serialization
    fn to_compact_string(&self, indent: Indentation) -> String;
}

impl SchemaExt for Schema {
    fn try_with_column(&self, field: Field) -> std::result::Result<Schema, ArrowError> {
        if self.column_with_name(field.name()).is_some() {
            return Err(ArrowError::SchemaError(format!(
                "Can not append column {} on schema: {:?}",
                field.name(),
                self
            )));
        };
        let mut fields: Vec<FieldRef> = self.fields().iter().cloned().collect();
        fields.push(FieldRef::new(field));
        Ok(Self::new_with_metadata(fields, self.metadata.clone()))
    }

    fn try_with_column_at(
        &self,
        index: usize,
        field: Field,
    ) -> std::result::Result<Schema, ArrowError> {
        if self.column_with_name(field.name()).is_some() {
            return Err(ArrowError::SchemaError(format!(
                "Failed to modify schema: Inserting column {} would create a duplicate column in schema: {:?}",
                field.name(),
                self
            )));
        };
        let mut fields: Vec<FieldRef> = self.fields().iter().cloned().collect();
        fields.insert(index, FieldRef::new(field));
        Ok(Self::new_with_metadata(fields, self.metadata.clone()))
    }

    /// Project the schema to remove the given column.
    ///
    /// This only works on top-level fields right now. If a field does not exist,
    /// the schema will be returned as is.
    fn without_column(&self, column_name: &str) -> Schema {
        let fields: Vec<FieldRef> = self
            .fields()
            .iter()
            .filter(|f| f.name() != column_name)
            .cloned()
            .collect();
        Self::new_with_metadata(fields, self.metadata.clone())
    }

    fn field_names(&self) -> Vec<&String> {
        self.fields().iter().map(|f| f.name()).collect()
    }

    fn to_compact_string(&self, indent: Indentation) -> String {
        let mut result = "{".to_string();
        result += &indent.value();
        for (field_idx, field) in self.fields.iter().enumerate() {
            result += field.to_compact_string(indent.deepen()).as_str();
            if field_idx < self.fields.len() - 1 {
                result += ",";
            }
            result += indent.value().as_str();
        }
        result += "}";
        result
    }
}