Skip to content

Commit

Permalink
Failing deriving Schemas with transient fields without defaults (#654)
Browse files Browse the repository at this point in the history
  • Loading branch information
987Nabil committed Jun 30, 2024
1 parent 91899ff commit dacdbae
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,18 @@ object DeriveSchema {
}
val hasDefaultAnnotation =
annotations.exists {
case q"new _root_.zio.schema.annotation.fieldDefaultValue(..$_)" => true
case _ => false
case ann if ann.toString.contains("new fieldDefaultValue") => true
case _ => false
}
if (hasDefaultAnnotation || defaultConstructorValues.get(i).isEmpty) {
val transientField =
annotations.exists {
case ann if ann.toString().endsWith("new transientField()") => true
case _ => false
}
if (transientField && !(hasDefaultAnnotation || defaultConstructorValues.contains(i))) {
throw new IllegalStateException(s"Field ${symbol.name} is transient and must have a default value.")
}
if (hasDefaultAnnotation || !defaultConstructorValues.contains(i)) {
annotations
} else {
annotations :+
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,10 @@ private case class DeriveSchema()(using val ctx: Quotes) {
.map(_.asExpr.asInstanceOf[Expr[Any]])
val hasDefaultAnnotation =
field.annotations.exists(_.tpe <:< TypeRepr.of[zio.schema.annotation.fieldDefaultValue[_]])
val transientField = field.annotations.exists(_.tpe <:< TypeRepr.of[zio.schema.annotation.transientField])
if (transientField && !hasDefaultAnnotation && defaults.get(field.name).isEmpty) {
report.errorAndAbort(s"Field ${field.name} is transient and must have a default value.")
}
if (hasDefaultAnnotation || defaults.get(field.name).isEmpty) {
annos
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1629,7 +1629,7 @@ object JsonCodecSpec extends ZIOSpecDefault {
query: String,
pageNumber: Int,
resultPerPage: Int,
@transientField nextPage: String
@transientField nextPage: String = ""
)

val searchRequestWithTransientFieldSchema: Schema[SearchRequestWithTransientField] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1169,7 +1169,7 @@ object ThriftCodecSpec extends ZIOSpecDefault {
implicit val schema: Schema[PersonWithOptionalField] = DeriveSchema.gen[PersonWithOptionalField]
}

case class PersonWithTransientField(name: String, @transientField age: Int)
case class PersonWithTransientField(name: String, @transientField age: Int = 0)

object PersonWithTransientField {
implicit val schema: Schema[PersonWithTransientField] = DeriveSchema.gen[PersonWithTransientField]
Expand Down

0 comments on commit dacdbae

Please sign in to comment.