1use std::sync::Arc;
19
20use rudb_common::{Error, LogicalType, Result, Value};
21
22use crate::buffer::Buffer;
23use crate::string::{StringColumn, StringView};
24use crate::validity::Validity;
25
26pub const VECTOR_SIZE: usize = 1024;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum Form {
49 Flat,
51 Constant,
53 Sequence,
55 Dictionary,
57}
58
59#[derive(Debug, Clone, PartialEq)]
64#[non_exhaustive]
65pub enum Data {
66 Empty,
68 Bool(Buffer<bool>),
70 Int8(Buffer<i8>),
72 Int16(Buffer<i16>),
74 Int32(Buffer<i32>),
76 Int64(Buffer<i64>),
78 Int128(Buffer<i128>),
80 UInt8(Buffer<u8>),
82 UInt16(Buffer<u16>),
84 UInt32(Buffer<u32>),
86 UInt64(Buffer<u64>),
88 UInt128(Buffer<u128>),
90 Float32(Buffer<f32>),
92 Float64(Buffer<f64>),
94 Interval(Buffer<(i32, i32, i64)>),
96 Varlen(StringColumn),
98}
99
100impl Data {
101 #[must_use]
108 pub fn len(&self) -> usize {
109 macro_rules! lengths {
110 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
111 match self {
112 Self::Empty => 0,
113 $(Self::$variant(values) => values.len(),)+
114 }
115 };
116 }
117 crate::for_each_layout!(all, lengths)
118 }
119
120 #[must_use]
122 pub fn is_empty(&self) -> bool {
123 self.len() == 0
124 }
125
126 #[must_use]
132 pub fn footprint(&self) -> usize {
133 macro_rules! sizes {
134 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
135 match self {
136 Self::Empty => 0,
137 $(Self::$variant(values) => values.footprint(),)+
138 }
139 };
140 }
141 crate::for_each_layout!(all, sizes)
142 }
143
144 #[must_use]
149 pub fn signed_at(&self, index: usize) -> Option<i128> {
150 macro_rules! widened {
151 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
152 match self {
153 $(Self::$variant(v) => v.get(index).map(|&x| i128::from(x)),)+
154 _ => None,
155 }
156 };
157 }
158 crate::for_each_layout!(signed, widened)
159 }
160
161 #[must_use]
163 pub fn unsigned_at(&self, index: usize) -> Option<u128> {
164 macro_rules! widened {
165 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
166 match self {
167 $(Self::$variant(v) => v.get(index).map(|&x| u128::from(x)),)+
168 _ => None,
169 }
170 };
171 }
172 crate::for_each_layout!(unsigned, widened)
173 }
174
175 #[must_use]
177 pub fn str_at(&self, index: usize) -> Option<&str> {
178 match self {
179 Self::Varlen(column) => column.get(index),
180 _ => None,
181 }
182 }
183
184 #[must_use]
189 pub fn bytes_at(&self, index: usize) -> Option<&[u8]> {
190 match self {
191 Self::Varlen(column) => column.bytes(index),
192 _ => None,
193 }
194 }
195}
196
197#[derive(Debug, Clone, PartialEq)]
199pub struct Vector {
200 ty: LogicalType,
201 len: usize,
202 validity: Validity,
203 body: Body,
204}
205
206#[derive(Debug, Clone, PartialEq)]
208enum Body {
209 Flat(Data),
210 Constant(Box<Value>),
211 Sequence {
212 start: i64,
213 step: i64,
214 },
215 Dictionary {
225 codes: Vec<u32>,
226 values: Arc<Vector>,
227 },
228}
229
230impl Vector {
231 pub fn flat(ty: LogicalType, data: Data) -> Result<Self> {
239 let len = data.len();
240 if !matches!(data, Data::Empty) && layout_of(&data) != ty.physical() {
241 return Err(Error::internal(format!(
242 "a {ty} vector cannot hold {:?} data",
243 layout_of(&data)
244 )));
245 }
246 Ok(Self { ty, len, validity: Validity::AllValid, body: Body::Flat(data) })
247 }
248
249 pub fn from_values(ty: LogicalType, values: &[Value]) -> Result<Self> {
261 let mut data = empty_data_for(&ty)?;
262 for value in values {
263 push_value(&mut data, value)?;
264 }
265 let validity = Validity::from_iter(values.len(), |index| !values[index].is_null());
266 Ok(Self { ty, len: values.len(), validity, body: Body::Flat(data) })
267 }
268
269 #[must_use]
274 pub fn constant(ty: LogicalType, value: Value, len: usize) -> Self {
275 let validity = if value.is_null() { Validity::AllInvalid } else { Validity::AllValid };
276 Self { ty, len, validity, body: Body::Constant(Box::new(value)) }
277 }
278
279 #[must_use]
284 pub fn sequence(start: i64, step: i64, len: usize) -> Self {
285 Self {
286 ty: LogicalType::BigInt,
287 len,
288 validity: Validity::AllValid,
289 body: Body::Sequence { start, step },
290 }
291 }
292
293 pub fn dictionary(codes: Vec<u32>, values: Vector) -> Result<Self> {
323 if let Some(&bad) = codes.iter().find(|&&code| code as usize >= values.len()) {
324 return Err(Error::internal(format!(
325 "dictionary code {bad} is past the end of a {} value dictionary",
326 values.len()
327 )));
328 }
329 let (codes, values) = compose(codes, values);
330 Ok(Self {
331 ty: values.ty.clone(),
332 len: codes.len(),
333 validity: Validity::AllValid,
334 body: Body::Dictionary { codes, values: Arc::new(values) },
335 })
336 }
337
338 #[must_use]
340 pub fn with_validity(mut self, validity: Validity) -> Self {
341 self.validity = validity;
342 self
343 }
344
345 #[must_use]
347 pub fn logical_type(&self) -> &LogicalType {
348 &self.ty
349 }
350
351 #[must_use]
353 pub fn len(&self) -> usize {
354 self.len
355 }
356
357 #[must_use]
359 pub fn is_empty(&self) -> bool {
360 self.len == 0
361 }
362
363 #[must_use]
375 pub fn footprint(&self) -> usize {
376 let body = match &self.body {
377 Body::Flat(data) => data.footprint(),
378 Body::Constant(value) => value.footprint(),
379 Body::Sequence { .. } => 0,
380 Body::Dictionary { codes, values } => {
381 codes.capacity() * size_of::<u32>() + values.footprint()
382 }
383 };
384 size_of::<Self>() + self.validity.footprint() + body
385 }
386
387 #[must_use]
389 pub fn validity(&self) -> &Validity {
390 &self.validity
391 }
392
393 #[must_use]
395 pub fn form(&self) -> Form {
396 match self.body {
397 Body::Flat(_) => Form::Flat,
398 Body::Constant(_) => Form::Constant,
399 Body::Sequence { .. } => Form::Sequence,
400 Body::Dictionary { .. } => Form::Dictionary,
401 }
402 }
403
404 #[must_use]
409 pub fn data(&self) -> Option<&Data> {
410 match &self.body {
411 Body::Flat(data) => Some(data),
412 _ => None,
413 }
414 }
415
416 #[must_use]
423 pub fn constant_value(&self) -> Option<&Value> {
424 match &self.body {
425 Body::Constant(value) => Some(value.as_ref()),
426 _ => None,
427 }
428 }
429
430 #[must_use]
444 pub fn dictionary_parts(&self) -> Option<(&[u32], &Self)> {
445 match &self.body {
446 Body::Dictionary { codes, values } => Some((codes, values.as_ref())),
447 _ => None,
448 }
449 }
450
451 #[must_use]
453 pub fn sequence_parts(&self) -> Option<(i64, i64)> {
454 match self.body {
455 Body::Sequence { start, step } => Some((start, step)),
456 _ => None,
457 }
458 }
459
460 #[must_use]
466 pub fn value_at(&self, index: usize) -> Value {
467 if index >= self.len || !self.validity.is_valid(index) {
468 return Value::Null;
469 }
470 match &self.body {
471 Body::Constant(value) => value.as_ref().clone(),
472 Body::Sequence { start, step } => Value::BigInt(start + step * index as i64),
473 Body::Dictionary { codes, values } => match codes.get(index) {
474 Some(&code) => values.value_at(code as usize),
475 None => Value::Null,
476 },
477 Body::Flat(data) => value_from(&self.ty, data, index),
478 }
479 }
480
481 pub fn iter(&self) -> impl Iterator<Item = Value> + '_ {
483 (0..self.len).map(|index| self.value_at(index))
484 }
485
486 pub fn slice(&self, at: usize, len: usize) -> Result<Self> {
508 let end = at.checked_add(len).ok_or_else(|| Error::internal("a slice that wraps"))?;
509 if end > self.len {
510 return Err(Error::internal(format!("rows {at} to {end} of a vector of {}", self.len)));
511 }
512 if at == 0 && len == self.len {
513 return Ok(self.clone());
514 }
515 let validity = Validity::from_iter(len, |row| self.validity.is_valid(at + row));
516 let body = match &self.body {
517 Body::Constant(value) => Body::Constant(value.clone()),
518 Body::Sequence { start, step } => {
519 Body::Sequence { start: start + step * at as i64, step: *step }
520 }
521 Body::Dictionary { codes, values } => {
522 Body::Dictionary { codes: codes[at..end].to_vec(), values: Arc::clone(values) }
523 }
524 Body::Flat(_) => {
528 let indices: Vec<u32> =
529 (at..end).map(|row| u32::try_from(row).unwrap_or(u32::MAX)).collect();
530 return self.gather(&indices);
531 }
532 };
533 Ok(Self { ty: self.ty.clone(), len, validity, body })
534 }
535
536 pub fn flatten(&self) -> Result<Self> {
547 if let Body::Flat(_) = self.body {
548 return Ok(self.clone());
549 }
550 self.copied((0..self.len).collect(), false)
551 }
552
553 pub fn gather(&self, indices: &[u32]) -> Result<Self> {
569 self.copied(indices.iter().map(|&index| index as usize).collect(), true)
570 }
571
572 fn copied(&self, at: Vec<usize>, constants_stay: bool) -> Result<Self> {
579 let rows = at.len();
580 let (at, leaf) = self.resolve(at);
581 let live: Vec<bool> = at.iter().map(|&index| index != NOWHERE).collect();
582 let validity = Validity::from_run(&live);
583 let body = match &leaf.body {
584 Body::Constant(value) => {
587 if constants_stay && matches!(validity, Validity::AllValid) {
588 return Ok(Self::constant(self.ty.clone(), value.as_ref().clone(), rows));
589 }
590 let mut data = empty_data_for(&self.ty)?;
591 for &index in &at {
592 push_value(&mut data, if index == NOWHERE { &Value::Null } else { value })?;
593 }
594 Body::Flat(data)
595 }
596 Body::Sequence { start, step } => Body::Flat(Data::Int64(
599 at.iter()
600 .map(|&index| if index == NOWHERE { 0 } else { start + step * index as i64 })
601 .collect(),
602 )),
603 Body::Flat(Data::Empty) => {
607 return Ok(Self::constant(self.ty.clone(), Value::Null, rows));
608 }
609 Body::Flat(data) => Body::Flat(copy_of(data, &at)),
610 Body::Dictionary { .. } => {
612 return Err(Error::internal("a dictionary survived being resolved"));
613 }
614 };
615 Ok(Self { ty: self.ty.clone(), len: rows, validity, body })
616 }
617
618 fn resolve(&self, mut at: Vec<usize>) -> (Vec<usize>, &Self) {
624 let mut source = self;
625 loop {
626 for slot in &mut at {
627 if *slot >= source.len || !source.validity.is_valid(*slot) {
628 *slot = NOWHERE;
629 }
630 }
631 let Body::Dictionary { codes, values } = &source.body else {
632 return (at, source);
633 };
634 for slot in &mut at {
635 *slot = match codes.get(*slot) {
636 Some(&code) => code as usize,
637 None => NOWHERE,
638 };
639 }
640 source = values.as_ref();
641 }
642 }
643}
644
645impl AsRef<Vector> for Vector {
652 fn as_ref(&self) -> &Vector {
653 self
654 }
655}
656
657fn compose(codes: Vec<u32>, values: Vector) -> (Vec<u32>, Vector) {
669 if !matches!(values.validity, Validity::AllValid) {
672 return (codes, values);
673 }
674 let Vector { ty, len, validity, body } = values;
675 match body {
676 Body::Dictionary { codes: inner, values: leaf } => {
677 debug_assert!(
678 !matches!(leaf.body, Body::Dictionary { .. })
679 || !matches!(leaf.validity, Validity::AllValid),
680 "a dictionary was stacked on a dictionary without going through the constructor"
681 );
682 (codes.iter().map(|&code| inner[code as usize]).collect(), Arc::unwrap_or_clone(leaf))
687 }
688 body => (codes, Vector { ty, len, validity, body }),
689 }
690}
691
692const NOWHERE: usize = usize::MAX;
697
698fn copy_of(data: &Data, at: &[usize]) -> Data {
704 macro_rules! copied {
705 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
706 match data {
707 Data::Empty => Data::Empty,
708 $(Data::$variant(values) => {
709 let mut out = Buffer::with_capacity(at.len());
710 for &index in at {
711 out.push(values.get(index).copied().unwrap_or($zero));
714 }
715 Data::$variant(out)
716 })+
717 Data::Varlen(values) => {
721 let mut out = StringColumn::with_capacity(at.len());
722 let views = values.views();
727 out.reserve_bytes(
728 at.iter()
729 .filter_map(|&index| views.get(index))
730 .filter(|view| !view.is_inline())
731 .map(StringView::len)
732 .sum(),
733 );
734 for &index in at {
735 out.push_from(values, index);
736 }
737 Data::Varlen(out)
738 }
739 }
740 };
741 }
742 crate::for_each_layout!(fixed, copied)
743}
744
745fn layout_of(data: &Data) -> rudb_common::PhysicalType {
750 use rudb_common::PhysicalType as P;
751 macro_rules! layouts {
752 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
753 match data {
754 Data::Empty => P::Empty,
755 $(Data::$variant(_) => P::$variant,)+
756 }
757 };
758 }
759 crate::for_each_layout!(all, layouts)
760}
761
762fn value_from(ty: &LogicalType, data: &Data, index: usize) -> Value {
767 let signed = || data.signed_at(index);
768 let unsigned = || data.unsigned_at(index);
769 let value = match ty {
770 LogicalType::Boolean => match data {
771 Data::Bool(v) => v.get(index).map(|&x| Value::Boolean(x)),
772 _ => None,
773 },
774 LogicalType::TinyInt => signed().and_then(|x| i8::try_from(x).ok()).map(Value::TinyInt),
775 LogicalType::SmallInt => signed().and_then(|x| i16::try_from(x).ok()).map(Value::SmallInt),
776 LogicalType::Integer => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Integer),
777 LogicalType::BigInt => signed().and_then(|x| i64::try_from(x).ok()).map(Value::BigInt),
778 LogicalType::HugeInt => signed().map(Value::HugeInt),
779 LogicalType::UTinyInt => unsigned().and_then(|x| u8::try_from(x).ok()).map(Value::UTinyInt),
780 LogicalType::USmallInt => {
781 unsigned().and_then(|x| u16::try_from(x).ok()).map(Value::USmallInt)
782 }
783 LogicalType::UInteger => {
784 unsigned().and_then(|x| u32::try_from(x).ok()).map(Value::UInteger)
785 }
786 LogicalType::UBigInt => unsigned().and_then(|x| u64::try_from(x).ok()).map(Value::UBigInt),
787 LogicalType::UHugeInt => unsigned().map(Value::UHugeInt),
788 LogicalType::Float => match data {
789 Data::Float32(v) => v.get(index).map(|&x| Value::Float(x)),
790 _ => None,
791 },
792 LogicalType::Double => match data {
793 Data::Float64(v) => v.get(index).map(|&x| Value::Double(x)),
794 _ => None,
795 },
796 LogicalType::Decimal { width, scale } => {
797 signed().map(|unscaled| Value::Decimal { unscaled, width: *width, scale: *scale })
798 }
799 LogicalType::Varchar => data.str_at(index).map(|s| Value::Varchar(s.to_string())),
800 LogicalType::Blob | LogicalType::Bit => {
801 data.bytes_at(index).map(|bytes| Value::Blob(bytes.to_vec()))
802 }
803 LogicalType::Date => signed().and_then(|x| i32::try_from(x).ok()).map(Value::Date),
804 LogicalType::Time | LogicalType::TimeTz => {
805 signed().and_then(|x| i64::try_from(x).ok()).map(Value::Time)
806 }
807 LogicalType::Timestamp
808 | LogicalType::TimestampS
809 | LogicalType::TimestampMs
810 | LogicalType::TimestampNs
811 | LogicalType::TimestampTz => {
812 signed().and_then(|x| i64::try_from(x).ok()).map(Value::Timestamp)
813 }
814 LogicalType::Interval => match data {
815 Data::Interval(v) => {
816 v.get(index).map(|&(months, days, micros)| Value::Interval { months, days, micros })
817 }
818 _ => None,
819 },
820 _ => None,
821 };
822 value.unwrap_or(Value::Null)
823}
824
825fn empty_data_for(ty: &LogicalType) -> Result<Data> {
827 use rudb_common::PhysicalType as P;
828 macro_rules! empties {
829 ($(($variant:ident, $native:ty, $zero:expr)),+ $(,)?) => {
830 match ty.physical() {
831 P::Empty => Data::Empty,
832 $(P::$variant => Data::$variant(Buffer::new()),)+
833 P::Varlen => Data::Varlen(StringColumn::new()),
834 other => {
835 return Err(Error::not_implemented(format!(
836 "a flat vector of {other:?} data, which arrives with the storage layer"
837 )));
838 }
839 }
840 };
841 }
842 Ok(crate::for_each_layout!(fixed, empties))
843}
844
845fn push_value(data: &mut Data, value: &Value) -> Result<()> {
850 macro_rules! push {
851 ($vec:expr, $variant:path, $zero:expr) => {
852 match value {
853 Value::Null => $vec.push($zero),
854 $variant(x) => $vec.push(*x),
855 other => {
856 return Err(Error::internal(format!(
857 "{other:?} does not belong in this vector"
858 )));
859 }
860 }
861 };
862 }
863 macro_rules! decimal {
869 ($vec:expr, $ty:ty, $unscaled:expr) => {
870 match <$ty>::try_from(*$unscaled) {
871 Ok(x) => $vec.push(x),
872 Err(_) => {
873 return Err(Error::internal(format!(
874 "an unscaled decimal of {} does not fit the run its precision chose",
875 $unscaled
876 )));
877 }
878 }
879 };
880 }
881 match data {
882 Data::Empty => {}
883 Data::Bool(v) => push!(v, Value::Boolean, false),
884 Data::Int8(v) => push!(v, Value::TinyInt, 0),
885 Data::Int16(v) => match value {
886 Value::Null => v.push(0),
887 Value::SmallInt(x) => v.push(*x),
888 Value::Decimal { unscaled, .. } => decimal!(v, i16, unscaled),
889 other => return Err(Error::internal(format!("{other:?} is not a 16 bit value"))),
890 },
891 Data::Int32(v) => match value {
892 Value::Null => v.push(0),
893 Value::Integer(x) | Value::Date(x) => v.push(*x),
894 Value::Decimal { unscaled, .. } => decimal!(v, i32, unscaled),
895 other => return Err(Error::internal(format!("{other:?} is not a 32 bit value"))),
896 },
897 Data::Int64(v) => match value {
898 Value::Null => v.push(0),
899 Value::BigInt(x) | Value::Time(x) | Value::Timestamp(x) => v.push(*x),
900 Value::Decimal { unscaled, .. } => decimal!(v, i64, unscaled),
901 other => return Err(Error::internal(format!("{other:?} is not a 64 bit value"))),
902 },
903 Data::Int128(v) => match value {
904 Value::Null => v.push(0),
905 Value::HugeInt(x) => v.push(*x),
906 Value::Decimal { unscaled, .. } => v.push(*unscaled),
907 other => return Err(Error::internal(format!("{other:?} is not a 128 bit value"))),
908 },
909 Data::UInt8(v) => push!(v, Value::UTinyInt, 0),
910 Data::UInt16(v) => push!(v, Value::USmallInt, 0),
911 Data::UInt32(v) => push!(v, Value::UInteger, 0),
912 Data::UInt64(v) => push!(v, Value::UBigInt, 0),
913 Data::UInt128(v) => push!(v, Value::UHugeInt, 0),
914 Data::Float32(v) => push!(v, Value::Float, 0.0),
915 Data::Float64(v) => push!(v, Value::Double, 0.0),
916 Data::Interval(v) => match value {
917 Value::Null => v.push((0, 0, 0)),
918 Value::Interval { months, days, micros } => v.push((*months, *days, *micros)),
919 other => return Err(Error::internal(format!("{other:?} is not an interval"))),
920 },
921 Data::Varlen(column) => match value {
922 Value::Null => {
923 column.push("");
924 }
925 Value::Varchar(text) => {
926 column.push(text);
927 }
928 Value::Blob(bytes) => {
932 column.push_bytes(bytes);
933 }
934 other => return Err(Error::internal(format!("{other:?} is not a string"))),
935 },
936 }
937 Ok(())
938}
939
940#[cfg(test)]
941mod tests {
942 use std::sync::Arc;
943
944 use rudb_common::{LogicalType, Value};
945
946 use super::{Body, Data, Form, VECTOR_SIZE, Vector};
947 use crate::string::StringColumn;
948 use crate::validity::Validity;
949
950 fn integers(values: &[i32]) -> Vector {
951 Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec().into())).unwrap()
952 }
953
954 #[test]
955 fn slicing_a_dictionary_keeps_it_a_dictionary_where_gathering_would_not() {
956 let values = Vector::from_values(
957 LogicalType::Varchar,
958 &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
959 )
960 .unwrap();
961 let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
962
963 let piece = vector.slice(1, 3).unwrap();
964 assert_eq!(piece.form(), Form::Dictionary, "the form is the whole point");
965 assert_eq!(piece.len(), 3);
966 assert_eq!(
967 piece.iter().collect::<Vec<_>>(),
968 [
969 Value::Varchar("blue".into()),
970 Value::Varchar("blue".into()),
971 Value::Varchar("red".into())
972 ]
973 );
974 assert_eq!(vector.gather(&[1, 2, 3]).unwrap().form(), Form::Flat, "which a gather loses");
975 }
976
977 #[test]
978 fn slicing_a_dictionary_shares_the_dictionary_rather_than_copying_it() {
979 let values = Vector::from_values(
984 LogicalType::Varchar,
985 &[Value::Varchar("red".into()), Value::Varchar("blue".into())],
986 )
987 .unwrap();
988 let vector = Vector::dictionary(vec![0, 1, 1, 0, 1], values).unwrap();
989 let Body::Dictionary { values: whole, .. } = &vector.body else {
990 panic!("a dictionary vector holds a dictionary");
991 };
992
993 let piece = vector.slice(1, 3).unwrap();
994 let Body::Dictionary { codes, values: cut } = &piece.body else {
995 panic!("a slice of a dictionary is a dictionary");
996 };
997 assert!(Arc::ptr_eq(whole, cut), "the cut copied the dictionary");
998 assert_eq!(codes, &[1, 1, 0], "the codes are the part that is cut");
999
1000 let again = piece.slice(1, 2).unwrap();
1002 let Body::Dictionary { values: cut, .. } = &again.body else {
1003 panic!("a slice of a slice of a dictionary is a dictionary");
1004 };
1005 assert!(Arc::ptr_eq(whole, cut), "the second cut copied the dictionary");
1006 assert_eq!(
1007 again.iter().collect::<Vec<_>>(),
1008 [Value::Varchar("blue".into()), Value::Varchar("red".into())]
1009 );
1010 }
1011
1012 #[test]
1013 fn a_slice_carries_the_nulls_that_were_in_its_range_and_not_the_others() {
1014 let vector =
1015 integers(&[1, 2, 3, 4]).with_validity(Validity::from_run(&[false, true, false, true]));
1016 let piece = vector.slice(1, 2).unwrap();
1017 assert!(piece.validity().is_valid(0));
1018 assert!(!piece.validity().is_valid(1));
1019 assert_eq!(piece.value_at(1), Value::Null);
1020 }
1021
1022 #[test]
1023 fn slicing_a_sequence_moves_its_start_rather_than_writing_the_values_out() {
1024 let vector = Vector::sequence(100, 5, 10);
1025 let piece = vector.slice(3, 4).unwrap();
1026 assert_eq!(piece.form(), Form::Sequence);
1027 assert_eq!(
1028 piece.iter().collect::<Vec<_>>(),
1029 [Value::BigInt(115), Value::BigInt(120), Value::BigInt(125), Value::BigInt(130)]
1030 );
1031 }
1032
1033 #[test]
1034 fn slicing_a_constant_is_a_shorter_constant() {
1035 let vector = Vector::constant(LogicalType::Integer, Value::Integer(9), 8);
1036 let piece = vector.slice(2, 3).unwrap();
1037 assert_eq!(piece.form(), Form::Constant);
1038 assert_eq!(piece.len(), 3);
1039 assert_eq!(piece.value_at(2), Value::Integer(9));
1040 }
1041
1042 #[test]
1043 fn slicing_the_whole_vector_hands_it_back_as_it_was() {
1044 let vector = integers(&[1, 2, 3]);
1045 assert_eq!(
1046 vector.slice(0, 3).unwrap().iter().collect::<Vec<_>>(),
1047 [Value::Integer(1), Value::Integer(2), Value::Integer(3)]
1048 );
1049 }
1050
1051 #[test]
1052 fn a_slice_past_the_end_is_an_error_rather_than_a_short_vector() {
1053 let error = integers(&[1, 2, 3]).slice(2, 2).unwrap_err();
1054 assert!(error.to_string().contains("of a vector of 3"), "{error}");
1055 }
1056
1057 #[test]
1058 fn the_vector_size_is_the_one_the_design_is_built_around() {
1059 assert_eq!(VECTOR_SIZE, 1024);
1062 assert_eq!(VECTOR_SIZE / 64, 16);
1063 }
1064
1065 #[test]
1066 fn a_flat_vector_reads_back_what_was_put_in_it() {
1067 let vector = integers(&[1, 2, 3]);
1068 assert_eq!(vector.form(), Form::Flat);
1069 assert_eq!(vector.len(), 3);
1070 assert_eq!(vector.value_at(1), Value::Integer(2));
1071 assert_eq!(
1072 vector.iter().collect::<Vec<_>>(),
1073 vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]
1074 );
1075 }
1076
1077 #[test]
1078 fn a_vector_built_from_values_reads_the_same_values_back() {
1079 let vector = Vector::from_values(
1080 LogicalType::Varchar,
1081 &[
1082 Value::Varchar("a".to_string()),
1083 Value::Null,
1084 Value::Varchar("a string too long to sit inside a view".to_string()),
1085 ],
1086 )
1087 .expect("strings and a null");
1088 assert_eq!(vector.len(), 3);
1089 assert_eq!(vector.value_at(0), Value::Varchar("a".to_string()));
1090 assert_eq!(vector.value_at(1), Value::Null);
1091 assert_eq!(
1092 vector.value_at(2),
1093 Value::Varchar("a string too long to sit inside a view".to_string())
1094 );
1095 }
1096
1097 #[test]
1100 fn a_null_in_the_middle_does_not_move_the_values_after_it() {
1101 let vector = Vector::from_values(
1102 LogicalType::Integer,
1103 &[Value::Integer(1), Value::Null, Value::Integer(3)],
1104 )
1105 .expect("integers and a null");
1106 assert_eq!(vector.value_at(2), Value::Integer(3));
1107 assert!(vector.validity().has_nulls(3), "the middle one is null");
1108 }
1109
1110 #[test]
1111 fn a_value_the_type_cannot_hold_is_refused() {
1112 let wrong = Vector::from_values(LogicalType::Integer, &[Value::Varchar("x".to_string())]);
1113 assert!(wrong.is_err(), "a string is not an integer");
1114 }
1115
1116 #[test]
1117 fn a_type_that_does_not_match_its_layout_is_refused_at_construction() {
1118 let wrong = Vector::flat(LogicalType::Varchar, Data::Int32(vec![1].into()));
1120 assert!(wrong.is_err());
1121 let right = Vector::flat(LogicalType::Date, Data::Int32(vec![1].into()));
1122 assert!(right.is_ok(), "a date is stored in an i32 and that has to be allowed");
1123 }
1124
1125 #[test]
1126 fn a_constant_vector_costs_one_value_whatever_its_length() {
1127 let vector = Vector::constant(LogicalType::Integer, Value::Integer(7), VECTOR_SIZE);
1128 assert_eq!(vector.form(), Form::Constant);
1129 assert_eq!(vector.len(), VECTOR_SIZE);
1130 assert_eq!(vector.value_at(0), Value::Integer(7));
1131 assert_eq!(vector.value_at(VECTOR_SIZE - 1), Value::Integer(7));
1132 assert_eq!(vector.value_at(VECTOR_SIZE), Value::Null, "past the end is null, not a panic");
1133 }
1134
1135 #[test]
1136 fn a_constant_null_is_all_invalid_without_being_told() {
1137 let vector = Vector::constant(LogicalType::Integer, Value::Null, 8);
1138 assert_eq!(vector.validity(), &Validity::AllInvalid);
1139 assert_eq!(vector.value_at(3), Value::Null);
1140 }
1141
1142 #[test]
1143 fn a_sequence_vector_is_sixteen_bytes_of_row_identifiers() {
1144 let vector = Vector::sequence(100, 1, VECTOR_SIZE);
1145 assert_eq!(vector.form(), Form::Sequence);
1146 assert_eq!(vector.value_at(0), Value::BigInt(100));
1147 assert_eq!(vector.value_at(923), Value::BigInt(1023));
1148 let stepped = Vector::sequence(0, 5, 4);
1149 assert_eq!(
1150 stepped.iter().collect::<Vec<_>>(),
1151 vec![Value::BigInt(0), Value::BigInt(5), Value::BigInt(10), Value::BigInt(15)]
1152 );
1153 }
1154
1155 #[test]
1156 fn a_dictionary_vector_reads_through_its_codes() {
1157 let mut column = StringColumn::new();
1158 column.push("red");
1159 column.push("green");
1160 let values = Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap();
1161 let vector = Vector::dictionary(vec![0, 1, 1, 0], values).unwrap();
1162 assert_eq!(vector.form(), Form::Dictionary);
1163 assert_eq!(vector.logical_type(), &LogicalType::Varchar);
1164 assert_eq!(vector.value_at(2), Value::Varchar("green".into()));
1165 assert_eq!(vector.len(), 4);
1166 }
1167
1168 #[test]
1169 fn a_dictionary_code_past_the_end_is_refused() {
1170 let values = integers(&[1, 2]);
1173 assert!(Vector::dictionary(vec![0, 2], values).is_err());
1174 }
1175
1176 #[test]
1177 fn every_form_flattens_to_the_same_values_it_reads_out() {
1178 let mut column = StringColumn::new();
1182 column.push("alpha");
1183 column.push("beta");
1184 let dictionary = Vector::dictionary(
1185 vec![1, 0, 1],
1186 Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
1187 )
1188 .unwrap();
1189 let cases = [
1190 Vector::constant(LogicalType::Integer, Value::Integer(3), 5),
1191 Vector::sequence(7, -2, 5),
1192 dictionary,
1193 ];
1194 for vector in cases {
1195 let flat = vector.flatten().unwrap();
1196 assert_eq!(flat.form(), Form::Flat);
1197 assert_eq!(flat.len(), vector.len());
1198 for index in 0..vector.len() {
1199 assert_eq!(flat.value_at(index), vector.value_at(index), "at {index}");
1200 }
1201 }
1202 }
1203
1204 #[test]
1205 fn a_null_still_occupies_a_position_after_flattening() {
1206 let vector = Vector::sequence(0, 1, 4).with_validity(Validity::from_iter(4, |i| i != 1));
1210 let flat = vector.flatten().unwrap();
1211 assert_eq!(flat.value_at(0), Value::BigInt(0));
1212 assert_eq!(flat.value_at(1), Value::Null);
1213 assert_eq!(flat.value_at(2), Value::BigInt(2));
1214 assert_eq!(flat.value_at(3), Value::BigInt(3));
1215 }
1216
1217 #[test]
1222 fn a_null_behind_a_dictionary_survives_flattening() {
1223 let values =
1224 Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
1225 let dictionary = Vector::dictionary(vec![1, 0, 1], values).unwrap();
1226 let flat = dictionary.flatten().unwrap();
1227 assert_eq!(flat.value_at(0), Value::Null);
1228 assert_eq!(flat.value_at(1), Value::Integer(3));
1229 assert_eq!(flat.value_at(2), Value::Null);
1230 }
1231
1232 #[test]
1235 fn gathering_reads_what_reading_one_position_at_a_time_reads() {
1236 let mut column = StringColumn::new();
1237 column.push("alpha");
1238 column.push("beta");
1239 column.push("gamma");
1240 let cases = [
1241 integers(&[10, 20, 30, 40]),
1242 integers(&[10, 20, 30, 40]).with_validity(Validity::from_iter(4, |i| i != 2)),
1243 Vector::constant(LogicalType::Integer, Value::Integer(9), 4),
1244 Vector::sequence(100, -7, 4),
1245 Vector::sequence(100, -7, 4).with_validity(Validity::from_iter(4, |i| i % 2 == 0)),
1246 Vector::dictionary(
1247 vec![2, 0, 1, 2],
1248 Vector::flat(LogicalType::Varchar, Data::Varlen(column)).unwrap(),
1249 )
1250 .unwrap(),
1251 Vector::dictionary(
1252 vec![1, 0, 1, 0],
1253 Vector::from_values(LogicalType::Integer, &[Value::Integer(5), Value::Null])
1254 .unwrap(),
1255 )
1256 .unwrap(),
1257 ];
1258 let wanted = [3_u32, 0, 2, 2, 1];
1259 for vector in cases {
1260 let gathered = vector.gather(&wanted).unwrap();
1261 assert_eq!(gathered.len(), wanted.len());
1262 assert_eq!(gathered.logical_type(), vector.logical_type());
1263 for (slot, &index) in wanted.iter().enumerate() {
1264 assert_eq!(
1265 gathered.value_at(slot),
1266 vector.value_at(index as usize),
1267 "slot {slot} of {:?}",
1268 vector.form()
1269 );
1270 }
1271 }
1272 }
1273
1274 #[test]
1278 fn gathering_a_position_that_is_not_there_is_a_null_and_not_a_wrong_value() {
1279 let vector = integers(&[1, 2, 3]);
1280 let gathered = vector.gather(&[2, 9]).unwrap();
1281 assert_eq!(gathered.value_at(0), Value::Integer(3));
1282 assert_eq!(gathered.value_at(1), Value::Null);
1283 }
1284
1285 #[test]
1289 fn gathering_from_a_vector_of_no_values_is_that_many_nulls() {
1290 let vector = Vector::flat(LogicalType::Null, Data::Empty).unwrap();
1291 let gathered = vector.gather(&[0, 1, 2]).unwrap();
1292 assert_eq!(gathered.len(), 3);
1293 assert_eq!(gathered.value_at(0), Value::Null);
1294 assert_eq!(gathered.value_at(2), Value::Null);
1295 }
1296
1297 #[test]
1300 fn gathering_a_constant_stays_a_constant() {
1301 let vector = Vector::constant(LogicalType::Integer, Value::Integer(4), 100);
1302 let gathered = vector.gather(&[7, 7, 99]).unwrap();
1303 assert_eq!(gathered.form(), Form::Constant);
1304 assert_eq!(gathered.len(), 3);
1305 assert_eq!(gathered.value_at(2), Value::Integer(4));
1306 }
1307
1308 #[test]
1313 fn gathering_walks_a_dictionary_over_a_dictionary_to_the_values() {
1314 let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9]))
1315 .unwrap()
1316 .with_validity(Validity::from_iter(3, |index| index != 2));
1317 let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
1318 let gathered = outer.gather(&[0, 1]).unwrap();
1319 assert_eq!(gathered.form(), Form::Flat);
1320 assert_eq!(gathered.value_at(0), Value::Integer(8));
1321 assert_eq!(gathered.value_at(1), Value::Null);
1322 }
1323
1324 #[test]
1329 fn a_dictionary_over_a_dictionary_is_composed_into_one_level() {
1330 let inner = Vector::dictionary(vec![2, 1, 0], integers(&[7, 8, 9])).unwrap();
1331 let outer = Vector::dictionary(vec![1, 2], inner).unwrap();
1332 let (codes, values) = outer.dictionary_parts().unwrap();
1333 assert_eq!(codes, [1, 0]);
1334 assert_eq!(values.form(), Form::Flat);
1335 assert_eq!(outer.value_at(0), Value::Integer(8));
1336 assert_eq!(outer.value_at(1), Value::Integer(7));
1337 }
1338
1339 #[test]
1342 fn stacking_dictionaries_does_not_make_them_deeper() {
1343 let mut vector = integers(&[10, 20, 30, 40]);
1344 for _ in 0..4 {
1345 vector = Vector::dictionary(vec![3, 2, 1, 0], vector).unwrap();
1346 }
1347 let (codes, values) = vector.dictionary_parts().unwrap();
1348 assert_eq!(values.form(), Form::Flat);
1349 assert_eq!(codes, [0, 1, 2, 3]);
1350 assert_eq!(
1351 vector.iter().collect::<Vec<_>>(),
1352 integers(&[10, 20, 30, 40]).iter().collect::<Vec<_>>()
1353 );
1354 }
1355
1356 #[test]
1359 fn composing_a_dictionary_keeps_the_nulls_its_values_hold() {
1360 let values =
1361 Vector::from_values(LogicalType::Integer, &[Value::Integer(3), Value::Null]).unwrap();
1362 let inner = Vector::dictionary(vec![1, 0, 1], values).unwrap();
1363 let outer = Vector::dictionary(vec![0, 1], inner).unwrap();
1364 assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Flat);
1365 assert_eq!(outer.value_at(0), Value::Null);
1366 assert_eq!(outer.value_at(1), Value::Integer(3));
1367 }
1368
1369 #[test]
1373 fn a_dictionary_holding_its_own_nulls_is_not_composed_past() {
1374 let inner = Vector::dictionary(vec![0, 1, 2], integers(&[1, 2, 3]))
1375 .unwrap()
1376 .with_validity(Validity::from_iter(3, |index| index != 1));
1377 let outer = Vector::dictionary(vec![1, 2, 0], inner).unwrap();
1378 assert_eq!(outer.dictionary_parts().unwrap().1.form(), Form::Dictionary);
1379 assert_eq!(outer.value_at(0), Value::Null);
1380 assert_eq!(outer.value_at(1), Value::Integer(3));
1381 assert_eq!(outer.value_at(2), Value::Integer(1));
1382 }
1383
1384 #[test]
1385 fn flattening_a_flat_vector_is_the_same_vector() {
1386 let vector = integers(&[1, 2, 3]);
1387 assert_eq!(vector.flatten().unwrap(), vector);
1388 }
1389
1390 #[test]
1391 fn a_decimal_reads_its_width_and_scale_from_the_type_and_not_the_data() {
1392 let ty = LogicalType::decimal(9, 2).unwrap();
1393 let vector = Vector::flat(ty, Data::Int32(vec![1234].into())).unwrap();
1394 assert_eq!(vector.value_at(0), Value::Decimal { unscaled: 1234, width: 9, scale: 2 });
1395 assert_eq!(vector.value_at(0).to_string(), "12.34");
1396 }
1397
1398 #[test]
1399 fn a_decimal_writes_into_whichever_of_the_four_runs_its_precision_chose() {
1400 for (width, scale, unscaled) in
1403 [(4u8, 1u8, 25i128), (9, 2, 1234), (18, 3, 123_456), (38, 4, 1_234_567)]
1404 {
1405 let ty = LogicalType::decimal(width, scale).unwrap();
1406 let value = Value::Decimal { unscaled, width, scale };
1407 let vector = Vector::from_values(ty, &[value.clone(), Value::Null]).unwrap();
1408 assert_eq!(vector.value_at(0), value, "a decimal of width {width}");
1409 assert_eq!(vector.value_at(1), Value::Null, "a null decimal of width {width}");
1410 }
1411 }
1412
1413 #[test]
1418 fn a_blob_holds_bytes_that_are_not_text() {
1419 let bytes = |raw: &[u8]| Value::Blob(raw.to_vec());
1420 let values = [
1421 bytes(b"a\xffb"),
1422 bytes(b"\x00\x01\x02"),
1423 Value::Null,
1424 bytes(b"\xed\xa0\x80 and long enough to leave the view"),
1425 bytes(b""),
1426 ];
1427 let vector = Vector::from_values(LogicalType::Blob, &values).unwrap();
1428 for (index, value) in values.iter().enumerate() {
1429 assert_eq!(&vector.value_at(index), value, "row {index}");
1430 }
1431 }
1432
1433 #[test]
1434 fn a_decimal_too_wide_for_the_run_its_type_chose_is_an_error_and_not_a_wrong_number() {
1435 let ty = LogicalType::decimal(4, 1).unwrap();
1438 let value = Value::Decimal { unscaled: 1_000_000, width: 4, scale: 1 };
1439 let error = Vector::from_values(ty, &[value]).unwrap_err();
1440 assert!(error.to_string().contains("does not fit"), "{error}");
1441 }
1442
1443 #[test]
1444 fn a_flat_vector_costs_its_values_and_a_constant_costs_one() {
1445 let flat = integers(&[1; 1000]);
1446 assert!(
1447 flat.footprint() >= 4000,
1448 "a thousand i32 are four thousand bytes: {}",
1449 flat.footprint()
1450 );
1451 let constant = Vector::constant(LogicalType::Integer, Value::Integer(1), 1_000_000);
1454 assert!(constant.footprint() < 200, "a constant is one value: {}", constant.footprint());
1455 let sequence = Vector::sequence(0, 1, 1_000_000);
1456 assert!(sequence.footprint() < 200, "a sequence is two numbers: {}", sequence.footprint());
1457 }
1458
1459 #[test]
1460 fn a_string_vector_costs_the_bytes_of_its_long_strings() {
1461 let short =
1462 Vector::from_values(LogicalType::Varchar, &[Value::Varchar("red".into())]).unwrap();
1463 let long = "a string well past the sixteen bytes a view holds inline".to_string();
1464 let spilled =
1465 Vector::from_values(LogicalType::Varchar, &[Value::Varchar(long.clone())]).unwrap();
1466 assert!(
1467 spilled.footprint() >= short.footprint() + long.len(),
1468 "the arena is counted: {} against {}",
1469 spilled.footprint(),
1470 short.footprint()
1471 );
1472 }
1473}