-
-
Save sundaram161989/d7a639f5d1e2e183fbdf8626c88d2f7f to your computer and use it in GitHub Desktop.
Custom H2 Profile with JdbcType for Array's and an extension to support "ARRAY_CONTAINS" function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.{ PreparedStatement, ResultSet } | |
import slick.ast.Library.SqlFunction | |
import slick.ast.TypedType | |
import slick.jdbc.{ H2Profile, JdbcType } | |
import slick.lifted.{ ExtensionMethods, Rep } | |
import scala.collection.JavaConverters._ | |
import scala.reflect.ClassTag | |
trait CustomH2Profile extends H2Profile { | |
class SeqJdbcType[T]( | |
baseSqlType: String, | |
colToType: Any => T | |
)(implicit override val classTag: ClassTag[Seq[T]], ctag: ClassTag[T]) | |
extends DriverJdbcType[Seq[T]] { | |
override def sqlType: Int = java.sql.Types.ARRAY | |
override def setValue(v: Seq[T], p: PreparedStatement, idx: Int): Unit = { | |
val array = p.getConnection.createArrayOf(baseSqlType, v.asJava.toArray) | |
p.setArray(idx, array) | |
} | |
override def getValue(r: ResultSet, idx: Int): Seq[T] = | |
r.getArray(idx).getArray.asInstanceOf[Array[Object]].toList.map(colToType) | |
override def updateValue(v: Seq[T], r: ResultSet, idx: Int): Unit = { | |
// do nothing | |
} | |
} | |
class SeqColumnExtensionMethods[B0, SEQ[B0], P1](val c: Rep[P1])(implicit tm0: JdbcType[B0], | |
tm: JdbcType[SEQ[B0]]) | |
extends ExtensionMethods[SEQ[B0], P1] { | |
protected implicit def b1Type: TypedType[SEQ[B0]] = implicitly[TypedType[SEQ[B0]]] | |
val Contains = new SqlFunction("ARRAY_CONTAINS") | |
def contains[P2, R](e: Rep[P2])(implicit om: o#arg[B0, P2]#to[Boolean, R]): Rep[R] = | |
om.column(Contains, n, e.toNode)(api.booleanColumnType) | |
} | |
override val api = CustomApi | |
object CustomApi extends API { | |
implicit val seqStringType: DriverJdbcType[Seq[String]] = | |
new SeqJdbcType[String](baseSqlType = "VARCHAR", colToType = _.toString) | |
implicit def simpleArrayColumnExtensionMethods[B1, SEQ[B1]]( | |
c: Rep[SEQ[B1]] | |
)(implicit tm: JdbcType[B1], tm1: JdbcType[SEQ[B1]]): SeqStringColumnExtensionMethods[B1, SEQ, SEQ[B1]] = | |
new SeqStringColumnExtensionMethods[B1, SEQ, SEQ[B1]](c) | |
} | |
} | |
object CustomH2Profile extends CustomH2Profile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment