Skip to content

Commit

Permalink
#464 Accessing enum field in Entity created using EntityClass.new cau…
Browse files Browse the repository at this point in the history
…ses ClassCastException
  • Loading branch information
Tapac committed Jan 10, 2019
1 parent 7517d61 commit cfd27cd
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/main/kotlin/org/jetbrains/exposed/sql/Table.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty1
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor

Expand Down Expand Up @@ -236,10 +237,11 @@ open class Table(name: String = ""): ColumnSet(), DdlAware {
*/
fun <T:Enum<T>> enumerationByName(name: String, length: Int, klass: KClass<T>): Column<T> = registerColumn(name, EnumerationNameColumnType(klass, length))

@Suppress("UNCHECKED_CAST")
fun <T:Enum<T>> customEnumeration(name: String, sql: String? = null, fromDb: (Any) -> T, toDb: (T) -> Any) =
registerColumn<T>(name, object : ColumnType() {
override fun sqlType(): String = sql ?: error("Column $name should exists in database ")
override fun valueFromDB(value: Any) = fromDb(value)
override fun valueFromDB(value: Any) = if (value::class.isSubclassOf(Enum::class)) value as T else fromDb(value)
override fun notNullValueToDB(value: Any) = toDb(value as T)
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,9 @@ class DDLTests : DatabaseTestsBase() {
val entity = EnumClass.new {
enum = Foo.Baz
}

assertEquals(Foo.Baz, entity.enum)
entity.id.value // flush entity
assertEquals(Foo.Baz, entity.enum)
assertEquals(Foo.Baz, EnumClass.reload(entity)!!.enum)
} finally {
try {
Expand Down

0 comments on commit cfd27cd

Please sign in to comment.