Is it possible to use IN clause in plain sql Slick?

孤者浪人 提交于 2019-11-29 16:52:20

问题


For example, I want to create the following query:

SELECT c.* FROM Coffees c WHERE c.name IN ('robusta', 'arabica')

My attempt failed:

val cnames = List("robusta", "arabica")
sql""" SELECT c.* FROM Coffees c WHERE c.name IN ${cnames} """
  could not find implicit value for parameter pconv: 
  scala.slick.jdbc.SetParameter[List[String]]

Is it possible to somehow use in clause in Slick plain sql queries?


回答1:


I don't see anything out of the box to handle this. You're best bet is probably something like this:

val cnames = List("robusta", "arabica").map("'" + _ + "'").mkString(",")
val query = sql""" SELECT c.* FROM Coffees c WHERE c.name IN (${cnames}) """



回答2:


The type safe "lifted embedding" API supports this as well:

val ids = List(1,2,3)
val q = for {
  f <- Foo if f.id inSet ids // ids is not bound
}

slick.typesafe.com/doc/1.0.1/api/index.html#scala.slick.lifted.ColumnExtensionMethods




回答3:


Although it's not safe for SQL injection, you can use #$ interpolator:

val ids = idList.map("'" + _ + "'").mkString(",")
val q = sql"""select name from mytable where id in (#$ids)"""



回答4:


There is a library that (among other things) introduces a binder for list properties to Slick's SQL interpolator: https://index.scala-lang.org/tarao/slick-jdbc-extension-scala/slick-jdbc-extension

Example code from the page:

  import util.NonEmpty

  def findAll(entryIds: Option[NonEmpty[Long]]): Seq[Entry] = entryIds match {
    case Some(ids) => run { sql"""
    | SELECT * FROM ${table}
    | WHERE entry_id IN $ids
    """.as[Entry] }
    case None => Seq.empty
  }


来源:https://stackoverflow.com/questions/17408444/is-it-possible-to-use-in-clause-in-plain-sql-slick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!