Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
15 changes: 5 additions & 10 deletions avro/src/main/scala/magnolify/avro/AvroType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package magnolify.avro

import magnolia1._
import magnolify.shared.{doc => _, _}
import magnolify.shared.doc.getDoc
import magnolify.shims.FactoryCompat
import org.apache.avro.generic.GenericData.EnumSymbol
import org.apache.avro.generic._
Expand Down Expand Up @@ -128,14 +129,14 @@ object AvroField {
override protected def buildSchema(cm: CaseMapper): Schema = Schema
.createRecord(
caseClass.typeName.short,
getDoc(caseClass.annotations, caseClass.typeName.full),
getDoc(caseClass.annotations, caseClass.typeName.full).orNull,
caseClass.typeName.owner,
false,
caseClass.parameters.map { p =>
new Schema.Field(
cm.map(p.label),
p.typeclass.schema(cm),
getDoc(p.annotations, s"${caseClass.typeName.full}#${p.label}"),
getDoc(p.annotations, s"${caseClass.typeName.full}#${p.label}").orNull,
p.default
.map(d => p.typeclass.makeDefault(d)(cm))
.getOrElse(p.typeclass.fallbackDefault)
Expand Down Expand Up @@ -169,12 +170,6 @@ object AvroField {
}
}

private def getDoc(annotations: Seq[Any], name: String): String = {
val docs = annotations.collect { case d: doc => d.toString }
require(docs.size <= 1, s"More than one @doc annotation: $name")
docs.headOption.orNull
}

@implicitNotFound("Cannot derive AvroField for sealed trait")
private sealed trait Dispatchable[T]
def split[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): AvroField[T] = ???
Expand Down Expand Up @@ -251,7 +246,7 @@ object AvroField {
// Some reader, i.e. `AvroParquetReader` reads enums as `Utf8`
new Aux[T, AnyRef, EnumSymbol] {
override protected def buildSchema(cm: CaseMapper): Schema = {
val doc = getDoc(et.annotations, s"Enum ${et.namespace}.${et.name}")
val doc = getDoc(et.annotations, s"Enum ${et.namespace}.${et.name}").orNull
Schema.createEnum(et.name, doc, et.namespace, et.values.asJava)
}
// `JacksonUtils.toJson` expects `String` for `ENUM` defaults
Expand Down Expand Up @@ -385,7 +380,7 @@ object AvroField {
override protected def buildSchema(cm: CaseMapper): Schema = {
val n = ReflectionUtils.name[T]
val ns = ReflectionUtils.namespace[T]
Schema.createFixed(n, getDoc(an.annotations, n), ns, size)
Schema.createFixed(n, getDoc(an.annotations, n).orNull, ns, size)
}

override def from(v: GenericFixed)(cm: CaseMapper): T = f(v.bytes())
Expand Down
14 changes: 13 additions & 1 deletion beam/src/main/scala/magnolify/beam/RowType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package magnolify.beam

import magnolia1.*
import magnolify.shared.*
import magnolify.shared.doc.getDoc
import org.apache.beam.sdk.schemas.Schema
import org.apache.beam.sdk.schemas.Schema.{Field, FieldType}
import org.apache.beam.sdk.values.Row
Expand All @@ -34,6 +35,7 @@ import scala.jdk.CollectionConverters.*
// https://beam.apache.org/documentation/programming-guide/#schema-definition
sealed trait RowType[T] extends Converter[T, Row, Row] {
def schema: Schema
def description: Option[String]
def apply(r: Row): T = from(r)
def apply(t: T): Row = to(t)
}
Expand All @@ -48,6 +50,7 @@ object RowType {
new RowType[T] {
private val caseMapper: CaseMapper = cm
override lazy val schema: Schema = mappedSchema
override val description: Option[String] = r.description

override def from(v: Row): T = r.from(v)(caseMapper)
override def to(v: T): Row = r.to(v)(caseMapper)
Expand Down Expand Up @@ -101,6 +104,7 @@ object RowField {
sealed trait Record[T] extends Aux[T, Row, Row] {
@transient private lazy val schemaCache: concurrent.Map[ju.UUID, Schema] =
concurrent.TrieMap.empty
def description: Option[String]
protected def buildSchema(cm: CaseMapper): Schema
def schema(cm: CaseMapper): Schema = schemaCache.getOrElseUpdate(cm.uuid, buildSchema(cm))
}
Expand Down Expand Up @@ -163,12 +167,20 @@ object RowField {
new Record[T] {
@transient @volatile private var cachedFieldIndices: (ju.UUID, Array[Int]) = _

// evaluated eagerly so duplicate @doc on nested records fail fast too
override val description: Option[String] =
getDoc(caseClass.annotations, caseClass.typeName.full)

override def fieldType(cm: CaseMapper): FieldType = FieldType.row(schema(cm))

override protected def buildSchema(cm: CaseMapper): Schema =
caseClass.parameters
.foldLeft(Schema.builder()) { case (s, p) =>
s.addField(cm.map(p.label), p.typeclass.fieldType(cm))
val f = Field.of(cm.map(p.label), p.typeclass.fieldType(cm))
s.addField(
getDoc(p.annotations, s"${caseClass.typeName.full}#${p.label}")
.fold(f)(f.withDescription)
)
}
.build()

Expand Down
132 changes: 132 additions & 0 deletions beam/src/test/scala/magnolify/beam/RowTypeSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import magnolify.cats.TestEq.*
import magnolify.scalacheck.auto.*
import magnolify.scalacheck.TestArbitrary.*
import magnolify.shared.CaseMapper
import magnolify.shared.doc
import magnolify.test.ADT
import magnolify.test.MagnolifySuite
import magnolify.test.Simple.*
Expand Down Expand Up @@ -416,6 +417,107 @@ class RowTypeSuite extends MagnolifySuite {
assertEquals(result.o, None)
assertEquals(result.l, List.empty[Required])
}

test("BeamDoc") {
val rt = ensureSerializable(RowType[BeamDoc])
assertEquals(rt.description, Some("Beam doc"))
assertEquals(rt.schema.getField("s").getDescription, "string")
assertEquals(rt.schema.getField("i").getDescription, "integers")
assertEquals(rt.schema.getField("plain").getDescription, "")
// rebuilt schema on a deserialized instance: `@transient` schemaCache starts empty
val v = BeamDoc("s", Integers(1, 2L), "plain")
val row = rt.to(v)
assert(!(row.getSchema eq rt.schema))
assertEquals(row.getSchema, rt.schema)
assertEquals(rt(row), v)
}

test("BeamNestedDoc") {
val rt = ensureSerializable(RowType[BeamNestedDoc])
assertEquals(rt.description, Some("Beam nested doc"))
val schema = rt.schema

assertEquals(schema.getField("d").getDescription, "nested")
assertEquals(schema.getField("d").getType.getRowSchema.getField("s").getDescription, "string")

assertEquals(schema.getField("od").getDescription, "optional nested")
assertEquals(
schema.getField("od").getType.getRowSchema.getField("i").getDescription,
"integers"
)

assertEquals(schema.getField("ld").getDescription, "list nested")
assertEquals(
schema
.getField("ld")
.getType
.getCollectionElementType
.getRowSchema
.getField("s")
.getDescription,
"string"
)

assertEquals(schema.getField("md").getDescription, "map nested")
assertEquals(
schema.getField("md").getType.getMapValueType.getRowSchema.getField("i").getDescription,
"integers"
)

val d = BeamDoc("s", Integers(1, 2L), "plain")
val v = BeamNestedDoc("s", d, Some(d), List(d), Map("k" -> d))
val row = rt.to(v)
assert(!(row.getSchema eq rt.schema))
assertEquals(row.getSchema, rt.schema)
assertEquals(rt(row), v)
}

test("BeamDocCaseMapper") {
val schema = RowType[BeamNestedDoc](CaseMapper(_.toUpperCase)).schema
assertEquals(schema.getField("S").getDescription, "string")
assertEquals(schema.getField("D").getDescription, "nested")
assertEquals(schema.getField("D").getType.getRowSchema.getField("I").getDescription, "integers")
}

test("BeamCustomDoc") {
val rt = ensureSerializable(RowType[BeamCustomDoc])
assertEquals(rt.description, Some("doc: Beam doc, version: 1"))
assertEquals(rt.schema.getField("s").getDescription, "doc: string, version: 2")
val v = BeamCustomDoc("s")
val row = rt.to(v)
assert(!(row.getSchema eq rt.schema))
assertEquals(row.getSchema, rt.schema)
assertEquals(rt(row), v)
}

test("BeamNullDoc") {
val rt = ensureSerializable(RowType[BeamNullDoc])
assertEquals(rt.description, None)
assertEquals(rt.schema.getField("i").getDescription, "")
val v = BeamNullDoc(Integers(1, 2L))
val row = rt.to(v)
assert(!(row.getSchema eq rt.schema))
assertEquals(row.getSchema, rt.schema)
assertEquals(rt(row), v)
}

test("NoDoc") {
assertEquals(RowType[Integers].description, None)
}

testFail(RowType[DoubleRecordDoc])(
"More than one @doc annotation: magnolify.beam.DoubleRecordDoc"
)
testFail(RowType[DoubleFieldDoc])(
"More than one @doc annotation: magnolify.beam.DoubleFieldDoc#i"
)
// duplicate @doc on a nested record fails fast even when only the parent is derived
testFail(RowType[NestedDoubleRecordDoc])(
"More than one @doc annotation: magnolify.beam.DoubleRecordDoc"
)
testFail(RowType[NullDocRecordDoc])(
"More than one @doc annotation: magnolify.beam.NullDocRecordDoc"
)
}

case class Empty()
Expand Down Expand Up @@ -466,3 +568,33 @@ case class Maps(
)

case class SealedTest(shape: ADT.Shape, point: ADT.Rect, enumColor: ADT.Color)

@doc("Beam doc")
case class BeamDoc(@doc("string") s: String, @doc("integers") i: Integers, plain: String)

@doc("Beam nested doc")
case class BeamNestedDoc(
@doc("string") s: String,
@doc("nested") d: BeamDoc,
@doc("optional nested") od: Option[BeamDoc],
@doc("list nested") ld: List[BeamDoc],
@doc("map nested") md: Map[String, BeamDoc]
)

class customDoc(doc: String, version: Int) extends doc(s"doc: $doc, version: $version")

@customDoc("Beam doc", 1)
case class BeamCustomDoc(@customDoc("string", 2) s: String)

@doc("doc1")
@doc("doc2")
case class DoubleRecordDoc(i: Int)
case class DoubleFieldDoc(@doc("doc1") @doc("doc2") i: Int)
case class NestedDoubleRecordDoc(drd: DoubleRecordDoc)

@doc(null)
case class BeamNullDoc(@doc(null) i: Integers)

@doc(null)
@doc("doc")
case class NullDocRecordDoc(i: Int)
5 changes: 4 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,10 @@ ThisBuild / mimaBinaryIssueFilters ++= Seq(
ProblemFilters.exclude[MissingClassProblem]("magnolify.avro.ArrayIsBinaryNode"),
ProblemFilters.exclude[MissingClassProblem]("magnolify.avro.ArrayIsBinaryNode$"),
ProblemFilters.exclude[MissingClassProblem]("magnolify.avro.ArrayIsTextNode"),
ProblemFilters.exclude[MissingClassProblem]("magnolify.avro.ArrayIsTextNode$")
ProblemFilters.exclude[MissingClassProblem]("magnolify.avro.ArrayIsTextNode$"),
// sealed traits, so external implementations are impossible
ProblemFilters.exclude[ReversedMissingMethodProblem]("magnolify.beam.RowType.description"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("magnolify.beam.RowField#Record.description")
)
ThisBuild / tlVersionIntroduced := Map("3" -> "0.10.0")

Expand Down
18 changes: 17 additions & 1 deletion docs/beam.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,20 @@ case class LowerCamel(firstName: String, lastName: String)
val toSnakeCase = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE).convert _
val rowType = RowType[LowerCamel](CaseMapper(toSnakeCase))
rowType.to(LowerCamel("John", "Doe")) // Row(first_name: John, last_name: Doe)
```
```

## Field and record descriptions

Beam schema fields support descriptions, and RowType exposes the top-level record description via RowType#description (class-level @doc on nested case classes is not stored in the parent Beam Schema). Annotate the case class and its fields with @doc (or a subclass of @doc) to populate them:

```scala mdoc:compile-only
import magnolify.beam.*
import magnolify.shared.doc

@doc("My record")
case class Record(@doc("int field") i: Int, @doc("string field") s: String)

val rowType = RowType[Record]
rowType.description // Some("My record")
rowType.schema.getField("i").getDescription // "int field"
```
7 changes: 1 addition & 6 deletions parquet/src/main/scala/magnolify/parquet/ParquetField.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package magnolify.parquet

import magnolia1.*
import magnolify.shared.{Converter as _, *}
import magnolify.shared.doc.getDoc
import magnolify.shims.FactoryCompat

import java.nio.{ByteBuffer, ByteOrder}
Expand Down Expand Up @@ -195,12 +196,6 @@ object ParquetField {

implicit def apply[T]: ParquetField[T] = macro Magnolia.gen[T]

private def getDoc(annotations: Seq[Any], name: String): Option[String] = {
val docs = annotations.collect { case d: magnolify.shared.doc => d.toString }
require(docs.size <= 1, s"More than one @doc annotation: $name")
docs.headOption
}

// ////////////////////////////////////////////////

def from[T]: FromWord[T] = new FromWord[T]
Expand Down
16 changes: 16 additions & 0 deletions shared/src/main/scala/magnolify/shared/doc.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,23 @@
package magnolify.shared

import scala.annotation.StaticAnnotation
import scala.reflect.ClassTag

class doc(doc: String) extends StaticAnnotation with Serializable {
override def toString: String = doc
}

object doc {
private[magnolify] def getDoc(annotations: Seq[Any], name: String): Option[String] =
getDocAs[doc](annotations, name)

// `D` keeps each module's own annotation family apart, e.g. `magnolify.tensorflow.doc`
private[magnolify] def getDocAs[D](annotations: Seq[Any], name: String)(implicit
ct: ClassTag[D]
): Option[String] = {
// `Option` guards against a `@doc` whose `toString` returns `null`
val docs = annotations.collect { case ct(d) => Option(d.toString) }
require(docs.size <= 1, s"More than one @doc annotation: $name")
docs.headOption.flatten
}
}
46 changes: 46 additions & 0 deletions shared/src/test/scala/magnolify/shared/DocSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2026 Spotify AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package magnolify.shared

import org.scalacheck.{Prop, Properties}

class DocSpec extends Properties("doc") {
private class versionedDoc(doc: String, version: Int) extends doc(s"$doc, version: $version")
private class nullDoc extends doc(null)

private def getDoc(annotations: Seq[Any], name: String = "test"): Option[String] =
doc.getDoc(annotations, name)

private def rejects(annotations: Seq[Any], name: String): Prop = Prop {
try {
doc.getDoc(annotations, name)
false
} catch {
case e: IllegalArgumentException =>
e.getMessage == s"requirement failed: More than one @doc annotation: $name"
}
}

property("no annotation") = getDoc(Seq.empty) == None
property("single annotation") = getDoc(Seq(new doc("x"))) == Some("x")
property("empty string is kept") = getDoc(Seq(new doc(""))) == Some("")
property("null toString is dropped") = getDoc(Seq(new doc(null))) == None
property("subclass") = getDoc(Seq(new versionedDoc("x", 1))) == Some("x, version: 1")
property("null toString subclass is dropped") = getDoc(Seq(new nullDoc)) == None
property("duplicate") = rejects(Seq(new doc("a"), new doc("b")), "duplicate")
property("duplicate with null") = rejects(Seq(new doc(null), new doc("b")), "duplicate")
}
Loading
Loading