Skip to content

Commit

Permalink
Style tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Dec 21, 2023
1 parent dd79f34 commit 507dac1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
39 changes: 23 additions & 16 deletions R/backend-mssql.R
Original file line number Diff line number Diff line change
Expand Up @@ -591,35 +591,42 @@ mssql_bit_int_bit <- function(f) {

#' @export
`db_sql_render.Microsoft SQL Server` <- function(con, sql, ..., cte = FALSE, use_star = TRUE) {
sql$lazy_query <- sql$lazy_query %>%
purrr::modify_tree(
is_node = is_list,
post = mssql_update_where_clause
)

sql$lazy_query <- purrr::modify_tree(
sql$lazy_query,
is_node = function(x) inherits(x, "lazy_query"),
post = mssql_update_where_clause
)

NextMethod()
}

mssql_update_where_clause <- function(qry) {
if (inherits(qry, "lazy_query") && "where" %in% names(qry)) {
qry$where <- purrr::map(
qry$where,
~ set_expr(.x, mssql_where_cast(get_expr(.x)))
)
if (!has_name(qry, "where")) {
return(qry)
}

# Post-process where statement to ensure we cast BIT to BOOLEAN
transform_expr <- function(x) {
set_expr(x, bit_to_boolean(get_expr(x)))
}

qry$where <- lapply(qry$where, transform_expr)
qry
}

mssql_where_cast <- function(x_expr) {
bit_to_boolean <- function(x_expr) {
needs_logicals <- c("|", "&", "||", "&&", "!", "(")

if (is_call(x_expr, needs_logicals)) {
if (is_atomic(x_expr) || is_symbol(x_expr)) {
expr(cast(!!x_expr %AS% BIT) == 1L)
} else if (is_call(x_expr, needs_logicals)) {
args <- as.list(x_expr[2:length(x_expr)])
x_expr[2:length(x_expr)] <- purrr::map(args, mssql_where_cast)
} else if (is_atomic(x_expr) || is_symbol(x_expr)) {
x_expr <- expr(cast(!!x_expr %AS% BIT) == 1L)
x_expr[2:length(x_expr)] <- lapply(args, bit_to_boolean)
x_expr
} else {
x_expr
}
x_expr
}

utils::globalVariables(c("BIT", "CAST", "%AS%", "%is%", "convert", "DATE", "DATENAME", "DATEPART", "IIF", "NOT", "SUBSTRING", "LTRIM", "RTRIM", "CHARINDEX", "SYSDATETIME", "SECOND", "MINUTE", "HOUR", "DAY", "DAYOFWEEK", "DAYOFYEAR", "MONTH", "QUARTER", "YEAR", "BIGINT", "INT", "%AND%", "%BETWEEN%"))
2 changes: 1 addition & 1 deletion tests/testthat/_snaps/backend-mssql.md
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@
SELECT `df`.*
FROM `df`
WHERE (cast(`x` AS `BIT`) = 1)
) `LHS`
) AS `LHS`
INNER JOIN `df`
ON (`LHS`.`x` = `df`.`x`)

Expand Down

0 comments on commit 507dac1

Please sign in to comment.