Created
February 4, 2019 02:31
-
-
Save colearendt/faaf6593e78ec017b074148dac4808fa to your computer and use it in GitHub Desktop.
Example functions and configuration files for using the config package to simplify connecting to a database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
default: | |
gis: | |
drv: !expr RPostgres::Postgres() | |
db: mydatabase | |
port: 5432 | |
host: somehost.dev.example.com | |
prod: | |
gis: | |
drv: !expr RPostgres::Postgres() | |
db: proddb | |
port: 5432 | |
host: somehost.prod.example.com |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
connect_to_db <- function(dbname = "gis", file = "config.yml", override_params = list()) { | |
# grab configuration values | |
params <- config::get(dbname, file = file) | |
# update list values / allow an "override" from the caller | |
final_params <- purrr::list_modify(params, !!!override_params) | |
# make connection by passing in arguments from a list | |
con <- do.call(DBI::dbConnect, args = final_params) | |
} | |
# the exact same function, except the user is read from an environment variable or whatever else you want | |
connect_to_db_user_from_env_var <- function(dbname = "gis", file = "config.yml") { | |
connect_to_db( | |
dbname = dbname, | |
file = file, | |
override_params = list( | |
"user" = Sys.getenv("DB_USER"), | |
"password" = Sys.getenv("DB_PASSWORD") | |
) | |
) | |
} | |
# create template file | |
# if creating these config files is annoying... add a helper to create them for you! | |
create_template <- function(dbname = "gis", file = "test.yml") { | |
raw <- yaml::as.yaml( | |
x = list( | |
"default" = list( | |
"gis" = list( | |
"drv" = "XXhacky_workaroundXX", | |
"db" = dbname, | |
"port" = "5432", | |
"host" = "placeholder" | |
) | |
) | |
) | |
) | |
# hacky workaround because the yaml package wants to quote "!expr" | |
updated <- stringr::str_replace_all(raw, "XXhacky_workaroundXX", "!expr RPostgres::Postgres()") | |
writeLines(updated, file) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment