From 2d10b319f4f5e3e8a10a686b68a14010f6de527d Mon Sep 17 00:00:00 2001 From: Michel Hartmann Date: Thu, 12 Sep 2024 09:39:57 +0200 Subject: [PATCH] AVRO-4046: Respect writer's schema for default values (#3127) Only use default values from reader's schema for fields that are not defined in the writer's schema Co-authored-by: Michel Hartmann --- lang/php/lib/Datum/AvroIODatumReader.php | 1 + lang/php/test/IODatumReaderTest.php | 34 +++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lang/php/lib/Datum/AvroIODatumReader.php b/lang/php/lib/Datum/AvroIODatumReader.php index a479c2bd64f..c9a5ae3953b 100644 --- a/lang/php/lib/Datum/AvroIODatumReader.php +++ b/lang/php/lib/Datum/AvroIODatumReader.php @@ -358,6 +358,7 @@ public function readRecord($writers_schema, $readers_schema, $decoder) } } // Fill in default values + $writers_fields = $writers_schema->fieldsHash(); foreach ($readers_fields as $field_name => $field) { if (isset($writers_fields[$field_name])) { continue; diff --git a/lang/php/test/IODatumReaderTest.php b/lang/php/test/IODatumReaderTest.php index dc6ead359de..acdc8c484df 100644 --- a/lang/php/test/IODatumReaderTest.php +++ b/lang/php/test/IODatumReaderTest.php @@ -37,7 +37,7 @@ public function testSchemaMatching() JSON; $readers_schema = $writers_schema; $this->assertTrue(AvroIODatumReader::schemasMatch( - AvroSchema::parse($writers_schema), + AvroSchema::parse($writers_schema), AvroSchema::parse($readers_schema))); } @@ -90,4 +90,36 @@ public function testRecordNullField() $this->assertSame('0200', bin2hex($bin)); } + + public function testRecordFieldWithDefault() + { + $schema = AvroSchema::parse(<<<_JSON +{ + "name": "RecordWithDefaultValue", + "type": "record", + "fields": [ + { + "name": "field1", + "type": "string", + "default": "default" + } + ] +} +_JSON + ); + + $io = new AvroStringIO(); + $writer = new AvroIODatumWriter(); + $writer->writeData($schema, ['field1' => "foobar"], new AvroIOBinaryEncoder($io)); + + $bin = $io->string(); + $reader = new AvroIODatumReader(); + $record = $reader->readRecord( + $schema, + $schema, + new AvroIOBinaryDecoder(new AvroStringIO($bin)) + ); + + $this->assertEquals(['field1' => "foobar"], $record); + } }