File: sql.R

package info (click to toggle)
r-cran-dbplyr 2.5.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,644 kB
  • sloc: sh: 13; makefile: 2
file content (65 lines) | stat: -rw-r--r-- 1,746 bytes parent folder | download | duplicates (2)
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
#' SQL escaping.
#'
#' These functions are critical when writing functions that translate R
#' functions to sql functions. Typically a conversion function should escape
#' all its inputs and return an sql object.
#'
#' @param ... Character vectors that will be combined into a single SQL
#'   expression.
#' @export
sql <- function(...) {
  x <- c_character(...)
  structure(x, class = c("sql", "character"))
}

# See setOldClass definition in zzz.R

# c() is also called outside of the dbplyr context so must supply default
# connection - this seems like a design mistake, and probably an indication
# that within dbplyr c() should be replaced with a more specific function
#' @export
c.sql <- function(..., drop_null = FALSE, con = simulate_dbi()) {
  input <- list(...)

  if (drop_null) input <- purrr::compact(input) # nocov

  out <- unlist(lapply(input, escape, collapse = NULL, con = con))
  sql(out)
}

#' @export
c.ident <- c.sql

#' @export
unique.sql <- function(x, ...) {
  sql(NextMethod()) # nocov
}

#' @rdname sql
#' @export
is.sql <- function(x) inherits(x, "sql")

#' @export
print.sql <- function(x, ...) cat(format(x, ...), sep = "\n")
#' @export
format.sql <- function(x, ...) {
  if (length(x) == 0) {
    paste0("<SQL> [empty]")
  } else {
    paste0("<SQL> ", x, ifelse(names2(x) == "", "", paste0(" AS ", names2(x))))
  }
}

#' @rdname sql
#' @export
#' @param x Object to coerce
#' @param con Needed when `x` is directly supplied from the user so that
#'   schema specifications can be quoted using the correct identifiers.
as.sql <- function(x, con) UseMethod("as.sql")

#' @export
as.sql.ident <- function(x, con) x
#' @export
as.sql.sql <- function(x, con) x
#' @export
as.sql.character <- function(x, con) ident(x)