R/utils.R

Defines functions apply_case quote_values quote_ids

Documented in apply_case quote_ids quote_values

#' Quote identifiers (e.g.: table names or field names) for SQL queries.
#'
#' Identifiers are quoted only if it contains at least one non-alphanumeric
#' character.
#'
#' @param ids Character vector of identifiers to quote.
#' @return A character vector containing the same identifiers, quoted if
#'         necessary.
#' @import chk
#' @import DBI
quote_ids <- function(ids) {
  chk::chk_character(ids)

  is_alphanum <- grepl("^[A-Za-z_][A-Za-z0-9_]*$", ids)
  is_keyword <- ids %in% c(tolower(.SQL_KEYWORDS), toupper(.SQL_KEYWORDS))

  do_quote <- (rep(getOption("sqlq_always_quote", FALSE), length(ids)) |
               !is_alphanum | is_keyword)

  conn <- getOption("sqlq_conn", DBI::ANSI())

  return(ifelse(do_quote, DBI::dbQuoteIdentifier(conn, ids), ids))
}

#' Quote character values for SQL queries.
#'
#' Quote character values inside a vector or list. If other values are found
#' inside the list or vector, they are converted to character values.
#'
#' @param values Vector or list of values.
#' @return A character vector containing the same values, converted. All
#'         character values are quoted.
#' @import chk
#' @import DBI
quote_values <- function(values) {
  chk::chk_vector(values)
  string <- vapply(values, is.character, FUN.VALUE = TRUE)
  conn <- getOption("sqlq_conn", DBI::ANSI())
  return(as.character(ifelse(string, DBI::dbQuoteString(conn, values), values)))
}

#' Put string in right case according to global option.
#'
#' If global option sqlq_case is set to "lower", put the string in lowercase,
#' if it is set to "upper", put the string in uppercase.
#' Otherwise the string is not changed.
#'
#' @param s The string whose case must be changed.
#' @return The string in the right case.
#' @import chk
apply_case <- function(s) {
  chk::chk_string(s)
  return(if (getOption("sqlq_uppercase", TRUE)) toupper(s) else tolower(s))
}

Try the sqlq package in your browser

Any scripts or data that you put into this service are public.

sqlq documentation built on Sept. 16, 2025, 9:10 a.m.