View SQL query in Slick
Asked Answered
P

2

48

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?

Pavilion answered 2/5, 2014 at 18:3 Comment(0)
I
74

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.

Imponderable answered 2/5, 2014 at 18:52 Comment(6)
This doesn't work with DBIOAction, is there another way for this?Pentimento
@Mhd.Tahawi could you provide an example? I don't think I get your question.Imponderable
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...Elam
@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.Imponderable
@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...Elam
DBIOAction can't implement .statements since DBIOAction doesn't even have to contain a SQL statement. It could be just about anything in there.Hanford
V
31

For slick 3.0

println(sortedQuery.result.statements.headOption)
Venomous answered 31/5, 2016 at 0:6 Comment(1)
Works as well on Slick version 3.1.1Separates

© 2022 - 2024 — McMap. All rights reserved.