Skip to content

Commit

Permalink
AVRO-3946: [Rust] Log warning/error for strange union types
Browse files Browse the repository at this point in the history
A Union schema without any variants will log an ERROR from now on.
A Union schema with a single variant will log a WARN suggesting to drop
the union.

Signed-off-by: Martin Tzvetanov Grigorov <mgrigorov@apache.org>
  • Loading branch information
martin-g committed Feb 26, 2024
1 parent 9e72af2 commit 903b5b8
Showing 1 changed file with 70 additions and 1 deletion.
71 changes: 70 additions & 1 deletion lang/rust/avro/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1606,6 +1606,8 @@ impl Parser {

self.register_resolving_schema(&fully_qualified_name, &aliases);

debug!("Going to parse record schema: {:?}", &fully_qualified_name);

let fields: Vec<RecordField> = fields_opt
.and_then(|fields| fields.as_array())
.ok_or(Error::GetRecordFieldsJson)
Expand Down Expand Up @@ -1786,7 +1788,22 @@ impl Parser {
.iter()
.map(|v| self.parse(v, enclosing_namespace))
.collect::<Result<Vec<_>, _>>()
.and_then(|schemas| Ok(Schema::Union(UnionSchema::new(schemas)?)))
.and_then(|schemas| {
if schemas.is_empty() {
error!(
"Union schemas should have at least two members! \
Please enable debug logging to find out which Record schema \
declares the union with 'RUST_LOG=apache_avro::schema=debug'."
);
} else if schemas.len() == 1 {
warn!(
"Union schema with just one member! Consider dropping the union! \
Please enable debug logging to find out which Record schema \
declares the union with 'RUST_LOG=apache_avro::schema=debug'."
);
}
Ok(Schema::Union(UnionSchema::new(schemas)?))
})
}

/// Parse a `serde_json::Value` representing a Avro fixed type into a
Expand Down Expand Up @@ -6639,4 +6656,56 @@ mod tests {

Ok(())
}

#[test]
fn avro_3946_union_with_single_type() -> TestResult {
let schema = r#"
{
"type": "record",
"name": "Issue",
"namespace": "invalid.example",
"fields": [
{
"name": "myField",
"type": ["long"]
}
]
}"#;

let _ = Schema::parse_str(schema)?;

assert_logged(
"Union schema with just one member! Consider dropping the union! \
Please enable debug logging to find out which Record schema \
declares the union with 'RUST_LOG=apache_avro::schema=debug'.",
);

Ok(())
}

#[test]
fn avro_3946_union_without_any_types() -> TestResult {
let schema = r#"
{
"type": "record",
"name": "Issue",
"namespace": "invalid.example",
"fields": [
{
"name": "myField",
"type": []
}
]
}"#;

let _ = Schema::parse_str(schema)?;

assert_logged(
"Union schemas should have at least two members! \
Please enable debug logging to find out which Record schema \
declares the union with 'RUST_LOG=apache_avro::schema=debug'.",
);

Ok(())
}
}

0 comments on commit 903b5b8

Please sign in to comment.