Skip to main content

reifydb_core/value/column/
columns.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use std::{
5	collections::HashMap,
6	hash::Hash,
7	mem,
8	ops::{Deref, Index, IndexMut},
9};
10
11use indexmap::IndexMap;
12use reifydb_type::{
13	Result,
14	fragment::Fragment,
15	util::cowvec::CowVec,
16	value::{Value, constraint::Constraint, datetime::DateTime, row_number::RowNumber, r#type::Type},
17};
18
19use crate::{
20	encoded::shape::{RowShape, RowShapeField},
21	interface::{
22		catalog::{table::Table, view::View},
23		resolved::{ResolvedRingBuffer, ResolvedTable, ResolvedView},
24	},
25	row::Row,
26	value::column::{Column, ColumnData, headers::ColumnHeaders},
27};
28
29#[derive(Debug, Clone)]
30pub struct Columns {
31	pub row_numbers: CowVec<RowNumber>,
32	pub created_at: CowVec<DateTime>,
33	pub updated_at: CowVec<DateTime>,
34	pub columns: CowVec<Column>,
35}
36
37impl Deref for Columns {
38	type Target = [Column];
39
40	fn deref(&self) -> &Self::Target {
41		self.columns.deref()
42	}
43}
44
45impl Index<usize> for Columns {
46	type Output = Column;
47
48	fn index(&self, index: usize) -> &Self::Output {
49		self.columns.index(index)
50	}
51}
52
53impl IndexMut<usize> for Columns {
54	fn index_mut(&mut self, index: usize) -> &mut Self::Output {
55		&mut self.columns.make_mut()[index]
56	}
57}
58
59impl Columns {
60	/// Create a 1-column, 1-row Columns from a single Value.
61	/// Used to store scalar values inside `Variable::Scalar(Columns)`.
62	pub fn scalar(value: Value) -> Self {
63		let data = match value {
64			Value::None {
65				..
66			} => ColumnData::none_typed(Type::Boolean, 1),
67			Value::Boolean(v) => ColumnData::bool([v]),
68			Value::Float4(v) => ColumnData::float4([v.into()]),
69			Value::Float8(v) => ColumnData::float8([v.into()]),
70			Value::Int1(v) => ColumnData::int1([v]),
71			Value::Int2(v) => ColumnData::int2([v]),
72			Value::Int4(v) => ColumnData::int4([v]),
73			Value::Int8(v) => ColumnData::int8([v]),
74			Value::Int16(v) => ColumnData::int16([v]),
75			Value::Utf8(v) => ColumnData::utf8([v]),
76			Value::Uint1(v) => ColumnData::uint1([v]),
77			Value::Uint2(v) => ColumnData::uint2([v]),
78			Value::Uint4(v) => ColumnData::uint4([v]),
79			Value::Uint8(v) => ColumnData::uint8([v]),
80			Value::Uint16(v) => ColumnData::uint16([v]),
81			Value::Date(v) => ColumnData::date([v]),
82			Value::DateTime(v) => ColumnData::datetime([v]),
83			Value::Time(v) => ColumnData::time([v]),
84			Value::Duration(v) => ColumnData::duration([v]),
85			Value::IdentityId(v) => ColumnData::identity_id([v]),
86			Value::Uuid4(v) => ColumnData::uuid4([v]),
87			Value::Uuid7(v) => ColumnData::uuid7([v]),
88			Value::Blob(v) => ColumnData::blob([v]),
89			Value::Int(v) => ColumnData::int(vec![v]),
90			Value::Uint(v) => ColumnData::uint(vec![v]),
91			Value::Decimal(v) => ColumnData::decimal(vec![v]),
92			Value::DictionaryId(v) => ColumnData::dictionary_id(vec![v]),
93			Value::Any(v) => ColumnData::any(vec![v]),
94			Value::Type(v) => ColumnData::any(vec![Box::new(Value::Type(v))]),
95			Value::List(v) => ColumnData::any(vec![Box::new(Value::List(v))]),
96			Value::Record(v) => ColumnData::any(vec![Box::new(Value::Record(v))]),
97			Value::Tuple(v) => ColumnData::any(vec![Box::new(Value::Tuple(v))]),
98		};
99		let column = Column {
100			name: Fragment::internal("value"),
101			data,
102		};
103		Self {
104			row_numbers: CowVec::new(Vec::new()),
105			created_at: CowVec::new(Vec::new()),
106			updated_at: CowVec::new(Vec::new()),
107			columns: CowVec::new(vec![column]),
108		}
109	}
110
111	/// Extract the single value from a 1-column, 1-row Columns.
112	/// Panics if the Columns does not have exactly 1 column and 1 row.
113	pub fn scalar_value(&self) -> Value {
114		debug_assert_eq!(self.len(), 1, "scalar_value() requires exactly 1 column, got {}", self.len());
115		debug_assert_eq!(
116			self.row_count(),
117			1,
118			"scalar_value() requires exactly 1 row, got {}",
119			self.row_count()
120		);
121		self.columns[0].data().get_value(0)
122	}
123
124	pub fn new(columns: Vec<Column>) -> Self {
125		let n = columns.first().map_or(0, |c| c.data().len());
126		assert!(columns.iter().all(|c| c.data().len() == n));
127
128		Self {
129			row_numbers: CowVec::new(Vec::new()),
130			created_at: CowVec::new(Vec::new()),
131			updated_at: CowVec::new(Vec::new()),
132			columns: CowVec::new(columns),
133		}
134	}
135
136	pub fn with_system_columns(
137		columns: Vec<Column>,
138		row_numbers: Vec<RowNumber>,
139		created_at: Vec<DateTime>,
140		updated_at: Vec<DateTime>,
141	) -> Self {
142		let n = columns.first().map_or(0, |c| c.data().len());
143		assert!(columns.iter().all(|c| c.data().len() == n));
144		assert_eq!(row_numbers.len(), n, "row_numbers length must match column data length");
145		assert_eq!(created_at.len(), n, "created_at length must match column data length");
146		assert_eq!(updated_at.len(), n, "updated_at length must match column data length");
147
148		Self {
149			row_numbers: CowVec::new(row_numbers),
150			created_at: CowVec::new(created_at),
151			updated_at: CowVec::new(updated_at),
152			columns: CowVec::new(columns),
153		}
154	}
155
156	pub fn single_row<'b>(rows: impl IntoIterator<Item = (&'b str, Value)>) -> Columns {
157		let mut columns = Vec::new();
158		let mut index = HashMap::new();
159
160		for (idx, (name, value)) in rows.into_iter().enumerate() {
161			let data = match value {
162				Value::None {
163					..
164				} => ColumnData::none_typed(Type::Boolean, 1),
165				Value::Boolean(v) => ColumnData::bool([v]),
166				Value::Float4(v) => ColumnData::float4([v.into()]),
167				Value::Float8(v) => ColumnData::float8([v.into()]),
168				Value::Int1(v) => ColumnData::int1([v]),
169				Value::Int2(v) => ColumnData::int2([v]),
170				Value::Int4(v) => ColumnData::int4([v]),
171				Value::Int8(v) => ColumnData::int8([v]),
172				Value::Int16(v) => ColumnData::int16([v]),
173				Value::Utf8(v) => ColumnData::utf8([v.clone()]),
174				Value::Uint1(v) => ColumnData::uint1([v]),
175				Value::Uint2(v) => ColumnData::uint2([v]),
176				Value::Uint4(v) => ColumnData::uint4([v]),
177				Value::Uint8(v) => ColumnData::uint8([v]),
178				Value::Uint16(v) => ColumnData::uint16([v]),
179				Value::Date(v) => ColumnData::date([v]),
180				Value::DateTime(v) => ColumnData::datetime([v]),
181				Value::Time(v) => ColumnData::time([v]),
182				Value::Duration(v) => ColumnData::duration([v]),
183				Value::IdentityId(v) => ColumnData::identity_id([v]),
184				Value::Uuid4(v) => ColumnData::uuid4([v]),
185				Value::Uuid7(v) => ColumnData::uuid7([v]),
186				Value::Blob(v) => ColumnData::blob([v.clone()]),
187				Value::Int(v) => ColumnData::int(vec![v]),
188				Value::Uint(v) => ColumnData::uint(vec![v]),
189				Value::Decimal(v) => ColumnData::decimal(vec![v]),
190				Value::DictionaryId(v) => ColumnData::dictionary_id(vec![v]),
191				Value::Type(t) => ColumnData::any(vec![Box::new(Value::Type(t))]),
192				Value::Any(v) => ColumnData::any(vec![v]),
193				Value::List(v) => ColumnData::any(vec![Box::new(Value::List(v))]),
194				Value::Record(v) => ColumnData::any(vec![Box::new(Value::Record(v))]),
195				Value::Tuple(v) => ColumnData::any(vec![Box::new(Value::Tuple(v))]),
196			};
197
198			let column = Column {
199				name: Fragment::internal(name.to_string()),
200				data,
201			};
202			index.insert(name, idx);
203			columns.push(column);
204		}
205
206		Self {
207			row_numbers: CowVec::new(Vec::new()),
208			created_at: CowVec::new(Vec::new()),
209			updated_at: CowVec::new(Vec::new()),
210			columns: CowVec::new(columns),
211		}
212	}
213
214	pub fn apply_headers(&mut self, headers: &ColumnHeaders) {
215		// Apply the column names from headers to this Columns instance
216		for (i, name) in headers.columns.iter().enumerate() {
217			if i < self.len() {
218				let column = &mut self[i];
219				let data = mem::replace(column.data_mut(), ColumnData::none_typed(Type::Boolean, 0));
220
221				*column = Column {
222					name: name.clone(),
223					data,
224				};
225			}
226		}
227	}
228}
229
230impl Columns {
231	/// Get the row number (for single-row Columns). Panics if Columns has 0 or multiple rows.
232	pub fn number(&self) -> RowNumber {
233		assert_eq!(self.row_count(), 1, "number() requires exactly 1 row, got {}", self.row_count());
234		if self.row_numbers.is_empty() {
235			RowNumber(0)
236		} else {
237			self.row_numbers[0]
238		}
239	}
240
241	pub fn shape(&self) -> (usize, usize) {
242		let row_count = if !self.row_numbers.is_empty() {
243			self.row_numbers.len()
244		} else {
245			self.first().map(|c| c.data().len()).unwrap_or(0)
246		};
247		(row_count, self.len())
248	}
249
250	pub fn is_empty(&self) -> bool {
251		self.shape().0 == 0
252	}
253
254	pub fn row(&self, i: usize) -> Vec<Value> {
255		self.iter().map(|c| c.data().get_value(i)).collect()
256	}
257
258	pub fn column(&self, name: &str) -> Option<&Column> {
259		self.iter().find(|col| col.name().text() == name)
260	}
261
262	pub fn row_count(&self) -> usize {
263		if !self.row_numbers.is_empty() {
264			self.row_numbers.len()
265		} else {
266			self.first().map_or(0, |col| col.data().len())
267		}
268	}
269
270	pub fn get_row(&self, index: usize) -> Vec<Value> {
271		self.iter().map(|col| col.data().get_value(index)).collect()
272	}
273}
274
275impl IntoIterator for Columns {
276	type Item = Column;
277	type IntoIter = std::vec::IntoIter<Column>;
278
279	fn into_iter(self) -> Self::IntoIter {
280		self.columns.into_iter()
281	}
282}
283
284impl Column {
285	pub fn extend(&mut self, other: Column) -> Result<()> {
286		self.data_mut().extend(other.data().clone())
287	}
288}
289
290impl Columns {
291	pub fn from_rows(names: &[&str], result_rows: &[Vec<Value>]) -> Self {
292		let column_count = names.len();
293
294		let mut columns: Vec<Column> = names
295			.iter()
296			.map(|name| Column {
297				name: Fragment::internal(name.to_string()),
298				data: ColumnData::none_typed(Type::Boolean, 0),
299			})
300			.collect();
301
302		for row in result_rows {
303			assert_eq!(row.len(), column_count, "row length does not match column count");
304			for (i, value) in row.iter().enumerate() {
305				columns[i].data_mut().push_value(value.clone());
306			}
307		}
308
309		Columns::new(columns)
310	}
311
312	pub fn from_rows_with_row_numbers(
313		names: &[&str],
314		result_rows: &[Vec<Value>],
315		row_numbers: Vec<RowNumber>,
316	) -> Self {
317		let column_count = names.len();
318
319		let mut columns: Vec<Column> = names
320			.iter()
321			.map(|name| Column {
322				name: Fragment::internal(name.to_string()),
323				data: ColumnData::none_typed(Type::Boolean, 0),
324			})
325			.collect();
326
327		for row in result_rows {
328			assert_eq!(row.len(), column_count, "row length does not match column count");
329			for (i, value) in row.iter().enumerate() {
330				columns[i].data_mut().push_value(value.clone());
331			}
332		}
333
334		let n = row_numbers.len();
335		let now = DateTime::default();
336		Columns::with_system_columns(columns, row_numbers, vec![now; n], vec![now; n])
337	}
338}
339
340impl Columns {
341	pub fn empty() -> Self {
342		Self {
343			row_numbers: CowVec::new(vec![]),
344			created_at: CowVec::new(vec![]),
345			updated_at: CowVec::new(vec![]),
346			columns: CowVec::new(vec![]),
347		}
348	}
349
350	pub fn from_resolved_table(table: &ResolvedTable) -> Self {
351		Self::from_table(table.def())
352	}
353
354	/// Create empty Columns (0 rows) with shape from a Table
355	pub fn from_table(table: &Table) -> Self {
356		let columns: Vec<Column> = table
357			.columns
358			.iter()
359			.map(|col| Column {
360				name: Fragment::internal(&col.name),
361				data: ColumnData::with_capacity(col.constraint.get_type(), 0),
362			})
363			.collect();
364
365		Self {
366			row_numbers: CowVec::new(Vec::new()),
367			created_at: CowVec::new(Vec::new()),
368			updated_at: CowVec::new(Vec::new()),
369			columns: CowVec::new(columns),
370		}
371	}
372
373	/// Create empty Columns (0 rows) with shape from a View
374	pub fn from_view(view: &View) -> Self {
375		let columns: Vec<Column> = view
376			.columns()
377			.iter()
378			.map(|col| Column {
379				name: Fragment::internal(&col.name),
380				data: ColumnData::with_capacity(col.constraint.get_type(), 0),
381			})
382			.collect();
383
384		Self {
385			row_numbers: CowVec::new(Vec::new()),
386			created_at: CowVec::new(Vec::new()),
387			updated_at: CowVec::new(Vec::new()),
388			columns: CowVec::new(columns),
389		}
390	}
391
392	pub fn from_ringbuffer(ringbuffer: &ResolvedRingBuffer) -> Self {
393		let _source = ringbuffer.clone();
394
395		let columns: Vec<Column> = ringbuffer
396			.columns()
397			.iter()
398			.map(|col| {
399				let column_ident = Fragment::internal(&col.name);
400				Column {
401					name: column_ident,
402					data: ColumnData::with_capacity(col.constraint.get_type(), 0),
403				}
404			})
405			.collect();
406
407		Self {
408			row_numbers: CowVec::new(Vec::new()),
409			created_at: CowVec::new(Vec::new()),
410			updated_at: CowVec::new(Vec::new()),
411			columns: CowVec::new(columns),
412		}
413	}
414
415	pub fn from_resolved_view(view: &ResolvedView) -> Self {
416		Self::from_view(view.def())
417	}
418}
419
420impl Columns {
421	/// Extract a subset of rows by indices, returning a new Columns
422	pub fn extract_by_indices(&self, indices: &[usize]) -> Columns {
423		if indices.is_empty() {
424			return Columns::empty();
425		}
426
427		let new_columns: Vec<Column> = self
428			.columns
429			.iter()
430			.map(|col| {
431				let mut new_data = ColumnData::with_capacity(col.data().get_type(), indices.len());
432				for &idx in indices {
433					new_data.push_value(col.data().get_value(idx));
434				}
435				Column {
436					name: col.name.clone(),
437					data: new_data,
438				}
439			})
440			.collect();
441
442		let new_row_numbers: Vec<RowNumber> = if self.row_numbers.is_empty() {
443			Vec::new()
444		} else {
445			indices.iter().map(|&i| self.row_numbers[i]).collect()
446		};
447		let new_created_at: Vec<DateTime> = if self.created_at.is_empty() {
448			Vec::new()
449		} else {
450			indices.iter().map(|&i| self.created_at[i]).collect()
451		};
452		let new_updated_at: Vec<DateTime> = if self.updated_at.is_empty() {
453			Vec::new()
454		} else {
455			indices.iter().map(|&i| self.updated_at[i]).collect()
456		};
457		Columns {
458			row_numbers: CowVec::new(new_row_numbers),
459			created_at: CowVec::new(new_created_at),
460			updated_at: CowVec::new(new_updated_at),
461			columns: CowVec::new(new_columns),
462		}
463	}
464
465	/// Extract a single row by index, returning a new Columns with 1 row
466	pub fn extract_row(&self, index: usize) -> Columns {
467		self.extract_by_indices(&[index])
468	}
469
470	/// Project to a subset of columns by name, preserving the order of the provided names.
471	/// Columns not found in self are silently skipped.
472	pub fn project_by_names(&self, names: &[String]) -> Columns {
473		let new_columns: Vec<Column> = names
474			.iter()
475			.filter_map(|name| self.columns.iter().find(|c| c.name().text() == name.as_str()).cloned())
476			.collect();
477
478		if new_columns.is_empty() {
479			return Columns::empty();
480		}
481
482		Columns {
483			row_numbers: self.row_numbers.clone(),
484			created_at: self.created_at.clone(),
485			updated_at: self.updated_at.clone(),
486			columns: CowVec::new(new_columns),
487		}
488	}
489
490	/// Partition Columns into groups based on keys (one key per row).
491	/// Returns an IndexMap preserving insertion order of first occurrence.
492	pub fn partition_by_keys<K: Hash + Eq + Clone>(&self, keys: &[K]) -> IndexMap<K, Columns> {
493		assert_eq!(keys.len(), self.row_count(), "keys length must match row count");
494
495		// Group indices by key
496		let mut key_to_indices: IndexMap<K, Vec<usize>> = IndexMap::new();
497		for (idx, key) in keys.iter().enumerate() {
498			key_to_indices.entry(key.clone()).or_default().push(idx);
499		}
500
501		// Convert to Columns
502		key_to_indices.into_iter().map(|(key, indices)| (key, self.extract_by_indices(&indices))).collect()
503	}
504
505	/// Create Columns from a Row by decoding its encoded values
506	pub fn from_row(row: &Row) -> Self {
507		let mut columns = Vec::new();
508
509		for (idx, field) in row.shape.fields().iter().enumerate() {
510			let value = row.shape.get_value(&row.encoded, idx);
511
512			// Use the field type for the column data, handling undefined values
513			let column_type = if matches!(value, Value::None { .. }) {
514				field.constraint.get_type()
515			} else {
516				value.get_type()
517			};
518
519			let mut data = if column_type.is_option() {
520				ColumnData::none_typed(column_type.clone(), 0)
521			} else {
522				ColumnData::with_capacity(column_type.clone(), 1)
523			};
524			data.push_value(value);
525
526			if column_type == Type::DictionaryId
527				&& let ColumnData::DictionaryId(container) = &mut data
528				&& let Some(Constraint::Dictionary(dict_id, _)) = field.constraint.constraint()
529			{
530				container.set_dictionary_id(*dict_id);
531			}
532
533			let name = row.shape.get_field_name(idx).expect("RowShape missing name for field");
534
535			columns.push(Column {
536				name: Fragment::internal(name),
537				data,
538			});
539		}
540
541		Self {
542			row_numbers: CowVec::new(vec![row.number]),
543			created_at: CowVec::new(vec![DateTime::from_nanos(row.encoded.created_at_nanos())]),
544			updated_at: CowVec::new(vec![DateTime::from_nanos(row.encoded.updated_at_nanos())]),
545			columns: CowVec::new(columns),
546		}
547	}
548
549	/// Convert Columns back to a Row (assumes single row)
550	/// Panics if Columns contains more than 1 row
551	pub fn to_single_row(&self) -> Row {
552		assert_eq!(self.row_count(), 1, "to_row() requires exactly 1 row, got {}", self.row_count());
553		assert_eq!(
554			self.row_numbers.len(),
555			1,
556			"to_row() requires exactly 1 row number, got {}",
557			self.row_numbers.len()
558		);
559
560		let row_number = *self.row_numbers.first().unwrap();
561
562		// Build shape fields for the layout
563		let fields: Vec<RowShapeField> = self
564			.columns
565			.iter()
566			.map(|col| RowShapeField::unconstrained(col.name().text().to_string(), col.data().get_type()))
567			.collect();
568
569		let layout = RowShape::new(fields);
570		let mut encoded = layout.allocate();
571
572		// Get values and set them
573		let values: Vec<Value> = self.columns.iter().map(|col| col.data().get_value(0)).collect();
574		layout.set_values(&mut encoded, &values);
575
576		Row {
577			number: row_number,
578			encoded,
579			shape: layout,
580		}
581	}
582}
583
584#[cfg(test)]
585pub mod tests {
586	use reifydb_type::value::{date::Date, datetime::DateTime, duration::Duration, time::Time};
587
588	use super::*;
589
590	#[test]
591	fn test_single_row_temporal_types() {
592		let date = Date::from_ymd(2025, 1, 15).unwrap();
593		let datetime = DateTime::from_timestamp(1642694400).unwrap();
594		let time = Time::from_hms(14, 30, 45).unwrap();
595		let duration = Duration::from_days(30).unwrap();
596
597		let columns = Columns::single_row([
598			("date_col", Value::Date(date.clone())),
599			("datetime_col", Value::DateTime(datetime.clone())),
600			("time_col", Value::Time(time.clone())),
601			("interval_col", Value::Duration(duration.clone())),
602		]);
603
604		assert_eq!(columns.len(), 4);
605		assert_eq!(columns.shape(), (1, 4));
606
607		// Check that the values are correctly stored
608		assert_eq!(columns.column("date_col").unwrap().data().get_value(0), Value::Date(date));
609		assert_eq!(columns.column("datetime_col").unwrap().data().get_value(0), Value::DateTime(datetime));
610		assert_eq!(columns.column("time_col").unwrap().data().get_value(0), Value::Time(time));
611		assert_eq!(columns.column("interval_col").unwrap().data().get_value(0), Value::Duration(duration));
612	}
613
614	#[test]
615	fn test_single_row_mixed_types() {
616		let date = Date::from_ymd(2025, 7, 15).unwrap();
617		let time = Time::from_hms(9, 15, 30).unwrap();
618
619		let columns = Columns::single_row([
620			("bool_col", Value::Boolean(true)),
621			("int_col", Value::Int4(42)),
622			("str_col", Value::Utf8("hello".to_string())),
623			("date_col", Value::Date(date.clone())),
624			("time_col", Value::Time(time.clone())),
625			("none_col", Value::none()),
626		]);
627
628		assert_eq!(columns.len(), 6);
629		assert_eq!(columns.shape(), (1, 6));
630
631		// Check all values are correctly stored
632		assert_eq!(columns.column("bool_col").unwrap().data().get_value(0), Value::Boolean(true));
633		assert_eq!(columns.column("int_col").unwrap().data().get_value(0), Value::Int4(42));
634		assert_eq!(columns.column("str_col").unwrap().data().get_value(0), Value::Utf8("hello".to_string()));
635		assert_eq!(columns.column("date_col").unwrap().data().get_value(0), Value::Date(date));
636		assert_eq!(columns.column("time_col").unwrap().data().get_value(0), Value::Time(time));
637		assert_eq!(columns.column("none_col").unwrap().data().get_value(0), Value::none());
638	}
639
640	#[test]
641	fn test_single_row_normal_column_names_work() {
642		let columns = Columns::single_row([("normal_column", Value::Int4(42))]);
643		assert_eq!(columns.len(), 1);
644		assert_eq!(columns.column("normal_column").unwrap().data().get_value(0), Value::Int4(42));
645	}
646}