0
votes

I am starting to work with slick and scala and it seems that I still do not have the basics iron out:

I am using slick 3.0.0 and scala 2.11.7 and I am connecting to an Oracle database.

I want to get the number of rows in my table so I went and did a search and found the following: 1) This one tells me that .run does not exist:

mytable.length.run

2)This one tells me that there is a type mismatch found: slick.lifted.Rep[Int] and expected String:

var q = for(u <- mytable) yield u.id
print(q.size)

3)This one compiles and runs but prints Rep(Pure $@309962262):

var q = for{row <- mytable} yield row
println(Query(q.length))

So I am not sure if it is because I do not understand how this works but I was imagining that the following should happen:

A) constructQuery b) "run" query.

So the other queries that I am using are as follow:

val db = Database.forConfig("Oracle")
try{
   val f: Future[Unit] = {
   val query: StreamingDBIO[Seq[String], String] = participants.map(_.id).result // A)"Construct query"
   val stremQuery: DatabasePublisher[String] = db.stream(query) //B) "Run query"
   streamQuery.foreach(println)
}
Await.result(f, Duration.Inf)

}
finally db.close

What am I missing? is number 3 not giving me what I want because is not under a db.stream/db.run/db.something command? Or am I just lost =)

Thanks in advance Tona

1

1 Answers

3
votes

Querying a database in slick basically consists of these three steps:

  1. Create a Query
  2. Convert Query to an Action
  3. Execute the Action on a database

So your example would look something like this (types are optional and added for clarity):

val query = mytable.length  // length is an aggregation 
val action = query.result
val result: Future[Int] = db.run(action)

// Access result in a non blocking way (recommended):
result.map(count: Int => ...)

// or for completeness use Await (not recommended):
val count: Int = Await.result(result, Duration.Inf)

Further reading: