R/utils.R

Defines functions report_checks gicon ingest_db connect_db export_to_s3

Documented in connect_db export_to_s3 gicon ingest_db report_checks

#' Export to s3
#'
#' @param object name of the output object
#'
#' @return NULL
#' @export
export_to_s3 <- function(object) {
    aws.s3::s3save(
        object,
        object = glue::glue(
            "original_metadata_{Sys.Date() %>% stringr::str_replace_all('-', '_')}.rds"
        ),
        bucket = "fcatala-09142020-eu-west-1"
    )
}


#' MySQL connection function
#'
#' @param dbname database name inside de RDS
#'
#' @return connection object
#' @export
connect_db <- function(dbname) {
    DBI::dbConnect(
        drv = RMySQL::MySQL(),
        username = "admin",
        password = "c0v1drul3s",
        host = "mncovidseqdb-instance.cyu1oiz4la9s.eu-west-1.rds.amazonaws.com",
        port = 3306,
        dbname = dbname,
        ":memory:"
    )
}


#' Save data to RDS
#'
#' @param data tibble with the data to ingest
#' @param table name of the target table
#' @param dbname name of the target database
#'
#' @return NULL
#' @export
ingest_db <- function(data, table, dbname = "mysql_covid_seq") {
    cn <- connect_db(dbname)
    on.exit(DBI::dbDisconnect(cn))
    DBI::dbWriteTable(
        conn = cn,
        name = table,
        value = data,
        append = TRUE,
        row.names = FALSE
    )
}

#' Creates printable symbol with DT
#'
#' @param x symbol name
#'
#' @return string
#' @export
gicon <- function(x) {
    as.character(icon(x, lib = "glyphicon"))
}

#' Title
#'
#' @param res_nrwos number of rows resulting of the check
#' @param original_nrows expected number of rows
#' @param var tested column name
#' @param message error message to print
#' @param out_table table where export the results
#'
#' @return tibble
#' @export
report_checks <- function(res_nrwos, original_nrows, var, message, out_table) {
    tibble::tibble(
        var = var,
        icon = ifelse(original_nrows != res_nrwos, gicon("remove"), gicon("ok")),
        msg = ifelse(icon == gicon("ok"), "", message)
    ) %>%
        dplyr::bind_rows(out_table)
}
MicrobialGenomics/covidseq documentation built on Jan. 27, 2021, 7:58 p.m.