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 }
Tags: 關系數據庫 數據庫編程 數據庫表 官方網站 import
文章來源: