datatypes/vectors/
operations.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod cast;
mod filter;
mod find_unique;
mod replicate;
mod take;

use std::sync::Arc;

use common_base::BitVec;

use crate::error::{self, Result};
use crate::types::LogicalPrimitiveType;
use crate::vectors::constant::ConstantVector;
use crate::vectors::{
    BinaryVector, BooleanVector, ConcreteDataType, Decimal128Vector, ListVector, NullVector,
    PrimitiveVector, StringVector, UInt32Vector, Vector, VectorRef,
};

/// Vector compute operations.
pub trait VectorOp {
    /// Copies each element according `offsets` parameter.
    /// - `i-th` element should be copied `offsets[i] - offsets[i - 1]` times
    /// - `0-th` element would be copied `offsets[0]` times
    ///
    /// # Panics
    /// Panics if `offsets.len() != self.len()`.
    fn replicate(&self, offsets: &[usize]) -> VectorRef;

    /// Mark `i-th` bit of `selected` to `true` if the `i-th` element of `self` is unique, which
    /// means there is no elements behind it have same value as it.
    ///
    /// The caller should ensure
    /// 1. the length of `selected` bitmap is equal to `vector.len()`.
    /// 2. `vector` and `prev_vector` are sorted.
    ///
    /// If there are multiple duplicate elements, this function retains the **first** element.
    /// The first element is considered as unique if the first element of `self` is different
    /// from its previous element, that is the last element of `prev_vector`.
    ///
    /// # Panics
    /// Panics if
    /// - `selected.len() < self.len()`.
    /// - `prev_vector` and `self` have different data types.
    fn find_unique(&self, selected: &mut BitVec, prev_vector: Option<&dyn Vector>);

    /// Filters the vector, returns elements matching the `filter` (i.e. where the values are true).
    ///
    /// Note that the nulls of `filter` are interpreted as `false` will lead to these elements being masked out.
    fn filter(&self, filter: &BooleanVector) -> Result<VectorRef>;

    /// Cast vector to the provided data type and return a new vector with type to_type, if possible.
    ///
    /// TODO(dennis) describe behaviors in details.
    fn cast(&self, to_type: &ConcreteDataType) -> Result<VectorRef>;

    /// Take elements from the vector by the given indices.
    ///
    /// # Panics
    /// Panics if an index is out of bounds.
    fn take(&self, indices: &UInt32Vector) -> Result<VectorRef>;
}

macro_rules! impl_scalar_vector_op {
    ($($VectorType: ident),+) => {$(
        impl VectorOp for $VectorType {
            fn replicate(&self, offsets: &[usize]) -> VectorRef {
                replicate::replicate_scalar(self, offsets)
            }

            fn find_unique(&self, selected: &mut BitVec, prev_vector: Option<&dyn Vector>) {
                let prev_vector = prev_vector.map(|pv| pv.as_any().downcast_ref::<$VectorType>().unwrap());
                find_unique::find_unique_scalar(self, selected, prev_vector);
            }

            fn filter(&self, filter: &BooleanVector) -> Result<VectorRef> {
                filter::filter_non_constant!(self, $VectorType, filter)
            }

            fn cast(&self, to_type: &ConcreteDataType) -> Result<VectorRef> {
                if let Some(vector) = self.as_any().downcast_ref::<BinaryVector>() {
                    match to_type {
                        ConcreteDataType::Json(_) => {
                            let json_vector = vector.convert_binary_to_json()?;
                            return Ok(Arc::new(json_vector) as VectorRef);
                        }
                        ConcreteDataType::Vector(d) => {
                            let vector = vector.convert_binary_to_vector(d.dim)?;
                            return Ok(Arc::new(vector) as VectorRef);
                        }
                        _ => {}
                    }
                }
                cast::cast_non_constant!(self, to_type)
            }

            fn take(&self, indices: &UInt32Vector) -> Result<VectorRef> {
                take::take_indices!(self, $VectorType, indices)
            }
        }
    )+};
}

impl_scalar_vector_op!(BinaryVector, BooleanVector, ListVector, StringVector);

impl VectorOp for Decimal128Vector {
    fn replicate(&self, offsets: &[usize]) -> VectorRef {
        std::sync::Arc::new(replicate::replicate_decimal128(self, offsets))
    }

    fn find_unique(&self, selected: &mut BitVec, prev_vector: Option<&dyn Vector>) {
        let prev_vector = prev_vector.and_then(|pv| pv.as_any().downcast_ref::<Decimal128Vector>());
        find_unique::find_unique_scalar(self, selected, prev_vector);
    }

    fn filter(&self, filter: &BooleanVector) -> Result<VectorRef> {
        filter::filter_non_constant!(self, Decimal128Vector, filter)
    }

    fn cast(&self, to_type: &ConcreteDataType) -> Result<VectorRef> {
        cast::cast_non_constant!(self, to_type)
    }

    fn take(&self, indices: &UInt32Vector) -> Result<VectorRef> {
        take::take_indices!(self, Decimal128Vector, indices)
    }
}

impl<T: LogicalPrimitiveType> VectorOp for PrimitiveVector<T> {
    fn replicate(&self, offsets: &[usize]) -> VectorRef {
        std::sync::Arc::new(replicate::replicate_primitive(self, offsets))
    }

    fn find_unique(&self, selected: &mut BitVec, prev_vector: Option<&dyn Vector>) {
        let prev_vector =
            prev_vector.and_then(|pv| pv.as_any().downcast_ref::<PrimitiveVector<T>>());
        find_unique::find_unique_scalar(self, selected, prev_vector);
    }

    fn filter(&self, filter: &BooleanVector) -> Result<VectorRef> {
        filter::filter_non_constant!(self, PrimitiveVector<T>, filter)
    }

    fn cast(&self, to_type: &ConcreteDataType) -> Result<VectorRef> {
        cast::cast_non_constant!(self, to_type)
    }

    fn take(&self, indices: &UInt32Vector) -> Result<VectorRef> {
        take::take_indices!(self, PrimitiveVector<T>, indices)
    }
}

impl VectorOp for NullVector {
    fn replicate(&self, offsets: &[usize]) -> VectorRef {
        replicate::replicate_null(self, offsets)
    }

    fn find_unique(&self, selected: &mut BitVec, prev_vector: Option<&dyn Vector>) {
        let prev_vector = prev_vector.and_then(|pv| pv.as_any().downcast_ref::<NullVector>());
        find_unique::find_unique_null(self, selected, prev_vector);
    }

    fn filter(&self, filter: &BooleanVector) -> Result<VectorRef> {
        filter::filter_non_constant!(self, NullVector, filter)
    }
    fn cast(&self, _to_type: &ConcreteDataType) -> Result<VectorRef> {
        // TODO(dennis): impl it when NullVector has other datatype.
        error::UnsupportedOperationSnafu {
            op: "cast",
            vector_type: self.vector_type_name(),
        }
        .fail()
    }

    fn take(&self, indices: &UInt32Vector) -> Result<VectorRef> {
        take::take_indices!(self, NullVector, indices)
    }
}

impl VectorOp for ConstantVector {
    fn replicate(&self, offsets: &[usize]) -> VectorRef {
        self.replicate_vector(offsets)
    }

    fn find_unique(&self, selected: &mut BitVec, prev_vector: Option<&dyn Vector>) {
        let prev_vector = prev_vector.and_then(|pv| pv.as_any().downcast_ref::<ConstantVector>());
        find_unique::find_unique_constant(self, selected, prev_vector);
    }

    fn filter(&self, filter: &BooleanVector) -> Result<VectorRef> {
        self.filter_vector(filter)
    }

    fn cast(&self, to_type: &ConcreteDataType) -> Result<VectorRef> {
        self.cast_vector(to_type)
    }

    fn take(&self, indices: &UInt32Vector) -> Result<VectorRef> {
        self.take_vector(indices)
    }
}