1use std::collections::BTreeMap;
27use std::fmt;
28
29use chrono::NaiveDateTime;
30use itertools::Itertools;
31use serde_json::Value as JsonValue;
32
33use crate::schema::{RecordField, SchemaNode, SchemaPiece, SchemaPieceOrNamed};
34
35#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct SchemaResolutionError(pub String);
38
39impl SchemaResolutionError {
40 pub fn new<S>(msg: S) -> SchemaResolutionError
41 where
42 S: Into<String>,
43 {
44 SchemaResolutionError(msg.into())
45 }
46}
47
48impl fmt::Display for SchemaResolutionError {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50 self.0.fmt(f)
51 }
52}
53
54impl std::error::Error for SchemaResolutionError {}
55
56#[derive(Clone, Debug, PartialEq)]
57pub struct DecimalValue {
58 pub unscaled: Vec<u8>,
60 pub precision: usize,
61 pub scale: usize,
62}
63
64#[derive(Clone, Copy, Debug, PartialEq)] pub enum Scalar {
66 Null,
67 Boolean(bool),
68 Int(i32),
69 Long(i64),
70 Float(f32),
71 Double(f64),
72 Date(i32),
73 Timestamp(NaiveDateTime),
74}
75
76impl From<Scalar> for Value {
77 fn from(s: Scalar) -> Self {
78 match s {
79 Scalar::Null => Value::Null,
80 Scalar::Boolean(v) => Value::Boolean(v),
81 Scalar::Int(v) => Value::Int(v),
82 Scalar::Long(v) => Value::Long(v),
83 Scalar::Float(v) => Value::Float(v),
84 Scalar::Double(v) => Value::Double(v),
85 Scalar::Date(v) => Value::Date(v),
86 Scalar::Timestamp(v) => Value::Timestamp(v),
87 }
88 }
89}
90
91#[derive(Clone, Debug, PartialEq)]
95pub enum Value {
96 Null,
99 Boolean(bool),
101 Int(i32),
103 Long(i64),
105 Float(f32),
107 Double(f64),
109 Date(i32),
112 Timestamp(NaiveDateTime),
114
115 Decimal(DecimalValue),
121 Bytes(Vec<u8>),
123 String(String),
125 Fixed(usize, Vec<u8>),
128 Enum(usize, String),
135 Union {
137 index: usize,
139 inner: Box<Value>,
141 n_variants: usize,
144 null_variant: Option<usize>,
146 },
147 Array(Vec<Value>),
149 Map(BTreeMap<String, Value>),
151 Record(Vec<(String, Value)>),
158 Json(serde_json::Value),
163 Uuid(uuid::Uuid),
165}
166
167pub trait ToAvro {
170 fn avro(self) -> Value;
172}
173
174macro_rules! to_avro(
175 ($t:ty, $v:expr) => (
176 impl ToAvro for $t {
177 fn avro(self) -> Value {
178 $v(self)
179 }
180 }
181 );
182);
183
184to_avro!(bool, Value::Boolean);
185to_avro!(i32, Value::Int);
186to_avro!(i64, Value::Long);
187to_avro!(f32, Value::Float);
188to_avro!(f64, Value::Double);
189to_avro!(String, Value::String);
190
191impl ToAvro for () {
192 fn avro(self) -> Value {
193 Value::Null
194 }
195}
196
197impl ToAvro for usize {
198 fn avro(self) -> Value {
199 (self as i64).avro()
200 }
201}
202
203impl<'a> ToAvro for &'a str {
204 fn avro(self) -> Value {
205 Value::String(self.to_owned())
206 }
207}
208
209impl<'a> ToAvro for &'a [u8] {
210 fn avro(self) -> Value {
211 Value::Bytes(self.to_owned())
212 }
213}
214
215impl<T> ToAvro for BTreeMap<String, T>
216where
217 T: ToAvro,
218{
219 fn avro(self) -> Value {
220 Value::Map(
221 self.into_iter()
222 .map(|(key, value)| (key, value.avro()))
223 .collect::<_>(),
224 )
225 }
226}
227
228impl<'a, T> ToAvro for BTreeMap<&'a str, T>
229where
230 T: ToAvro,
231{
232 fn avro(self) -> Value {
233 Value::Map(
234 self.into_iter()
235 .map(|(key, value)| (key.to_owned(), value.avro()))
236 .collect::<_>(),
237 )
238 }
239}
240
241impl ToAvro for Value {
242 fn avro(self) -> Value {
243 self
244 }
245}
246
247impl Default for Value {
258 fn default() -> Self {
259 Value::Null
260 }
261}
262
263#[derive(Debug, Clone)]
265pub struct Record<'a> {
266 pub fields: Vec<(String, Value)>,
270 schema_lookup: &'a BTreeMap<String, usize>,
271 schema_fields: &'a Vec<RecordField>,
272}
273
274impl<'a> Record<'a> {
275 pub fn new(schema: SchemaNode<'a>) -> Option<Record<'a>> {
279 let ret = match schema.inner {
280 SchemaPiece::Record {
281 fields: schema_fields,
282 lookup: schema_lookup,
283 ..
284 } => {
285 let mut fields = Vec::with_capacity(schema_fields.len());
286 for schema_field in schema_fields.iter() {
287 fields.push((schema_field.name.clone(), Value::Null));
288 }
289
290 Some(Record {
291 fields,
292 schema_lookup,
293 schema_fields,
294 })
295 }
296 _ => None,
297 };
298 ret
299 }
300
301 pub fn put<V>(&mut self, field: &str, value: V)
307 where
308 V: ToAvro,
309 {
310 if let Some(&position) = self.schema_lookup.get(field) {
311 self.fields[position].1 = value.avro()
312 }
313 }
314
315 pub fn field_by_name(&self, name: &str) -> Option<&'a RecordField> {
317 self.schema_lookup
318 .get(name)
319 .map(|idx| &self.schema_fields[*idx])
320 }
321}
322
323impl<'a> ToAvro for Record<'a> {
324 fn avro(self) -> Value {
325 Value::Record(self.fields)
326 }
327}
328
329impl ToAvro for JsonValue {
330 fn avro(self) -> Value {
331 match self {
332 JsonValue::Null => Value::Null,
333 JsonValue::Bool(b) => Value::Boolean(b),
334 JsonValue::Number(ref n) if n.is_i64() => Value::Long(n.as_i64().unwrap()),
335 JsonValue::Number(ref n) if n.is_f64() => Value::Double(n.as_f64().unwrap()),
336 JsonValue::Number(n) => Value::Long(n.as_u64().unwrap() as i64), JsonValue::String(s) => Value::String(s),
338 JsonValue::Array(items) => {
339 Value::Array(items.into_iter().map(|item| item.avro()).collect::<_>())
340 }
341 JsonValue::Object(items) => Value::Map(
342 items
343 .into_iter()
344 .map(|(key, value)| (key, value.avro()))
345 .collect::<_>(),
346 ),
347 }
348 }
349}
350
351impl Value {
352 pub fn validate(&self, schema: SchemaNode) -> bool {
357 match (self, schema.inner) {
358 (&Value::Null, SchemaPiece::Null) => true,
359 (&Value::Boolean(_), SchemaPiece::Boolean) => true,
360 (&Value::Int(_), SchemaPiece::Int) => true,
361 (&Value::Long(_), SchemaPiece::Long) => true,
362 (&Value::Float(_), SchemaPiece::Float) => true,
363 (&Value::Double(_), SchemaPiece::Double) => true,
364 (&Value::Date(_), SchemaPiece::Date) => true,
365 (&Value::Timestamp(_), SchemaPiece::TimestampMicro) => true,
366 (&Value::Timestamp(_), SchemaPiece::TimestampMilli) => true,
367 (
368 &Value::Decimal(DecimalValue {
369 precision: vp,
370 scale: vs,
371 ..
372 }),
373 SchemaPiece::Decimal {
374 precision: sp,
375 scale: ss,
376 fixed_size: _,
377 },
378 ) => vp == *sp && vs == *ss,
379 (&Value::Bytes(_), SchemaPiece::Bytes) => true,
380 (&Value::String(_), SchemaPiece::String) => true,
381 (&Value::Fixed(n, _), SchemaPiece::Fixed { size }) => n == *size,
382 (&Value::String(ref s), SchemaPiece::Enum { symbols, .. }) => symbols.contains(s),
383 (&Value::Enum(i, ref s), SchemaPiece::Enum { symbols, .. }) => {
384 symbols.get(i).map(|symbol| symbol == s).unwrap_or(false)
385 }
386 (
387 &Value::Union {
388 index,
389 ref inner,
390 n_variants,
391 null_variant,
392 },
393 SchemaPiece::Union(schema_inner),
394 ) => {
395 schema_inner.variants().len() > index
396 && n_variants == schema_inner.variants().len()
397 && inner.validate(schema.step(&schema_inner.variants()[index]))
398 && match null_variant {
399 None => !schema_inner
400 .variants()
401 .iter()
402 .any(|v| v == &SchemaPieceOrNamed::Piece(SchemaPiece::Null)),
403 Some(null_variant_idx) => {
404 schema_inner.variants().get(null_variant_idx)
405 == Some(&SchemaPieceOrNamed::Piece(SchemaPiece::Null))
406 }
407 }
408 }
409 (&Value::Array(ref items), SchemaPiece::Array(inner)) => {
410 let node = schema.step(&**inner);
411 items.iter().all(|item| item.validate(node))
412 }
413 (&Value::Map(ref items), SchemaPiece::Map(inner)) => {
414 let node = schema.step(&**inner);
415 items.iter().all(|(_, value)| value.validate(node))
416 }
417 (&Value::Record(ref record_fields), SchemaPiece::Record { fields, .. }) => {
418 fields.len() == record_fields.len()
419 && fields.iter().zip_eq(record_fields.iter()).all(
420 |(field, &(ref name, ref value))| {
421 let node = schema.step(&field.schema);
422 field.name == *name && value.validate(node)
423 },
424 )
425 }
426 (Value::Json(_), SchemaPiece::Json) => true,
427 (Value::Uuid(_), SchemaPiece::Uuid) => true,
428 _ => false,
429 }
430 }
431
432 pub fn into_string(self) -> Option<String> {
434 match self {
435 Value::String(s) => Some(s),
436 _ => None,
437 }
438 }
439
440 pub fn into_nullable_bool(self) -> Option<bool> {
441 match self {
442 Value::Boolean(b) => Some(b),
443 Value::Union { inner, .. } => inner.into_nullable_bool(),
444 _ => None,
445 }
446 }
447
448 pub fn into_integral(self) -> Option<i64> {
449 match self {
450 Value::Int(i) => Some(i as i64),
451 Value::Long(l) => Some(l),
452 _ => None,
453 }
454 }
455
456 pub fn into_usize(self) -> Option<usize> {
457 self.into_integral().and_then(|i| i.try_into().ok())
458 }
459}
460
461#[cfg(test)]
462mod tests {
463 use std::str::FromStr;
464
465 use crate::Schema;
466
467 use super::*;
468
469 #[mz_ore::test]
470 fn validate() {
471 let value_schema_valid = vec![
472 (Value::Int(42), "\"int\"", true),
473 (Value::Int(42), "\"boolean\"", false),
474 (
475 Value::Union {
476 index: 0,
477 inner: Box::new(Value::Null),
478 n_variants: 2,
479 null_variant: Some(0),
480 },
481 r#"["null", "int"]"#,
482 true,
483 ),
484 (
485 Value::Union {
486 index: 1,
487 inner: Box::new(Value::Int(42)),
488 n_variants: 2,
489 null_variant: Some(0),
490 },
491 r#"["null", "int"]"#,
492 true,
493 ),
494 (
495 Value::Union {
496 index: 1,
497 inner: Box::new(Value::Null),
498 n_variants: 2,
499 null_variant: Some(1),
500 },
501 r#"["double", "int"]"#,
502 false,
503 ),
504 (
505 Value::Union {
506 index: 3,
507 inner: Box::new(Value::Int(42)),
508 n_variants: 4,
509 null_variant: Some(0),
510 },
511 r#"["null", "double", "string", "int"]"#,
512 true,
513 ),
514 (
515 Value::Array(vec![Value::Long(42i64)]),
516 r#"{"type": "array", "items": "long"}"#,
517 true,
518 ),
519 (
520 Value::Array(vec![Value::Boolean(true)]),
521 r#"{"type": "array", "items": "long"}"#,
522 false,
523 ),
524 (Value::Record(vec![]), "\"null\"", false),
525 ];
526
527 for (value, schema_str, valid) in value_schema_valid.into_iter() {
528 let schema = Schema::from_str(schema_str).unwrap();
529 assert_eq!(
530 valid,
531 value.validate(schema.top_node()),
532 "Schema failed to validate against value: {} {:#?}",
533 schema_str,
534 value
535 );
536 }
537 }
538
539 #[mz_ore::test]
540 fn validate_fixed() {
541 let schema =
542 Schema::from_str(r#"{"type": "fixed", "size": 4, "name": "some_fixed"}"#).unwrap();
543
544 assert!(Value::Fixed(4, vec![0, 0, 0, 0]).validate(schema.top_node()));
545 assert!(!Value::Fixed(5, vec![0, 0, 0, 0, 0]).validate(schema.top_node()));
546 }
547
548 #[mz_ore::test]
549 fn validate_enum() {
550 let schema = Schema::from_str(r#"{"type": "enum", "name": "some_enum", "symbols": ["spades", "hearts", "diamonds", "clubs"]}"#).unwrap();
551
552 assert!(Value::Enum(0, "spades".to_string()).validate(schema.top_node()));
553 assert!(Value::String("spades".to_string()).validate(schema.top_node()));
554
555 assert!(!Value::Enum(1, "spades".to_string()).validate(schema.top_node()));
556 assert!(!Value::String("lorem".to_string()).validate(schema.top_node()));
557
558 let other_schema = Schema::from_str(r#"{"type": "enum", "name": "some_other_enum", "symbols": ["hearts", "diamonds", "clubs", "spades"]}"#).unwrap();
559
560 assert!(!Value::Enum(0, "spades".to_string()).validate(other_schema.top_node()));
561 }
562
563 #[mz_ore::test]
564 fn validate_record() {
565 let schema = Schema::from_str(
566 r#"{
567 "type": "record",
568 "fields": [
569 {"type": "long", "name": "a"},
570 {"type": "string", "name": "b"}
571 ],
572 "name": "some_record"
573 }"#,
574 )
575 .unwrap();
576
577 assert!(
578 Value::Record(vec![
579 ("a".to_string(), Value::Long(42i64)),
580 ("b".to_string(), Value::String("foo".to_string())),
581 ])
582 .validate(schema.top_node())
583 );
584
585 assert!(
586 !Value::Record(vec![
587 ("b".to_string(), Value::String("foo".to_string())),
588 ("a".to_string(), Value::Long(42i64)),
589 ])
590 .validate(schema.top_node())
591 );
592
593 assert!(
594 !Value::Record(vec![
595 ("a".to_string(), Value::Boolean(false)),
596 ("b".to_string(), Value::String("foo".to_string())),
597 ])
598 .validate(schema.top_node())
599 );
600
601 assert!(
602 !Value::Record(vec![
603 ("a".to_string(), Value::Long(42i64)),
604 ("c".to_string(), Value::String("foo".to_string())),
605 ])
606 .validate(schema.top_node())
607 );
608
609 assert!(
610 !Value::Record(vec![
611 ("a".to_string(), Value::Long(42i64)),
612 ("b".to_string(), Value::String("foo".to_string())),
613 ("c".to_string(), Value::Null),
614 ])
615 .validate(schema.top_node())
616 );
617 }
618
619 #[mz_ore::test]
620 fn validate_decimal() {
621 assert!(
622 Value::Decimal(DecimalValue {
623 unscaled: vec![7],
624 precision: 12,
625 scale: 5
626 })
627 .validate(
628 Schema::from_str(
629 r#"
630 {
631 "type": "bytes",
632 "logicalType": "decimal",
633 "precision": 12,
634 "scale": 5
635 }
636 "#
637 )
638 .unwrap()
639 .top_node()
640 )
641 );
642
643 assert!(
644 !Value::Decimal(DecimalValue {
645 unscaled: vec![7],
646 precision: 13,
647 scale: 5
648 })
649 .validate(
650 Schema::from_str(
651 r#"
652 {
653 "type": "bytes",
654 "logicalType": "decimal",
655 "precision": 12,
656 "scale": 5
657 }
658 "#
659 )
660 .unwrap()
661 .top_node()
662 )
663 );
664 }
665}