Skip to content

Commit

Permalink
Ensure placeholders and parameters are processed in a consistent order
Browse files Browse the repository at this point in the history
  • Loading branch information
coreywoodfield committed Nov 18, 2024
1 parent fcfd615 commit 383d813
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions relate/src/main/scala/com/lucidchart/relate/Parameters.scala
Original file line number Diff line number Diff line change
Expand Up @@ -632,14 +632,17 @@ trait MultipleParameter extends Parameter {
}
}

class TupleParameter(val params: Iterable[SingleParameter]) extends MultipleParameter {
class TupleParameter(_params: Iterable[SingleParameter]) extends MultipleParameter {
// get a `Seq` to make sure placeholder and parameterize get the same ordering
override protected val params = _params.toSeq
def placeholder = params.iterator.map(_.placeholder).mkString(",")
}

object TupleParameter {
def apply(params: SingleParameter*) = new TupleParameter(params)
}

class TuplesParameter(val params: Iterable[TupleParameter]) extends MultipleParameter {
class TuplesParameter(_params: Iterable[TupleParameter]) extends MultipleParameter {
override protected val params = _params.toSeq
def placeholder = if (params.isEmpty) "" else params.map(_.placeholder).mkString("(", "),(", ")")
}
17 changes: 17 additions & 0 deletions relate/src/test/scala/ParameterizationTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,23 @@ class ParameterizationTest extends Specification {
val querySql = sql"SELECT * FROM myTable WHERE id IN ($hashSet)"
querySql.toString mustEqual "SELECT * FROM myTable WHERE id IN (?,?,?)"
}

"provide placeholders and parameters in the same order" in {
val setParams = scala.collection.mutable.Map.empty[Int, Int]
case class Param(int: Int) extends SingleParameter {
protected[this] def set(statement: PreparedStatement, i: Int) = setParams(i) = int
override def placeholder = int.toString
}

val paramsSet: Parameter = Set(Param(1), Param(2), Param(3))
paramsSet.parameterize(null, 1)
val query = sql"SELECT * FROM myTable WHERE id IN ($paramsSet)".toString

setParams must haveSize(3)
val order = setParams.toSeq.sortBy(_._1).map(_._2).mkString(",")
// the order of the "placeholders" should match the order of the parameters
query mustEqual s"SELECT * FROM myTable WHERE id IN ($order)"
}
}

"tuple paramater" should {
Expand Down

0 comments on commit 383d813

Please sign in to comment.