46

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?

Andrew Swan
  • 13,427
  • 22
  • 69
  • 98
src091
  • 2,807
  • 7
  • 44
  • 74

2 Answers2

72

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.

Peter Perháč
  • 20,434
  • 21
  • 120
  • 152
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
  • 2
    This doesn't work with `DBIOAction`, is there another way for this? – Moha the almighty camel Apr 13 '18 at 12:13
  • @Mhd.Tahawi could you provide an example? I don't think I get your question. – Ende Neu Apr 16 '18 at 07:55
  • 1
    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 `SQLAction`s 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... – Justin du Coeur May 31 '18 at 19:51
  • @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. – Ende Neu Jun 04 '18 at 10:40
  • @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... – Justin du Coeur Jun 04 '18 at 23:21
  • `DBIOAction` can't implement `.statements` since `DBIOAction` doesn't even have to contain a SQL statement. It could be just about anything in there. – Tim Gautier Apr 05 '22 at 19:54
31

For slick 3.0

println(sortedQuery.result.statements.headOption)
binshi
  • 1,248
  • 2
  • 17
  • 33