在sql插值器中使用方法

时间:2017-12-29 09:16:34

标签: sql scala unit-testing junit slick

使用scala 2.11和Slick 2.11

在scala类中,我有两种方法:

  • getSQL,返回String SQL
  • getSqlStreamingAction,它使用sql interpolator
  • 返回一个组合的SqlStreamingAction

代码

def getSQL(id: Int): String = {
    var fields_string = "";
    for ((k,v) <- field_map) fields_string += k + ", ";
    fields_string = fields_string.dropRight(2) // remove last ", "
    "SELECT "+ fields_string +" FROM my_table WHERE id = " + id
  }

def getSqlStreamingAction (id: Int): SqlStreamingAction[Vector[OtherObject], OtherObject, Effect] = {
    val r = GetResult(r => OtherObject(r.<<, r.<<))

    // this works
    var fields_string = "";
    for ((k,v) <- field_map) fields_string += k + ", ";
    sql"""SELECT #$fields_string FROM my_table WHERE id = #$id""".as(r)

    // But I want to use the method getSQL to retrieve the SQL String
    // I imagine something like this, but of course it doesn't work :)
    //sql"getSQL($id)".as(r)

我想为单元测试目的分离方法,所以我想对sql插值器使用getSQL方法

那么,我如何使用Slick sql插值器的方法?

注意:我在Scala中很新鲜

1 个答案:

答案 0 :(得分:0)

-1对我来说。

解决方案:

def getSqlStreamingAction (id: Int): SqlStreamingAction[Vector[OtherObject], OtherObject, Effect] = {
    val r = GetResult(r => OtherObject(r.<<, r.<<))

    var sql_string: String = getSQL(id)
    sql"""#$sql_string""".as(r)