reifydb-sub-flow 0.4.12

Flow subsystem for stream processing and data flows
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
use reifydb_type::{
	fragment::Fragment,
	util::cowvec::CowVec,
	value::{Value, datetime::DateTime, row_number::RowNumber},
};

/// Builder for creating combined columns when joining left and right sides.
/// Encapsulates the logic for merging column names (with conflict resolution)
/// and types from both sides of a join.
pub(crate) struct JoinedColumnsBuilder {
	left_column_count: usize,
	/// Pre-computed aliased names for right columns
	right_column_names: Vec<String>,
}

impl JoinedColumnsBuilder {
	/// Create a new builder from left and right Columns templates.
	/// Handles name conflicts by applying the alias prefix.
	pub(crate) fn new(left: &Columns, right: &Columns, alias: &Option<String>) -> Self {
		let left_column_count = left.columns.len();

		// Collect left column names for conflict detection
		let left_names: Vec<String> = left.columns.iter().map(|c| c.name.as_ref().to_string()).collect();

		// Compute right column names with alias prefix
		let alias_str = alias.as_deref().unwrap_or("other");
		let mut right_column_names = Vec::with_capacity(right.columns.len());
		let mut all_names = left_names.clone();

		for col in right.columns.iter() {
			let col_name = col.name.as_ref();
			let prefixed_name = format!("{}_{}", alias_str, col_name);

			// Check for conflict with existing names
			let mut final_name = prefixed_name.clone();
			if all_names.contains(&final_name) {
				let mut counter = 2;
				loop {
					let candidate = format!("{}_{}", prefixed_name, counter);
					if !all_names.contains(&candidate) {
						final_name = candidate;
						break;
					}
					counter += 1;
				}
			}

			all_names.push(final_name.clone());
			right_column_names.push(final_name);
		}

		Self {
			left_column_count,
			right_column_names,
		}
	}

	/// Join a single left row with a single right row.
	/// Both Columns must contain exactly one row.
	pub(crate) fn join_single(&self, row_number: RowNumber, left: &Columns, right: &Columns) -> Columns {
		debug_assert_eq!(left.row_count(), 1, "left must have exactly 1 row");
		debug_assert_eq!(right.row_count(), 1, "right must have exactly 1 row");

		self.join_one_to_many(&[row_number], left, 0, right)
	}

	/// Join a single left row at left_idx with a single right row at right_idx.
	/// Avoids extraction by accessing values directly at the specified indices.
	pub(crate) fn join_at_indices(
		&self,
		row_number: RowNumber,
		left: &Columns,
		left_idx: usize,
		right: &Columns,
		right_idx: usize,
	) -> Columns {
		let total_columns = self.left_column_count + self.right_column_names.len();
		let mut result_columns = Vec::with_capacity(total_columns);

		// Add left columns - single value from left_idx
		for left_col in left.columns.iter() {
			let mut col_data = ColumnData::with_capacity(left_col.data().get_type(), 1);
			col_data.push_value(left_col.data().get_value(left_idx));
			result_columns.push(Column {
				name: left_col.name.clone(),
				data: col_data,
			});
		}

		// Add right columns - single value from right_idx
		for (right_col, aliased_name) in right.columns.iter().zip(self.right_column_names.iter()) {
			let mut col_data = ColumnData::with_capacity(right_col.data().get_type(), 1);
			col_data.push_value(right_col.data().get_value(right_idx));
			result_columns.push(Column {
				name: Fragment::internal(aliased_name),
				data: col_data,
			});
		}

		Columns {
			row_numbers: CowVec::new(vec![row_number]),
			created_at: CowVec::new(Self::extract_single_timestamp(&left.created_at, left_idx)),
			updated_at: CowVec::new(Self::extract_single_timestamp(&left.updated_at, left_idx)),
			columns: CowVec::new(result_columns),
		}
	}

	/// Join one left row (at left_idx) with all right rows.
	/// Produces right.row_count() output rows.
	pub(crate) fn join_one_to_many(
		&self,
		row_numbers: &[RowNumber],
		left: &Columns,
		left_idx: usize,
		right: &Columns,
	) -> Columns {
		let right_count = right.row_count();
		debug_assert_eq!(row_numbers.len(), right_count, "row_numbers must match right row count");

		let total_columns = self.left_column_count + self.right_column_names.len();
		let mut result_columns = Vec::with_capacity(total_columns);

		// Add left columns - duplicate the left row value for each right row
		for left_col in left.columns.iter() {
			let left_value = left_col.data().get_value(left_idx);
			let mut col_data = ColumnData::with_capacity(left_col.data().get_type(), right_count);
			for _ in 0..right_count {
				col_data.push_value(left_value.clone());
			}
			result_columns.push(Column {
				name: left_col.name.clone(),
				data: col_data,
			});
		}

		// Add right columns - copy all values from right
		for (right_col, aliased_name) in right.columns.iter().zip(self.right_column_names.iter()) {
			let mut col_data = ColumnData::with_capacity(right_col.data().get_type(), right_count);
			for row_idx in 0..right_count {
				col_data.push_value(right_col.data().get_value(row_idx));
			}
			result_columns.push(Column {
				name: Fragment::internal(aliased_name),
				data: col_data,
			});
		}

		Columns {
			row_numbers: CowVec::new(row_numbers.to_vec()),
			created_at: CowVec::new(Self::duplicate_timestamp(&left.created_at, left_idx, right_count)),
			updated_at: CowVec::new(Self::duplicate_timestamp(&left.updated_at, left_idx, right_count)),
			columns: CowVec::new(result_columns),
		}
	}

	/// Join all left rows with one right row (at right_idx).
	/// Produces left.row_count() output rows.
	pub(crate) fn join_many_to_one(
		&self,
		row_numbers: &[RowNumber],
		left: &Columns,
		right: &Columns,
		right_idx: usize,
	) -> Columns {
		let left_count = left.row_count();
		debug_assert_eq!(row_numbers.len(), left_count, "row_numbers must match left row count");

		let total_columns = self.left_column_count + self.right_column_names.len();
		let mut result_columns = Vec::with_capacity(total_columns);

		// Add left columns - copy all values from left
		for left_col in left.columns.iter() {
			let mut col_data = ColumnData::with_capacity(left_col.data().get_type(), left_count);
			for row_idx in 0..left_count {
				col_data.push_value(left_col.data().get_value(row_idx));
			}
			result_columns.push(Column {
				name: left_col.name.clone(),
				data: col_data,
			});
		}

		// Add right columns - duplicate the right row value for each left row
		for (right_col, aliased_name) in right.columns.iter().zip(self.right_column_names.iter()) {
			let right_value = right_col.data().get_value(right_idx);
			let mut col_data = ColumnData::with_capacity(right_col.data().get_type(), left_count);
			for _ in 0..left_count {
				col_data.push_value(right_value.clone());
			}
			result_columns.push(Column {
				name: Fragment::internal(aliased_name),
				data: col_data,
			});
		}

		Columns {
			row_numbers: CowVec::new(row_numbers.to_vec()),
			created_at: left.created_at.clone(),
			updated_at: left.updated_at.clone(),
			columns: CowVec::new(result_columns),
		}
	}

	/// Join left rows (at specified indices) with right rows (at specified indices) (cartesian product).
	/// Produces left_indices.len() * right_indices.len() output rows.
	pub(crate) fn join_cartesian(
		&self,
		row_numbers: &[RowNumber],
		left: &Columns,
		left_indices: &[usize],
		right: &Columns,
		right_indices: &[usize],
	) -> Columns {
		let left_count = left_indices.len();
		let right_count = right_indices.len();
		let result_count = left_count * right_count;
		debug_assert_eq!(row_numbers.len(), result_count, "row_numbers must match cartesian product size");

		let total_columns = self.left_column_count + self.right_column_names.len();
		let mut result_columns = Vec::with_capacity(total_columns);

		// Add left columns - for each left index, duplicate value for all right rows
		for left_col in left.columns.iter() {
			let mut col_data = ColumnData::with_capacity(left_col.data().get_type(), result_count);
			for &left_idx in left_indices {
				let left_value = left_col.data().get_value(left_idx);
				for _ in 0..right_count {
					col_data.push_value(left_value.clone());
				}
			}
			result_columns.push(Column {
				name: left_col.name.clone(),
				data: col_data,
			});
		}

		// Add right columns - repeat right rows at specified indices for each left row
		for (right_col, aliased_name) in right.columns.iter().zip(self.right_column_names.iter()) {
			let mut col_data = ColumnData::with_capacity(right_col.data().get_type(), result_count);
			for _ in 0..left_count {
				for &right_idx in right_indices {
					col_data.push_value(right_col.data().get_value(right_idx));
				}
			}
			result_columns.push(Column {
				name: Fragment::internal(aliased_name),
				data: col_data,
			});
		}

		Columns {
			row_numbers: CowVec::new(row_numbers.to_vec()),
			created_at: CowVec::new(Self::expand_timestamps_cartesian(
				&left.created_at,
				left_indices,
				right_count,
			)),
			updated_at: CowVec::new(Self::expand_timestamps_cartesian(
				&left.updated_at,
				left_indices,
				right_count,
			)),
			columns: CowVec::new(result_columns),
		}
	}

	/// Create unmatched left columns (left join with no right match).
	/// Right side columns are filled with Undefined values.
	pub(crate) fn unmatched_left(
		&self,
		row_number: RowNumber,
		left: &Columns,
		left_idx: usize,
		right_shape: &Columns,
	) -> Columns {
		let total_columns = self.left_column_count + self.right_column_names.len();
		let mut result_columns = Vec::with_capacity(total_columns);

		// Add left columns - single value from left_idx
		for left_col in left.columns.iter() {
			let mut col_data = ColumnData::with_capacity(left_col.data().get_type(), 1);
			col_data.push_value(left_col.data().get_value(left_idx));
			result_columns.push(Column {
				name: left_col.name.clone(),
				data: col_data,
			});
		}

		// Add right columns with Undefined values
		for (right_col, aliased_name) in right_shape.columns.iter().zip(self.right_column_names.iter()) {
			let mut col_data = ColumnData::with_capacity(right_col.data().get_type(), 1);
			col_data.push_value(Value::none());
			result_columns.push(Column {
				name: Fragment::internal(aliased_name),
				data: col_data,
			});
		}

		Columns {
			row_numbers: CowVec::new(vec![row_number]),
			created_at: CowVec::new(Self::extract_single_timestamp(&left.created_at, left_idx)),
			updated_at: CowVec::new(Self::extract_single_timestamp(&left.updated_at, left_idx)),
			columns: CowVec::new(result_columns),
		}
	}

	/// Create unmatched left columns for multiple left rows.
	/// Right side columns are filled with Undefined values.
	pub(crate) fn unmatched_left_batch(
		&self,
		row_numbers: &[RowNumber],
		left: &Columns,
		left_indices: &[usize],
		right_shape: &Columns,
	) -> Columns {
		let count = left_indices.len();
		debug_assert_eq!(row_numbers.len(), count, "row_numbers must match indices count");

		let total_columns = self.left_column_count + self.right_column_names.len();
		let mut result_columns = Vec::with_capacity(total_columns);

		// Add left columns - values from specified indices
		for left_col in left.columns.iter() {
			let mut col_data = ColumnData::with_capacity(left_col.data().get_type(), count);
			for &idx in left_indices {
				col_data.push_value(left_col.data().get_value(idx));
			}
			result_columns.push(Column {
				name: left_col.name.clone(),
				data: col_data,
			});
		}

		// Add right columns with Undefined values
		for (right_col, aliased_name) in right_shape.columns.iter().zip(self.right_column_names.iter()) {
			let mut col_data = ColumnData::with_capacity(right_col.data().get_type(), count);
			for _ in 0..count {
				col_data.push_value(Value::none());
			}
			result_columns.push(Column {
				name: Fragment::internal(aliased_name),
				data: col_data,
			});
		}

		Columns {
			row_numbers: CowVec::new(row_numbers.to_vec()),
			created_at: CowVec::new(Self::extract_timestamps_at_indices(&left.created_at, left_indices)),
			updated_at: CowVec::new(Self::extract_timestamps_at_indices(&left.updated_at, left_indices)),
			columns: CowVec::new(result_columns),
		}
	}

	/// Get the pre-computed aliased names for right columns.
	pub(crate) fn right_column_names(&self) -> &[String] {
		&self.right_column_names
	}

	fn extract_single_timestamp(ts: &CowVec<DateTime>, idx: usize) -> Vec<DateTime> {
		if ts.is_empty() {
			Vec::new()
		} else {
			vec![ts[idx]]
		}
	}

	fn duplicate_timestamp(ts: &CowVec<DateTime>, idx: usize, count: usize) -> Vec<DateTime> {
		if ts.is_empty() {
			Vec::new()
		} else {
			vec![ts[idx]; count]
		}
	}

	fn expand_timestamps_cartesian(
		ts: &CowVec<DateTime>,
		left_indices: &[usize],
		right_count: usize,
	) -> Vec<DateTime> {
		if ts.is_empty() {
			return Vec::new();
		}
		let mut result = Vec::with_capacity(left_indices.len() * right_count);
		for &left_idx in left_indices {
			for _ in 0..right_count {
				result.push(ts[left_idx]);
			}
		}
		result
	}

	fn extract_timestamps_at_indices(ts: &CowVec<DateTime>, indices: &[usize]) -> Vec<DateTime> {
		if ts.is_empty() {
			Vec::new()
		} else {
			indices.iter().map(|&i| ts[i]).collect()
		}
	}
}