@@ -22,7 +22,7 @@ package com.audienceproject.spark.dynamodb.reflect
22
22
23
23
import com .audienceproject .spark .dynamodb .attribute
24
24
import org .apache .spark .sql .catalyst .ScalaReflection
25
- import org .apache .spark .sql .types .{Metadata , MetadataBuilder , StructField , StructType }
25
+ import org .apache .spark .sql .types .{StructField , StructType }
26
26
27
27
import scala .reflect .ClassTag
28
28
import scala .reflect .runtime .{universe => ru }
@@ -32,35 +32,37 @@ import scala.reflect.runtime.{universe => ru}
32
32
*/
33
33
private [dynamodb] object SchemaAnalysis {
34
34
35
- def apply [T <: Product : ClassTag : ru.TypeTag ]: StructType = {
35
+ def apply [T <: Product : ClassTag : ru.TypeTag ]: ( StructType , Map [ String , String ]) = {
36
36
37
37
val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader)
38
38
39
39
val classObj = scala.reflect.classTag[T ].runtimeClass
40
40
val classSymbol = runtimeMirror.classSymbol(classObj)
41
41
42
- val sparkFields = classSymbol.primaryConstructor.typeSignature.paramLists.head.map(field => {
43
- val sparkType = ScalaReflection .schemaFor(field.typeSignature).dataType
42
+ val params = classSymbol.primaryConstructor.typeSignature.paramLists.head
43
+ val (sparkFields, aliasMap) = params.foldLeft((List .empty[StructField ], Map .empty[String , String ]))({
44
+ case ((list, map), field) =>
45
+ val sparkType = ScalaReflection .schemaFor(field.typeSignature).dataType
44
46
45
- // Black magic from here:
46
- // https://stackoverflow.com/questions/23046958/accessing-an-annotation-value-in-scala
47
- val attrName = field.annotations.collectFirst({
48
- case ann : ru.AnnotationApi if ann.tree.tpe =:= ru.typeOf[attribute] =>
49
- ann.tree.children.tail.collectFirst({
50
- case ru.Literal (ru.Constant (name : String )) => name
51
- })
52
- }).flatten
47
+ // Black magic from here:
48
+ // https://stackoverflow.com/questions/23046958/accessing-an-annotation-value-in-scala
49
+ val attrName = field.annotations.collectFirst({
50
+ case ann : ru.AnnotationApi if ann.tree.tpe =:= ru.typeOf[attribute] =>
51
+ ann.tree.children.tail.collectFirst({
52
+ case ru.Literal (ru.Constant (name : String )) => name
53
+ })
54
+ }).flatten
53
55
54
- if (attrName.isDefined) {
55
- val metadata = new MetadataBuilder ().putString(" alias" , field.name.toString).build()
56
- StructField (attrName.get, sparkType, nullable = true , metadata)
57
- } else {
58
- StructField (field.name.toString, sparkType, nullable = true , Metadata .empty)
59
- }
56
+ if (attrName.isDefined) {
57
+ val sparkField = StructField (attrName.get, sparkType, nullable = true )
58
+ (list :+ sparkField, map + (attrName.get -> field.name.toString))
59
+ } else {
60
+ val sparkField = StructField (field.name.toString, sparkType, nullable = true )
61
+ (list :+ sparkField, map)
62
+ }
60
63
})
61
64
62
- StructType (sparkFields)
63
-
65
+ (StructType (sparkFields), aliasMap)
64
66
}
65
67
66
68
}
0 commit comments