reifydb-engine 0.4.12

Query execution and processing engine for ReifyDB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use std::{any, marker::PhantomData};

use any::TypeId;
use reifydb_catalog::{
	catalog::Catalog,
	error::{CatalogError, CatalogObjectKind},
};
use reifydb_core::{
	encoded::shape::RowShape,
	error::CoreError,
	interface::catalog::id::IndexId,
	internal_error,
	key::{EncodableKey, index_entry::IndexEntryKey},
};
use reifydb_runtime::context::clock::Clock;
use reifydb_transaction::transaction::{Transaction, command::CommandTransaction};
use reifydb_type::{
	fragment::Fragment,
	value::{Value, identity::IdentityId, row_number::RowNumber, r#type::Type},
};

use super::{
	BulkInsertResult, RingBufferInsertResult, TableInsertResult,
	validation::{
		reorder_rows_trusted, reorder_rows_trusted_rb, validate_and_coerce_rows, validate_and_coerce_rows_rb,
	},
};
use crate::{
	Result,
	bulk_insert::primitive::{
		ringbuffer::{PendingRingBufferInsert, RingBufferInsertBuilder},
		table::{PendingTableInsert, TableInsertBuilder},
	},
	engine::StandardEngine,
	transaction::operation::{
		dictionary::DictionaryOperations, ringbuffer::RingBufferOperations, table::TableOperations,
	},
	vm::instruction::dml::{
		primary_key,
		shape::{get_or_create_ringbuffer_shape, get_or_create_table_shape},
	},
};

/// Marker trait for validation mode (sealed)
pub trait ValidationMode: sealed::Sealed + 'static {}

/// Validated mode - performs full type checking and constraint validation
pub struct Validated;
impl ValidationMode for Validated {}

/// Trusted mode - skips validation for pre-validated internal data
pub struct Trusted;
impl ValidationMode for Trusted {}

pub mod sealed {

	use super::{Trusted, Validated};
	pub trait Sealed {}
	impl Sealed for Validated {}
	impl Sealed for Trusted {}
}

/// Main builder for bulk insert operations.
///
/// Type parameter `V` tracks the validation mode at compile time.
pub struct BulkInsertBuilder<'e, V: ValidationMode = Validated> {
	engine: &'e StandardEngine,
	identity: IdentityId,
	pending_tables: Vec<PendingTableInsert>,
	pending_ringbuffers: Vec<PendingRingBufferInsert>,
	_validation: PhantomData<V>,
}

impl<'e> BulkInsertBuilder<'e, Validated> {
	/// Create a new bulk insert builder with full validation enabled.
	pub(crate) fn new(engine: &'e StandardEngine, identity: IdentityId) -> Self {
		Self {
			engine,
			identity,
			pending_tables: Vec::new(),
			pending_ringbuffers: Vec::new(),
			_validation: PhantomData,
		}
	}
}

impl<'e> BulkInsertBuilder<'e, Trusted> {
	/// Create a new bulk insert builder with validation disabled (trusted mode).
	pub(crate) fn new_trusted(engine: &'e StandardEngine, identity: IdentityId) -> Self {
		Self {
			engine,
			identity,
			pending_tables: Vec::new(),
			pending_ringbuffers: Vec::new(),
			_validation: PhantomData,
		}
	}
}

impl<'e, V: ValidationMode> BulkInsertBuilder<'e, V> {
	/// Begin inserting into a table.
	///
	/// The qualified name can be either "namespace::table" or just "table"
	/// (which uses the default namespace).
	pub fn table<'a>(&'a mut self, qualified_name: &str) -> TableInsertBuilder<'a, 'e, V> {
		let (namespace, table) = parse_qualified_name(qualified_name);
		TableInsertBuilder::new(self, namespace, table)
	}

	/// Begin inserting into a ring buffer.
	///
	/// The qualified name can be either "namespace::ringbuffer" or just "ringbuffer"
	/// (which uses the default namespace).
	pub fn ringbuffer<'a>(&'a mut self, qualified_name: &str) -> RingBufferInsertBuilder<'a, 'e, V> {
		let (namespace, ringbuffer) = parse_qualified_name(qualified_name);
		RingBufferInsertBuilder::new(self, namespace, ringbuffer)
	}

	/// Add a pending table insert (called by TableInsertBuilder::done)
	pub(super) fn add_table_insert(&mut self, pending: PendingTableInsert) {
		self.pending_tables.push(pending);
	}

	/// Add a pending ring buffer insert (called by RingBufferInsertBuilder::done)
	pub(super) fn add_ringbuffer_insert(&mut self, pending: PendingRingBufferInsert) {
		self.pending_ringbuffers.push(pending);
	}

	/// Execute all pending inserts in a single transaction.
	///
	/// Returns a summary of what was inserted. On error, the entire
	/// transaction is rolled back (no partial inserts).
	pub fn execute(self) -> Result<BulkInsertResult> {
		self.engine.reject_if_read_only()?;
		let mut txn = self.engine.begin_command(self.identity)?;
		let catalog = self.engine.catalog();
		let clock = self.engine.clock();
		let mut result = BulkInsertResult::default();

		// Process all pending table inserts
		for pending in self.pending_tables {
			let table_result =
				execute_table_insert(&catalog, &mut txn, &pending, TypeId::of::<V>(), clock)?;
			result.tables.push(table_result);
		}

		// Process all pending ring buffer inserts
		for pending in self.pending_ringbuffers {
			let rb_result =
				execute_ringbuffer_insert(&catalog, &mut txn, &pending, TypeId::of::<V>(), clock)?;
			result.ringbuffers.push(rb_result);
		}

		// Commit the transaction
		txn.commit()?;

		Ok(result)
	}
}

/// Execute a table insert within a transaction
fn execute_table_insert(
	catalog: &Catalog,
	txn: &mut CommandTransaction,
	pending: &PendingTableInsert,
	type_id: TypeId,
	clock: &Clock,
) -> Result<TableInsertResult> {
	// 1. Look up namespace and table from catalog
	let namespace = catalog
		.find_namespace_by_name(&mut Transaction::Command(txn), &pending.namespace)?
		.ok_or_else(|| CatalogError::NotFound {
			kind: CatalogObjectKind::Namespace,
			namespace: pending.namespace.to_string(),
			name: String::new(),
			fragment: Fragment::None,
		})?;

	let table = catalog
		.find_table_by_name(&mut Transaction::Command(txn), namespace.id(), &pending.table)?
		.ok_or_else(|| CatalogError::NotFound {
			kind: CatalogObjectKind::Table,
			namespace: pending.namespace.to_string(),
			name: pending.table.to_string(),
			fragment: Fragment::None,
		})?;

	// 2. Get or create shape with proper field names and constraints
	let shape = get_or_create_table_shape(catalog, &table, &mut Transaction::Command(txn))?;

	// 3. Validate and coerce all rows in batch (fail-fast)
	let is_validated = type_id == TypeId::of::<Validated>();
	let coerced_rows = if is_validated {
		validate_and_coerce_rows(&pending.rows, &table)?
	} else {
		reorder_rows_trusted(&pending.rows, &table)?
	};

	let mut encoded_rows = Vec::with_capacity(coerced_rows.len());

	for mut values in coerced_rows {
		// Handle auto-increment columns
		for (idx, col) in table.columns.iter().enumerate() {
			if col.auto_increment && matches!(values[idx], Value::None { .. }) {
				values[idx] = catalog.column_sequence_next_value(txn, table.id, col.id)?;
			}
		}

		// Handle dictionary encoding
		for (idx, col) in table.columns.iter().enumerate() {
			if let Some(dict_id) = col.dictionary_id {
				let dictionary = catalog
					.find_dictionary(&mut Transaction::Command(txn), dict_id)?
					.ok_or_else(|| {
						internal_error!(
							"Dictionary {:?} not found for column {}",
							dict_id,
							col.name
						)
					})?;
				let entry_id = txn.insert_into_dictionary(&dictionary, &values[idx])?;
				values[idx] = entry_id.to_value();
			}
		}

		// Validate constraints (coercion is done in batch, but final constraint check still needed)
		if is_validated {
			for (idx, col) in table.columns.iter().enumerate() {
				col.constraint.validate(&values[idx])?;
			}
		}

		// Encode the row
		let mut row = shape.allocate();
		for (idx, value) in values.iter().enumerate() {
			shape.set_value(&mut row, idx, value);
		}

		let now_nanos = clock.now_nanos();
		row.set_timestamps(now_nanos, now_nanos);

		encoded_rows.push(row);
	}

	let total_rows = encoded_rows.len();
	if total_rows == 0 {
		return Ok(TableInsertResult {
			namespace: pending.namespace.clone(),
			table: pending.table.clone(),
			inserted: 0,
		});
	}

	let row_numbers = catalog.next_row_number_batch(txn, table.id, total_rows as u64)?;

	// Hoist loop-invariant computations out of the insertion loop
	let pk_def = primary_key::get_primary_key(catalog, &mut Transaction::Command(txn), &table)?;
	let row_number_shape = if pk_def.is_some() {
		Some(RowShape::testing(&[Type::Uint8]))
	} else {
		None
	};

	// 5. Insert all rows with their row numbers
	for (row, &row_number) in encoded_rows.iter().zip(row_numbers.iter()) {
		txn.insert_table(&table, &shape, row.clone(), row_number)?;

		// Handle primary key index if table has one
		if let Some(ref pk_def) = pk_def {
			let index_key = primary_key::encode_primary_key(pk_def, row, &table, &shape)?;
			let index_entry_key =
				IndexEntryKey::new(table.id, IndexId::primary(pk_def.id), index_key.clone());

			// Check for primary key violation
			if txn.contains_key(&index_entry_key.encode())? {
				let key_columns = pk_def.columns.iter().map(|c| c.name.clone()).collect();
				return Err(CoreError::PrimaryKeyViolation {
					fragment: Fragment::None,
					table_name: table.name.clone(),
					key_columns,
				}
				.into());
			}

			// Store the index entry
			let rns = row_number_shape.as_ref().unwrap();
			let mut row_number_encoded = rns.allocate();
			rns.set_u64(&mut row_number_encoded, 0, u64::from(row_number));
			txn.set(&index_entry_key.encode(), row_number_encoded)?;
		}
	}

	Ok(TableInsertResult {
		namespace: pending.namespace.clone(),
		table: pending.table.clone(),
		inserted: total_rows as u64,
	})
}

/// Execute a ring buffer insert within a transaction
fn execute_ringbuffer_insert(
	catalog: &Catalog,
	txn: &mut CommandTransaction,
	pending: &PendingRingBufferInsert,
	type_id: TypeId,
	clock: &Clock,
) -> Result<RingBufferInsertResult> {
	let namespace = catalog
		.find_namespace_by_name(&mut Transaction::Command(txn), &pending.namespace)?
		.ok_or_else(|| CatalogError::NotFound {
			kind: CatalogObjectKind::Namespace,
			namespace: pending.namespace.to_string(),
			name: String::new(),
			fragment: Fragment::None,
		})?;

	let ringbuffer = catalog
		.find_ringbuffer_by_name(&mut Transaction::Command(txn), namespace.id(), &pending.ringbuffer)?
		.ok_or_else(|| CatalogError::NotFound {
			kind: CatalogObjectKind::RingBuffer,
			namespace: pending.namespace.to_string(),
			name: pending.ringbuffer.to_string(),
			fragment: Fragment::None,
		})?;

	let mut metadata = catalog
		.find_ringbuffer_metadata(&mut Transaction::Command(txn), ringbuffer.id)?
		.ok_or_else(|| CatalogError::NotFound {
			kind: CatalogObjectKind::RingBuffer,
			namespace: pending.namespace.to_string(),
			name: pending.ringbuffer.to_string(),
			fragment: Fragment::None,
		})?;

	// Get or create shape with proper field names and constraints
	let shape = get_or_create_ringbuffer_shape(catalog, &ringbuffer, &mut Transaction::Command(txn))?;

	// 3. Validate and coerce all rows in batch (fail-fast)
	let is_validated = type_id == TypeId::of::<Validated>();
	let coerced_rows = if is_validated {
		validate_and_coerce_rows_rb(&pending.rows, &ringbuffer)?
	} else {
		reorder_rows_trusted_rb(&pending.rows, &ringbuffer)?
	};

	let mut inserted_count = 0u64;

	// 4. Process each coerced row
	for mut values in coerced_rows {
		// Handle dictionary encoding
		for (idx, col) in ringbuffer.columns.iter().enumerate() {
			if let Some(dict_id) = col.dictionary_id {
				let dictionary = catalog
					.find_dictionary(&mut Transaction::Command(txn), dict_id)?
					.ok_or_else(|| {
						internal_error!(
							"Dictionary {:?} not found for column {}",
							dict_id,
							col.name
						)
					})?;
				let entry_id = txn.insert_into_dictionary(&dictionary, &values[idx])?;
				values[idx] = entry_id.to_value();
			}
		}

		// Validate constraints (coercion is done in batch, but final constraint check still needed)
		if is_validated {
			for (idx, col) in ringbuffer.columns.iter().enumerate() {
				col.constraint.validate(&values[idx])?;
			}
		}

		// Encode the row
		let mut row = shape.allocate();
		for (idx, value) in values.iter().enumerate() {
			shape.set_value(&mut row, idx, value);
		}

		let now_nanos = clock.now_nanos();
		row.set_timestamps(now_nanos, now_nanos);

		if metadata.is_full() {
			let oldest_row = RowNumber(metadata.head);
			txn.remove_from_ringbuffer(&ringbuffer, oldest_row)?;
			metadata.head += 1;
			metadata.count -= 1;
		}

		// Allocate row number
		let row_number = catalog.next_row_number_for_ringbuffer(txn, ringbuffer.id)?;

		// Store the row
		txn.insert_ringbuffer_at(&ringbuffer, &shape, row_number, row)?;

		// Update metadata
		if metadata.is_empty() {
			metadata.head = row_number.0;
		}
		metadata.count += 1;
		metadata.tail = row_number.0 + 1;

		inserted_count += 1;
	}

	// Save updated metadata
	catalog.update_ringbuffer_metadata(txn, metadata)?;

	Ok(RingBufferInsertResult {
		namespace: pending.namespace.clone(),
		ringbuffer: pending.ringbuffer.clone(),
		inserted: inserted_count,
	})
}

/// Parse a qualified name like "namespace::table" into (namespace, name).
/// If no namespace is provided, uses "default".
fn parse_qualified_name(qualified_name: &str) -> (String, String) {
	if let Some((ns, name)) = qualified_name.rsplit_once("::") {
		(ns.to_string(), name.to_string())
	} else {
		("default".to_string(), qualified_name.to_string())
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn parse_qualified_name_simple() {
		assert_eq!(parse_qualified_name("table"), ("default".to_string(), "table".to_string()));
	}

	#[test]
	fn parse_qualified_name_single_namespace() {
		assert_eq!(parse_qualified_name("ns::table"), ("ns".to_string(), "table".to_string()));
	}

	#[test]
	fn parse_qualified_name_nested_namespace() {
		assert_eq!(parse_qualified_name("a::b::table"), ("a::b".to_string(), "table".to_string()));
	}

	#[test]
	fn parse_qualified_name_deeply_nested_namespace() {
		assert_eq!(parse_qualified_name("a::b::c::table"), ("a::b::c".to_string(), "table".to_string()));
	}

	#[test]
	fn parse_qualified_name_empty_string() {
		assert_eq!(parse_qualified_name(""), ("default".to_string(), "".to_string()));
	}
}