21

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?

4

4 回答 4

32

类型安全的“提升嵌入”API 也支持这一点:

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

于 2013-07-02T10:11:42.343 回答
4

虽然 SQL 注入不安全,但您可以使用#$插值器:

val ids = idList.mkString("'", "','", "'")
val q = sql"""select name from mytable where id in (#$ids)"""
于 2016-09-13T06:21:40.707 回答
2

我没有看到任何开箱即用的东西来处理这个问题。你最好的选择可能是这样的:

val cnames = List("robusta", "arabica").mkString("'", "','", "'")
val query = sql""" SELECT c.* FROM Coffees c WHERE c.name IN (${cnames}) """
于 2013-07-01T16:30:43.943 回答
0

有一个库(除其他外)将列表属性的绑定器引入到 Slick 的 SQL 插值器: https ://index.scala-lang.org/tarao/slick-jdbc-extension-scala/slick-jdbc-extension

页面中的示例代码:

  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
  }
于 2019-03-19T18:57:27.880 回答