Table Of Contents

Previous topic

Slick - Scala Language Integrated Connection Kit

Next topic

Getting Started

This Page

Introduction

What is Slick?

Slick is a 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 write your database queries in Scala instead of SQL, thus profiting from the static checking, compile-time safety and compositionality of Scala. Slick features an extensible query compiler which can generate code for different backends.

It includes the following features:

  • Lifted query embedding (fully featured, composable, uses lifted types, evolved from ScalaQuery)
  • Direct query embedding (experimental, limited features, uses ordinary Scala types, based on macros)
  • Simple execution of raw SQL queries
  • Session management based on JDBC Connections

Slick requires Scala 2.10. ScalaQuery, the predecessor of Slick, is available for Scala 2.9.

Supported database systems

The following database systems are directly supported for type-safe queries (with lifted and direct embedding):

Accessing other databases is possible, with a reduced feature set.

Quick Overview

Accessing databases using Slick’s lifted embedding requires the following steps.

  1. Add the Slick jar and its dependencies to your project

  2. Pick a driver for a particular db and create a session (or simply pick threadLocalSession)

    import scala.slick.driver.H2Driver.simple._
    import Database.threadLocalSession
    
  3. 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
    }
    
  4. 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.