1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
|
sql_case_match <- function(.x, ..., .default = NULL, .ptype = NULL) {
error_call <- current_call()
check_not_supplied(.ptype, call = error_call)
x_expr <- enexpr(.x)
if (!is_symbol(x_expr) && !is_call(x_expr)) {
msg <- "{.arg .x} must be a variable or function call, not {.obj_type_friendly {.x}}."
cli_abort(msg, call = error_call)
}
formulas <- list2(...)
formulas <- purrr::compact(formulas)
n <- length(formulas)
if (n == 0) {
cli_abort("No cases provided", call = error_call)
}
con <- sql_current_con()
query <- vector("list", n)
value <- vector("list", n)
for (i in seq_len(n)) {
f <- formulas[[i]]
env <- environment(f)
query[[i]] <- sql_case_match_clause(f, .x, con)
value[[i]] <- escape(enpar(quo(!!f[[3]]), tidy = FALSE, env = env), con = con)
}
clauses <- purrr::map2_chr(query, value, ~ paste0("WHEN (", .x, ") THEN ", .y))
if (!is_null(.default)) {
.default <- escape(enpar(quo(.default), tidy = FALSE, env = env), con = sql_current_con())
clauses[[n + 1]] <- paste0("ELSE ", .default)
}
same_line_sql <- sql(paste0("CASE ", paste0(clauses, collapse = " "), " END"))
if (nchar(same_line_sql) <= 80) {
return(same_line_sql)
}
sql(paste0(
"CASE\n",
paste0(clauses, collapse = "\n"),
"\nEND"
))
}
sql_case_match_clause <- function(f, x, con) {
env <- environment(f)
f_query <- f[[2]]
if (is_call(f_query, "c")) {
# need to handle `c(...)` specially because on `expr(c(1, y))` it returns
# `sql('1', '`y`')`
f_query <- translate_sql_(call_args(f_query), con)
} else if (is_call(f_query) || is_symbol(f_query)) {
f_query <- translate_sql(!!f_query, con = con)
}
# NA need to be translated to `IS NULL` instead of `IN (NULL)`
# due to the preceeding translation it might be NA or the string NULL
missing_loc <- is.na(f_query) | f_query == "NULL"
f_query <- vctrs::vec_slice(f_query, !missing_loc)
has_na <- any(missing_loc)
query <- NULL
if (!is_empty(f_query)) {
values <- sql_vector(f_query, parens = TRUE, collapse = ", ", con = con)
query <- translate_sql(!!x %in% !!values)
}
if (has_na) {
query <- paste(c(query, build_sql(x, " IS NULL")), collapse = " OR ")
}
query
}
sql_if <- function(cond, if_true, if_false = quo(NULL), missing = quo(NULL)) {
out <- build_sql("CASE WHEN ", enpar(cond), " THEN ", enpar(if_true))
# `ifelse()` and `if_else()` have a three value logic: they return `NA` resp.
# `missing` if `cond` is `NA`. To get the same in SQL it is necessary to
# translate to
# CASE
# WHEN <cond> THEN `if_true`
# WHEN NOT <cond> THEN `if_false`
# WHEN <cond> IS NULL THEN `missing`
# END
#
# Together these cases cover every possible case. So, if `if_false` and
# `missing` are identical they can be simplified to `ELSE <if_false>`
if (!quo_is_null(if_false) && identical(if_false, missing)) {
out <- paste0(out, " ELSE ", enpar(if_false), " END")
return(sql(out))
}
if (!quo_is_null(if_false)) {
false_sql <- build_sql(" WHEN NOT ", enpar(cond), " THEN ", enpar(if_false))
out <- paste0(out, false_sql)
}
if (!quo_is_null(missing)) {
missing_cond <- translate_sql(is.na(!!cond), con = sql_current_con())
missing_sql <- build_sql(" WHEN ", missing_cond, " THEN ", enpar(missing))
out <- paste0(out, missing_sql)
}
sql(paste0(out, " END"))
}
sql_case_when <- function(...,
.default = NULL,
.ptype = NULL,
.size = NULL,
error_call = caller_env()) {
# TODO: switch to dplyr::case_when_prepare when available
check_not_supplied(.ptype, call = error_call)
check_not_supplied(.size, call = error_call)
formulas <- list2(...)
n <- length(formulas)
if (n == 0) {
cli_abort("No cases provided")
}
query <- vector("list", n)
value <- vector("list", n)
for (i in seq_len(n)) {
f <- formulas[[i]]
env <- environment(f)
query[[i]] <- escape(enpar(quo(!!f[[2]]), tidy = FALSE, env = env), con = sql_current_con())
value[[i]] <- escape(enpar(quo(!!f[[3]]), tidy = FALSE, env = env), con = sql_current_con())
}
clauses <- purrr::map2_chr(query, value, ~ paste0("WHEN ", .x, " THEN ", .y))
# if a formula like TRUE ~ "other" is at the end of a sequence, use ELSE statement
# TRUE has precedence over `.default`
if (is_true(formulas[[n]][[2]])) {
clauses[[n]] <- paste0("ELSE ", value[[n]])
} else if (!is_null(.default)) {
.default <- escape(enpar(quo(.default), tidy = FALSE, env = env), con = sql_current_con())
clauses[[n + 1]] <- paste0("ELSE ", .default)
}
same_line_sql <- sql(paste0("CASE ", paste0(clauses, collapse = " "), " END"))
if (nchar(same_line_sql) <= 80) {
return(same_line_sql)
}
sql(paste0(
"CASE\n",
paste0(clauses, collapse = "\n"),
"\nEND"
))
}
sql_switch <- function(x, ...) {
input <- list2(...)
named <- names2(input) != ""
clauses <- purrr::map2_chr(names(input)[named], input[named], function(x, y) {
build_sql("WHEN (", x , ") THEN (", y, ") ")
})
n_unnamed <- sum(!named)
if (n_unnamed == 0) {
# do nothing
} else if (n_unnamed == 1) {
clauses <- c(clauses, build_sql("ELSE ", input[!named], " "))
} else {
cli_abort("Can only have one unnamed (ELSE) input")
}
build_sql("CASE ", x, " ", !!!clauses, "END")
}
sql_is_null <- function(x) {
x_sql <- enpar(enquo(x))
sql_expr((!!x_sql %is% NULL))
}
enpar <- function(x, tidy = TRUE, env = NULL) {
if (!is_quosure(x)) {
cli_abort("Internal error: `x` must be a quosure.") # nocov
}
if (tidy) {
x_sql <- eval_tidy(x, env = env)
} else {
x_sql <- eval_bare(x, env = env)
}
if (quo_is_call(x)) {
build_sql("(", x_sql, ")")
} else {
x_sql
}
}
|