The lifted embedding is Slick's stable query API which is based
on ScalaQuery. This example shows how
to insert data and perform a simple query:
object Coffees extends Table[(String, Int, Double)]("COFFEES") {
def name = column[String]("COF_NAME", O.PrimaryKey)
def supID = column[Int]("SUP_ID")
def price = column[Double]("PRICE")
def * = name ~ supID ~ price
}
Coffees.insertAll(
("Colombian", 101, 7.99),
("Colombian_Decaf", 101, 8.99),
("French_Roast_Decaf", 49, 9.99)
)
val q = for {
c <- Coffees if c.supID === 101
// ^ comparing Rep[Int] to Rep[Int]!
} yield (c.name, c.price)
println(q.selectStatement)
q.foreach { case (n, p) => println(n + ": " + p) }
The direct embedding is a new experimental API for Slick that
uses macros to allow expressions
operating on standard Scala types to be used for database queries. This
example uses a Scala case class to perform a
simple query:
@table("COFFEES") case class Coffee(
@column("COF_NAME") name: String,
@column("SUP_ID") supID: Int,
@column("PRICE") price: Double
)
val coffees = Queryable[Coffee]
// for inserts use lifted embedding or SQL
val l = for {
c <- coffees if c.supID == 101
// ^ comparing Int to Int!
} yield (c.name, c.price)
backend.result( l, session )
.foreach { case (n, p) => println(n + ": " + p) }
Slick also allows you to write your own SQL queries and execute them
with an API which is optimized for Scala, much easier to use and more
concise than JDBC. This example uses plain SQL code to insert some data
and perform a query, mapping its results to a case class:
case class Coffee(name: String, supID: Int, price: Double)
implicit val getCoffeeResult = GetResult(r => Coffee(r.<<, r.<<, r.<<))
Database.forURL("...") withSession {
Seq(
Coffee("Colombian", 101, 7.99),
Coffee("Colombian_Decaf", 101, 8.99),
Coffee("French_Roast_Decaf", 49, 9.99)
).foreach(c => sqlu"""
insert into coffees values (${c.name}, ${c.supID}, ${c.price})
""").execute)
val sup = 101
val q = sql"select * from coffees where sup_id = $sup".as[Coffee]
// A bind variable to prevent SQL injection ^
q.foreach(println)
}