Git Product home page Git Product logo

elixir-avro's Introduction

elixir-avro

elixir-avro is a library designed to facilitate the conversion of Avro schemas into Elixir code. This library bridges the gap between Avro schema definitions and Elixir code, enabling seamless integration of Avro-defined data structures into Elixir projects.

Installation

If available in Hex, the package can be installed by adding elixir_avro to your list of dependencies in mix.exs:

def deps do
  [
    {:elixir_avro, "~> 0.1.0"}
  ]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/elixir_avro.

Usage

Run this command to generate Elixir code from Avro schema files:

This will generate Elixir code for the Avro schema files in the avro directory, one for each Avro type defined in the schemas.

Example

Given the following Avro schema definition in avro/user.avsc:

{
  "name": "User",
  "namespace": "registry",
  "fullname": "registry.User",
  "doc": "User registry information",
  "type": "record",
  "fields": [
    {
      "name": "firstname",
      "type": "string"
    },
    {
      "name": "lastname",
      "type": "string"
    },
    {
      "name": "age",
      "type": "int"
    },
    {
      "name": "role",
      "type": {
        "type": "enum",
        "name": "Role",
        "doc": "User's role.",
        "fullname": "registry.user.Role",
        "namespace": "registry.user",
        "symbols": [
          "ADMIN",
          "USER"
        ]
      }
    }
  ]
}

Running the following command:

mix elixir_avro_codegen --schemas-path avro/ --target-path lib --prefix MyApp.Avro

Will generate the following Elixir code in lib/:

# lib/my_app/avro/registry/user.ex
defmodule MyApp.Avro.Registry.User do
  @moduledoc """
  DO NOT EDIT MANUALLY: This module was automatically generated from an AVRO schema.

  ### Description
  User registry information

  ### Fields
  - __fullname__: User's full name
  - __role__: User's role.
  """

  use TypedStruct

  alias ElixirAvro.AvroType.Value.Decoder
  alias ElixirAvro.AvroType.Value.Encoder

  @expected_keys MapSet.new(["fullname", "role"])

  typedstruct do
    field :fullname, String.t(), enforce: true
    field :role, MyApp.Avro.Registry.User.Role.t(), enforce: true
  end

  @module_prefix MyApp.Avro

  def to_avro(%__MODULE__{} = struct) do
    {:ok,
     %{
      # ...
     }}
  end

  def from_avro(%{"fullname" => fullname, "role" => role}) do
    {:ok,
     %__MODULE__{
      # ...
     }}
  rescue
    e -> {:error, inspect(e)}
  end

  # ...
end
# lib/my_app/avro/registry/user/role.ex
defmodule MyApp.Avro.Registry.User.Role do
  @moduledoc """
  DO NOT EDIT MANUALLY: This module was automatically generated from an AVRO schema.

  ### Description
  User's role.

  """

  use ElixirAvro.Macro.ElixirEnum

  @values ["ADMIN", "USER"]

  def to_avro(value) do
    {:ok, to_avro_string(value)}
  rescue
    _ -> {:error, :invalid_enum_value}
  end

  def from_avro(value) do
    {:ok, from_avro_string(value)}
  rescue
    _ -> {:error, :invalid_enum_string_value}
  end
end

The generated path is a concatenation of the --prefix option (snake-cased) and the Avro schema type's namespace.

CLI Options

Usage: mix elixir_avro_codegen <-s directory> <-t directory> <-p name> [-v]
-s, --schemas-path <directory>    The path to the directory containing the Avro schema files.
-t, --target-path <directory>     The path to the directory where the generated Elixir code will be saved.
-p, --prefix <name>               The prefix to be used for the generated Elixir modules.
-v, --verbose                     Enable verbose output.

Compile-time generation

In your mix.exs file, in project function, add the following configuration:

  def project do
    [
      # ...
      elixir_avro_codegen: [
        schema_path: "avro",
        target_path: "avro",
        prefix: "MyApp.Avro"
      ],
      compilers: Mix.compilers() ++ [:elixir_avro_codegen],
      # ...
    ]
  end

The parameters used in the elixir_avro_codegen configuration are the same as the CLI options.

Custom logical types

To enable custom logical types support, you can create a module that conforms to the ElixirAvro.AvroType.LogicalType behaviour. Implementing this behaviour necessitates the user to define encode and decode functions. Here's an example:

defmodule My.Custom.LogicalType.Enum do
  @moduledoc false
  @behaviour ElixirAvro.AvroType.LogicalType
  @type t :: :admin | :user
  @values ["admin", "user"]
  defstruct [:value]

  @impl ElixirAvro.AvroType.LogicalType
  def decode(value) when value in @values, do: {:ok, %__MODULE__{value: String.to_atom(value)}}
  def decode(value), do: {:error, "Unknown value #{value}"}

  @impl ElixirAvro.AvroType.LogicalType
  def encode(%__MODULE__{value: value}), do: {:ok, Atom.to_string(value)}
end

Then, in order to let the library be able to use the custom logical type, you need to add the following configuration in your config file:

config :elixir_avro, :custom_logical_types, %{
  {"string", "custom-logical-enum"} => My.Custom.LogicalType.Enum
}

The key, which consists of a tuple containing the primitive type, will be utilized for deserializing the Avro custom logical type, along with its corresponding name as specified in the Avro file.

License

The MIT License (MIT)

Copyright (c) 2020 Prima.it

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

elixir-avro's People

Contributors

cottinisimone avatar mikhaildicefm avatar prima-pulumi-github-iac[bot] avatar

Stargazers

 avatar

Watchers

Matteo Foccoli avatar Angelo Poerio avatar Andreas Liljeqvist avatar Ash Dorey avatar Davide Di Somma avatar Mike Johnson avatar Davide Fedrigo avatar Francesco Bracchi avatar ricfrank avatar Juan González avatar Belate Atorrasagasti avatar Jouderian Nobre Junior avatar Daniele Bartocci avatar Alessandro Nuzzo avatar Damiano Giacomello avatar Davide Anghileri avatar Benjamin Allen avatar Emanuele Macri avatar Matteo Ugolotti avatar David Soler Marco avatar Michele Mari avatar  avatar Daniele Contini avatar Manel Juan avatar Javier Porto avatar emiliano carluccio avatar Mattia Tamellini avatar  avatar Luca Peppe avatar danielefongo avatar Mattia Zignale avatar  avatar Gianluca avatar  avatar Gianluca De Cola avatar Laura Trapani avatar Joel Pearson avatar

elixir-avro's Issues

`fixed` type does not appear to be supported

Hi,
When trying to use a 'fixed' data type with a size of 16 (to represent a UUID), I get the following error:

** (exit) "reference 'myavro.fixed' not found"
   (elixir_avro 0.1.0) lib/elixir_avro/schema/resolver.ex:56: ElixirAvro.Schema.Resolver.resolve_reference/2
   (elixir 1.14.5) lib/enum.ex:975: Enum."-each/2-lists^foreach/1-0-"/2
   (elixir_avro 0.1.0) lib/elixir_avro/schema/resolver.ex:24: ElixirAvro.Schema.Resolver.resolve_types/2
   (elixir_avro 0.1.0) lib/elixir_avro/codegen.ex:28: ElixirAvro.Codegen.run/1
   (mix 1.14.5) lib/mix/task.ex:421: anonymous fn/3 in Mix.Task.run_task/4
   (mix 1.14.5) lib/mix/cli.ex:84: Mix.CLI.run_task/2

Types refactor

ElixirAvro.Template.Names is a module to build the final name of a generated module and its typespec string. This module is then referenced in all the code to build the name everytime is needed. I would change this behaviour to include the module_name inside the avro_types. Moreover would be better to create a AvroType.Reference type to handle all the cases where the type is a string. It should contains the final module name too. ElixirAvro.Template.Names should be then be moved in the avro_type, renamed and used in that location only.

Add missing specs

While generating from_avro and to_avro functions we need to generate their specs too

Primitive type improvements and doctests

At the moment the primitive types are handled as strings. Would be better to force the primitive types using atoms and parse them. An invalid primitive should let the schema parsing fail

Add some doctests for Primitive parsing

Unexpected error when using a combination of `union` types and `default`

Hi,
I've noticed that when using a union type such as ["null", "string"] with a default value of null (as is recommended in the spec), generation fails with an error:

Field in question:

{
  "name": "field",
  "default": null,
  "type": [
    "null",
    "string"
  ],
  "doc": "..."
},

Command run:

mix elixir_avro_codegen --schemas-path avro/ --target-path gen/elixir_avro/ --prefix MyAvro

Error:

** (RuntimeError) default values in record field not implemented. 
{:avro_record_field, "field", "...", {:avro_union_type, {2, {1, {:avro_primitive_type, "string", []}, {0, {:avro_primitive_type, "null", []}, nil, nil}, nil}}, {2, {"string", {1, true}, {"null", {0, true}, nil, nil}, nil}}}, :null, :ascending, []}
    (elixir_avro 0.1.0) lib/elixir_avro/avro_type/record_field.ex:38: ElixirAvro.AvroType.RecordField.from_erl/1
    (elixir 1.14.5) lib/enum.ex:1658: Enum."-map/2-lists^map/1-0-"/2
    (elixir 1.14.5) lib/enum.ex:1658: Enum."-map/2-lists^map/1-0-"/2
    (elixir_avro 0.1.0) lib/elixir_avro/avro_type/record.ex:35: ElixirAvro.AvroType.Record.from_erl/1
    (elixir 1.14.5) lib/enum.ex:1658: Enum."-map/2-lists^map/1-0-"/2
    (elixir 1.14.5) lib/enum.ex:1658: Enum."-map/2-lists^map/1-0-"/2
    (elixir_avro 0.1.0) lib/elixir_avro/codegen.ex:29: ElixirAvro.Codegen.run/1
    (mix 1.14.5) lib/mix/task.ex:421: anonymous fn/3 in Mix.Task.run_task/4

CodeGen module testing

  • test/mix/tasks/elixir_avro.generate.code_test.exs should be renamed as test/mix/tasks/task.elixir_avro.codegen_test.exs and test args parsing
  • new test/elixir_avro/codegen_test.exs should be created and should improve tests contained in test/mix/tasks/elixir_avro.generate.code_test.exs to test from_avro and to_avro functions of the generated modules.

Handle LogicalTypes differently

Create new module, like Logical, or edit CustomProp module and handle all the logical types logic. A logical type is a CustomProp having name as logicalType and value as the primitive type name.
Eg. [{"name": "logicalType", "value": "uuid"}]

The resulting struct should be something like CustomProp { name: "logicalType", value: "date", logical?: true }

At the moment the logic is splitted between lib/elixir_avro/template/spec.ex, lib/elixir_avro/avro_type/value/decoder.ex and lib/elixir_avro/avro_type/value/encoder.ex.

RecordField `default` types handling

Looking at erlavro doc record_field() type is a union type of :undefined, avro:in() and avro_value(). avro:in() could be a primitive type while avro_value() could be a type or a reference. At the moment we only handle :undefined, discarding any default values. Avro specification for defaults states:

default: A default value for this field, used when reading instances that lack this field (optional). Permitted values depend on the field's schema type, according to the table below. Default values for union fields correspond to the first schema in the union. Default values for bytes and fixed fields are JSON strings, where Unicode code points 0-255 are mapped to unsigned 8-bit byte values 0-255.

field default values
avro type json type example
null null null
boolean boolean true
int,long integer 1
float,double number 1.1
bytes string "\u00FF"
string string "foo"
record object {"a": 1}
enum string "FOO"
array array [1]
map object {"a": 1}
fixed string "\u00ff"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.