R dbplyr "smart" 是否足以确定 SQL 数据库类型并应用适当的语法?

Is R dbplyr "smart" enough to determine the SQL database type and apply appropriate syntax?

library(tidyverse)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
copy_to(con, mtcars)
mtcars2 <- tbl(con, "mtcars")

随着我开始学习 SQL 我的第一个重要教训是语法会因数据库类型而异。

例如,这种类型的查询通常有效:

mtcars3 <- DBI::dbGetQuery(con, "SELECT * FROM mtcars LIMIT 5")

但在某些 SQL 数据库上,我尝试 SELECT * FROM xyz LIMIT 5 时出现语法错误。然后我尝试了一些类似的东西:

DBI::dbGetQuery(con, "SELECT TOP 5 * FROM xyz")

而且我能够得到我想要的结果。

这让我很好奇 当我开始专门使用 dbplyr 并完全放弃使用 SQL 查询(尽可能)时会发生什么。 dbplyr 是否 "smart" 足以识别我正在使用的不同 SQL 数据库?更重要的是,dbplyr 会根据数据库类型应用正确的语法吗?

是的,dbplyr 'smart' 足以在将 dplyr 命令转换为数据库 (SQL) 语法时使用 table 的连接类型。考虑以下示例:

library(dplyr)
library(dbplyr)
data(mtcars)

# mimic postgre database
df_postgre = tbl_lazy(mtcars, con = simulate_postgres())
df_postgre %>% head(5) %>% show_query()

# resulting SQL translation
<SQL>
SELECT *
FROM `df`
LIMIT 5

# mimic MS server database
df_server = tbl_lazy(mtcars, con = simulate_mssql())
df_server %>% head(5) %>% show_query()

# resulting SQL translation
<SQL>
SELECT TOP(5) *
FROM `df`

您可以尝试使用 dbplyr 中的不同 simulate_* 函数来检查您的特定数据库的翻译。