Skip to content
This repository has been archived by the owner on Oct 28, 2024. It is now read-only.

Make SqlWithParams composable #61

Merged
merged 2 commits into from
May 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ trait SqlInterpolatorTrait {
* val select = conn.select(sql"select * from test where id = \$id")
* }}}
*
* The code above produces `select * from test where id = :p1` statement
* with `p1` parameter bound to value `10`.
* The code above produces `select * from test where id = ?` statement
* with the sole parameter bound to value `10`.
*
* The interpolator supports also literal values that allow to dynamically
* construct statements. To use this feature, instead of \$, use #\$,
Expand All @@ -40,24 +40,22 @@ trait SqlInterpolatorTrait {
* val select = conn.select(sql"select * from #\$table where id = \$id")
* }}}
*
* The code above produces `select * from test where id = :p1` statement
* with `p1` parameter bound to value `10`.
* The code above produces `select * from test where id = ?` statement
* with the sole parameter bound to value `10`.
*/
def sql(args: Any*): SqlWithParams = {
sc.checkLengths(args)

var sqlArgs = Vector.empty[Any]
val argsIter = args.iterator
var sqlArgIdx = 1
val sql = new StringBuilder

sc.parts.foreach { part =>
if (part.endsWith("#") && argsIter.hasNext) {
sql.append(part.take(part.length - 1))
sql.append(argsIter.next)
} else if (argsIter.hasNext) {
sql.append(part).append(":p").append(sqlArgIdx)
sqlArgIdx += 1
sql.append(part).append("?")
sqlArgs = sqlArgs :+ argsIter.next
} else {
sql.append(part)
Expand Down
19 changes: 18 additions & 1 deletion rdbc-api-scala/src/main/scala/io/rdbc/sapi/SqlWithParams.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,22 @@ import io.rdbc.ImmutIndexedSeq
* val id = 0
* val s: SqlWithParams = sql"select * from test where id = \$id"
* }}}
*
* Instances created by the interpolator can be composed:
* {{{
* import io.rdbc.sapi._
* val x = 0
* val y = 0
* val s: SqlWithParams =
* sql"select * from test where x = \x" +
* sql"and y = $y"
* }}}
*/
case class SqlWithParams(sql: String, params: ImmutIndexedSeq[Any])
case class SqlWithParams(sql: String, params: ImmutIndexedSeq[Any]) {
def +(other: SqlWithParams): SqlWithParams = {
copy(
sql = sql + other.sql,
params = params.toVector ++ other.params
)
}
}