reifydb-sdk 0.4.10

SDK for building ReifyDB operators
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use reifydb_core::{
	encoded::{key::EncodedKey, shape::RowShape},
	interface::change::{Change, Diff},
	row::Row,
	value::column::columns::Columns,
};
use reifydb_type::value::{Value, row_number::RowNumber};

use super::helpers::get_values;
use crate::testing::state::TestStateStore;

/// Assertions for Change outputs
pub struct ChangeAssertion<'a> {
	change: &'a Change,
}

impl<'a> ChangeAssertion<'a> {
	/// Create a new Change assertion
	pub fn new(change: &'a Change) -> Self {
		Self {
			change,
		}
	}

	/// Assert the number of diffs in the change
	pub fn has_diffs(&self, count: usize) -> &Self {
		assert_eq!(
			self.change.diffs.len(),
			count,
			"Expected {} diffs, found {}",
			count,
			self.change.diffs.len()
		);
		self
	}

	/// Assert the change is empty (no diffs)
	pub fn is_empty(&self) -> &Self {
		assert!(self.change.diffs.is_empty(), "Expected empty change, found {} diffs", self.change.diffs.len());
		self
	}

	/// Assert the change has at least one insert
	pub fn has_insert(&self) -> &Self {
		let has_insert = self.change.diffs.iter().any(|d| matches!(d, Diff::Insert { .. }));
		assert!(has_insert, "Expected at least one insert diff");
		self
	}

	/// Assert the change has at least one update
	pub fn has_update(&self) -> &Self {
		let has_update = self.change.diffs.iter().any(|d| matches!(d, Diff::Update { .. }));
		assert!(has_update, "Expected at least one update diff");
		self
	}

	/// Assert the change has at least one remove
	pub fn has_remove(&self) -> &Self {
		let has_remove = self.change.diffs.iter().any(|d| matches!(d, Diff::Remove { .. }));
		assert!(has_remove, "Expected at least one remove diff");
		self
	}

	/// Assert a specific diff exists at the given index
	pub fn diff_at(&self, index: usize) -> DiffAssertion<'_> {
		assert!(
			index < self.change.diffs.len(),
			"Diff index {} out of range (total: {})",
			index,
			self.change.diffs.len()
		);
		DiffAssertion::new(&self.change.diffs[index])
	}

	/// Get all insert diffs
	pub fn inserts(&self) -> Vec<&Columns> {
		self.change
			.diffs
			.iter()
			.filter_map(|d| match d {
				Diff::Insert {
					post,
				} => Some(post),
				_ => None,
			})
			.collect()
	}

	/// Get all update diffs
	pub fn updates(&self) -> Vec<(&Columns, &Columns)> {
		self.change
			.diffs
			.iter()
			.filter_map(|d| match d {
				Diff::Update {
					pre,
					post,
				} => Some((pre, post)),
				_ => None,
			})
			.collect()
	}

	/// Get all remove diffs
	pub fn removes(&self) -> Vec<&Columns> {
		self.change
			.diffs
			.iter()
			.filter_map(|d| match d {
				Diff::Remove {
					pre,
				} => Some(pre),
				_ => None,
			})
			.collect()
	}

	/// Assert the number of inserts
	pub fn has_inserts(&self, count: usize) -> &Self {
		let actual = self.inserts().len();
		assert_eq!(actual, count, "Expected {} inserts, found {}", count, actual);
		self
	}

	/// Assert the number of updates
	pub fn has_updates(&self, count: usize) -> &Self {
		let actual = self.updates().len();
		assert_eq!(actual, count, "Expected {} updates, found {}", count, actual);
		self
	}

	/// Assert the number of removes
	pub fn has_removes(&self, count: usize) -> &Self {
		let actual = self.removes().len();
		assert_eq!(actual, count, "Expected {} removes, found {}", count, actual);
		self
	}
}

/// Assertions for a single diff
pub struct DiffAssertion<'a> {
	diff: &'a Diff,
}

impl<'a> DiffAssertion<'a> {
	pub fn new(diff: &'a Diff) -> Self {
		Self {
			diff,
		}
	}

	/// Assert this is an insert diff
	pub fn is_insert(&self) -> &Columns {
		match self.diff {
			Diff::Insert {
				post,
			} => post,
			_ => panic!("Expected insert diff, found {:?}", self.diff),
		}
	}

	/// Assert this is an update diff
	pub fn is_update(&self) -> (&Columns, &Columns) {
		match self.diff {
			Diff::Update {
				pre,
				post,
			} => (pre, post),
			_ => panic!("Expected update diff, found {:?}", self.diff),
		}
	}

	/// Assert this is a remove diff
	pub fn is_remove(&self) -> &Columns {
		match self.diff {
			Diff::Remove {
				pre,
			} => pre,
			_ => panic!("Expected remove diff, found {:?}", self.diff),
		}
	}
}

/// Assertions for Row values
pub struct RowAssertion<'a> {
	row: &'a Row,
}

impl<'a> RowAssertion<'a> {
	/// Create a new row assertion
	pub fn new(row: &'a Row) -> Self {
		Self {
			row,
		}
	}

	/// Assert the row number
	pub fn has_number(&self, number: impl Into<RowNumber>) -> &Self {
		let expected = number.into();
		assert_eq!(
			self.row.number, expected,
			"Expected row number {:?}, found {:?}",
			expected, self.row.number
		);
		self
	}

	/// Assert the row values match (using the row's layout)
	pub fn has_values(&self, expected: &[Value]) -> &Self {
		let actual = get_values(&self.row.shape, &self.row.encoded);
		assert_eq!(actual, expected, "Row values mismatch. Expected: {:?}, Actual: {:?}", expected, actual);
		self
	}

	/// Assert a specific field value (for named layouts)
	pub fn has_field(&self, field_name: &str, expected: Value) -> &Self {
		let values = get_values(&self.row.shape, &self.row.encoded);
		let field_index =
			self.row.shape
				.find_field_index(field_name)
				.unwrap_or_else(|| panic!("Field '{}' not found in layout", field_name));

		assert_eq!(
			values[field_index], expected,
			"Field '{}' mismatch. Expected: {:?}, Actual: {:?}",
			field_name, expected, values[field_index]
		);
		self
	}

	/// Get the values from the row
	pub fn values(&self) -> Vec<Value> {
		get_values(&self.row.shape, &self.row.encoded)
	}
}

/// Assertions for state store
pub struct StateAssertion<'a> {
	store: &'a TestStateStore,
}

impl<'a> StateAssertion<'a> {
	/// Create a new state assertion
	pub fn new(store: &'a TestStateStore) -> Self {
		Self {
			store,
		}
	}

	/// Assert the state is empty
	pub fn is_empty(&self) -> &Self {
		assert!(self.store.is_empty(), "Expected empty state, found {} entries", self.store.len());
		self
	}

	/// Assert the state has a specific number of entries
	pub fn has_entries(&self, count: usize) -> &Self {
		self.store.assert_count(count);
		self
	}

	/// Assert a key exists
	pub fn has_key(&self, key: &EncodedKey) -> &Self {
		self.store.assert_exists(key);
		self
	}

	/// Assert a key does not exist
	pub fn not_has_key(&self, key: &EncodedKey) -> &Self {
		self.store.assert_not_exists(key);
		self
	}

	/// Assert a key has specific values
	pub fn key_has_values(&self, key: &EncodedKey, expected: &[Value], shape: &RowShape) -> &Self {
		self.store.assert_value(key, expected, shape);
		self
	}

	/// Assert all keys match a predicate
	pub fn all_keys<F>(&self, predicate: F) -> &Self
	where
		F: Fn(&EncodedKey) -> bool,
	{
		for key in self.store.keys() {
			assert!(predicate(key), "Key {:?} did not match predicate", key);
		}
		self
	}
}

/// Helper to create assertions
pub trait Assertable {
	type Assertion<'a>
	where
		Self: 'a;

	fn assert(&self) -> Self::Assertion<'_>;
}

impl Assertable for Change {
	type Assertion<'a>
		= ChangeAssertion<'a>
	where
		Self: 'a;

	fn assert(&self) -> ChangeAssertion<'_> {
		ChangeAssertion::new(self)
	}
}

impl Assertable for Row {
	type Assertion<'a>
		= RowAssertion<'a>
	where
		Self: 'a;

	fn assert(&self) -> RowAssertion<'_> {
		RowAssertion::new(self)
	}
}

impl Assertable for TestStateStore {
	type Assertion<'a>
		= StateAssertion<'a>
	where
		Self: 'a;

	fn assert(&self) -> StateAssertion<'_> {
		StateAssertion::new(self)
	}
}

#[cfg(test)]
pub mod tests {
	use reifydb_core::encoded::shape::RowShape;
	use reifydb_type::value::r#type::Type;

	use super::*;
	use crate::testing::{
		builders::{TestChangeBuilder, TestRowBuilder},
		helpers::encode_key,
		state::TestStateStore,
	};

	#[test]
	fn test_flow_change_assertions() {
		let change = TestChangeBuilder::new()
			.insert_row(1, vec![Value::Int8(10i64)])
			.update_row(2, vec![Value::Int8(20i64)], vec![Value::Int8(30i64)])
			.remove_row(3, vec![Value::Int8(40i64)])
			.build();

		change.assert()
			.has_diffs(3)
			.has_insert()
			.has_update()
			.has_remove()
			.has_inserts(1)
			.has_updates(1)
			.has_removes(1);

		// Need to keep assertion alive for lifetime
		let change_assert = change.assert();
		let diff_assert = change_assert.diff_at(0);
		let insert_columns = diff_assert.is_insert();
		// Convert to Row for assertion (Columns has to_row())
		let insert_row = insert_columns.to_single_row();
		insert_row.assert().has_number(1).has_values(&[Value::Int8(10i64)]);
	}

	#[test]
	fn test_row_assertions() {
		let row = TestRowBuilder::new(42)
			.with_values(vec![Value::Int8(100i64), Value::Utf8("test".into())])
			.build();

		row.assert().has_number(42).has_values(&[Value::Int8(100i64), Value::Utf8("test".into())]);

		assert_eq!(row.assert().values().len(), 2);
	}

	#[test]
	fn test_state_assertions() {
		let mut store = TestStateStore::new();
		let shape = RowShape::testing(&[Type::Int8]);
		let key1 = encode_key("key1");
		let key2 = encode_key("key2");

		store.set_value(key1.clone(), &[Value::Int8(10i64)], &shape);
		store.set_value(key2.clone(), &[Value::Int8(20i64)], &shape);

		store.assert()
			.has_entries(2)
			.has_key(&key1)
			.has_key(&key2)
			.key_has_values(&key1, &[Value::Int8(10i64)], &shape)
			.all_keys(|k| k.0.len() == 6); // "key1" and "key2" are 6 bytes (4 chars + 2-byte terminator 0xffff)
	}

	#[test]
	#[should_panic(expected = "Expected 5 diffs, found 1")]
	fn test_assertion_failure() {
		let change = TestChangeBuilder::new().insert_row(1, vec![Value::Int8(10i64)]).build();

		change.assert().has_diffs(5);
	}
}