1use super::{
2 ast::{CompareOp, ComparePredicate, Predicate},
3 coercion::{CoercionId, CoercionSpec, supports_coercion},
4};
5use crate::{
6 db::identity::{EntityName, EntityNameError, IndexName, IndexNameError},
7 model::{entity::EntityModel, field::EntityFieldKind, index::IndexModel},
8 value::{CoercionFamily, CoercionFamilyExt, Value},
9};
10use std::{
11 collections::{BTreeMap, BTreeSet},
12 fmt,
13};
14
15#[derive(Clone, Debug, Eq, PartialEq)]
27pub(crate) enum ScalarType {
28 Account,
29 Blob,
30 Bool,
31 Date,
32 Decimal,
33 Duration,
34 Enum,
35 E8s,
36 E18s,
37 Float32,
38 Float64,
39 Int,
40 Int128,
41 IntBig,
42 Principal,
43 Subaccount,
44 Text,
45 Timestamp,
46 Uint,
47 Uint128,
48 UintBig,
49 Ulid,
50 Unit,
51}
52
53macro_rules! scalar_coercion_family_from_registry {
55 ( @args $self:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
56 match $self {
57 $( ScalarType::$scalar => $coercion_family, )*
58 }
59 };
60}
61
62macro_rules! scalar_matches_value_from_registry {
63 ( @args $self:expr, $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
64 matches!(
65 ($self, $value),
66 $( (ScalarType::$scalar, $value_pat) )|*
67 )
68 };
69}
70
71macro_rules! scalar_supports_numeric_coercion_from_registry {
72 ( @args $self:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
73 match $self {
74 $( ScalarType::$scalar => $supports_numeric_coercion, )*
75 }
76 };
77}
78
79#[cfg(test)]
80macro_rules! scalar_supports_arithmetic_from_registry {
81 ( @args $self:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
82 match $self {
83 $( ScalarType::$scalar => $supports_arithmetic, )*
84 }
85 };
86}
87
88macro_rules! scalar_is_keyable_from_registry {
89 ( @args $self:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
90 match $self {
91 $( ScalarType::$scalar => $is_keyable, )*
92 }
93 };
94}
95
96#[cfg(test)]
97macro_rules! scalar_supports_equality_from_registry {
98 ( @args $self:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
99 match $self {
100 $( ScalarType::$scalar => $supports_equality, )*
101 }
102 };
103}
104
105macro_rules! scalar_supports_ordering_from_registry {
106 ( @args $self:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
107 match $self {
108 $( ScalarType::$scalar => $supports_ordering, )*
109 }
110 };
111}
112
113impl ScalarType {
114 #[must_use]
115 pub const fn coercion_family(&self) -> CoercionFamily {
116 scalar_registry!(scalar_coercion_family_from_registry, self)
117 }
118
119 #[must_use]
120 pub const fn is_orderable(&self) -> bool {
121 self.supports_ordering()
124 }
125
126 #[must_use]
127 pub const fn matches_value(&self, value: &Value) -> bool {
128 scalar_registry!(scalar_matches_value_from_registry, self, value)
129 }
130
131 #[must_use]
132 pub const fn supports_numeric_coercion(&self) -> bool {
133 scalar_registry!(scalar_supports_numeric_coercion_from_registry, self)
134 }
135
136 #[must_use]
137 #[cfg(test)]
138 #[expect(dead_code)]
139 pub const fn supports_arithmetic(&self) -> bool {
140 scalar_registry!(scalar_supports_arithmetic_from_registry, self)
141 }
142
143 #[must_use]
144 pub const fn is_keyable(&self) -> bool {
145 scalar_registry!(scalar_is_keyable_from_registry, self)
146 }
147
148 #[must_use]
149 #[cfg(test)]
150 #[expect(dead_code)]
151 pub const fn supports_equality(&self) -> bool {
152 scalar_registry!(scalar_supports_equality_from_registry, self)
153 }
154
155 #[must_use]
156 pub const fn supports_ordering(&self) -> bool {
157 scalar_registry!(scalar_supports_ordering_from_registry, self)
158 }
159}
160
161#[derive(Clone, Debug, Eq, PartialEq)]
172pub(crate) enum FieldType {
173 Scalar(ScalarType),
174 List(Box<Self>),
175 Set(Box<Self>),
176 Map { key: Box<Self>, value: Box<Self> },
177 Unsupported,
178}
179
180impl FieldType {
181 #[must_use]
182 pub const fn coercion_family(&self) -> Option<CoercionFamily> {
183 match self {
184 Self::Scalar(inner) => Some(inner.coercion_family()),
185 Self::List(_) | Self::Set(_) | Self::Map { .. } => Some(CoercionFamily::Collection),
186 Self::Unsupported => None,
187 }
188 }
189
190 #[must_use]
191 pub const fn is_text(&self) -> bool {
192 matches!(self, Self::Scalar(ScalarType::Text))
193 }
194
195 #[must_use]
196 pub const fn is_collection(&self) -> bool {
197 matches!(self, Self::List(_) | Self::Set(_) | Self::Map { .. })
198 }
199
200 #[must_use]
201 pub const fn is_list_like(&self) -> bool {
202 matches!(self, Self::List(_) | Self::Set(_))
203 }
204
205 #[must_use]
206 pub const fn is_map(&self) -> bool {
207 matches!(self, Self::Map { .. })
208 }
209
210 #[must_use]
211 pub fn map_types(&self) -> Option<(&Self, &Self)> {
212 match self {
213 Self::Map { key, value } => Some((key.as_ref(), value.as_ref())),
214 _ => {
215 None
217 }
218 }
219 }
220
221 #[must_use]
222 pub const fn is_orderable(&self) -> bool {
223 match self {
224 Self::Scalar(inner) => inner.is_orderable(),
225 _ => false,
226 }
227 }
228
229 #[must_use]
230 pub const fn is_keyable(&self) -> bool {
231 match self {
232 Self::Scalar(inner) => inner.is_keyable(),
233 _ => false,
234 }
235 }
236
237 #[must_use]
238 pub const fn supports_numeric_coercion(&self) -> bool {
239 match self {
240 Self::Scalar(inner) => inner.supports_numeric_coercion(),
241 _ => false,
242 }
243 }
244}
245
246fn validate_index_fields(
247 fields: &BTreeMap<String, FieldType>,
248 indexes: &[&IndexModel],
249) -> Result<(), ValidateError> {
250 let mut seen_names = BTreeSet::new();
251 for index in indexes {
252 if seen_names.contains(index.name) {
253 return Err(ValidateError::DuplicateIndexName {
254 name: index.name.to_string(),
255 });
256 }
257 seen_names.insert(index.name);
258
259 let mut seen = BTreeSet::new();
260 for field in index.fields {
261 if !fields.contains_key(*field) {
262 return Err(ValidateError::IndexFieldUnknown {
263 index: **index,
264 field: (*field).to_string(),
265 });
266 }
267 if seen.contains(*field) {
268 return Err(ValidateError::IndexFieldDuplicate {
269 index: **index,
270 field: (*field).to_string(),
271 });
272 }
273 seen.insert(*field);
274
275 let field_type = fields
276 .get(*field)
277 .expect("index field existence checked above");
278 if matches!(field_type, FieldType::Map { .. }) {
281 return Err(ValidateError::IndexFieldMapUnsupported {
282 index: **index,
283 field: (*field).to_string(),
284 });
285 }
286 if matches!(field_type, FieldType::Unsupported) {
289 return Err(ValidateError::IndexFieldUnsupported {
290 index: **index,
291 field: (*field).to_string(),
292 });
293 }
294 }
295 }
296
297 Ok(())
298}
299
300#[derive(Clone, Debug)]
308pub struct SchemaInfo {
309 fields: BTreeMap<String, FieldType>,
310}
311
312impl SchemaInfo {
313 #[must_use]
314 pub(crate) fn field(&self, name: &str) -> Option<&FieldType> {
315 self.fields.get(name)
316 }
317
318 pub fn from_entity_model(model: &EntityModel) -> Result<Self, ValidateError> {
319 let entity_name = EntityName::try_from_str(model.entity_name).map_err(|err| {
321 ValidateError::InvalidEntityName {
322 name: model.entity_name.to_string(),
323 source: err,
324 }
325 })?;
326
327 if !model
328 .fields
329 .iter()
330 .any(|field| std::ptr::eq(field, model.primary_key))
331 {
332 return Err(ValidateError::InvalidPrimaryKey {
333 field: model.primary_key.name.to_string(),
334 });
335 }
336
337 let mut fields = BTreeMap::new();
338 for field in model.fields {
339 if fields.contains_key(field.name) {
340 return Err(ValidateError::DuplicateField {
341 field: field.name.to_string(),
342 });
343 }
344 let ty = field_type_from_model_kind(&field.kind);
345 fields.insert(field.name.to_string(), ty);
346 }
347
348 let pk_field_type = fields
349 .get(model.primary_key.name)
350 .expect("primary key verified above");
351 if !pk_field_type.is_keyable() {
352 return Err(ValidateError::InvalidPrimaryKeyType {
353 field: model.primary_key.name.to_string(),
354 });
355 }
356
357 validate_index_fields(&fields, model.indexes)?;
358 for index in model.indexes {
359 IndexName::try_from_parts(&entity_name, index.fields).map_err(|err| {
360 ValidateError::InvalidIndexName {
361 index: **index,
362 source: err,
363 }
364 })?;
365 }
366
367 Ok(Self { fields })
368 }
369}
370
371#[derive(Debug, thiserror::Error)]
373pub enum ValidateError {
374 #[error("invalid entity name '{name}': {source}")]
375 InvalidEntityName {
376 name: String,
377 #[source]
378 source: EntityNameError,
379 },
380
381 #[error("invalid index name for '{index}': {source}")]
382 InvalidIndexName {
383 index: IndexModel,
384 #[source]
385 source: IndexNameError,
386 },
387
388 #[error("unknown field '{field}'")]
389 UnknownField { field: String },
390
391 #[error("unsupported field type for '{field}'")]
392 UnsupportedFieldType { field: String },
393
394 #[error("duplicate field '{field}'")]
395 DuplicateField { field: String },
396
397 #[error("primary key '{field}' not present in entity fields")]
398 InvalidPrimaryKey { field: String },
399
400 #[error("primary key '{field}' has an unsupported type")]
401 InvalidPrimaryKeyType { field: String },
402
403 #[error("index '{index}' references unknown field '{field}'")]
404 IndexFieldUnknown { index: IndexModel, field: String },
405
406 #[error("index '{index}' references unsupported field '{field}'")]
407 IndexFieldUnsupported { index: IndexModel, field: String },
408
409 #[error(
410 "index '{index}' references map field '{field}'; map fields are not queryable/indexable in 0.7.x"
411 )]
412 IndexFieldMapUnsupported { index: IndexModel, field: String },
413
414 #[error("index '{index}' repeats field '{field}'")]
415 IndexFieldDuplicate { index: IndexModel, field: String },
416
417 #[error("duplicate index name '{name}'")]
418 DuplicateIndexName { name: String },
419
420 #[error("operator {op} is not valid for field '{field}'")]
421 InvalidOperator { field: String, op: String },
422
423 #[error("coercion {coercion:?} is not valid for field '{field}'")]
424 InvalidCoercion { field: String, coercion: CoercionId },
425
426 #[error("invalid literal for field '{field}': {message}")]
427 InvalidLiteral { field: String, message: String },
428
429 #[error("map field '{field}' is not queryable/indexable in 0.7.x")]
430 MapFieldNotQueryable { field: String },
431}
432
433pub fn validate(schema: &SchemaInfo, predicate: &Predicate) -> Result<(), ValidateError> {
434 match predicate {
435 Predicate::True | Predicate::False => Ok(()),
436 Predicate::And(children) | Predicate::Or(children) => {
437 for child in children {
438 validate(schema, child)?;
439 }
440 Ok(())
441 }
442 Predicate::Not(inner) => validate(schema, inner),
443 Predicate::Compare(cmp) => validate_compare(schema, cmp),
444 Predicate::IsNull { field } | Predicate::IsMissing { field } => {
445 let field_type = ensure_field_exists(schema, field)?;
447 if matches!(field_type, FieldType::Map { .. }) {
448 return Err(ValidateError::MapFieldNotQueryable {
449 field: field.clone(),
450 });
451 }
452
453 Ok(())
454 }
455 Predicate::IsEmpty { field } => {
456 let field_type = ensure_field(schema, field)?;
457 if field_type.is_text() || field_type.is_collection() {
458 Ok(())
459 } else {
460 Err(invalid_operator(field, "is_empty"))
461 }
462 }
463 Predicate::IsNotEmpty { field } => {
464 let field_type = ensure_field(schema, field)?;
465 if field_type.is_text() || field_type.is_collection() {
466 Ok(())
467 } else {
468 Err(invalid_operator(field, "is_not_empty"))
469 }
470 }
471 Predicate::MapContainsKey {
472 field,
473 key,
474 coercion,
475 } => validate_map_key(schema, field, key, coercion),
476 Predicate::MapContainsValue {
477 field,
478 value,
479 coercion,
480 } => validate_map_value(schema, field, value, coercion),
481 Predicate::MapContainsEntry {
482 field,
483 key,
484 value,
485 coercion,
486 } => validate_map_entry(schema, field, key, value, coercion),
487 Predicate::TextContains { field, value } => {
488 validate_text_contains(schema, field, value, "text_contains")
489 }
490 Predicate::TextContainsCi { field, value } => {
491 validate_text_contains(schema, field, value, "text_contains_ci")
492 }
493 }
494}
495
496pub fn validate_model(model: &EntityModel, predicate: &Predicate) -> Result<(), ValidateError> {
497 let schema = SchemaInfo::from_entity_model(model)?;
498 validate(&schema, predicate)
499}
500
501fn validate_compare(schema: &SchemaInfo, cmp: &ComparePredicate) -> Result<(), ValidateError> {
502 let field_type = ensure_field(schema, &cmp.field)?;
503
504 match cmp.op {
505 CompareOp::Eq | CompareOp::Ne => {
506 validate_eq_ne(&cmp.field, field_type, &cmp.value, &cmp.coercion)
507 }
508 CompareOp::Lt | CompareOp::Lte | CompareOp::Gt | CompareOp::Gte => {
509 validate_ordering(&cmp.field, field_type, &cmp.value, &cmp.coercion, cmp.op)
510 }
511 CompareOp::In | CompareOp::NotIn => {
512 validate_in(&cmp.field, field_type, &cmp.value, &cmp.coercion, cmp.op)
513 }
514 CompareOp::Contains => validate_contains(&cmp.field, field_type, &cmp.value, &cmp.coercion),
515 CompareOp::StartsWith | CompareOp::EndsWith => {
516 validate_text_compare(&cmp.field, field_type, &cmp.value, &cmp.coercion, cmp.op)
517 }
518 }
519}
520
521fn validate_eq_ne(
522 field: &str,
523 field_type: &FieldType,
524 value: &Value,
525 coercion: &CoercionSpec,
526) -> Result<(), ValidateError> {
527 if field_type.is_list_like() {
528 ensure_list_literal(field, value, field_type)?;
529 } else if field_type.is_map() {
530 ensure_map_literal(field, value, field_type)?;
531 } else {
532 ensure_scalar_literal(field, value)?;
533 }
534
535 ensure_coercion(field, field_type, value, coercion)
536}
537
538fn validate_ordering(
539 field: &str,
540 field_type: &FieldType,
541 value: &Value,
542 coercion: &CoercionSpec,
543 op: CompareOp,
544) -> Result<(), ValidateError> {
545 if matches!(coercion.id, CoercionId::CollectionElement) {
546 return Err(ValidateError::InvalidCoercion {
547 field: field.to_string(),
548 coercion: coercion.id,
549 });
550 }
551
552 if !field_type.is_orderable() {
553 return Err(invalid_operator(field, format!("{op:?}")));
554 }
555
556 ensure_scalar_literal(field, value)?;
557
558 ensure_coercion(field, field_type, value, coercion)
559}
560
561fn validate_in(
563 field: &str,
564 field_type: &FieldType,
565 value: &Value,
566 coercion: &CoercionSpec,
567 op: CompareOp,
568) -> Result<(), ValidateError> {
569 if field_type.is_collection() {
570 return Err(invalid_operator(field, format!("{op:?}")));
571 }
572
573 let Value::List(items) = value else {
574 return Err(invalid_literal(field, "expected list literal"));
575 };
576
577 for item in items {
578 ensure_coercion(field, field_type, item, coercion)?;
579 }
580
581 Ok(())
582}
583
584fn validate_contains(
586 field: &str,
587 field_type: &FieldType,
588 value: &Value,
589 coercion: &CoercionSpec,
590) -> Result<(), ValidateError> {
591 if field_type.is_text() {
592 return Err(invalid_operator(
594 field,
595 format!("{:?}", CompareOp::Contains),
596 ));
597 }
598
599 let element_type = match field_type {
600 FieldType::List(inner) | FieldType::Set(inner) => inner.as_ref(),
601 _ => {
602 return Err(invalid_operator(
603 field,
604 format!("{:?}", CompareOp::Contains),
605 ));
606 }
607 };
608
609 if matches!(coercion.id, CoercionId::TextCasefold) {
610 return Err(ValidateError::InvalidCoercion {
612 field: field.to_string(),
613 coercion: coercion.id,
614 });
615 }
616
617 ensure_coercion(field, element_type, value, coercion)
618}
619
620fn validate_text_compare(
622 field: &str,
623 field_type: &FieldType,
624 value: &Value,
625 coercion: &CoercionSpec,
626 op: CompareOp,
627) -> Result<(), ValidateError> {
628 if !field_type.is_text() {
629 return Err(invalid_operator(field, format!("{op:?}")));
630 }
631
632 ensure_text_literal(field, value)?;
633
634 ensure_coercion(field, field_type, value, coercion)
635}
636
637fn ensure_map_types<'a>(
639 schema: &'a SchemaInfo,
640 field: &str,
641 op: &str,
642) -> Result<(&'a FieldType, &'a FieldType), ValidateError> {
643 let field_type = ensure_field(schema, field)?;
644 field_type
645 .map_types()
646 .ok_or_else(|| invalid_operator(field, op))
647}
648
649fn validate_map_key(
650 schema: &SchemaInfo,
651 field: &str,
652 key: &Value,
653 coercion: &CoercionSpec,
654) -> Result<(), ValidateError> {
655 ensure_no_text_casefold(field, coercion)?;
656
657 let (key_type, _) = ensure_map_types(schema, field, "map_contains_key")?;
658
659 ensure_coercion(field, key_type, key, coercion)
660}
661
662fn validate_map_value(
663 schema: &SchemaInfo,
664 field: &str,
665 value: &Value,
666 coercion: &CoercionSpec,
667) -> Result<(), ValidateError> {
668 ensure_no_text_casefold(field, coercion)?;
669
670 let (_, value_type) = ensure_map_types(schema, field, "map_contains_value")?;
671
672 ensure_coercion(field, value_type, value, coercion)
673}
674
675fn validate_map_entry(
676 schema: &SchemaInfo,
677 field: &str,
678 key: &Value,
679 value: &Value,
680 coercion: &CoercionSpec,
681) -> Result<(), ValidateError> {
682 ensure_no_text_casefold(field, coercion)?;
683
684 let (key_type, value_type) = ensure_map_types(schema, field, "map_contains_entry")?;
685
686 ensure_coercion(field, key_type, key, coercion)?;
687 ensure_coercion(field, value_type, value, coercion)?;
688
689 Ok(())
690}
691
692fn validate_text_contains(
694 schema: &SchemaInfo,
695 field: &str,
696 value: &Value,
697 op: &str,
698) -> Result<(), ValidateError> {
699 let field_type = ensure_field(schema, field)?;
700 if !field_type.is_text() {
701 return Err(invalid_operator(field, op));
702 }
703
704 ensure_text_literal(field, value)?;
705
706 Ok(())
707}
708
709fn ensure_field<'a>(schema: &'a SchemaInfo, field: &str) -> Result<&'a FieldType, ValidateError> {
710 let field_type = schema
711 .field(field)
712 .ok_or_else(|| ValidateError::UnknownField {
713 field: field.to_string(),
714 })?;
715
716 if matches!(field_type, FieldType::Map { .. }) {
719 return Err(ValidateError::MapFieldNotQueryable {
720 field: field.to_string(),
721 });
722 }
723
724 if matches!(field_type, FieldType::Unsupported) {
725 return Err(ValidateError::UnsupportedFieldType {
726 field: field.to_string(),
727 });
728 }
729
730 Ok(field_type)
731}
732
733fn ensure_field_exists<'a>(
734 schema: &'a SchemaInfo,
735 field: &str,
736) -> Result<&'a FieldType, ValidateError> {
737 schema
738 .field(field)
739 .ok_or_else(|| ValidateError::UnknownField {
740 field: field.to_string(),
741 })
742}
743
744fn invalid_operator(field: &str, op: impl fmt::Display) -> ValidateError {
745 ValidateError::InvalidOperator {
746 field: field.to_string(),
747 op: op.to_string(),
748 }
749}
750
751fn invalid_literal(field: &str, msg: &str) -> ValidateError {
752 ValidateError::InvalidLiteral {
753 field: field.to_string(),
754 message: msg.to_string(),
755 }
756}
757
758fn ensure_no_text_casefold(field: &str, coercion: &CoercionSpec) -> Result<(), ValidateError> {
760 if matches!(coercion.id, CoercionId::TextCasefold) {
761 return Err(ValidateError::InvalidCoercion {
762 field: field.to_string(),
763 coercion: coercion.id,
764 });
765 }
766
767 Ok(())
768}
769
770fn ensure_text_literal(field: &str, value: &Value) -> Result<(), ValidateError> {
772 if !matches!(value, Value::Text(_)) {
773 return Err(invalid_literal(field, "expected text literal"));
774 }
775
776 Ok(())
777}
778
779fn ensure_scalar_literal(field: &str, value: &Value) -> Result<(), ValidateError> {
781 if matches!(value, Value::List(_)) {
782 return Err(invalid_literal(field, "expected scalar literal"));
783 }
784
785 Ok(())
786}
787
788fn ensure_coercion(
789 field: &str,
790 field_type: &FieldType,
791 literal: &Value,
792 coercion: &CoercionSpec,
793) -> Result<(), ValidateError> {
794 if matches!(coercion.id, CoercionId::TextCasefold) && !field_type.is_text() {
795 return Err(ValidateError::InvalidCoercion {
797 field: field.to_string(),
798 coercion: coercion.id,
799 });
800 }
801
802 if matches!(coercion.id, CoercionId::NumericWiden)
807 && (!field_type.supports_numeric_coercion() || !literal.supports_numeric_coercion())
808 {
809 return Err(ValidateError::InvalidCoercion {
810 field: field.to_string(),
811 coercion: coercion.id,
812 });
813 }
814
815 if !matches!(coercion.id, CoercionId::NumericWiden) {
816 let left_family =
817 field_type
818 .coercion_family()
819 .ok_or_else(|| ValidateError::UnsupportedFieldType {
820 field: field.to_string(),
821 })?;
822 let right_family = literal.coercion_family();
823
824 if !supports_coercion(left_family, right_family, coercion.id) {
825 return Err(ValidateError::InvalidCoercion {
826 field: field.to_string(),
827 coercion: coercion.id,
828 });
829 }
830 }
831
832 if matches!(
833 coercion.id,
834 CoercionId::Strict | CoercionId::CollectionElement
835 ) && !literal_matches_type(literal, field_type)
836 {
837 return Err(invalid_literal(
838 field,
839 "literal type does not match field type",
840 ));
841 }
842
843 Ok(())
844}
845
846fn ensure_list_literal(
847 field: &str,
848 literal: &Value,
849 field_type: &FieldType,
850) -> Result<(), ValidateError> {
851 if !literal_matches_type(literal, field_type) {
852 return Err(invalid_literal(
853 field,
854 "list literal does not match field element type",
855 ));
856 }
857
858 Ok(())
859}
860
861fn ensure_map_literal(
862 field: &str,
863 literal: &Value,
864 field_type: &FieldType,
865) -> Result<(), ValidateError> {
866 if !literal_matches_type(literal, field_type) {
867 return Err(invalid_literal(
868 field,
869 "map literal does not match field key/value types",
870 ));
871 }
872
873 Ok(())
874}
875
876pub(crate) fn literal_matches_type(literal: &Value, field_type: &FieldType) -> bool {
877 match field_type {
878 FieldType::Scalar(inner) => inner.matches_value(literal),
879 FieldType::List(element) | FieldType::Set(element) => match literal {
880 Value::List(items) => items.iter().all(|item| literal_matches_type(item, element)),
881 _ => false,
882 },
883 FieldType::Map { key, value } => match literal {
884 Value::List(entries) => entries.iter().all(|entry| match entry {
885 Value::List(pair) if pair.len() == 2 => {
886 literal_matches_type(&pair[0], key) && literal_matches_type(&pair[1], value)
887 }
888 _ => false,
889 }),
890 _ => false,
891 },
892 FieldType::Unsupported => {
893 false
895 }
896 }
897}
898
899fn field_type_from_model_kind(kind: &EntityFieldKind) -> FieldType {
900 match kind {
901 EntityFieldKind::Account => FieldType::Scalar(ScalarType::Account),
902 EntityFieldKind::Blob => FieldType::Scalar(ScalarType::Blob),
903 EntityFieldKind::Bool => FieldType::Scalar(ScalarType::Bool),
904 EntityFieldKind::Date => FieldType::Scalar(ScalarType::Date),
905 EntityFieldKind::Decimal => FieldType::Scalar(ScalarType::Decimal),
906 EntityFieldKind::Duration => FieldType::Scalar(ScalarType::Duration),
907 EntityFieldKind::Enum => FieldType::Scalar(ScalarType::Enum),
908 EntityFieldKind::E8s => FieldType::Scalar(ScalarType::E8s),
909 EntityFieldKind::E18s => FieldType::Scalar(ScalarType::E18s),
910 EntityFieldKind::Float32 => FieldType::Scalar(ScalarType::Float32),
911 EntityFieldKind::Float64 => FieldType::Scalar(ScalarType::Float64),
912 EntityFieldKind::Int => FieldType::Scalar(ScalarType::Int),
913 EntityFieldKind::Int128 => FieldType::Scalar(ScalarType::Int128),
914 EntityFieldKind::IntBig => FieldType::Scalar(ScalarType::IntBig),
915 EntityFieldKind::Principal => FieldType::Scalar(ScalarType::Principal),
916 EntityFieldKind::Subaccount => FieldType::Scalar(ScalarType::Subaccount),
917 EntityFieldKind::Text => FieldType::Scalar(ScalarType::Text),
918 EntityFieldKind::Timestamp => FieldType::Scalar(ScalarType::Timestamp),
919 EntityFieldKind::Uint => FieldType::Scalar(ScalarType::Uint),
920 EntityFieldKind::Uint128 => FieldType::Scalar(ScalarType::Uint128),
921 EntityFieldKind::UintBig => FieldType::Scalar(ScalarType::UintBig),
922 EntityFieldKind::Ulid => FieldType::Scalar(ScalarType::Ulid),
923 EntityFieldKind::Unit => FieldType::Scalar(ScalarType::Unit),
924 EntityFieldKind::Ref { key_kind, .. } => field_type_from_model_kind(key_kind),
925 EntityFieldKind::List(inner) => {
926 FieldType::List(Box::new(field_type_from_model_kind(inner)))
927 }
928 EntityFieldKind::Set(inner) => FieldType::Set(Box::new(field_type_from_model_kind(inner))),
929 EntityFieldKind::Map { key, value } => FieldType::Map {
930 key: Box::new(field_type_from_model_kind(key)),
931 value: Box::new(field_type_from_model_kind(value)),
932 },
933 EntityFieldKind::Unsupported => FieldType::Unsupported,
934 }
935}
936
937impl fmt::Display for FieldType {
938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939 match self {
940 Self::Scalar(inner) => write!(f, "{inner:?}"),
941 Self::List(inner) => write!(f, "List<{inner}>"),
942 Self::Set(inner) => write!(f, "Set<{inner}>"),
943 Self::Map { key, value } => write!(f, "Map<{key}, {value}>"),
944 Self::Unsupported => write!(f, "Unsupported"),
945 }
946 }
947}
948
949#[cfg(test)]
954mod tests {
955 use super::{FieldType, ScalarType, ValidateError, ensure_coercion, validate_model};
957 use crate::{
958 db::query::{
959 FieldRef,
960 predicate::{CoercionId, CoercionSpec, Predicate},
961 },
962 model::field::{EntityFieldKind, EntityFieldModel},
963 test_fixtures::InvalidEntityModelBuilder,
964 traits::EntitySchema,
965 types::{
966 Account, Date, Decimal, Duration, E8s, E18s, Float32, Float64, Int, Int128, Nat,
967 Nat128, Principal, Subaccount, Timestamp, Ulid,
968 },
969 value::{CoercionFamily, Value, ValueEnum},
970 };
971 use std::collections::BTreeSet;
972
973 fn registry_scalars() -> Vec<ScalarType> {
975 macro_rules! collect_scalars {
976 ( @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
977 vec![ $( ScalarType::$scalar ),* ]
978 };
979 ( @args $($ignore:tt)*; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
980 vec![ $( ScalarType::$scalar ),* ]
981 };
982 }
983
984 let scalars = scalar_registry!(collect_scalars);
985
986 scalars
987 }
988
989 const SCALAR_TYPE_VARIANT_COUNT: usize = 23;
991
992 fn scalar_index(scalar: ScalarType) -> usize {
994 match scalar {
995 ScalarType::Account => 0,
996 ScalarType::Blob => 1,
997 ScalarType::Bool => 2,
998 ScalarType::Date => 3,
999 ScalarType::Decimal => 4,
1000 ScalarType::Duration => 5,
1001 ScalarType::Enum => 6,
1002 ScalarType::E8s => 7,
1003 ScalarType::E18s => 8,
1004 ScalarType::Float32 => 9,
1005 ScalarType::Float64 => 10,
1006 ScalarType::Int => 11,
1007 ScalarType::Int128 => 12,
1008 ScalarType::IntBig => 13,
1009 ScalarType::Principal => 14,
1010 ScalarType::Subaccount => 15,
1011 ScalarType::Text => 16,
1012 ScalarType::Timestamp => 17,
1013 ScalarType::Uint => 18,
1014 ScalarType::Uint128 => 19,
1015 ScalarType::UintBig => 20,
1016 ScalarType::Ulid => 21,
1017 ScalarType::Unit => 22,
1018 }
1019 }
1020
1021 fn scalar_from_index(index: usize) -> Option<ScalarType> {
1023 let scalar = match index {
1024 0 => ScalarType::Account,
1025 1 => ScalarType::Blob,
1026 2 => ScalarType::Bool,
1027 3 => ScalarType::Date,
1028 4 => ScalarType::Decimal,
1029 5 => ScalarType::Duration,
1030 6 => ScalarType::Enum,
1031 7 => ScalarType::E8s,
1032 8 => ScalarType::E18s,
1033 9 => ScalarType::Float32,
1034 10 => ScalarType::Float64,
1035 11 => ScalarType::Int,
1036 12 => ScalarType::Int128,
1037 13 => ScalarType::IntBig,
1038 14 => ScalarType::Principal,
1039 15 => ScalarType::Subaccount,
1040 16 => ScalarType::Text,
1041 17 => ScalarType::Timestamp,
1042 18 => ScalarType::Uint,
1043 19 => ScalarType::Uint128,
1044 20 => ScalarType::UintBig,
1045 21 => ScalarType::Ulid,
1046 22 => ScalarType::Unit,
1047 _ => return None,
1048 };
1049
1050 Some(scalar)
1051 }
1052
1053 fn sample_value_for_scalar(scalar: ScalarType) -> Value {
1055 match scalar {
1056 ScalarType::Account => Value::Account(Account::dummy(1)),
1057 ScalarType::Blob => Value::Blob(vec![0u8, 1u8]),
1058 ScalarType::Bool => Value::Bool(true),
1059 ScalarType::Date => Value::Date(Date::EPOCH),
1060 ScalarType::Decimal => Value::Decimal(Decimal::ZERO),
1061 ScalarType::Duration => Value::Duration(Duration::ZERO),
1062 ScalarType::Enum => Value::Enum(ValueEnum::loose("example")),
1063 ScalarType::E8s => Value::E8s(E8s::from_atomic(0)),
1064 ScalarType::E18s => Value::E18s(E18s::from_atomic(0)),
1065 ScalarType::Float32 => {
1066 Value::Float32(Float32::try_new(0.0).expect("Float32 sample should be finite"))
1067 }
1068 ScalarType::Float64 => {
1069 Value::Float64(Float64::try_new(0.0).expect("Float64 sample should be finite"))
1070 }
1071 ScalarType::Int => Value::Int(0),
1072 ScalarType::Int128 => Value::Int128(Int128::from(0i128)),
1073 ScalarType::IntBig => Value::IntBig(Int::from(0i32)),
1074 ScalarType::Principal => Value::Principal(Principal::anonymous()),
1075 ScalarType::Subaccount => Value::Subaccount(Subaccount::dummy(2)),
1076 ScalarType::Text => Value::Text("text".to_string()),
1077 ScalarType::Timestamp => Value::Timestamp(Timestamp::EPOCH),
1078 ScalarType::Uint => Value::Uint(0),
1079 ScalarType::Uint128 => Value::Uint128(Nat128::from(0u128)),
1080 ScalarType::UintBig => Value::UintBig(Nat::from(0u64)),
1081 ScalarType::Ulid => Value::Ulid(Ulid::nil()),
1082 ScalarType::Unit => Value::Unit,
1083 }
1084 }
1085
1086 fn field(name: &'static str, kind: EntityFieldKind) -> EntityFieldModel {
1087 EntityFieldModel { name, kind }
1088 }
1089
1090 crate::test_entity_schema! {
1091 ScalarPredicateEntity,
1092 id = Ulid,
1093 path = "predicate_validate::ScalarEntity",
1094 entity_name = "ScalarEntity",
1095 primary_key = "id",
1096 pk_index = 0,
1097 fields = [
1098 ("id", EntityFieldKind::Ulid),
1099 ("email", EntityFieldKind::Text),
1100 ("age", EntityFieldKind::Uint),
1101 ("created_at", EntityFieldKind::Timestamp),
1102 ("active", EntityFieldKind::Bool),
1103 ],
1104 indexes = [],
1105 }
1106
1107 crate::test_entity_schema! {
1108 CollectionPredicateEntity,
1109 id = Ulid,
1110 path = "predicate_validate::CollectionEntity",
1111 entity_name = "CollectionEntity",
1112 primary_key = "id",
1113 pk_index = 0,
1114 fields = [
1115 ("id", EntityFieldKind::Ulid),
1116 ("tags", EntityFieldKind::List(&EntityFieldKind::Text)),
1117 ("principals", EntityFieldKind::Set(&EntityFieldKind::Principal)),
1118 (
1119 "attributes",
1120 EntityFieldKind::Map {
1121 key: &EntityFieldKind::Text,
1122 value: &EntityFieldKind::Uint,
1123 }
1124 ),
1125 ],
1126 indexes = [],
1127 }
1128
1129 crate::test_entity_schema! {
1130 NumericCoercionPredicateEntity,
1131 id = Ulid,
1132 path = "predicate_validate::NumericCoercionEntity",
1133 entity_name = "NumericCoercionEntity",
1134 primary_key = "id",
1135 pk_index = 0,
1136 fields = [
1137 ("id", EntityFieldKind::Ulid),
1138 ("date", EntityFieldKind::Date),
1139 ("int_big", EntityFieldKind::IntBig),
1140 ("uint_big", EntityFieldKind::UintBig),
1141 ("int_small", EntityFieldKind::Int),
1142 ("uint_small", EntityFieldKind::Uint),
1143 ("decimal", EntityFieldKind::Decimal),
1144 ("e8s", EntityFieldKind::E8s),
1145 ],
1146 indexes = [],
1147 }
1148
1149 #[test]
1150 fn validate_model_accepts_scalars_and_coercions() {
1151 let model = <ScalarPredicateEntity as EntitySchema>::MODEL;
1152
1153 let predicate = Predicate::And(vec![
1154 FieldRef::new("id").eq(Ulid::nil()),
1155 FieldRef::new("email").text_eq_ci("User@example.com"),
1156 FieldRef::new("age").lt(30u32),
1157 ]);
1158
1159 assert!(validate_model(model, &predicate).is_ok());
1160 }
1161
1162 #[test]
1163 fn validate_model_rejects_map_predicates_in_0_7_x() {
1164 let model = <CollectionPredicateEntity as EntitySchema>::MODEL;
1165
1166 let allowed = Predicate::And(vec![
1168 FieldRef::new("tags").is_empty(),
1169 FieldRef::new("principals").is_not_empty(),
1170 ]);
1171 assert!(validate_model(model, &allowed).is_ok());
1172
1173 let map_contains =
1174 FieldRef::new("attributes").map_contains_entry("k", 1u64, CoercionId::Strict);
1175 assert!(matches!(
1176 validate_model(model, &map_contains),
1177 Err(ValidateError::MapFieldNotQueryable { field }) if field == "attributes"
1178 ));
1179
1180 let map_presence = Predicate::IsMissing {
1181 field: "attributes".to_string(),
1182 };
1183 assert!(matches!(
1184 validate_model(model, &map_presence),
1185 Err(ValidateError::MapFieldNotQueryable { field }) if field == "attributes"
1186 ));
1187 }
1188
1189 #[test]
1190 fn validate_model_rejects_unsupported_fields() {
1191 let model = InvalidEntityModelBuilder::from_fields(
1192 vec![
1193 field("id", EntityFieldKind::Ulid),
1194 field("broken", EntityFieldKind::Unsupported),
1195 ],
1196 0,
1197 );
1198
1199 let predicate = FieldRef::new("broken").eq(1u64);
1200
1201 assert!(matches!(
1202 validate_model(&model, &predicate),
1203 Err(ValidateError::UnsupportedFieldType { field }) if field == "broken"
1204 ));
1205 }
1206
1207 #[test]
1208 fn validate_model_accepts_text_contains() {
1209 let model = <ScalarPredicateEntity as EntitySchema>::MODEL;
1210
1211 let predicate = FieldRef::new("email").text_contains("example");
1212 assert!(validate_model(model, &predicate).is_ok());
1213
1214 let predicate = FieldRef::new("email").text_contains_ci("EXAMPLE");
1215 assert!(validate_model(model, &predicate).is_ok());
1216 }
1217
1218 #[test]
1219 fn validate_model_rejects_text_contains_on_non_text() {
1220 let model = <ScalarPredicateEntity as EntitySchema>::MODEL;
1221
1222 let predicate = FieldRef::new("age").text_contains("1");
1223 assert!(matches!(
1224 validate_model(model, &predicate),
1225 Err(ValidateError::InvalidOperator { field, op })
1226 if field == "age" && op == "text_contains"
1227 ));
1228 }
1229
1230 #[test]
1231 fn validate_model_rejects_numeric_widen_for_registry_exclusions() {
1232 let model = <NumericCoercionPredicateEntity as EntitySchema>::MODEL;
1233
1234 let date_pred = FieldRef::new("date").lt(1i64);
1235 assert!(matches!(
1236 validate_model(model, &date_pred),
1237 Err(ValidateError::InvalidCoercion { field, coercion })
1238 if field == "date" && coercion == CoercionId::NumericWiden
1239 ));
1240
1241 let int_big_pred = FieldRef::new("int_big").lt(Int::from(1i32));
1242 assert!(matches!(
1243 validate_model(model, &int_big_pred),
1244 Err(ValidateError::InvalidCoercion { field, coercion })
1245 if field == "int_big" && coercion == CoercionId::NumericWiden
1246 ));
1247
1248 let uint_big_pred = FieldRef::new("uint_big").lt(Nat::from(1u64));
1249 assert!(matches!(
1250 validate_model(model, &uint_big_pred),
1251 Err(ValidateError::InvalidCoercion { field, coercion })
1252 if field == "uint_big" && coercion == CoercionId::NumericWiden
1253 ));
1254 }
1255
1256 #[test]
1257 fn validate_model_accepts_numeric_widen_for_registry_allowed_scalars() {
1258 let model = <NumericCoercionPredicateEntity as EntitySchema>::MODEL;
1259 let predicate = Predicate::And(vec![
1260 FieldRef::new("int_small").lt(9u64),
1261 FieldRef::new("uint_small").lt(9i64),
1262 FieldRef::new("decimal").lt(9u64),
1263 FieldRef::new("e8s").lt(9u64),
1264 ]);
1265
1266 assert!(validate_model(model, &predicate).is_ok());
1267 }
1268
1269 #[test]
1270 fn numeric_widen_authority_tracks_registry_flags() {
1271 for scalar in registry_scalars() {
1272 let field_type = FieldType::Scalar(scalar.clone());
1273 let literal = sample_value_for_scalar(scalar.clone());
1274 let expected = scalar.supports_numeric_coercion();
1275 let actual = ensure_coercion(
1276 "value",
1277 &field_type,
1278 &literal,
1279 &CoercionSpec::new(CoercionId::NumericWiden),
1280 )
1281 .is_ok();
1282
1283 assert_eq!(
1284 actual, expected,
1285 "numeric widen drift for scalar {scalar:?}: expected {expected}, got {actual}"
1286 );
1287 }
1288 }
1289
1290 #[test]
1291 fn numeric_widen_is_not_inferred_from_coercion_family() {
1292 let mut numeric_family_with_no_numeric_widen = 0usize;
1293
1294 for scalar in registry_scalars() {
1295 if scalar.coercion_family() != CoercionFamily::Numeric {
1296 continue;
1297 }
1298
1299 let field_type = FieldType::Scalar(scalar.clone());
1300 let literal = sample_value_for_scalar(scalar.clone());
1301 let numeric_widen_allowed = ensure_coercion(
1302 "value",
1303 &field_type,
1304 &literal,
1305 &CoercionSpec::new(CoercionId::NumericWiden),
1306 )
1307 .is_ok();
1308
1309 assert_eq!(
1310 numeric_widen_allowed,
1311 scalar.supports_numeric_coercion(),
1312 "numeric family must not imply numeric widen for scalar {scalar:?}"
1313 );
1314
1315 if !scalar.supports_numeric_coercion() {
1316 numeric_family_with_no_numeric_widen =
1317 numeric_family_with_no_numeric_widen.saturating_add(1);
1318 }
1319 }
1320
1321 assert!(
1322 numeric_family_with_no_numeric_widen > 0,
1323 "expected at least one numeric-family scalar without numeric widen support"
1324 );
1325 }
1326
1327 #[test]
1328 fn scalar_registry_covers_all_variants_exactly_once() {
1329 let scalars = registry_scalars();
1330 let mut names = BTreeSet::new();
1331 let mut seen = [false; SCALAR_TYPE_VARIANT_COUNT];
1332
1333 for scalar in scalars {
1334 let index = scalar_index(scalar.clone());
1335 assert!(!seen[index], "duplicate scalar entry: {scalar:?}");
1336 seen[index] = true;
1337
1338 let name = format!("{scalar:?}");
1339 assert!(names.insert(name.clone()), "duplicate scalar entry: {name}");
1340 }
1341
1342 let mut missing = Vec::new();
1343 for (index, was_seen) in seen.iter().enumerate() {
1344 if !*was_seen {
1345 let scalar = scalar_from_index(index).expect("index is in range");
1346 missing.push(format!("{scalar:?}"));
1347 }
1348 }
1349
1350 assert!(missing.is_empty(), "missing scalar entries: {missing:?}");
1351 assert_eq!(names.len(), SCALAR_TYPE_VARIANT_COUNT);
1352 }
1353
1354 #[test]
1355 fn scalar_keyability_matches_value_storage_key() {
1356 for scalar in registry_scalars() {
1357 let value = sample_value_for_scalar(scalar.clone());
1358 let scalar_keyable = scalar.is_keyable();
1359 let value_keyable = value.as_storage_key().is_some();
1360
1361 assert_eq!(
1362 value_keyable, scalar_keyable,
1363 "Value::as_storage_key drift for scalar {scalar:?}"
1364 );
1365 }
1366 }
1367}