Use PRQL with knitr

Loading {prqlr} makes the prql code chunks executable in R Markdown and Quarto Markdown files.

Output formats

It can either output the results of the actual query execution or display a SQL query compiled from a PRQL query.

Use with {DBI} connections

If using with database connections (set the name of {DBI} connection to the connection chunk option), PRQL code chunks pass the output SQL to {knitr}’s SQL engine and behaves like SQL code chunks. So, usage is the same as for SQL code chunks.

For example, let’s render an R Markdown file named test.Rmd with the following contents with the knitr::knit() function.

```{r}
#| echo: false

library(DBI)
library(prqlr)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
```

```{prql}
#| connection: con

from mtcars
filter cyl > 6
select [cyl, mpg]
derive [mpg_int = round 0 mpg]
take 3
```

After rendering, a Markdown file named test.md is generated with the following contents.


```elm
from mtcars
filter cyl > 6
select [cyl, mpg]
derive [mpg_int = round 0 mpg]
take 3
```


| cyl|  mpg| mpg_int|
|---:|----:|-------:|
|   8| 18.7|      19|
|   8| 14.3|      14|
|   8| 16.4|      16|

Note that the syntax highlighting of Elm is the best for PRQL, so the output code blocks are marked as elm. This can be changed by setting the lang chunk option.

Without database connections

PRQL code chunks without the connection option will generate SQL code blocks.

```{r}
#| echo: false

library(prqlr)
```

```{prql}
from mtcars
filter cyl > 6
select [cyl, mpg]
derive [mpg_int = round 0 mpg]
take 3
```

The R Markdown file above will be converted to the Markdown file below.


```elm
from mtcars
filter cyl > 6
select [cyl, mpg]
derive [mpg_int = round 0 mpg]
take 3
```

```sql
SELECT
  cyl,
  mpg,
  ROUND(mpg, 0) AS mpg_int
FROM
  mtcars
WHERE
  cyl > 6
LIMIT
  3

-- Generated by PRQL compiler version:0.5.1 (https://prql-lang.org)
```

Engine options

We can pass some options of prql_compile() via the chunk option engine-opts (or engine.opts).

Note that the format option is always TRUE for PRQL code chunks.

```{r}
#| echo: false

library(prqlr)
```

## YAML-style

```{prql}
#| engine-opts:
#|   target: sql.mssql
#|   signature_comment: false

from mtcars
take 3
```

## R-style

```{prql engine.opts=list(target="sql.mssql", signature_comment=FALSE)}
from mtcars
take 3
```