OMOP/R/createPrimaryKeys.R

39 lines
1.6 KiB
R

# Copyright 2019 Observational Health Data Sciences and Informatics
#
# This file is part of CdmDdlBase
#
# 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
#
# http://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.
#' Create a primary key sql script from two csv files that detail the OMOP CDM Specifications.
#' @param cdmVersionNum The version of the CDM you are creating, e.g. 5.3
#' @export
createPrimaryKeys <- function(cdmVersion = cdmVersion){
cdmFieldCsvLoc <- paste0("inst/csv/OMOP_CDMv", cdmVersion, "_Field_Level.csv")
cdmSpecs <- read.csv(cdmFieldCsvLoc, stringsAsFactors = FALSE)
primaryKeys <- subset(cdmSpecs, isPrimaryKey == "Yes")
pkFields <- primaryKeys$cdmFieldName
sql_result <- c(paste0("--@targetdialect CDM Primary Key Constraints for OMOP Common Data Model ", cdmVersion, "\n"))
for (pkField in pkFields){
subquery <- subset(primaryKeys, cdmFieldName==pkField)
sql_result <- c(sql_result, paste0("\nALTER TABLE @cdmDatabaseSchema.", subquery$cdmTableName, " ADD CONSTRAINT xpk_", subquery$cdmTableName, " PRIMARY KEY NONCLUSTERED (", subquery$cdmFieldName , ");\n"))
}
return(paste0(sql_result, collapse = ""))
}