reifydb-type 0.4.12

Core type system and value representations 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
458
459
460
461
462
463
464
465
466
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use serde::{Deserialize, Serialize};

use crate::{
	error::{ConstraintKind, Error, TypeError},
	fragment::Fragment,
	value::{
		Value,
		constraint::{bytes::MaxBytes, precision::Precision, scale::Scale},
		dictionary::DictionaryId,
		sumtype::SumTypeId,
		r#type::Type,
	},
};

pub mod bytes;
pub mod precision;
pub mod scale;

/// Represents a type with optional constraints
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeConstraint {
	base_type: Type,
	constraint: Option<Constraint>,
}

/// Constraint types for different data types
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Constraint {
	/// Maximum number of bytes for UTF8, BLOB, INT, UINT
	MaxBytes(MaxBytes),
	/// Precision and scale for DECIMAL
	PrecisionScale(Precision, Scale),
	/// Dictionary constraint: (catalog dictionary ID, id_type)
	Dictionary(DictionaryId, Type),
	/// Sum type constraint: links a logical column to a catalog SumType
	SumType(SumTypeId),
}

/// FFI-safe representation of a TypeConstraint
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct FFITypeConstraint {
	/// Base type code (Type::to_u8)
	pub base_type: u8,
	/// Constraint type: 0=None, 1=MaxBytes, 2=PrecisionScale, 3=Dictionary, 4=SumType
	pub constraint_type: u8,
	/// First constraint param: MaxBytes value OR precision OR dictionary_id low 32 bits
	pub constraint_param1: u32,
	/// Second constraint param: scale (PrecisionScale) OR id_type (Dictionary)
	pub constraint_param2: u32,
}

impl TypeConstraint {
	/// Create an unconstrained type
	pub const fn unconstrained(ty: Type) -> Self {
		Self {
			base_type: ty,
			constraint: None,
		}
	}

	/// Create a type with a constraint
	pub fn with_constraint(ty: Type, constraint: Constraint) -> Self {
		Self {
			base_type: ty,
			constraint: Some(constraint),
		}
	}

	/// Create a dictionary type constraint
	pub fn dictionary(dictionary_id: DictionaryId, id_type: Type) -> Self {
		Self {
			base_type: Type::DictionaryId,
			constraint: Some(Constraint::Dictionary(dictionary_id, id_type)),
		}
	}

	/// Create a sum type constraint (tag stored as Uint1)
	pub fn sumtype(id: SumTypeId) -> Self {
		Self {
			base_type: Type::Uint1,
			constraint: Some(Constraint::SumType(id)),
		}
	}

	/// Get the base type
	pub fn get_type(&self) -> Type {
		self.base_type.clone()
	}

	/// Get the storage type. For DictionaryId with a Dictionary constraint,
	/// returns the id_type (e.g. Uint4). For all other types, returns the base_type.
	pub fn storage_type(&self) -> Type {
		match (&self.base_type, &self.constraint) {
			(Type::DictionaryId, Some(Constraint::Dictionary(_, id_type))) => id_type.clone(),
			_ => self.base_type.clone(),
		}
	}

	/// Get the constraint
	pub fn constraint(&self) -> &Option<Constraint> {
		&self.constraint
	}

	/// Convert to FFI representation
	pub fn to_ffi(&self) -> FFITypeConstraint {
		let base_type = self.base_type.to_u8();
		match &self.constraint {
			None => FFITypeConstraint {
				base_type,
				constraint_type: 0,
				constraint_param1: 0,
				constraint_param2: 0,
			},
			Some(Constraint::MaxBytes(max)) => FFITypeConstraint {
				base_type,
				constraint_type: 1,
				constraint_param1: max.value(),
				constraint_param2: 0,
			},
			Some(Constraint::PrecisionScale(p, s)) => FFITypeConstraint {
				base_type,
				constraint_type: 2,
				constraint_param1: p.value() as u32,
				constraint_param2: s.value() as u32,
			},
			Some(Constraint::Dictionary(dict_id, id_type)) => FFITypeConstraint {
				base_type,
				constraint_type: 3,
				constraint_param1: dict_id.to_u64() as u32,
				constraint_param2: id_type.to_u8() as u32,
			},
			Some(Constraint::SumType(id)) => FFITypeConstraint {
				base_type,
				constraint_type: 4,
				constraint_param1: id.to_u64() as u32,
				constraint_param2: 0,
			},
		}
	}

	/// Create from FFI representation
	pub fn from_ffi(ffi: FFITypeConstraint) -> Self {
		let ty = Type::from_u8(ffi.base_type);
		match ffi.constraint_type {
			1 => Self::with_constraint(ty, Constraint::MaxBytes(MaxBytes::new(ffi.constraint_param1))),
			2 => Self::with_constraint(
				ty,
				Constraint::PrecisionScale(
					Precision::new(ffi.constraint_param1 as u8),
					Scale::new(ffi.constraint_param2 as u8),
				),
			),
			3 => Self::with_constraint(
				ty,
				Constraint::Dictionary(
					DictionaryId::from(ffi.constraint_param1 as u64),
					Type::from_u8(ffi.constraint_param2 as u8),
				),
			),
			4 => Self::with_constraint(
				ty,
				Constraint::SumType(SumTypeId::from(ffi.constraint_param1 as u64)),
			),
			_ => Self::unconstrained(ty),
		}
	}

	/// Validate a value against this type constraint
	pub fn validate(&self, value: &Value) -> Result<(), Error> {
		// First check type compatibility
		let value_type = value.get_type();
		if value_type != self.base_type && !matches!(value, Value::None { .. }) {
			// For Option types, also accept values matching the inner type
			if let Type::Option(inner) = &self.base_type {
				if value_type != **inner {
					unimplemented!()
				}
			} else {
				unimplemented!()
			}
		}

		// If None, only allow for Option types
		if matches!(value, Value::None { .. }) {
			if self.base_type.is_option() {
				return Ok(());
			} else {
				return Err(TypeError::ConstraintViolation {
					kind: ConstraintKind::NoneNotAllowed {
						column_type: self.base_type.clone(),
					},
					message: format!(
						"Cannot insert none into non-optional column of type {}. Declare the column as Option({}) to allow none values.",
						self.base_type, self.base_type
					),
					fragment: Fragment::None,
				}
				.into());
			}
		}

		// Check constraints if present
		match (&self.base_type, &self.constraint) {
			(Type::Utf8, Some(Constraint::MaxBytes(max))) => {
				if let Value::Utf8(s) = value {
					let byte_len = s.len();
					let max_value: usize = (*max).into();
					if byte_len > max_value {
						return Err(TypeError::ConstraintViolation {
							kind: ConstraintKind::Utf8MaxBytes {
								actual: byte_len,
								max: max_value,
							},
							message: format!(
								"UTF8 value exceeds maximum byte length: {} bytes (max: {} bytes)",
								byte_len, max_value
							),
							fragment: Fragment::None,
						}
						.into());
					}
				}
			}
			(Type::Blob, Some(Constraint::MaxBytes(max))) => {
				if let Value::Blob(blob) = value {
					let byte_len = blob.len();
					let max_value: usize = (*max).into();
					if byte_len > max_value {
						return Err(TypeError::ConstraintViolation {
							kind: ConstraintKind::BlobMaxBytes {
								actual: byte_len,
								max: max_value,
							},
							message: format!(
								"BLOB value exceeds maximum byte length: {} bytes (max: {} bytes)",
								byte_len, max_value
							),
							fragment: Fragment::None,
						}
						.into());
					}
				}
			}
			(Type::Int, Some(Constraint::MaxBytes(max))) => {
				if let Value::Int(vi) = value {
					// Calculate byte size of Int by
					// converting to string and estimating
					// This is a rough estimate: each
					// decimal digit needs ~3.32 bits, so
					// ~0.415 bytes
					let str_len = vi.to_string().len();
					let byte_len = (str_len * 415 / 1000) + 1; // Rough estimate
					let max_value: usize = (*max).into();
					if byte_len > max_value {
						return Err(TypeError::ConstraintViolation {
							kind: ConstraintKind::IntMaxBytes {
								actual: byte_len,
								max: max_value,
							},
							message: format!(
								"INT value exceeds maximum byte length: {} bytes (max: {} bytes)",
								byte_len, max_value
							),
							fragment: Fragment::None,
						}
						.into());
					}
				}
			}
			(Type::Uint, Some(Constraint::MaxBytes(max))) => {
				if let Value::Uint(vu) = value {
					// Calculate byte size of Uint by
					// converting to string and estimating
					// This is a rough estimate: each
					// decimal digit needs ~3.32 bits, so
					// ~0.415 bytes
					let str_len = vu.to_string().len();
					let byte_len = (str_len * 415 / 1000) + 1; // Rough estimate
					let max_value: usize = (*max).into();
					if byte_len > max_value {
						return Err(TypeError::ConstraintViolation {
							kind: ConstraintKind::UintMaxBytes {
								actual: byte_len,
								max: max_value,
							},
							message: format!(
								"UINT value exceeds maximum byte length: {} bytes (max: {} bytes)",
								byte_len, max_value
							),
							fragment: Fragment::None,
						}
						.into());
					}
				}
			}
			(Type::Decimal, Some(Constraint::PrecisionScale(precision, scale))) => {
				if let Value::Decimal(decimal) = value {
					// Calculate precision and scale from
					// BigDecimal
					let decimal_str = decimal.to_string();

					// Calculate scale (digits after decimal
					// point)
					let decimal_scale: u8 = if let Some(dot_pos) = decimal_str.find('.') {
						let after_dot = &decimal_str[dot_pos + 1..];
						after_dot.len().min(255) as u8
					} else {
						0
					};

					// Calculate precision (total number of
					// significant digits)
					let decimal_precision: u8 =
						decimal_str.chars().filter(|c| c.is_ascii_digit()).count().min(255)
							as u8;

					let scale_value: u8 = (*scale).into();
					let precision_value: u8 = (*precision).into();

					if decimal_scale > scale_value {
						return Err(TypeError::ConstraintViolation {
							kind: ConstraintKind::DecimalScale {
								actual: decimal_scale,
								max: scale_value,
							},
							message: format!(
								"DECIMAL value exceeds maximum scale: {} decimal places (max: {} decimal places)",
								decimal_scale, scale_value
							),
							fragment: Fragment::None,
						}
						.into());
					}
					if decimal_precision > precision_value {
						return Err(TypeError::ConstraintViolation {
							kind: ConstraintKind::DecimalPrecision {
								actual: decimal_precision,
								max: precision_value,
							},
							message: format!(
								"DECIMAL value exceeds maximum precision: {} digits (max: {} digits)",
								decimal_precision, precision_value
							),
							fragment: Fragment::None,
						}
						.into());
					}
				}
			}
			// No constraint or non-applicable constraint
			_ => {}
		}

		Ok(())
	}

	/// Check if this type is unconstrained
	pub fn is_unconstrained(&self) -> bool {
		self.constraint.is_none()
	}

	/// Get a human-readable string representation
	#[allow(clippy::inherent_to_string)]
	pub fn to_string(&self) -> String {
		match &self.constraint {
			None => format!("{}", self.base_type),
			Some(Constraint::MaxBytes(max)) => {
				format!("{}({})", self.base_type, max)
			}
			Some(Constraint::PrecisionScale(p, s)) => {
				format!("{}({},{})", self.base_type, p, s)
			}
			Some(Constraint::Dictionary(dict_id, id_type)) => {
				format!("DictionaryId(dict={}, {})", dict_id, id_type)
			}
			Some(Constraint::SumType(id)) => {
				format!("SumType({})", id)
			}
		}
	}
}

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

	#[test]
	fn test_unconstrained_type() {
		let tc = TypeConstraint::unconstrained(Type::Utf8);
		assert_eq!(tc.base_type, Type::Utf8);
		assert_eq!(tc.constraint, None);
		assert!(tc.is_unconstrained());
	}

	#[test]
	fn test_constrained_utf8() {
		let tc = TypeConstraint::with_constraint(Type::Utf8, Constraint::MaxBytes(MaxBytes::new(50)));
		assert_eq!(tc.base_type, Type::Utf8);
		assert_eq!(tc.constraint, Some(Constraint::MaxBytes(MaxBytes::new(50))));
		assert!(!tc.is_unconstrained());
	}

	#[test]
	fn test_constrained_decimal() {
		let tc = TypeConstraint::with_constraint(
			Type::Decimal,
			Constraint::PrecisionScale(Precision::new(10), Scale::new(2)),
		);
		assert_eq!(tc.base_type, Type::Decimal);
		assert_eq!(tc.constraint, Some(Constraint::PrecisionScale(Precision::new(10), Scale::new(2))));
	}

	#[test]
	fn test_validate_utf8_within_limit() {
		let tc = TypeConstraint::with_constraint(Type::Utf8, Constraint::MaxBytes(MaxBytes::new(10)));
		let value = Value::Utf8("hello".to_string());
		assert!(tc.validate(&value).is_ok());
	}

	#[test]
	fn test_validate_utf8_exceeds_limit() {
		let tc = TypeConstraint::with_constraint(Type::Utf8, Constraint::MaxBytes(MaxBytes::new(5)));
		let value = Value::Utf8("hello world".to_string());
		assert!(tc.validate(&value).is_err());
	}

	#[test]
	fn test_validate_unconstrained() {
		let tc = TypeConstraint::unconstrained(Type::Utf8);
		let value = Value::Utf8("any length string is fine here".to_string());
		assert!(tc.validate(&value).is_ok());
	}

	#[test]
	fn test_validate_none_rejected_for_non_option() {
		let tc = TypeConstraint::with_constraint(Type::Utf8, Constraint::MaxBytes(MaxBytes::new(5)));
		let value = Value::none();
		assert!(tc.validate(&value).is_err());
	}

	#[test]
	fn test_validate_none_accepted_for_option() {
		let tc = TypeConstraint::unconstrained(Type::Option(Box::new(Type::Utf8)));
		let value = Value::none();
		assert!(tc.validate(&value).is_ok());
	}

	#[test]
	fn test_to_string() {
		let tc1 = TypeConstraint::unconstrained(Type::Utf8);
		assert_eq!(tc1.to_string(), "Utf8");

		let tc2 = TypeConstraint::with_constraint(Type::Utf8, Constraint::MaxBytes(MaxBytes::new(50)));
		assert_eq!(tc2.to_string(), "Utf8(50)");

		let tc3 = TypeConstraint::with_constraint(
			Type::Decimal,
			Constraint::PrecisionScale(Precision::new(10), Scale::new(2)),
		);
		assert_eq!(tc3.to_string(), "Decimal(10,2)");
	}
}