Slick is Typesafe‘s modern database query and access library for Scala. It allows you to work with stored data almost as if you were using Scala collections while at the same time giving you full control over when a database access happens and which data is transferred. You can also use SQL directly.
val limit = 10.0
// Your query could look like this:
( for( c <- Coffees; if c.price < limit ) yield c.name ).list
// or this:
sql"select name from coffees where price < $limit".as[String].list
When using Scala instead of SQL for your queries you profit from the compile-time safety and compositionality. Slick can generate queries for different backends including your own, using its extensible query compiler.
Slick offers a unique combination of features:
Slick requires Scala 2.10. (For Scala 2.9 please use ScalaQuery, the predecessor of Slick).
Other SQL databases can be accessed right away with a reduced feature set. Writing a fully featured plugin for your own SQL-based backend can be achieved with a reasonable amount of work. Support for other backends (like NoSQL) is under development but not yet available.
Accessing databases using Slick’s lifted embedding requires the following steps.
Add the Slick jar and its dependencies to your project
Pick a driver for a particular db and create a session (or simply pick threadLocalSession)
import scala.slick.driver.H2Driver.simple._
import Database.threadLocalSession
Describe your Database schema
object Coffees extends Table[(String, Double)]("COFFEES") {
def name = column[String]("COF_NAME", O.PrimaryKey)
def price = column[Double]("PRICE")
def * = name ~ price
}
Write queries using for-comprehensions or map/flatMap wrapped in a session scope
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
( for( c <- Coffees; if c.price < 10.0 ) yield c.name ).list
// or
Coffees.filter(_.price < 10.0).map(_.name).list
}
The next chapter explains these steps and further aspects in more detail.