View SQL query in Slick

23,916

Solution 1

Slick 2.X:

You can print the query statement as shown on the Slick documentation:

val invoker = q.invoker
val statement = q.selectStatement

For other type of statements look at insertStatement, deleteStatement and updateStatement.

Slick 3.X:

val res = table.filter(_.id === 1L).result
res.statements.foreach(println)

Docs.

Solution 2

For slick 3.0

println(sortedQuery.result.statements.headOption)
Share:
23,916

Related videos on Youtube

src091
Author by

src091

Updated on September 19, 2020

Comments

  • src091
    src091 over 3 years

    Is there a way to observe an SQL statement that will be generated by Query?
    For example, I have this:
    val q = actions.filter(v => v.actionHash === hash && v.carriedAt > past)
    Can I view its underlying raw SQL?

  • wlk
    wlk almost 8 years
    Works as well on Slick version 3.1.1
  • Moha the almighty camel
    Moha the almighty camel about 6 years
    This doesn't work with DBIOAction, is there another way for this?
  • Ende Neu
    Ende Neu about 6 years
    @Mhd.Tahawi could you provide an example? I don't think I get your question.
  • Justin du Coeur
    Justin du Coeur almost 6 years
    The thing is, .statements works fine for a SQLAction, but it doesn't exist for a DBIOAction, which is what you get when you compose a bunch of SQLActions together in a for comprehension and yield the final result. Far as I can tell, Monadic joins lose the ability to use .statements. That's kind of a pain...
  • Ende Neu
    Ende Neu almost 6 years
    @JustinduCoeur right, I see that SQLAction is a subclass of DBIOAction and BasicAction and that the actual implementations are Invokers (like StreamingInvokerAction). Maybe the statement print can only be done at invoker level and not in the upper trait, unfortunately I don't have an answer for that.
  • Justin du Coeur
    Justin du Coeur almost 6 years
    @EndeNeu Agreed, although I think it's a hole in the API. Ideally, traits like DBIOAction would provide a best-effort implementation of .statements, based on what they are compositing. Not the end of the world, but it was frustrating to discover the lack, given how useful .statements is for debugging...
  • Tim Gautier
    Tim Gautier about 2 years
    DBIOAction can't implement .statements since DBIOAction doesn't even have to contain a SQL statement. It could be just about anything in there.