You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@avro.apache.org by mg...@apache.org on 2023/11/15 13:57:59 UTC
(avro) branch avro-3904-SchemaCompatibility--can_read-should-return-Result created (now d90c6fbc4)
This is an automated email from the ASF dual-hosted git repository.
mgrigorov pushed a change to branch avro-3904-SchemaCompatibility--can_read-should-return-Result
in repository https://gitbox.apache.org/repos/asf/avro.git
at d90c6fbc4 AVRO-3904: [Rust] Change the return type of SchemaCompatibility::can_read() from `bool` to AvroResult<()>
This branch includes the following new commits:
new eb75e64dd AVRO-3901: [Rust] Unit tests and impl for better union support (#2583)
new d90c6fbc4 AVRO-3904: [Rust] Change the return type of SchemaCompatibility::can_read() from `bool` to AvroResult<()>
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(avro) 02/02: AVRO-3904: [Rust] Change the return type of SchemaCompatibility::can_read() from `bool` to AvroResult<()>
Posted by mg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mgrigorov pushed a commit to branch avro-3904-SchemaCompatibility--can_read-should-return-Result
in repository https://gitbox.apache.org/repos/asf/avro.git
commit d90c6fbc4536be44824d2616d28e510924f533db
Author: Martin Tzvetanov Grigorov <mg...@apache.org>
AuthorDate: Wed Nov 15 15:56:45 2023 +0200
AVRO-3904: [Rust] Change the return type of SchemaCompatibility::can_read() from `bool` to AvroResult<()>
Do not panic when schemata are incompatible. Return Err and let the user
deal with it.
Signed-off-by: Martin Tzvetanov Grigorov <mg...@apache.org>
---
lang/rust/avro/src/error.rs | 3 +
lang/rust/avro/src/schema.rs | 4 +-
lang/rust/avro/src/schema_compatibility.rs | 385 +++++++++++++++++------------
3 files changed, 235 insertions(+), 157 deletions(-)
diff --git a/lang/rust/avro/src/error.rs b/lang/rust/avro/src/error.rs
index 8fa146027..4761a57ee 100644
--- a/lang/rust/avro/src/error.rs
+++ b/lang/rust/avro/src/error.rs
@@ -478,6 +478,9 @@ pub enum Error {
#[error("Invalid Avro data! Cannot read codec type from value that is not Value::Bytes.")]
BadCodecMetadata,
+
+ #[error("Incompatible schemata: {0}.")]
+ IncompatibleSchemata(String),
}
impl serde::ser::Error for Error {
diff --git a/lang/rust/avro/src/schema.rs b/lang/rust/avro/src/schema.rs
index bc371b5e0..d45c82679 100644
--- a/lang/rust/avro/src/schema.rs
+++ b/lang/rust/avro/src/schema.rs
@@ -35,7 +35,7 @@ use std::{
io::Read,
str::FromStr,
};
-use strum_macros::{EnumDiscriminants, EnumString};
+use strum_macros::{Display, EnumDiscriminants, EnumString};
lazy_static! {
static ref ENUM_SYMBOL_NAME_R: Regex = Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").unwrap();
@@ -74,7 +74,7 @@ impl fmt::Display for SchemaFingerprint {
/// More information about Avro schemas can be found in the
/// [Avro Specification](https://avro.apache.org/docs/current/spec.html#schemas)
#[derive(Clone, Debug, EnumDiscriminants)]
-#[strum_discriminants(name(SchemaKind), derive(Hash, Ord, PartialOrd))]
+#[strum_discriminants(name(SchemaKind), derive(Display, Hash, Ord, PartialOrd))]
pub enum Schema {
/// A `null` Avro schema.
Null,
diff --git a/lang/rust/avro/src/schema_compatibility.rs b/lang/rust/avro/src/schema_compatibility.rs
index 8a0b2a4d7..4da5adc83 100644
--- a/lang/rust/avro/src/schema_compatibility.rs
+++ b/lang/rust/avro/src/schema_compatibility.rs
@@ -16,7 +16,10 @@
// under the License.
//! Logic for checking schema compatibility
-use crate::schema::{EnumSchema, FixedSchema, RecordSchema, Schema, SchemaKind};
+use crate::{
+ schema::{EnumSchema, FixedSchema, RecordSchema, Schema, SchemaKind},
+ AvroResult, Error,
+};
use std::{
collections::{hash_map::DefaultHasher, HashSet},
hash::Hasher,
@@ -37,7 +40,11 @@ impl Checker {
}
}
- pub(crate) fn can_read(&mut self, writers_schema: &Schema, readers_schema: &Schema) -> bool {
+ pub(crate) fn can_read(
+ &mut self,
+ writers_schema: &Schema,
+ readers_schema: &Schema,
+ ) -> AvroResult<()> {
self.full_match_schemas(writers_schema, readers_schema)
}
@@ -45,20 +52,18 @@ impl Checker {
&mut self,
writers_schema: &Schema,
readers_schema: &Schema,
- ) -> bool {
+ ) -> AvroResult<()> {
if self.recursion_in_progress(writers_schema, readers_schema) {
- return true;
+ return Ok(());
}
- if !SchemaCompatibility::match_schemas(writers_schema, readers_schema) {
- return false;
- }
+ SchemaCompatibility::match_schemas(writers_schema, readers_schema)?;
let w_type = SchemaKind::from(writers_schema);
let r_type = SchemaKind::from(readers_schema);
if w_type != SchemaKind::Union && (r_type.is_primitive() || r_type == SchemaKind::Fixed) {
- return true;
+ return Ok(());
}
match r_type {
@@ -68,10 +73,14 @@ impl Checker {
if let Schema::Map(r_m) = readers_schema {
self.full_match_schemas(w_m, r_m)
} else {
- unreachable!("readers_schema should have been Schema::Map")
+ Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Map".to_string(),
+ ))
}
} else {
- unreachable!("writers_schema should have been Schema::Map")
+ Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Map".to_string(),
+ ))
}
}
SchemaKind::Array => {
@@ -79,10 +88,14 @@ impl Checker {
if let Schema::Array(r_a) = readers_schema {
self.full_match_schemas(w_a, r_a)
} else {
- unreachable!("readers_schema should have been Schema::Array")
+ Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Array".to_string(),
+ ))
}
} else {
- unreachable!("writers_schema should have been Schema::Array")
+ Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Array".to_string(),
+ ))
}
}
SchemaKind::Union => self.match_union_schemas(writers_schema, readers_schema),
@@ -96,10 +109,18 @@ impl Checker {
symbols: r_symbols, ..
}) = readers_schema
{
- return !w_symbols.iter().any(|e| !r_symbols.contains(e));
+ if w_symbols.iter().any(|e| !r_symbols.contains(e)) {
+ return Err(Error::IncompatibleSchemata(
+ "Enum symbols are incompatible".to_string(),
+ ));
+ } else {
+ return Ok(());
+ }
}
}
- false
+ Err(Error::IncompatibleSchemata(
+ "Enum schemas are incompatible".to_string(),
+ ))
}
_ => {
if w_type == SchemaKind::Union {
@@ -109,16 +130,24 @@ impl Checker {
}
}
}
- false
+ Err(Error::IncompatibleSchemata(format!(
+ "Schemata types are incompatible! r_type: {r_type}, w_type: {w_type}"
+ )))
}
}
}
- fn match_record_schemas(&mut self, writers_schema: &Schema, readers_schema: &Schema) -> bool {
+ fn match_record_schemas(
+ &mut self,
+ writers_schema: &Schema,
+ readers_schema: &Schema,
+ ) -> AvroResult<()> {
let w_type = SchemaKind::from(writers_schema);
if w_type == SchemaKind::Union {
- return false;
+ return Err(Error::IncompatibleSchemata(
+ "writers_schema should not have been Schema::Union".to_string(),
+ ));
}
if let Schema::Record(RecordSchema {
@@ -133,19 +162,24 @@ impl Checker {
{
for field in r_fields.iter() {
if let Some(pos) = w_lookup.get(&field.name) {
- if !self.full_match_schemas(&w_fields[*pos].schema, &field.schema) {
- return false;
- }
+ return self.full_match_schemas(&w_fields[*pos].schema, &field.schema);
} else if field.default.is_none() {
- return false;
+ return Err(Error::IncompatibleSchemata(format!(
+ "Reader schema's field '{}' has no default value",
+ field.name
+ )));
}
}
}
}
- true
+ Ok(())
}
- fn match_union_schemas(&mut self, writers_schema: &Schema, readers_schema: &Schema) -> bool {
+ fn match_union_schemas(
+ &mut self,
+ writers_schema: &Schema,
+ readers_schema: &Schema,
+ ) -> AvroResult<()> {
let w_type = SchemaKind::from(writers_schema);
let r_type = SchemaKind::from(readers_schema);
@@ -153,18 +187,30 @@ impl Checker {
if w_type == SchemaKind::Union {
if let Schema::Union(u) = writers_schema {
- u.schemas
- .iter()
- .all(|schema| self.full_match_schemas(schema, readers_schema))
+ if u.schemas.iter().all(|schema| {
+ self.full_match_schemas(schema, readers_schema).unwrap();
+ true
+ }) {
+ Ok(())
+ } else {
+ Err(Error::IncompatibleSchemata(
+ "Union schemas are incompatible".to_string(),
+ ))
+ }
} else {
- unreachable!("writers_schema should have been Schema::Union")
+ Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Union".to_string(),
+ ))
}
- } else if let Schema::Union(u) = readers_schema {
- u.schemas
- .iter()
- .any(|schema| self.full_match_schemas(writers_schema, schema))
+ } else if let Schema::Union(union) = readers_schema {
+ for inner_schema in union.schemas.iter() {
+ self.full_match_schemas(writers_schema, inner_schema)?
+ }
+ Ok(())
} else {
- unreachable!("readers_schema should have been Schema::Union")
+ Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Union".to_string(),
+ ))
}
}
@@ -187,16 +233,16 @@ impl Checker {
impl SchemaCompatibility {
/// `can_read` performs a full, recursive check that a datum written using the
/// writers_schema can be read using the readers_schema.
- pub fn can_read(writers_schema: &Schema, readers_schema: &Schema) -> bool {
+ pub fn can_read(writers_schema: &Schema, readers_schema: &Schema) -> AvroResult<()> {
let mut c = Checker::new();
c.can_read(writers_schema, readers_schema)
}
/// `mutual_read` performs a full, recursive check that a datum written using either
/// the writers_schema or the readers_schema can be read using the other schema.
- pub fn mutual_read(writers_schema: &Schema, readers_schema: &Schema) -> bool {
- SchemaCompatibility::can_read(writers_schema, readers_schema)
- && SchemaCompatibility::can_read(readers_schema, writers_schema)
+ pub fn mutual_read(writers_schema: &Schema, readers_schema: &Schema) -> AvroResult<()> {
+ SchemaCompatibility::can_read(writers_schema, readers_schema)?;
+ SchemaCompatibility::can_read(readers_schema, writers_schema)
}
/// `match_schemas` performs a basic check that a datum written with the
@@ -204,29 +250,42 @@ impl SchemaCompatibility {
/// matching the types, including schema promotion, and matching the full name for
/// named types. Aliases for named types are not supported here, and the rust
/// implementation of Avro in general does not include support for aliases (I think).
- pub(crate) fn match_schemas(writers_schema: &Schema, readers_schema: &Schema) -> bool {
+ pub(crate) fn match_schemas(
+ writers_schema: &Schema,
+ readers_schema: &Schema,
+ ) -> AvroResult<()> {
let w_type = SchemaKind::from(writers_schema);
let r_type = SchemaKind::from(readers_schema);
if w_type == SchemaKind::Union || r_type == SchemaKind::Union {
- return true;
+ return Ok(());
}
if w_type == r_type {
if r_type.is_primitive() {
- return true;
+ return Ok(());
}
match r_type {
SchemaKind::Record => {
if let Schema::Record(RecordSchema { name: w_name, .. }) = writers_schema {
if let Schema::Record(RecordSchema { name: r_name, .. }) = readers_schema {
- return w_name.name == r_name.name;
+ if w_name.name == r_name.name {
+ return Ok(());
+ } else {
+ return Err(Error::IncompatibleSchemata(
+ "Record names do not match!".to_string(),
+ ));
+ }
} else {
- unreachable!("readers_schema should have been Schema::Record")
+ return Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Record".to_string(),
+ ));
}
} else {
- unreachable!("writers_schema should have been Schema::Record")
+ return Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Record".to_string(),
+ ));
}
}
SchemaKind::Fixed => {
@@ -246,23 +305,43 @@ impl SchemaCompatibility {
attributes: _,
}) = readers_schema
{
- return w_name.name == r_name.name && w_size == r_size;
+ if w_name.name == r_name.name && w_size == r_size {
+ return Ok(());
+ } else {
+ return Err(Error::IncompatibleSchemata(
+ "Fixed schemata names or sizes do not match!".to_string(),
+ ));
+ }
} else {
- unreachable!("readers_schema should have been Schema::Fixed")
+ return Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Fixed".to_string(),
+ ));
}
} else {
- unreachable!("writers_schema should have been Schema::Fixed")
+ return Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Fixed".to_string(),
+ ));
}
}
SchemaKind::Enum => {
if let Schema::Enum(EnumSchema { name: w_name, .. }) = writers_schema {
if let Schema::Enum(EnumSchema { name: r_name, .. }) = readers_schema {
- return w_name.name == r_name.name;
+ if w_name.name == r_name.name {
+ return Ok(());
+ } else {
+ return Err(Error::IncompatibleSchemata(
+ "Enum names do not match!".to_string(),
+ ));
+ }
} else {
- unreachable!("readers_schema should have been Schema::Enum")
+ return Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Enum".to_string(),
+ ));
}
} else {
- unreachable!("writers_schema should have been Schema::Enum")
+ return Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Enum".to_string(),
+ ));
}
}
SchemaKind::Map => {
@@ -270,10 +349,14 @@ impl SchemaCompatibility {
if let Schema::Map(r_m) = readers_schema {
return SchemaCompatibility::match_schemas(w_m, r_m);
} else {
- unreachable!("readers_schema should have been Schema::Map")
+ return Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Map".to_string(),
+ ));
}
} else {
- unreachable!("writers_schema should have been Schema::Map")
+ return Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Map".to_string(),
+ ));
}
}
SchemaKind::Array => {
@@ -281,10 +364,14 @@ impl SchemaCompatibility {
if let Schema::Array(r_a) = readers_schema {
return SchemaCompatibility::match_schemas(w_a, r_a);
} else {
- unreachable!("readers_schema should have been Schema::Array")
+ return Err(Error::IncompatibleSchemata(
+ "readers_schema should have been Schema::Array".to_string(),
+ ));
}
} else {
- unreachable!("writers_schema should have been Schema::Array")
+ return Err(Error::IncompatibleSchemata(
+ "writers_schema should have been Schema::Array".to_string(),
+ ));
}
}
_ => (),
@@ -296,7 +383,7 @@ impl SchemaCompatibility {
.iter()
.any(|&t| t == r_type)
{
- return true;
+ return Ok(());
}
if w_type == SchemaKind::Long
@@ -304,22 +391,24 @@ impl SchemaCompatibility {
.iter()
.any(|&t| t == r_type)
{
- return true;
+ return Ok(());
}
if w_type == SchemaKind::Float && r_type == SchemaKind::Double {
- return true;
+ return Ok(());
}
if w_type == SchemaKind::String && r_type == SchemaKind::Bytes {
- return true;
+ return Ok(());
}
if w_type == SchemaKind::Bytes && r_type == SchemaKind::String {
- return true;
+ return Ok(());
}
- false
+ Err(Error::IncompatibleSchemata(format!(
+ "Schemata types are incompatible! r_type: {r_type}, w_type: {w_type}"
+ )))
}
}
@@ -473,10 +562,9 @@ mod tests {
#[test]
fn test_broken() {
- assert!(!SchemaCompatibility::can_read(
- &int_string_union_schema(),
- &int_union_schema()
- ))
+ assert!(
+ SchemaCompatibility::can_read(&int_string_union_schema(), &int_union_schema()).is_err()
+ );
}
#[test]
@@ -528,7 +616,7 @@ mod tests {
assert!(!incompatible_schemas
.iter()
- .any(|(reader, writer)| SchemaCompatibility::can_read(writer, reader)));
+ .any(|(reader, writer)| SchemaCompatibility::can_read(writer, reader).is_ok()));
}
#[test]
@@ -577,7 +665,14 @@ mod tests {
assert!(compatible_schemas
.iter()
- .all(|(reader, writer)| SchemaCompatibility::can_read(writer, reader)));
+ .all(
+ |(reader, writer)| SchemaCompatibility::can_read(writer, reader)
+ .map_err(|err| {
+ println!("Error: {err}");
+ err
+ })
+ .is_ok()
+ ));
}
fn writer_schema() -> Schema {
@@ -596,19 +691,13 @@ mod tests {
fn test_missing_field() -> TestResult {
let reader_schema = Schema::parse_str(
r#"
- {"type":"record", "name":"Record", "fields":[
- {"name":"oldfield1", "type":"int"}
- ]}
-"#,
+ {"type":"record", "name":"Record", "fields":[
+ {"name":"oldfield1", "type":"int"}
+ ]}
+ "#,
)?;
- assert!(SchemaCompatibility::can_read(
- &writer_schema(),
- &reader_schema,
- ));
- assert!(!SchemaCompatibility::can_read(
- &reader_schema,
- &writer_schema()
- ));
+ SchemaCompatibility::can_read(&writer_schema(), &reader_schema)?;
+ assert!(SchemaCompatibility::can_read(&reader_schema, &writer_schema()).is_err());
Ok(())
}
@@ -622,14 +711,8 @@ mod tests {
]}
"#,
)?;
- assert!(SchemaCompatibility::can_read(
- &writer_schema(),
- &reader_schema
- ));
- assert!(!SchemaCompatibility::can_read(
- &reader_schema,
- &writer_schema()
- ));
+ SchemaCompatibility::can_read(&writer_schema(), &reader_schema)?;
+ assert!(SchemaCompatibility::can_read(&reader_schema, &writer_schema()).is_err());
Ok(())
}
@@ -644,14 +727,8 @@ mod tests {
]}
"#,
)?;
- assert!(SchemaCompatibility::can_read(
- &writer_schema(),
- &reader_schema
- ));
- assert!(SchemaCompatibility::can_read(
- &reader_schema,
- &writer_schema()
- ));
+ SchemaCompatibility::can_read(&writer_schema(), &reader_schema)?;
+ SchemaCompatibility::can_read(&reader_schema, &writer_schema())?;
Ok(())
}
@@ -666,14 +743,8 @@ mod tests {
]}
"#,
)?;
- assert!(SchemaCompatibility::can_read(
- &writer_schema(),
- &reader_schema
- ));
- assert!(!SchemaCompatibility::can_read(
- &reader_schema,
- &writer_schema()
- ));
+ SchemaCompatibility::can_read(&writer_schema(), &reader_schema)?;
+ assert!(SchemaCompatibility::can_read(&reader_schema, &writer_schema()).is_err());
Ok(())
}
@@ -688,54 +759,42 @@ mod tests {
]}
"#,
)?;
- assert!(!SchemaCompatibility::can_read(
- &writer_schema(),
- &reader_schema
- ));
- assert!(!SchemaCompatibility::can_read(
- &reader_schema,
- &writer_schema()
- ));
+ assert!(SchemaCompatibility::can_read(&writer_schema(), &reader_schema).is_err());
+ assert!(SchemaCompatibility::can_read(&reader_schema, &writer_schema()).is_err());
Ok(())
}
#[test]
- fn test_array_writer_schema() {
+ fn test_array_writer_schema() -> TestResult {
let valid_reader = string_array_schema();
let invalid_reader = string_map_schema();
- assert!(SchemaCompatibility::can_read(
- &string_array_schema(),
- &valid_reader
- ));
- assert!(!SchemaCompatibility::can_read(
- &string_array_schema(),
- &invalid_reader
- ));
+ SchemaCompatibility::can_read(&string_array_schema(), &valid_reader)?;
+ assert!(SchemaCompatibility::can_read(&string_array_schema(), &invalid_reader).is_err());
+
+ Ok(())
}
#[test]
- fn test_primitive_writer_schema() {
+ fn test_primitive_writer_schema() -> TestResult {
let valid_reader = Schema::String;
- assert!(SchemaCompatibility::can_read(
- &Schema::String,
- &valid_reader
- ));
- assert!(!SchemaCompatibility::can_read(
- &Schema::Int,
- &Schema::String
- ));
+ SchemaCompatibility::can_read(&Schema::String, &valid_reader)?;
+ assert!(SchemaCompatibility::can_read(&Schema::Int, &Schema::String).is_err());
+
+ Ok(())
}
#[test]
- fn test_union_reader_writer_subset_incompatibility() {
+ fn test_union_reader_writer_subset_incompatibility() -> TestResult {
// reader union schema must contain all writer union branches
let union_writer = union_schema(vec![Schema::Int, Schema::String]);
let union_reader = union_schema(vec![Schema::String]);
- assert!(!SchemaCompatibility::can_read(&union_writer, &union_reader));
- assert!(SchemaCompatibility::can_read(&union_reader, &union_writer));
+ assert!(SchemaCompatibility::can_read(&union_writer, &union_reader).is_err());
+ SchemaCompatibility::can_read(&union_reader, &union_writer)?;
+
+ Ok(())
}
#[test]
@@ -756,7 +815,7 @@ mod tests {
"#,
)?;
- assert!(!SchemaCompatibility::can_read(&string_schema, &int_schema));
+ assert!(SchemaCompatibility::can_read(&string_schema, &int_schema).is_err());
Ok(())
}
@@ -770,8 +829,8 @@ mod tests {
)?;
let enum_schema2 =
Schema::parse_str(r#"{"type":"enum", "name":"MyEnum", "symbols":["A","B","C"]}"#)?;
- assert!(!SchemaCompatibility::can_read(&enum_schema2, &enum_schema1));
- assert!(SchemaCompatibility::can_read(&enum_schema1, &enum_schema2));
+ assert!(SchemaCompatibility::can_read(&enum_schema2, &enum_schema1).is_err());
+ SchemaCompatibility::can_read(&enum_schema1, &enum_schema2)?;
Ok(())
}
@@ -843,10 +902,7 @@ mod tests {
fn test_union_resolution_no_structure_match() {
// short name match, but no structure match
let read_schema = union_schema(vec![Schema::Null, point_3d_no_default_schema()]);
- assert!(!SchemaCompatibility::can_read(
- &point_2d_fullname_schema(),
- &read_schema
- ));
+ assert!(SchemaCompatibility::can_read(&point_2d_fullname_schema(), &read_schema).is_err());
}
#[test]
@@ -858,10 +914,7 @@ mod tests {
point_2d_schema(),
point_3d_schema(),
]);
- assert!(!SchemaCompatibility::can_read(
- &point_2d_fullname_schema(),
- &read_schema
- ));
+ assert!(SchemaCompatibility::can_read(&point_2d_fullname_schema(), &read_schema).is_err());
}
#[test]
@@ -873,10 +926,7 @@ mod tests {
point_3d_schema(),
point_2d_schema(),
]);
- assert!(!SchemaCompatibility::can_read(
- &point_2d_fullname_schema(),
- &read_schema
- ));
+ assert!(SchemaCompatibility::can_read(&point_2d_fullname_schema(), &read_schema).is_err());
}
#[test]
@@ -888,14 +938,11 @@ mod tests {
point_3d_match_name_schema(),
point_3d_schema(),
]);
- assert!(!SchemaCompatibility::can_read(
- &point_2d_fullname_schema(),
- &read_schema
- ));
+ assert!(SchemaCompatibility::can_read(&point_2d_fullname_schema(), &read_schema).is_err());
}
#[test]
- fn test_union_resolution_full_name_match() {
+ fn test_union_resolution_full_name_match() -> TestResult {
// there is a full name match that should be chosen
let read_schema = union_schema(vec![
Schema::Null,
@@ -904,10 +951,9 @@ mod tests {
point_3d_schema(),
point_2d_fullname_schema(),
]);
- assert!(SchemaCompatibility::can_read(
- &point_2d_fullname_schema(),
- &read_schema
- ));
+ SchemaCompatibility::can_read(&point_2d_fullname_schema(), &read_schema)?;
+
+ Ok(())
}
#[test]
@@ -1078,7 +1124,7 @@ mod tests {
let schema_v1 = Schema::parse_str(RAW_SCHEMA_V1)?;
let schema_v2 = Schema::parse_str(RAW_SCHEMA_V2)?;
- assert!(SchemaCompatibility::can_read(&schema_v1, &schema_v2));
+ SchemaCompatibility::can_read(&schema_v1, &schema_v2)?;
Ok(())
}
@@ -1153,9 +1199,38 @@ mod tests {
];
for (schema_1, schema_2) in schemas {
- assert!(SchemaCompatibility::can_read(&schema_1, &schema_2));
+ SchemaCompatibility::can_read(&schema_1, &schema_2)?;
}
Ok(())
}
+
+ #[test]
+ fn test_avro_3904_schema_compatibility_should_not_panic() -> TestResult {
+ let schema_1 = Schema::parse_str(
+ r#"{
+ "type": "record",
+ "name": "StatisticsMap",
+ "fields": [
+ {"name": "success", "type": {"type": "map", "values": "int"}}
+ ]
+ }"#,
+ )?;
+
+ let schema_2 = Schema::parse_str(
+ r#"{
+ "type": "record",
+ "name": "StatisticsMap",
+ "fields": [
+ {"name": "success", "type": ["null", {"type": "map", "values": "int"}], "default": null}
+ ]
+ }"#,
+ )?;
+
+ assert!(SchemaCompatibility::can_read(&schema_1, &schema_2).is_err());
+
+ assert!(SchemaCompatibility::can_read(&schema_2, &schema_1).is_err());
+
+ Ok(())
+ }
}
(avro) 01/02: AVRO-3901: [Rust] Unit tests and impl for better union support (#2583)
Posted by mg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
mgrigorov pushed a commit to branch avro-3904-SchemaCompatibility--can_read-should-return-Result
in repository https://gitbox.apache.org/repos/asf/avro.git
commit eb75e64dded7dc8e86f32b9412c85fe3b8e11b8e
Author: chupaty <sg...@gmail.com>
AuthorDate: Tue Nov 14 23:41:07 2023 +1000
AVRO-3901: [Rust] Unit tests and impl for better union support (#2583)
* AVRO-3901: Unit tests and impl for better union support
* Apply suggestions from code review
Rename test cases
Co-authored-by: Martin Grigorov <ma...@users.noreply.github.com>
* Cleanup from review
* AVRO-3901: Fix formatting, clippy errors and improve naming
Signed-off-by: Martin Tzvetanov Grigorov <mg...@apache.org>
---------
Signed-off-by: Martin Tzvetanov Grigorov <mg...@apache.org>
Co-authored-by: Simon Gittins <Si...@tabcorp.com.au>
Co-authored-by: Martin Grigorov <ma...@users.noreply.github.com>
Co-authored-by: Martin Tzvetanov Grigorov <mg...@apache.org>
---
lang/rust/avro/src/encode.rs | 33 +++-
lang/rust/avro/tests/union_schema.rs | 342 +++++++++++++++++++++++++++++++++++
2 files changed, 372 insertions(+), 3 deletions(-)
diff --git a/lang/rust/avro/src/encode.rs b/lang/rust/avro/src/encode.rs
index 4593779ac..1f7e40da9 100644
--- a/lang/rust/avro/src/encode.rs
+++ b/lang/rust/avro/src/encode.rs
@@ -19,7 +19,7 @@ use crate::{
decimal::serialize_big_decimal,
schema::{
DecimalSchema, EnumSchema, FixedSchema, Name, Namespace, RecordSchema, ResolvedSchema,
- Schema, SchemaKind,
+ Schema, SchemaKind, UnionSchema,
},
types::{Value, ValueKind},
util::{zig_i32, zig_i64},
@@ -71,7 +71,19 @@ pub(crate) fn encode_internal<S: Borrow<Schema>>(
}
match value {
- Value::Null => (),
+ Value::Null => {
+ if let Schema::Union(union) = schema {
+ match union.schemas.iter().position(|sch| *sch == Schema::Null) {
+ None => {
+ return Err(Error::EncodeValueAsSchemaError {
+ value_kind: ValueKind::Null,
+ supported_schema: vec![SchemaKind::Null, SchemaKind::Union],
+ })
+ }
+ Some(p) => encode_long(p as i64, buffer),
+ }
+ } // else {()}
+ }
Value::Boolean(b) => buffer.push(u8::from(*b)),
// Pattern | Pattern here to signify that these _must_ have the same encoding.
Value::Int(i) | Value::Date(i) | Value::TimeMillis(i) => encode_int(*i, buffer),
@@ -242,11 +254,26 @@ pub(crate) fn encode_internal<S: Borrow<Schema>>(
));
}
}
+ } else if let Schema::Union(UnionSchema { schemas, .. }) = schema {
+ let original_size = buffer.len();
+ for (index, schema) in schemas.iter().enumerate() {
+ encode_long(index as i64, buffer);
+ match encode_internal(value, schema, names, enclosing_namespace, buffer) {
+ Ok(_) => return Ok(()),
+ Err(_) => {
+ buffer.truncate(original_size); //undo any partial encoding
+ }
+ }
+ }
+ return Err(Error::EncodeValueAsSchemaError {
+ value_kind: ValueKind::Record,
+ supported_schema: vec![SchemaKind::Record, SchemaKind::Union],
+ });
} else {
error!("invalid schema type for Record: {:?}", schema);
return Err(Error::EncodeValueAsSchemaError {
value_kind: ValueKind::Record,
- supported_schema: vec![SchemaKind::Record],
+ supported_schema: vec![SchemaKind::Record, SchemaKind::Union],
});
}
}
diff --git a/lang/rust/avro/tests/union_schema.rs b/lang/rust/avro/tests/union_schema.rs
new file mode 100644
index 000000000..09a1d1305
--- /dev/null
+++ b/lang/rust/avro/tests/union_schema.rs
@@ -0,0 +1,342 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use apache_avro::{from_value, AvroResult, Codec, Reader, Schema, Writer};
+use serde::{de::DeserializeOwned, Deserialize, Serialize};
+
+static SCHEMA_A_STR: &str = r#"{
+ "name": "A",
+ "type": "record",
+ "fields": [
+ {"name": "field_a", "type": "float"}
+ ]
+ }"#;
+
+static SCHEMA_B_STR: &str = r#"{
+ "name": "B",
+ "type": "record",
+ "fields": [
+ {"name": "field_b", "type": "long"}
+ ]
+ }"#;
+
+static SCHEMA_C_STR: &str = r#"{
+ "name": "C",
+ "type": "record",
+ "fields": [
+ {"name": "field_union", "type": ["A", "B"]},
+ {"name": "field_c", "type": "string"}
+ ]
+ }"#;
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct A {
+ field_a: f32,
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct B {
+ field_b: i64,
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+#[serde(untagged)]
+enum UnionAB {
+ A(A),
+ B(B),
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct C {
+ field_union: UnionAB,
+ field_c: String,
+}
+
+fn encode_decode<T>(input: &T, schema: &Schema, schemata: &[Schema]) -> AvroResult<T>
+where
+ T: DeserializeOwned + Serialize,
+{
+ let mut encoded: Vec<u8> = Vec::new();
+ let mut writer =
+ Writer::with_schemata(schema, schemata.iter().collect(), &mut encoded, Codec::Null);
+ writer.append_ser(input)?;
+ writer.flush()?;
+
+ let mut reader = Reader::with_schemata(schema, schemata.iter().collect(), encoded.as_slice())?;
+ from_value::<T>(&reader.next().expect("")?)
+}
+
+#[test]
+fn test_avro_3901_union_schema_round_trip_no_null() -> AvroResult<()> {
+ let schemata: Vec<Schema> =
+ Schema::parse_list(&[SCHEMA_A_STR, SCHEMA_B_STR, SCHEMA_C_STR]).expect("parsing schemata");
+
+ let input = C {
+ field_union: (UnionAB::A(A { field_a: 45.5 })),
+ field_c: "foo".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = C {
+ field_union: (UnionAB::B(B { field_b: 73 })),
+ field_c: "bar".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ Ok(())
+}
+
+static SCHEMA_D_STR: &str = r#"{
+ "name": "D",
+ "type": "record",
+ "fields": [
+ {"name": "field_union", "type": ["null", "A", "B"]},
+ {"name": "field_d", "type": "string"}
+ ]
+ }"#;
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+#[serde(untagged)]
+enum UnionNoneAB {
+ None,
+ A(A),
+ B(B),
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct D {
+ field_union: UnionNoneAB,
+ field_d: String,
+}
+
+#[test]
+fn test_avro_3901_union_schema_round_trip_null_at_start() -> AvroResult<()> {
+ let schemata: Vec<Schema> =
+ Schema::parse_list(&[SCHEMA_A_STR, SCHEMA_B_STR, SCHEMA_D_STR]).expect("parsing schemata");
+
+ let input = D {
+ field_union: UnionNoneAB::A(A { field_a: 54.25 }),
+ field_d: "fooy".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = D {
+ field_union: UnionNoneAB::None,
+ field_d: "fooyy".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = D {
+ field_union: UnionNoneAB::B(B { field_b: 103 }),
+ field_d: "foov".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ Ok(())
+}
+
+static SCHEMA_E_STR: &str = r#"{
+ "name": "E",
+ "type": "record",
+ "fields": [
+ {"name": "field_union", "type": ["A", "null", "B"]},
+ {"name": "field_e", "type": "string"}
+ ]
+ }"#;
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+#[serde(untagged)]
+enum UnionANoneB {
+ A(A),
+ None,
+ B(B),
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct E {
+ field_union: UnionANoneB,
+ field_e: String,
+}
+
+#[test]
+fn test_avro_3901_union_schema_round_trip_with_out_of_order_null() -> AvroResult<()> {
+ let schemata: Vec<Schema> =
+ Schema::parse_list(&[SCHEMA_A_STR, SCHEMA_B_STR, SCHEMA_E_STR]).expect("parsing schemata");
+
+ let input = E {
+ field_union: UnionANoneB::A(A { field_a: 23.75 }),
+ field_e: "barme".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = E {
+ field_union: UnionANoneB::None,
+ field_e: "barme2".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = E {
+ field_union: UnionANoneB::B(B { field_b: 89 }),
+ field_e: "barme3".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ Ok(())
+}
+
+static SCHEMA_F_STR: &str = r#"{
+ "name": "F",
+ "type": "record",
+ "fields": [
+ {"name": "field_union", "type": ["A", "B", "null"]},
+ {"name": "field_f", "type": "string"}
+ ]
+ }"#;
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+#[serde(untagged)]
+enum UnionABNone {
+ A(A),
+ B(B),
+ None,
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct F {
+ field_union: UnionABNone,
+ field_f: String,
+}
+
+#[test]
+fn test_avro_3901_union_schema_round_trip_with_end_null() -> AvroResult<()> {
+ let schemata: Vec<Schema> =
+ Schema::parse_list(&[SCHEMA_A_STR, SCHEMA_B_STR, SCHEMA_F_STR]).expect("parsing schemata");
+
+ let input = F {
+ field_union: UnionABNone::A(A { field_a: 23.75 }),
+ field_f: "aoe".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = F {
+ field_union: UnionABNone::B(B { field_b: 89 }),
+ field_f: "aoe3".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = F {
+ field_union: UnionABNone::None,
+ field_f: "aoee2".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ Ok(())
+}
+
+/*
+One could make an argument that we should be able to represent a union schema of [null,A,B] as Option<Enum<A,B>>.
+This is a failing test to show that we *can't*. My (Simon Gittins's) feeling is that this should NOT be implemented
+static SCHEMA_G_STR: &str = r#"{
+ "name": "G",
+ "type": "record",
+ "fields": [
+ {"name": "field_union", "type": ["null", "A", "B"]},
+ {"name": "field_g", "type": "string"}
+ ]
+ }"#;
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct G {
+ field_union: Option<UnionAB>,
+ field_g: String,
+}
+
+#[test]
+fn test_avro_3901_union_schema_as_optional_2() -> AvroResult<()> {
+ let schemata: Vec<Schema> =
+ Schema::parse_list(&[SCHEMA_A_STR, SCHEMA_B_STR, SCHEMA_G_STR]).expect("parsing schemata");
+
+ let input = G {
+ field_union: Some(UnionAB::A(A { field_a: 32.25 })),
+ field_g: "aj".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = G {
+ field_union: None,
+ field_g: "aja".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = G {
+ field_union: Some(UnionAB::B(B { field_b: 44 })),
+ field_g: "aju".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[2], &schemata)?;
+ assert_eq!(input, output);
+
+ Ok(())
+}
+*/
+static SCHEMA_H_STR: &str = r#"{
+ "name": "H",
+ "type": "record",
+ "fields": [
+ {"name": "field_union", "type": ["null", "long"]},
+ {"name": "field_h", "type": "string"}
+ ]
+ }"#;
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
+struct H {
+ field_union: Option<i64>,
+ field_h: String,
+}
+
+#[test]
+fn test_avro_3901_union_schema_as_optional() -> AvroResult<()> {
+ let schemata: Vec<Schema> = Schema::parse_list(&[SCHEMA_H_STR]).expect("parsing schemata");
+
+ let input = H {
+ field_union: Some(23),
+ field_h: "aaa".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[0], &schemata)?;
+ assert_eq!(input, output);
+
+ let input = H {
+ field_union: None,
+ field_h: "bbb".to_string(),
+ };
+ let output = encode_decode(&input, &schemata[0], &schemata)?;
+ assert_eq!(input, output);
+
+ Ok(())
+}