How to port Slick 2.1 plain SQL queries to Slick 3

2019-08-15 11:31发布

问题:

The following working code from Slick 2.1 returns a single integer (which in this example, happens to be the result of running a function called "foobar"):

def getFoobar(): Int = DB.withSession {
   val query = Q.queryNA[Int]("select foobar()")
   query.first
}

How would one port this to Slick 3.0? According to the Slick 3.0 docs, the query would have to be converted to an DBIOAction. So this is what I've tried:

import driver.api._

...

def getFoobar(): Future[Int] = {
   val query = sql"select foobar()".as[Int]
   db.run(query) 
}

but this results in the following compilation error:

[error]  found   : slick.profile.SqlStreamingAction[Vector[Int],Int,slick.dbio.Effect]#ResultAction    [Int,slick.dbio.NoStream,slick.dbio.Effect]
[error]  required: MyDAO.this.driver.api.DBIO[Seq[Int]]

It appears that the sql interpolator is yielding a SqlStreamingAction rather than a DBIO, as db.run is expecting.

What would be the correct way to write this in the new Slick 3 API?

回答1:

I used something similar and it worked for me

import slick.driver.MySQLDriver.api._

def get(id : String) : Future[Channel] = {
implicit val getChannelResult = GetResult(r => Channel(r.<<, r.<<, r.<<, r.<<, r.<<))
val query = sql"select * from Channel where id = $id".as[Channel]
db.run(myq.headOption)
}

The db.run(DBIOAction[T,NoStream,Nothing]) command would accept all types of actions like sqlstreamingaction , StreamingDriverAction , DriverAction etc.

I guess the problem lies with the driver or db configuration. So the error

[error]  required: MyDAO.this.driver.api.DBIO[Seq[Int]]

Can you just paste the driver and db configuration steps, so that we can get a deeper look into the code to identify the actual error step



标签: scala slick