# Connect to MySQL
#' @import mockable
# Make mockable functions from external functions to enable mocking in tests
dbConnect__ %mockable% DBI::dbConnect
dbListConnections__ %mockable% DBI::dbListConnections
dbDisconnect__ %mockable% DBI::dbDisconnect
dbGetInfo__ %mockable% DBI::dbGetInfo
dbIsValid__ %mockable% DBI::dbIsValid
MySQL__ %mockable% RMySQL::MySQL
#' @export
mysql_connect <- function(cred){
assertive::assert_is_list(cred)
assertive::assert_all_are_true(
c('database', 'host', 'port', 'user', 'password') %in% names(cred)
)
curr_con <- dbListConnections__(MySQL__())
if (length(curr_con) > 0){
matching_con <- which(sapply(curr_con, is_matching_con, cred = cred))
if (length(matching_con) > 1){
sapply(
curr_con[matching_con[2 : length(matching_con)]],
dbDisconnect__
)
}
con <- curr_con[[matching_con[1]]]
}else{
con <- dbConnect__(
drv = MySQL__(),
dbname = cred$database,
host = cred$host,
port = as.integer(cred$port),
user = cred$user,
password = cred$password
)
}
return(con)
}
is_matching_con <- function(con, cred){
assertive::assert_is_s4(con)
assertive::assert_all_are_true(dbIsValid__(con))
con_info <- dbGetInfo__(con)
check <- con_info$host == cred$host &&
con_info$dbname == cred$database &&
con_info$user == cred$user
return(check)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.