R/ccdm_tbl.R

Defines functions ccdm_tbl

Documented in ccdm_tbl

#' Create a tbl pointer to Core CDM
#'
#' If a name is not provided, will print a list of the available tables in PHC_DB_DEV.WHS_CORE_CDM.
#'
#' @param conn a DBI-compliant connection object. recommend using the 'connect_cdw()` function
#' @param name Table in the PHC_DB_DEV.WHS_CORE_CDM schema
#'
#' @return a tbl or a display of tables and views in the WHS_CORE_CDM schema
#'
#' @importFrom dplyr tbl
#' @importFrom dbplyr in_schema sql
#' @importFrom DBI dbListTables Id
#'
#' @export
#'
#' @examples

#' \dontrun{
#' conn <- connect_cdw()
#'
#' ccdm_tbl(conn)
#'
#' ccdm_tbl(conn, "HOSPITAL_ENCOUNTERS")
#'
#' disconnect_cdw(conn)
#'}


ccdm_tbl <- function(conn, name = NA) {

    # Todo: check that there's a valid connection
    if(is.na(name)) {
        paste0("Table/View not specified.\nHere's a list of available CoreCDM tables:\n\n")

        results <-
            DBI::dbGetQuery(conn, "SELECT * FROM PHC_DB_DEV.INFORMATION_SCHEMA.TABLES;") %>%
            dplyr::filter(TABLE_SCHEMA == "WHS_CORE_CDM") %>%
            dplyr::mutate(SIZE = prettyunits::pretty_bytes(BYTES)) %>%
            dplyr::mutate(COMMENT = stringr::str_trunc(COMMENT, 80)) %>%
            dplyr::filter(!is.na(TABLE_OWNER)) %>%
            dplyr::select(TABLE_NAME, TABLE_TYPE, ROW_COUNT, SIZE, LAST_ALTERED, COMMENT)

        return(results)

    }

    # get the tbl
    dplyr::tbl(conn, dbplyr::in_schema(sql("PHC_DB_DEV.WHS_CORE_CDM"), name))
   # dplyr::tbl(conn, DBI::Id(database = "HI_DB", schema = "WHS_CORE_CDM", table = name))

}
RollieParrish/ccdm documentation built on Dec. 31, 2020, 4:26 p.m.