斯卡拉光滑的方法到目前为止我无法理解

ses*_*ses 88 scala magic-methods scalaquery playframework-2.0 slick

我尝试了解一些Slick的作品以及它需要什么.

这是一个例子:

package models

case class Bar(id: Option[Int] = None, name: String)

object Bars extends Table[Bar]("bar") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)

  // This is the primary key column
  def name = column[String]("name")

  // Every table needs a * projection with the same type as the table's type parameter
  def * = id.? ~ name <>(Bar, Bar.unapply _)
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下*这里方法的目的是什么<>,为什么unapply?什么是Projection - 方法~'返回实例Projection2

Fai*_*aiz 196

[更新] - 增加(又一个)关于for理解的解释

  1. *方法:

    这将返回默认投影 - 您的描述方式如下:

    '我通常感兴趣的所有列(或计算值).

    你的桌子可能有几个字段; 您只需要一个子集作为默认投影.默认投影必须与表的类型参数匹配.

    我们一次拿一个.没有<>东西,只需*:

    // First take: Only the Table Defintion, no case class:
    
    object Bars extends Table[(Int, String)]("bar") {
      def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
      def name = column[String]("name")
    
      def * = id ~ name // Note: Just a simple projection, not using .? etc
    }
    
    // Note that the case class 'Bar' is not to be found. This is 
    // an example without it (with only the table definition)
    
    Run Code Online (Sandbox Code Playgroud)

    只需这样的表定义就可以进行如下查询:

    implicit val session: Session = // ... a db session obtained from somewhere
    
    // A simple select-all:
    val result = Query(Bars).list   // result is a List[(Int, String)]
    
    Run Code Online (Sandbox Code Playgroud)

    (Int, String)导致a 的默认投影List[(Int, String)] 用于简单查询,例如这些.

    // SELECT b.name, 1 FROM bars b WHERE b.id = 42;
    val q = 
       for (b <- Bars if b.id === 42) 
         yield (b.name ~ 1)
         // yield (b.name, 1) // this is also allowed: 
                              // tuples are lifted to the equivalent projection.
    
    Run Code Online (Sandbox Code Playgroud)

    这是什么类型的q?这是一个Query投影(String, Int).当被调用时,它返回一个List(String, Int)元组按投影.

     val result: List[(String, Int)] = q.list
    
    Run Code Online (Sandbox Code Playgroud)

    在这种情况下,您已yieldfor理解子句中定义了所需的投影.

  2. 现在关于<>Bar.unapply.

    这提供了所谓的映射投影.

    到目前为止,我们已经看到了如何使用sclick来表达Scala中的返回(或计算值)投影的查询; 因此,执行这些查询时,你必须考虑的结果行的查询作为Scala的元组.元组的类型将与定义的Projection(通过您for在上一个示例中的理解,默认*投影)相匹配 .这就是为什么field1 ~ field2返回的投影Projection2[A, B]这里 A是类型field1B是的类型field2.

    q.list.map {
      case (name, n) =>  // do something with name:String and n:Int
    }
    
    Queury(Bars).list.map {
      case (id, name) =>  // do something with id:Int and name:String 
    }
    
    Run Code Online (Sandbox Code Playgroud)

    我们正在处理元组,如果我们有太多列,这可能很麻烦.我们想把结果看作TupleN是命名字段的一些对象.

    (id ~ name)  // A projection
    
    // Assuming you have a Bar case class:
    case class Bar(id: Int, name: String) // For now, using a plain Int instead
                                          // of Option[Int] - for simplicity
    
    (id ~ name <> (Bar, Bar.unapply _)) // A MAPPED projection
    
    // Which lets you do:
    Query(Bars).list.map ( b.name ) 
    // instead of
    // Query(Bars).list.map { case (_, name) => name }
    
    // Note that I use list.map instead of mapResult just for explanation's sake.
    
    Run Code Online (Sandbox Code Playgroud)

    这是如何运作的?<>进行投影Projection2[Int, String]并返回类型的映射投影Bar.这两个参数Bar, Bar.unapply _ 告诉我这个(Int, String)投影必须如何映射到案例类.

    这是一种双向映射; Bar是case类的构造函数,所以这是从(id: Int, name: String)a到a 所需的信息Bar.而且unapply ,如果你已经猜到了,是相反的.

    哪里unapply来的?这是一个标准的Scala方法,可用于任何普通的case类 - 只是定义Bar为你提供了Bar.unapply一个可以用来取回它的提取器id以及用nameBar构建的提取器:

    val bar1 = Bar(1, "one")
    // later
    val Bar(id, name) = bar1  // id will be an Int bound to 1,
                              // name a String bound to "one"
    // Or in pattern matching
    val bars: List[Bar] = // gotten from somewhere
    val barNames = bars.map {
      case Bar(_, name) => name
    }
    
    val x = Bar.unapply(bar1)  // x is an Option[(String, Int)]
    
    Run Code Online (Sandbox Code Playgroud)

    因此,您的默认投影可以映射到您最期望使用的案例类:

    object Bars extends Table[Bar]("bar") {
      def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
      def name = column[String]("name")
      def * = id ~ name <>(Bar, Bar.unapply _)
    }
    
    Run Code Online (Sandbox Code Playgroud)

    或者您甚至可以按查询进行:

    case class Baz(name: String, num: Int)
    
    // SELECT b.name, 1 FROM bars b WHERE b.id = 42;
    val q1 = 
       for (b <- Bars if b.id === 42) 
         yield (b.name ~ 1 <> (Baz, Baz.unapply _))
    
    Run Code Online (Sandbox Code Playgroud)

    这里的类型q1Query带有映射投影的Baz.当被调用时,它返回ListBaz对象:

     val result: List[Baz] = q1.list
    
    Run Code Online (Sandbox Code Playgroud)
  3. 最后,作为旁白,.?提供选项提升 - Scala处理可能不是的价值的方式.

     (id ~ name)   // Projection2[Int, String] // this is just for illustration
     (id.? ~ name) // Projection2[Option[Int], String]
    
    Run Code Online (Sandbox Code Playgroud)

    包装起来,将与您原来的定义很好地配合Bar:

    case class Bar(id: Option[Int] = None, name: String)
    
    // SELECT b.id, b.name FROM bars b WHERE b.id = 42;
    val q0 = 
       for (b <- Bars if b.id === 42) 
         yield (b.id.? ~ b.name <> (Bar, Bar.unapply _))
    
    
    q0.list // returns a List[Bar]
    
    Run Code Online (Sandbox Code Playgroud)
  4. 回应关于Slick如何使用for理解的评论:

    不知何故,monads总是设法出现并要求成为解释的一部分......

    因为理解不仅仅是对集合的具体要求.它们可以用于任何类型的Monad,而集合只是Scala中可用的多种monad类型之一.

    但是由于收藏品很熟悉,它们为解释提供了一个很好的起点:

    val ns = 1 to 100 toList; // Lists for familiarity
    val result = 
      for { i <- ns if i*i % 2 == 0 } 
        yield (i*i)
    // result is a List[Int], List(4, 16, 36, ...)
    
    Run Code Online (Sandbox Code Playgroud)

    在Scala中,for comprehension是方法(可能是嵌套的)方法调用的语法糖:上面的代码(或多或少)等效于:

    ns.filter(i => i*i % 2 == 0).map(i => i*i)
    
    Run Code Online (Sandbox Code Playgroud)

    基本上,任何与filter,map,flatMap 的方法(换言之,一个单子)可以以用于 for理解在适当位置的ns.一个很好的例子是Option monad.这里就是同前面的例子中for语句的工作方式上都 ListOption单子:

    // (1)
    val result = 
      for { 
        i <- ns          // ns is a List monad
        i2 <- Some(i*i)  // Some(i*i) is Option
          if i2 % 2 == 0 // filter
      } yield i2
    
    // Slightly more contrived example:
    def evenSqr(n: Int) = { // return the square of a number 
      val sqr = n*n         // only when the square is even
      if (sqr % 2 == 0) Some (sqr)
      else None
    }
    
    // (2)
    result = 
      for { 
        i <- ns  
        i2 <- evenSqr(i) // i2 may/maynot be defined for i!
      } yield i2
    
    Run Code Online (Sandbox Code Playgroud)

    在最后一个示例中,转换可能如下所示:

    // 1st example
    val result = 
      ns.flatMap(i => Some(i*i)).filter(i2 => i2 %2 ==0)
    
    // Or for the 2nd example
    result = 
      ns.flatMap(i => evenSqr(i)) 
    
    Run Code Online (Sandbox Code Playgroud)

    在油滑,查询是一元-他们只是用对象map,flatMapfilter方法.所以for理解(在*方法的解释中显示)只是转换为:

    val q = 
      Query(Bars).filter(b => b.id === 42).map(b => b.name ~ 1)
    // Type of q is Query[(String, Int)]
    
    val r: List[(String, Int)] = q.list // Actually run the query
    
    Run Code Online (Sandbox Code Playgroud)

    正如你所看到的,flatMap,mapfilter用于产生Query通过反复改造Query(Bars) 与每个调用filtermap.在集合的情况下,这些方法实际上迭代并过滤集合,但在Slick中它们用于生成SQL.更多细节: Scala Slick如何将Scala代码转换为JDBC?


Dom*_*mra 6

由于没有其他人回答,这可能有助于您入门.我不太了解Slick.

Slick文档:

提升嵌入:

每个表都需要一个包含默认投影的*方法.这描述了从查询返回行(以表对象的形式)时返回的内容.Slick的*投影不必与数据库中的投影相匹配.您可以添加新列(例如,使用计算值)或省略某些列.对应于*投影的非提升类型作为Table的类型参数给出.对于简单的非映射表,这将是单列类型或列类型的元组.

换句话说,光滑需要知道如何处理从数据库返回的行.您定义的方法使用其解析器组合函数将列定义组合成可以在行上使用的内容.

  • Aha .. - 所有案例类都实现了Product trait,而unapply是Product的方法.魔法. (2认同)