Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpolation support for Traversable[SQLSyntax] #216

Closed
pheaver opened this issue Apr 17, 2014 · 2 comments
Closed

Interpolation support for Traversable[SQLSyntax] #216

pheaver opened this issue Apr 17, 2014 · 2 comments
Assignees
Milestone

Comments

@pheaver
Copy link

pheaver commented Apr 17, 2014

Sometimes I want to render SQL like this:

(a, b) IN ((1, 2), (3, 4), (5, 6))

To do that, I would expect something like this to work:

val columns: Seq[SQLSyntax] = Seq("a", "b").map(SQLSyntax.createUnsafely(_, Nil))
val values: Seq[SQLSyntax] = Seq(Seq(1, 2), Seq(3, 4), Seq(5, 6)).map { xs => sqls"($xs)" }
sqls"$columns IN ($values)"

However, the implementation in SQLInterpolationString treats all Traversables the same, without looking at whether the arguments are SQLSyntax, so that will actually render to the following SQL:

(?, ?) IN (?, ?, ?)

I believe this can be fixed like this:

private def addPlaceholders(sb: StringBuilder, param: Any): StringBuilder = param match {
  case _: String => sb += '?'
  case t: Traversable[_] => t.map(addPlaceholders(new StringBuilder, _)).addString(sb, ", ")
  case LastParameter => sb
  case SQLSyntax(s, _) => sb ++= s
  case _ => sb += '?'
}

private def buildParams(params: Traversable[Any]): Seq[Any] = params.foldLeft(Seq.newBuilder[Any]) {
  case (b, s: String) => b += s
  case (b, t: Traversable[_]) => b ++= buildParams(t)
  case (b, SQLSyntax(_, params)) => b ++= params
  case (b, n) => b += n
}.result()

I tested these definitions and it worked for the few examples I tried.

@seratch
Copy link
Member

seratch commented Apr 17, 2014

That sounds cool. If you have time, please send a pull request. Or you can leave it to me.

@seratch seratch self-assigned this Apr 17, 2014
@seratch seratch added this to the version 2.0.0 milestone Apr 17, 2014
@pheaver
Copy link
Author

pheaver commented Apr 17, 2014

Ok I will do a pull request soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants