setMethod("dbDriver", "character",
definition = function(drvName, ...) {
findDriver(drvName)(...)
}
)
findDriver <- function(drvName) {
# If it exists in the global environment, use that
d <- get2(drvName, globalenv())
if (!is.null(d)) return(d)
# Otherwise, see if the appropriately named package is available
if (has_namespace(drvName)) {
d <- get2(drvName, asNamespace(drvName))
if (!is.null(d)) return(d)
}
pkgName <- paste0("R", drvName)
# First, see if package with name R + drvName is available
if (has_namespace(pkgName)) {
d <- get2(drvName, asNamespace(pkgName))
if (!is.null(d)) return(d)
}
# Can't find it:
stop("Couldn't find driver ", drvName, ". Looked in:\n",
"* global namespace\n",
"* in package called ", drvName, "\n",
"* in package called ", pkgName,
call. = FALSE)
}
get2 <- function(x, env) {
if (!exists(x, envir = env)) return(NULL)
get(x, envir = env)
}
has_namespace <- function(x) {
suppressMessages(requireNamespace(x, quietly = TRUE))
}
Hadley