Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count rows with Slick 1.0.0

Tags:

scala

slick

I'm trying to create a query with Slick 1.0.0 that returns a row count equivalent to the following SQL statement:

SELECT COUNT(*) FROM table;

What I have so far is:

val query = for {
  row <- Table
} yield row
println(query.length)

This prints scala.slick.ast.FunctionSymbol$$anon$1@6860991f. Also, query.length appears to be of type scala.slick.lifted.Column. I cannot find a way to execute the query. All examples that I can find in the documentation and anywhere else do not operate on Column or are for ScalaQuery and do not work anymore.

What can I do to execute this?

like image 741
notan3xit Avatar asked Feb 12 '13 16:02

notan3xit


3 Answers

Any of these should do the trick:

Query(MyTable).list.length

or

(for{mt <- MyTable} yield mt).list.length

or

(for{mt <- MyTable} yield mt.count).first

Update:

Printing the H2 database log shows this for the last query, which looks optimal:

 03:31:26.560 [main] DEBUG h2database - jdbc[2]
 /**/PreparedStatement prep10 = conn1.prepareStatement("select select count(1) from \"MYTABLE\" s5", 1003, 1007);
like image 95
Jack Avatar answered Nov 09 '22 15:11

Jack


Although I wasn't able to check the resulting sql, you could get shorter source by dropping .list:

Query(MyTable.length).first
like image 20
fickludd Avatar answered Nov 09 '22 13:11

fickludd


Use:

val query = for(row <- Table) yield row 
println(Query(query.count).first)

The count is equivalent to "SELECT COUNT(*) FROM Table". In order to get the first and only row you have to use first to get the count.

like image 2
thikonom Avatar answered Nov 09 '22 14:11

thikonom