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

(feat) Support for Pydantic field alias and serialization_alias #583

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions dataclasses_avroschema/fields/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing_extensions import get_args

from dataclasses_avroschema import utils
from dataclasses_avroschema.fields.field_utils import ensure_null_first

p = Inflector()

Expand Down Expand Up @@ -78,7 +79,8 @@ def render(self) -> OrderedDict:
* tuple, he OrderedDict will contains the key symbols inside type
* dict, he OrderedDict will contains the key values inside type
"""
template = OrderedDict(self.get_metadata() + [("name", self.name), ("type", self.get_avro_type())])
avro_type = ensure_null_first(self.get_avro_type())
template = OrderedDict(self.get_metadata() + [("name", self.name), ("type", avro_type)])
default = self.get_default_value()

if default is not dataclasses.MISSING:
Expand Down Expand Up @@ -120,8 +122,7 @@ def to_dict(self) -> dict:
return dict(self.render())

@abc.abstractmethod
def get_avro_type(self) -> typing.Any:
... # pragma: no cover
def get_avro_type(self) -> typing.Any: ... # pragma: no cover

def fake(self) -> typing.Any:
return None
Expand Down
9 changes: 9 additions & 0 deletions dataclasses_avroschema/fields/field_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import enum
import typing
import uuid

from dataclasses_avroschema import types
Expand Down Expand Up @@ -97,3 +98,11 @@
datetime.datetime: {"type": LONG, "logicalType": TIMESTAMP_MILLIS},
uuid.uuid4: {"type": STRING, "logicalType": UUID},
}


def ensure_null_first(avro_type: typing.Any) -> typing.Any:
marcosschroh marked this conversation as resolved.
Show resolved Hide resolved
"""Ensures null appears first in avro_type, if present."""
if not isinstance(avro_type, list) or NULL not in avro_type:
return avro_type

return [NULL] + [atype for atype in avro_type if atype != NULL]
3 changes: 2 additions & 1 deletion dataclasses_avroschema/fields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
)
from dataclasses_avroschema.exceptions import InvalidMap
from dataclasses_avroschema.faker import fake
from dataclasses_avroschema.fields.field_utils import ensure_null_first
from dataclasses_avroschema.utils import is_pydantic_model

from . import field_utils
Expand Down Expand Up @@ -211,7 +212,7 @@ def generate_items_type(self) -> typing.Any:
parent=self.parent,
)

self.items_type = self.internal_field.get_avro_type()
self.items_type = ensure_null_first(self.internal_field.get_avro_type())


@dataclasses.dataclass
Expand Down
10 changes: 10 additions & 0 deletions dataclasses_avroschema/pydantic/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ def get_field_metadata(field_info: FieldInfo) -> dict[str, typing.Any]:
)
if field_info.description:
metadata["doc"] = field_info.description # type: ignore

aliases = set(metadata.get("aliases", []))

if field_info.alias:
marcosschroh marked this conversation as resolved.
Show resolved Hide resolved
aliases.add(field_info.alias)
if field_info.serialization_alias:
aliases.add(field_info.serialization_alias)
if aliases:
metadata["aliases"] = list(aliases)

return metadata

def parse_fields(self, exclude: typing.List) -> typing.List[Field]:
Expand Down
29 changes: 29 additions & 0 deletions tests/schemas/pydantic/test_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,35 @@ class User(AvroBaseModel):
assert User.avro_schema() == json.dumps(expected_schema)


def test_pydantic_record_schema_with_aliases():
class User(AvroBaseModel):
foo: str = Field(alias="FOO")
bar: str = Field(serialization_alias="BAR")

expected_schema = {
"type": "record",
"name": "User",
"fields": [
{"aliases": ["FOO"], "name": "foo", "type": "string"},
{"aliases": ["BAR"], "name": "bar", "type": "string"},
],
}
assert User.avro_schema() == json.dumps(expected_schema)


def test_pydantic_record_schema_null_first():
class User(AvroBaseModel):
foo: typing.Optional[typing.List[typing.Optional[str]]]

expected_schema = {
"type": "record",
"name": "User",
"fields": [{"name": "foo", "type": ["null", {"type": "array", "items": ["null", "string"], "name": "foo"}]}],
}

assert User.avro_schema() == json.dumps(expected_schema)


def test_pydantic_record_schema_complex_types(user_advance_avro_json, color_enum):
class UserAdvance(AvroBaseModel):
name: str
Expand Down
Loading