julianpeeters / avrohugger

Generate Scala case class definitions from Avro schemas
Apache License 2.0
201 stars 120 forks source link

Field names matching record name cause invalid scala code generation #172

Closed AlgMi closed 1 year ago

AlgMi commented 1 year ago

Example schema

@namespace("test.system")
protocol test_schema_protocol {
    record test_schema {
        long test_schema;
    }
}

Generated code

package test.system

import scala.annotation.switch

final case class test_schema(var test_schema: Long) extends org.apache.avro.specific.SpecificRecordBase {
  def this() = this(0L)
  def get(field$: Int): AnyRef = {
    (field$: @switch) match {
      case 0 => {
        test_schema
      }.asInstanceOf[AnyRef]
      case _ => new org.apache.avro.AvroRuntimeException("Bad index")
    }
  }
  def put(field$: Int, value: Any): Unit = {
    (field$: @switch) match {
      case 0 => this.test_schema = {
        value
      }.asInstanceOf[Long]
      case _ => new org.apache.avro.AvroRuntimeException("Bad index")
    }
    ()
  }
  def getSchema: org.apache.avro.Schema = test_schema.SCHEMA$
}

object test_schema {
  val SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"test_schema\",\"namespace\":\"test.system\",\"fields\":[{\"name\":\"test_schema\",\"type\":\"long\"}]}")
}

The problem - def getSchema: org.apache.avro.Schema = test_schema.SCHEMA$ Instead of calling companion object test_schema.SCHEMA$ a primitive field var test_schema: Long is used which obviously doesn't have SCHEMA$

Proposed solution - References to companion object should use FQDN like def getSchema: org.apache.avro.Schema =test.system.test_schema.SCHEMA$

julianpeeters commented 1 year ago

Thanks for the example, this should work now in avrohugger 1.5.1 and sbt-avrohugger 2.5.1.