Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: record MarshalJSON in case of default record with nullable field #451

Merged
merged 1 commit into from
Sep 16, 2024

Conversation

redaLaanait
Copy link
Contributor

I came across the following case where record MarshalJSON generates an Invalid schema, which avro.Parse fails to parse, returning the error:

invalid default for field a. not a record

Schema:

{
  "type": "record",
  "name": "test",
  "namespace": "org.hamba.avro",
  "fields": [
    {
      "name": "a",
      "type": {
        "type": "record",
        "name": "test2",
        "fields": [
          {
            "name": "b",
            "type": "int"
          },
          {
            "name": "c",
            "type": [
              "null",
              "int"
            ]
          }
        ]
      },
      "default": {
        "b": 1,
        "c": null
      }
    }
  ]
}

The generated invalid schema:

{
  "name": "org.hamba.avro.test",
  "type": "record",
  "fields": [
    {
      "name": "a",
      "type": {
        "name": "org.hamba.avro.test2",
        "type": "record",
        "fields": [
          {
            "name": "b",
            "type": "int"
          },
          {
            "name": "c",
            "type": [
              "null",
              "int"
            ]
          }
        ]
      },
      "default": {
        "b": 1,
        "c": {}
      }
    }
  ]
}

The default value of c should be null instead of an empty JSON object.

If I got it right, a fix could be to define a custom MarshalJSON for the nullDefault value:

type nullDefaultType struct{}

func (nullDefaultType) MarshalJSON() ([]byte, error) {
	return []byte("null"), nil
}

var nullDefault nullDefaultType = struct{}{}

Copy link
Member

@nrwiersma nrwiersma left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@nrwiersma nrwiersma merged commit 84f98c7 into hamba:main Sep 16, 2024
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants