Skip to content

Instantly share code, notes, and snippets.

@Pyppe
Created July 9, 2015 08:48
Show Gist options
  • Save Pyppe/0362b11012fcbdb804cd to your computer and use it in GitHub Desktop.
Save Pyppe/0362b11012fcbdb804cd to your computer and use it in GitHub Desktop.
object SlickEnumerationSupport {
def enumerationTypeName[V <: Enumeration.Value : ClassTag] = {
val valueSymbol = runtimeMirror.classSymbol(classTag[V].runtimeClass)
val valueTypeName = valueSymbol.name.decodedName.toString
val enumTypeName = valueSymbol.owner.name.decodedName.toString
// Always use public schema
s"${enumTypeName}_${valueTypeName}".toLowerCase
}
implicit def columnType[E <: Enumeration.Value](implicit tag: ClassTag[E]): BaseColumnType[E] = {
val enum = Enumeration.forValueClass(classTag[E].runtimeClass)
if (isH2Database) {
MappedColumnType.base[E, String] (
enum => enum.name,
name => Enumeration.forValueClass(classTag[E].runtimeClass).
withName(name).asInstanceOf[E]
)
} else {
new driver.DriverJdbcType[E] {
override val classTag: ClassTag[E] = tag
override def sqlType: Int = java.sql.Types.OTHER
override def sqlTypeName: String = enumerationTypeName(tag)
override def setValue(e: E, p: PreparedStatement, idx: Int): Unit = p.setObject(idx, asPgObject(e), sqlType)
override def getValue(r: ResultSet, idx: Int): E = {
val value = r.getString(idx)
if (r.wasNull) null.asInstanceOf[E] else enum.withName(value).asInstanceOf[E]
}
override def updateValue(e: E, r: ResultSet, idx: Int): Unit = r.updateObject(idx, asPgObject(e))
override def valueToSQLLiteral(e: E) = if (e eq null) "NULL" else s"'${e.name}'"
private def asPgObject(e: E) = {
val obj = new org.postgresql.util.PGobject
obj.setType(enumerationTypeName)
obj.setValue(if (e eq null) null else e.name)
obj
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment