R/addDataSource.R

Defines functions addDataSource

Documented in addDataSource

# @file addDataSource
#
# Copyright 2021 Observational Health Data Sciences and Informatics
#
# This file is part of Achilles
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     https://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


#' @title
#' addDataSource
#'
#' @description
#' \code{addDataSource} adds a data source to the datasource.json file used by AchillesWeb.
#'
#' @details
#' Used to update the datasources file with the reference to a specified datasource. This makes the
#' new datasource findable for OHDSI tools. If the datasources file exists, the data source will be
#' added to the file. If the datasources file does not exist, a new file wil be initialized with the
#' specified data source.
#'
#' @param jsonFolderPath        Folder path of the Json files generated by \code{exportToJson}.
#' @param dataSourcesFilePath   The full file path where datasource file will be saved.
#' @param dataSourceName        The human readable name of the new data source
#'
#' @return
#' none
#'
#' @examples
#' \dontrun{
#' jsonFolderPath <- "your/output/path"
#' dataSourcesFilePath <- "/path/to/datasources.json"
#' dataSourceName <- "My New CDM"
#' connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = "sql server",
#'                                                                 server = "yourserver")
#' exportToJson(connectionDetails,
#'              cdmDatabaseSchema = "cdm5",
#'              resultsDatabaseSchema = "results",
#'              outputPath = jsonFolderPath)
#' addDataSource(jsonFolderPath, dataSourcesFilePath, dataSourceName)
#' }
#' @export
addDataSource <- function(jsonFolderPath, dataSourcesFilePath, dataSourceName) {

  newEntry <- list(name = dataSourceName, folder = jsonFolderPath, cdmVersion = 5)

  j <- jsonlite::read_json(path = dataSourcesFilePath)

  exists <- sapply(j$datasources, function(entry) {
    tolower(entry$name) == tolower(newEntry$name) & tolower(entry$folder) == tolower(newEntry$folder)
  })

  if (any(exists)) {
    stop("Data source already in JSON file")
  }

  numElements <- length(j$datasources)
  j$datasources[[numElements + 1]] <- newEntry
  jsonlite::write_json(x = j, path = dataSourcesFilePath, auto_unbox = TRUE, pretty = TRUE)
  print(sprintf("%s added to JSON file", dataSourceName))
}
quinterpriest/Achilles documentation built on April 20, 2022, 12:47 a.m.