Skip to contents

Direct but not ideal approach

To connect to a database, you need to explicitly or implicitly provide key details like the database engine (Postgres, MySQL, etc.), database name, host, port, username, and password. This can be illustrated with the following code:

## The code below won't work. For illustrative purposes only
con <- 
  DBI::dbConnect(
    drv = RPostgres::Postgres(), 
    dbname = "postgres",
    host = "pegasus-proto-1.wd18lofki33y.us-east-1.rds.amazonaws.com", 
    port = "5432", 
    user = "postgres", 
    password = "some-password"
  )

The issue with this code is that if your database is accessible from the internet, anyone with this information could potentially connect to it.

AWS Secrets Manager

Since we host our databases on AWS using the RDS service, it makes sense to leverage AWS Secrets Manager.

AWS Secrets Manager is a service that securely stores and manages sensitive information, such as database credentials and API keys. We can store the username and password for a database in a single secret, or even store all the required details needed to connect to the database, including the driver, database name, host, port, username, and password. By configuring our server instance (where our IDE is running), we can ensure that the contents of the secrets are accessible directly from it.

Before using g6tr.db functions, please check if you have AWS_REGION=us-east-1 set in your .Renviron file. If not, please add it.

In this package, we provide convenient wrappers to retrieve secrets:

library(g6tr.db)

# list all available secrets
secretManager_list_secrets()
#>   Name                 ARN            Description KmsKeyId LastChangedDate    
#>   <chr>                <chr>          <chr>       <chr>    <dttm>             
#> 1 secret-name-1        arn:aws:secre… NA          NA       2020-09-30 12:43:24
#> 2 secret-name-2        arn:aws:secre… NA          arn:aws… 2023-12-11 15:32:24
#> 3 pegasus-test-secret  arn:aws:secre… Secret for… NA       2024-03-12 21:33:46

# retrieve the content of one of them
secretManager_get_secret("pegasus-test-secret")
#> $username
#> [1] "postgres"
#> 
#> $password
#> [1] "some-password"

As mentioned earlier, some secrets only store the username and password, but the rest of the information can be retrieved from the RDS API. We have helper functions for that as well:

rds_list_databases()
#>   DBInstanceIdentifier Engine   DBInstanceStatus
#>   <chr>                <chr>    <chr>           
#> 1 examples             postgres available       
#> 2 overquotas           postgres available       
#> 3 pegasus-proto-1      postgres available 

rds_get_database("pegasus-proto-1")
#> $Engine
#> [1] "postgres"
#> 
#> $MasterUsername
#> [1] "postgres"
#> 
#> $Endpoint
#> $Endpoint$Address
#> [1] "pegasus-proto-1.wd18lofki33y.us-east-1.rds.amazonaws.com"
#> 
#> $Endpoint$Port
#> [1] 5432

To connect to a database, identify which secret corresponds to which database and use the following:

con <- 
  rds_connect_to_database(
    database = rds_get_database("pegasus-proto-1"),
    secret = secretManager_get_secret("pegasus-test-secret")
  )

Connection object

The object created with the code above or in the first paragraph is a connection object. It serves as our entry point to the database, allowing us to work with it directly from R.

Here are some examples:

# List all tables
DBI::dbListTables(con)
#> [1] "answers"     "surveys"     "respondents" "questions"  

# Execute any SQL query
DBI::dbGetQuery(con, "SELECT COUNT(*) AS count FROM answers;")
#>    count
#> 1 876356

When it comes to uploading new surveys to a survey database, there’s no need to write SQL code manually. Instead, you can use the helper functions provided in this package, which will be discussed in a separate dedicated vignette.

tbl connection

Lastly, it’s worth noting that the dplyr package provides a convenient way to work with databases. You can create a connection to a table in the database with the following code:

tbl_answers <- dplyr::tbl(con, "answers")

If you print this object in the console, it’ll look like a regular tibble, and all (or almost all) dplyr verbs will work with it. All computations are performed on the database side: dplyr automatically converts your R code into SQL, sends it to the database, and returns the result. However, it’s important to note that you won’t be able to modify the tables this way.

We also provide a helper function that creates connections to all tables available in the database and returns them as a list:

all_tbls <- db_con_all_tables(con)