Invokers are the components of a Slick query that build up the SQL select statement. Slick exposes a variety of invokers that allow the construction of complex queries. Let's look at some of these invokers here:
map
invoker is useful to select individual columns or apply operations to columns:scala> db.withSession { implicit session => Tables.transactions.map { _.candidate }.take(5).list } List[String] = List(Obama, Barack, Paul, Ron, Paul, Ron, Paul, Ron, Obama, Barack)
filter
invoker is the equivalent of the WHERE
statements in SQL. Note that Slick fields must be compared using ===
:scala> db.withSession { implicit session => Tables.transactions.filter { _.candidate === "Obama, Barack" }.take(5).list } List[Tables.Transactions#TableElementType] = List(Transaction(Some(1),Obama, Barack,Doe, John,TX,None,200,2010-06-22), ...
Similarly, to filter out donations to Barack Obama, use the =!=
operator:
scala> db.withSession { implicit session => Tables.transactions.filter { _.candidate =!= "Obama, Barack" }.take(5).list } List[Tables.Transactions#TableElementType] = List(Transaction(Some(2),Paul, Ron,BROWN, TODD W MR.,OH,...
sortBy
invoker is the equivalent of the ORDER BY
statement in SQL:scala> db.withSession { implicit session => Tables.transactions.sortBy { _.date.desc }.take(5).list } List[Tables.Transactions#TableElementType] = List(Transaction(Some(65536),Obama, Barack,COPELAND, THOMAS,OH,Some(COLLEGE TEACHING),10000,2012-01-02)
leftJoin
, rightJoin
, innerJoin
, and outerJoin
invokers are used for joining tables. As we do not cover interactions between multiple tables in this tutorial, we cannot demonstrate joins. See the Slick documentation (http://slick.typesafe.com/doc/2.1.0/queries.html#joining-and-zipping) for examples of these.length
, min
, max
, sum
, and avg
can be used for computing summary statistics. These must be executed using .run
, rather than .list
, as they return single numbers. For instance, to get the total donations to Barack Obama:scala> db.withSession { implicit session => Tables.transactions.filter { _.candidate === "Obama, Barack" }.map { _.amount }.sum.run } Option[Int] = Some(849636799) // (in cents)