Created
May 2, 2016 19:34
-
-
Save davidpeklak/5f2e8f30becc03b6306d0782738ccd93 to your computer and use it in GitHub Desktop.
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 java.sql.{Connection, PreparedStatement} | |
object SqlInterpolation { | |
case class StatementPreparation(string: String, effect: PreparedStatement => Unit) { | |
override def toString: String = s"""StatementPreparation("$string", $effect)""" | |
} | |
implicit class ConnectionOps(val connection: Connection) extends AnyVal { | |
def prepareStatement(sp: StatementPreparation): PreparedStatement = { | |
import sp._ | |
val preparedStatement = connection.prepareStatement(string) | |
effect(preparedStatement) | |
preparedStatement | |
} | |
} | |
trait TypeSetter { | |
def apply(arg: Any, pos: Int): PreparedStatement => Unit | |
} | |
class TypeSetterImpl extends TypeSetter { | |
def apply(arg: Any, pos: Int): PreparedStatement => Unit = arg match { | |
case i: Int => new Function1[PreparedStatement, Unit] { | |
def apply(ps: PreparedStatement): Unit = ps.setInt(pos, i) | |
override def toString(): String = s"ps.setInt($pos, $i)" | |
} | |
case _ => _ => () | |
} | |
} | |
implicit val tsi = new TypeSetterImpl | |
implicit class SqlHelper(val stringContext: StringContext) extends AnyVal { | |
def sql(args: Any*)(implicit typeSetter: TypeSetter): StatementPreparation = { | |
val string = stringContext.parts.mkString(" ? ") | |
val effects = for ((arg, pos) <- args.zipWithIndex) yield typeSetter(arg, pos + 1) | |
val effect = new Function1[PreparedStatement, Unit] { | |
def apply(ps: PreparedStatement): Unit = effects.foreach(_(ps)) | |
override def toString(): String = effects.mkString(", ") | |
} | |
StatementPreparation(string, effect) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment