4

I would like to convert a (short) dplyr pipeline into a string representation of its equivalent SQL. For example:

library(dplyr)
dbplyr::lazy_frame() %>% filter(foo == 'bar')

will print out essentially what I'm looking for, namely:

<SQL>
SELECT *
FROM `df`
WHERE (`foo` = 'bar')

the problem is that this is merely printed out. In particular I don't see how to assign it to a string. I've tried appending %>% show_query() but I believe that has the same result (i.e., displaying the query rather conversion to a string). Appending %>% as.character() does produce something but it is not SQL (it's a character vector whose first element is "list(name = \"filter\", x = list(x = list(), vars = character(0)), dots = list(~foo == \"bar\"), args = list())").

2 Answers 2

4

You can capture the output:

library(dplyr)
x<-capture.output(dbplyr::lazy_frame() %>% filter(foo == 'bar'))
x
[1] "<SQL>"                 "SELECT *"              "FROM `df`"             "WHERE (`foo` = 'bar')"

or

dbplyr::lazy_frame() %>% filter(foo == 'bar')%>%capture.output
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you -- that does answer my question. I am going to wait to see if someone comes up with a dplyr/dbplyr function that converts it directly to a string (which after all must be possible in some way). If no one does, then I'll accept this.
3

Use remote_query to get an c("sql", "character") and then convert that to character.

library(dbplyr)

lazy_frame() %>%
  filter(foo == 'bar') %>%
  remote_query %>%
  as.character
## [1] "SELECT *\nFROM `df`\nWHERE (`foo` = 'bar')"

1 Comment

As of dbplyr 2.3.0 this needs the columns listed in the lasy-frame. I.e., something like lazy_frame(foo = 0). It would be nice if there was a way to avoid this, but I think there may not be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.