Skip to content

Commit

Permalink
Merge pull request #83 from lucidsoftware/parameterize-big-decimal
Browse files Browse the repository at this point in the history
Parameterize big decimal
  • Loading branch information
tmccombs authored Sep 26, 2023
2 parents 2964822 + ad9553d commit 2aa3fe9
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions relate/src/main/scala/com/lucidchart/relate/Parameterizable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,27 @@ import java.util.UUID

trait Parameterizable[-A] {
final def contraMap[B](f: B => A) = Parameterizable((statement, i, value: B) => set(statement, i, f(value)), setNull)
/**
* Set the parameterized value at index {@code i} in the prepared statement to the {@code value}.
*/
def set(statement: PreparedStatement, i: Int, value: A)
/**
* Set the parameterized value at index {@code i} in the prepared statement to {@code null}.
*/
def setNull(statement: PreparedStatement, i: Int)
final def setOption(statement: PreparedStatement, i: Int, value: Option[A]) =
value.fold(setNull(statement, i))(set(statement, i, _))
}

object Parameterizable {
/**
* Create new Parameterizable instance from functions for set and setNull
*
* @param f
* The function to implement [[Parameterizable#set]] with
* @param g
* The function to implement [[Parameterizable#setNull]] with
*/
def apply[A](f: (PreparedStatement, Int, A) => Unit, g: (PreparedStatement, Int) => Unit) = new Parameterizable [A] {
def set(statement: PreparedStatement, i: Int, value: A) = f(statement, i, value)
def setNull(statement: PreparedStatement, i: Int) = g(statement, i)
Expand All @@ -23,7 +37,9 @@ object Parameterizable {
def from[A, B : Parameterizable](f: A => B) = implicitly[Parameterizable[B]].contraMap(f)

implicit val array = apply(_.setArray(_, _: Array), _.setNull(_, Types.ARRAY))
// ideally, this would be named jBigDecimal, but that wouldn't be backwards compatibility
implicit val bigDecimal = apply(_.setBigDecimal(_, _: java.math.BigDecimal), _.setNull(_, Types.DECIMAL))
implicit val scalaBigDecimal = apply((stmt: PreparedStatement, i: Int, v: scala.math.BigDecimal) => stmt.setBigDecimal(i, v.bigDecimal), _.setNull(_, Types.DECIMAL))
implicit val blob = apply(_.setBlob(_, _: Blob), _.setNull(_, Types.BLOB))
implicit val boolean = apply(_.setBoolean(_, _: Boolean), _.setNull(_, Types.BOOLEAN))
implicit val byte = apply(_.setByte(_, _: Byte), _.setNull(_, Types.TINYINT))
Expand Down

0 comments on commit 2aa3fe9

Please sign in to comment.