• 浅谈Slick(1)- 基本功能描述


       Slick (Scala language-integrated connection kit)是scala的一个FRM(Functional Relational Mapper),即函数式的关系数据库编程工具库。Slick的主要目的是使关系数据库能更容易、更自然的融入函数式编程模式,它可以使使用者像对待scala集合一样来处理关系数据库表。也就是说可以用scala集合的那些丰富的操作函数来处理库表数据。Slick把数据库编程融入到scala编程中,编程人员可以不需要编写SQL代码。我把Slick官方网站上Slick3.1.1文档的Slick介绍章节中的一些描述和例子拿过来帮助介绍Slick的功能。下面是Slick数据库和类对象关系对应的一个例子:

     1 import slick.driver.H2Driver.api._
     2 object slickIntro {
     3   case class Coffee(id: Int, 
     4                     name: String,
     5                     supID: Int = 0,
     6                     price: Double ,
     7                     sales: Int = 0,
     8                     total: Int = 0)
     9 
    10   class Coffees(tag: Tag) extends Table[Coffee](tag, "COFFEES") {
    11     def id = column[Int]("COF_ID", O.PrimaryKey, O.AutoInc)
    12     def name = column[String]("COF_NAME")
    13     def supID = column[Int]("SUP_ID")
    14     def price = column[Double]("PRICE")
    15     def sales = column[Int]("SALES", O.Default(0))
    16     def total = column[Int]("TOTAL", O.Default(0))
    17     def * = (id, name, supID, price, sales, total) <> (Coffee.tupled, Coffee.unapply)
    18   }
    19   val coffees = TableQuery[Coffees]               
    20 //> coffees  : slick.lifted.TableQuery[worksheets.slickIntro.Coffees] = Rep(TableExpansion)
    21 }

    我们把数据库中的COFFEES表与Coffees类做了对应,包括字段、索引、默认值、返回结果集字段等。现在这个coffees就是scala里的一个对象,但它代表了数据库表。现在我们可以用scala语言来编写数据存取程序了:

    1 val limit = 10.0                                 //> limit  : Double = 10.0
    2 // // 写Query时就像下面这样:
    3 ( for( c <- coffees; if c.price < limit ) yield c.name ).result
    4    //> res0: slick.driver.H2Driver.StreamingDriverAction[Seq[String],String,slick.dbio.Effect.Read] = slick.driver.JdbcActionComponent$QueryActionExtensionMethodsImpl$$anon$1@46cdf8bd
    5 // 相当于 SQL: select COF_NAME from COFFEES where PRICE < 10.0

    或者下面这些不同的Query:

    1 // 返回"name"字段的Query
    2 // 相当于 SQL: select NAME from COFFEES
    3 coffees.map(_.name)                               
    4 //> res1: slick.lifted.Query[slick.lifted.Rep[String],String,Seq] = Rep(Bind)
    5 // 选择 price < 10.0 的所有记录Query
    6 // 相当于 SQL: select * from COFFEES where PRICE < 10.0
    7 coffees.filter(_.price < 10.0)                    
    8 //> res2: slick.lifted.Query[worksheets.slickIntro.Coffees,worksheets.slickIntro.Coffees#TableElementType,Seq] = Rep(Filter @1946988038)

    我们可以这样表述:coffees.map(_.name) >>> coffees.map{row=>row.name}, coffees.filter(_.price<10.0) >>> coffees.filter{row=>row.price<10.0),都是函数式集合操作语法。

    Slick把Query编写与scala语言集成,这使编程人员可以用熟悉惯用的scala来表述SQL Query,直接的好处是scalac在编译时就能够发现Query错误:

    1 //coffees.map(_.prices)   
    2 //编译错误:value prices is not a member of worksheets.slickIntro.Coffees    

    当然,嵌入scala的Query还可以获得运行效率的提升,因为在编译时可以进行前期优化。

    最新版本的Slick最大的特点是采用了Functional I/O技术,从而实现了安全的多线程无阻碍I/O操作。再就是实现了Query的函数组合(functional composition),使Query编程更贴近函数式编程模式。通过函数组合实现代码重复利用,提高编程工作效率。具体实现方式是利用freemonad(DBIOAction类型就是个freemonad)的延迟运算模式,将DBIOAction的编程和实际运算分离,在DBIOAction编程过程中不会产生副作用(side-effect),从而实现纯代码的函数组合。我们来看看Query函数组合和DBIOAction运算示范:

     1 import scala.concurrent.ExecutionContext.Implicits.global
     2 val qDelete = coffees.filter(_.price > 0.0).delete
     3 //> qDelete  : slick.driver.H2Driver.DriverAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write] ...
     4 val qAdd1 = (coffees returning coffees.map(_.id)) += Coffee(name="Columbia",price=128.0)
     5 //> qAdd1  : slick.profile.FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]...
     6 val qAdd2 = (coffees returning coffees.map(_.id)) += Coffee(name="Blue Mountain",price=828.0)
     7 //> qAdd2  : slick.profile.FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]...
     8 def getNameAndPrice(n: Int) = coffees.filter(_.id === n)
     9     .map(r => (r.name,r.price)).result.head      
    10 //> getNameAndPrice: (n: Int)slick.profile.SqlAction[(String, Double),slick.dbio.NoStream,slick.dbio.Effect.Read]
    11 
    12 val actions = for {
    13   _ <- coffees.schema.create
    14   _ <- qDelete
    15   c1 <- qAdd1
    16   c2 <- qAdd2
    17   (n1,p1) <- getNameAndPrice(c1)
    18   (n2,p2) <- getNameAndPrice(c2)
    19 } yield (n1,p1,n2,p2)                             
    20 //> actions  : slick.dbio.DBIOAction[(String, Double, String, Double),..

    我们可以放心的来组合这个actions,不用担心有任何副作用。actions的类型是:DBAction[String,Double,String,Double]。我们必须用Database.Run来真正开始运算,产生副作用:

     1 import java.sql.SQLException
     2 import scala.concurrent.Await
     3 import scala.concurrent.duration._
     4 val db = Database.forURL("jdbc:h2:mem:demo", driver="org.h2.Driver")
     5      //> db  : slick.driver.H2Driver.backend.DatabaseDef = slick.jdbc.JdbcBackend$DatabaseDef@1a5b6f42
     6 Await.result(
     7       db.run(actions.transactionally).map { res =>
     8         println(s"Add coffee: ${res._1},${res._2} and ${res._3},${res._4}")
     9       }.recover {
    10         case e: SQLException => println("Caught exception: " + e.getMessage)
    11       }, Duration.Inf)      //> Add coffee: Columbia,128.0 and Blue Mountain,828.0

    在特殊的情况下我们也可以引用纯SQL语句:Slick提供了Plain SQL API, 如下:

    1 val limit = 10.0
    2 sql"select COF_NAME from COFFEES where PRICE < $limit".as[String]
    3 // 用$来绑定变量: // select COF_NAME from COFFEES where PRICE < ?

    下面是这篇讨论的示范代码:

     1 package worksheets
     2 import slick.driver.H2Driver.api._
     3 object slickIntro {
     4   case class Coffee(id: Int = 0,
     5                     name: String,
     6                     supID: Int = 0,
     7                     price: Double,
     8                     sales: Int = 0,
     9                     total: Int = 0)
    10 
    11   class Coffees(tag: Tag) extends Table[Coffee](tag, "COFFEES") {
    12     def id = column[Int]("COF_ID", O.PrimaryKey, O.AutoInc)
    13     def name = column[String]("COF_NAME")
    14     def supID = column[Int]("SUP_ID")
    15     def price = column[Double]("PRICE")
    16     def sales = column[Int]("SALES", O.Default(0))
    17     def total = column[Int]("TOTAL", O.Default(0))
    18     def * = (id, name, supID, price, sales, total) <> (Coffee.tupled, Coffee.unapply)
    19   }
    20   val coffees = TableQuery[Coffees]
    21   
    22  val limit = 10.0
    23 // // 写Query时就像下面这样:
    24 ( for( c <- coffees; if c.price < limit ) yield c.name ).result
    25 // 相当于 SQL: select COF_NAME from COFFEES where PRICE < 10.0
    26 
    27 // 返回"name"字段的Query
    28 // 相当于 SQL: select NAME from COFFEES
    29 coffees.map(_.name)
    30 // 选择 price < 10.0 的所有记录Query
    31 // 相当于 SQL: select * from COFFEES where PRICE < 10.0
    32 coffees.filter(_.price < 10.0)
    33 //coffees.map(_.prices)
    34 //编译错误:value prices is not a member of worksheets.slickIntro.Coffees
    35 
    36 
    37 import scala.concurrent.ExecutionContext.Implicits.global
    38 val qDelete = coffees.filter(_.price > 0.0).delete
    39 val qAdd1 = (coffees returning coffees.map(_.id)) += Coffee(name="Columbia",price=128.0)
    40 val qAdd2 = (coffees returning coffees.map(_.id)) += Coffee(name="Blue Mountain",price=828.0)
    41 def getNameAndPrice(n: Int) = coffees.filter(_.id === n)
    42     .map(r => (r.name,r.price)).result.head
    43 
    44 val actions = for {
    45   _ <- coffees.schema.create
    46   _ <- qDelete
    47   c1 <- qAdd1
    48   c2 <- qAdd2
    49   (n1,p1) <- getNameAndPrice(c1)
    50   (n2,p2) <- getNameAndPrice(c2)
    51 } yield (n1,p1,n2,p2)
    52 import java.sql.SQLException
    53 import scala.concurrent.Await
    54 import scala.concurrent.duration._
    55 val db = Database.forURL("jdbc:h2:mem:demo", driver="org.h2.Driver")
    56 Await.result(
    57       db.run(actions.transactionally).map { res =>
    58         println(s"Add coffee: ${res._1},${res._2} and ${res._3},${res._4}")
    59       }.recover {
    60         case e: SQLException => println("Caught exception: " + e.getMessage)
    61       }, Duration.Inf)
    62       
    63 }

     

     

     

  • 相关阅读:
    Div+Css布局教程(-)CSS必备知识
    html表格设置
    wxAui Frame Management用法
    aui
    MySQL死锁
    InnoDB索引存储结构
    MySQL事务调优
    MySQL慢SQL语句常见诱因
    InnoDB的LRU淘汰策略
    InnoDB事务之redo log工作原理
  • 原文地址:https://www.cnblogs.com/tiger-xc/p/5891758.html
Copyright © 2020-2023  润新知