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

来源:互联网 发布:淘宝卖种子新规则 编辑:程序博客网 时间:2024/05/27 01:23

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

import slick.driver.H2Driver.api._object slickIntro {  case class Coffee(id: Int, 
                    name: String,                    supID: Int = 0,                    price: Double ,                    sales: Int = 0,                    total: Int = 0)  class Coffees(tag: Tag) extends Table[Coffee](tag, "COFFEES") {
    def id = column[Int]("COF_ID", O.PrimaryKey, O.AutoInc)    def name = column[String]("COF_NAME")    def supID = column[Int]("SUP_ID")    def price = column[Double]("PRICE")    def sales = column[Int]("SALES", O.Default(0))    def total = column[Int]("TOTAL", O.Default(0))    def * = (id, name, supID, price, sales, total) <> (Coffee.tupled, Coffee.unapply)  }  val coffees = TableQuery[Coffees]               //> coffees  : slick.lifted.TableQuery[worksheets.slickIntro.Coffees] = Rep(TableExpansion)}


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

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

或者下面这些不同的Query:

// 返回"name"字段的Query// 相当于 SQL: select NAME from COFFEEScoffees.map(_.name)                               //> res1: slick.lifted.Query[slick.lifted.Rep[String],String,Seq] = Rep(Bind)// 选择 price < 10.0 的所有记录Query// 相当于 SQL: select * from COFFEES where PRICE < 10.0coffees.filter(_.price < 10.0)                    //> 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错误:

//coffees.map(_.prices)   //编译错误: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运算示范:

import scala.concurrent.ExecutionContext.Implicits.globalval qDelete = coffees.filter(_.price > 0.0).delete//> qDelete  : slick.driver.H2Driver.DriverAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write] ...val qAdd1 = (coffees returning coffees.map(_.id)) += Coffee(name="Columbia",price=128.0)//> qAdd1  : slick.profile.FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]...val qAdd2 = (coffees returning coffees.map(_.id)) += Coffee(name="Blue Mountain",price=828.0)//> qAdd2  : slick.profile.FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Write]...def getNameAndPrice(n: Int) = coffees.filter(_.id === n)    .map(r => (r.name,r.price)).result.head      //> getNameAndPrice: (n: Int)slick.profile.SqlAction[(String, Double),slick.dbio.NoStream,slick.dbio.Effect.Read]val actions = for {  _ <- coffees.schema.create  _ <- qDelete  c1 <- qAdd1  c2 <- qAdd2  (n1,p1) <- getNameAndPrice(c1)  (n2,p2) <- getNameAndPrice(c2)} yield (n1,p1,n2,p2)                             //> actions  : slick.dbio.DBIOAction[(String, Double, String, Double),..

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

import java.sql.SQLExceptionimport scala.concurrent.Awaitimport scala.concurrent.duration._val db = Database.forURL("jdbc:h2:mem:demo", driver="org.h2.Driver")     //> db  : slick.driver.H2Driver.backend.DatabaseDef = slick.jdbc.JdbcBackend$DatabaseDef@1a5b6f42Await.result(      db.run(actions.transactionally).map { res =>        println(s"Add coffee: ${res._1},${res._2} and ${res._3},${res._4}")      }.recover {        case e: SQLException => println("Caught exception: " + e.getMessage)      }, Duration.Inf)      //> Add coffee: Columbia,128.0 and Blue Mountain,828.0

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

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


下面是这篇讨论的示范代码:
package worksheetsimport slick.driver.H2Driver.api._object slickIntro {  case class Coffee(id: Int = 0,                    name: String,                    supID: Int = 0,                    price: Double,                    sales: Int = 0,                    total: Int = 0)  class Coffees(tag: Tag) extends Table[Coffee](tag, "COFFEES") {    def id = column[Int]("COF_ID", O.PrimaryKey, O.AutoInc)    def name = column[String]("COF_NAME")    def supID = column[Int]("SUP_ID")    def price = column[Double]("PRICE")    def sales = column[Int]("SALES", O.Default(0))    def total = column[Int]("TOTAL", O.Default(0))    def * = (id, name, supID, price, sales, total) <> (Coffee.tupled, Coffee.unapply)  }  val coffees = TableQuery[Coffees]   val limit = 10.0// // 写Query时就像下面这样:( for( c <- coffees; if c.price < limit ) yield c.name ).result// 相当于 SQL: select COF_NAME from COFFEES where PRICE < 10.0// 返回"name"字段的Query// 相当于 SQL: select NAME from COFFEEScoffees.map(_.name)// 选择 price < 10.0 的所有记录Query// 相当于 SQL: select * from COFFEES where PRICE < 10.0coffees.filter(_.price < 10.0)//coffees.map(_.prices)//编译错误:value prices is not a member of worksheets.slickIntro.Coffeesimport scala.concurrent.ExecutionContext.Implicits.globalval qDelete = coffees.filter(_.price > 0.0).deleteval qAdd1 = (coffees returning coffees.map(_.id)) += Coffee(name="Columbia",price=128.0)val qAdd2 = (coffees returning coffees.map(_.id)) += Coffee(name="Blue Mountain",price=828.0)def getNameAndPrice(n: Int) = coffees.filter(_.id === n)    .map(r => (r.name,r.price)).result.headval actions = for {  _ <- coffees.schema.create  _ <- qDelete  c1 <- qAdd1  c2 <- qAdd2  (n1,p1) <- getNameAndPrice(c1)  (n2,p2) <- getNameAndPrice(c2)} yield (n1,p1,n2,p2)import java.sql.SQLExceptionimport scala.concurrent.Awaitimport scala.concurrent.duration._val db = Database.forURL("jdbc:h2:mem:demo", driver="org.h2.Driver")Await.result(      db.run(actions.transactionally).map { res =>        println(s"Add coffee: ${res._1},${res._2} and ${res._3},${res._4}")      }.recover {        case e: SQLException => println("Caught exception: " + e.getMessage)      }, Duration.Inf)      }






0 0
原创粉丝点击