Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dplyr pipeline into SQL string

Tags:

r

dplyr

dbplyr

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())").

like image 900
banbh Avatar asked Oct 29 '25 22:10

banbh


2 Answers

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
like image 178
DanielBonnery Avatar answered Oct 31 '25 15:10

DanielBonnery


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')"
like image 44
G. Grothendieck Avatar answered Oct 31 '25 13:10

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!