Created
November 15, 2015 13:34
-
-
Save wfaler/8cc931a23293514c546c to your computer and use it in GitHub Desktop.
Generic deriving of a type-class that sets column values with JDBC, can derive for any arbitrary case-class (if you add a few more basic types)
This file contains hidden or 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 shapeless._ | |
import java.sql.PreparedStatement | |
trait ToRow[A]{ | |
def toRow(a: A, statement: PreparedStatement): (Int) => Unit | |
} | |
implicit val stringToRow: ToRow[String] = new ToRow[String]{ | |
def toRow(s: String, statement: PreparedStatement) = statement.setString(_,s) | |
} | |
implicit val intToRow: ToRow[Int] = new ToRow[Int]{ | |
def toRow(s: Int, statement: PreparedStatement) = statement.setInt(_,s) | |
} | |
implicit val hnilToRow = new ToRow[HNil]{ | |
def toRow(s: HNil, statement: PreparedStatement) = (i: Int) => Unit | |
} | |
implicit def hconsToRow[H: ToRow, T <: HList: ToRow]: ToRow[H :: T] = new ToRow[H :: T]{ | |
def toRow(a: (H :: T), statement: PreparedStatement) = (i: Int) => { | |
a match{ | |
case (h :: t) => { | |
implicitly[ToRow[H]].toRow(h, statement)(i) | |
implicitly[ToRow[T]].toRow(t, statement)(i + 1) | |
} | |
} | |
} | |
} | |
implicit def caseClassToRow[C, R <: HList](implicit | |
gen: Generic.Aux[C, R], | |
rc: ToRow[R] | |
): ToRow[C] = new ToRow[C]{ | |
def toRow(c: C, statement: PreparedStatement) = rc.toRow(gen.to(c), statement) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment