R/sqlhelper.r

Defines functions sql_by_key

Documented in sql_by_key

#' GrafoDB uses two main sections for SQL query strings, one for each
#' enviroment: "test" and "prod". `get_section` takes care of this
#'
#' if env is "test", it yields "SQLite", otherwise "PostgreSQL".
#'
#' @param env environment used for get_sql
#' @return string identifing the correct section in TOML file for environment
#' @note comparing strings (`env == "test"`) can be expensive that's why this
#'   function is `memoised`.

get_section <- memoise::memoise(function(env = getenv()) {
  rutils::ifelse(env == "test", "SQLite", "PostgreSQL")
})


#' Adapter from older sql provider and the new based on sqlhelper
#'
#' @param .key the key for the query string (it get's prepended by
#'  the section obtained with `get_section`)
#' @param ... params passed to `sqlhelper::get_sql`
#' @param .multiline `TRUE if statements are multiple, otherwise concatenate
#'  as a single statement
#' @seealso sqlhelper::get_sql
#' @returns a vector (if `.multiline` is `TRUE`) or a string with the SQL.

sql_by_key <- function(.key, ..., .multiline = FALSE) {
  section <- get_section()
  env_key <- glue::glue("{section}/{.key}")
  sqlhelper::get_sql(env_key,
    params = list(...),
    .multiline = .multiline,
    config_path = system.file("ini/sql.toml", package = "GrafoDB"))
}
giupo/GrafoDB documentation built on Oct. 12, 2022, 9:43 a.m.