queryAddColumnsToPostgresDbAccordingDF.R 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #' Query to add columns to PostgreSQL database according df column names
  2. #' @details Veergude lisamine Postgresql andmebaasi etteantud df veergude nimede alusel.
  3. #' Andmebaasile lisatakse df veeru nimedega kokkulangevad andmebaasi veerud. Enne oleks
  4. #' vajalik kustutada samanimelised veerud \code{\link{df2PostgresReplaceFieldsArray}}.
  5. #' @param tbl The database table name.
  6. #' @param df The DataFrame name.
  7. #' @return query string.
  8. #' @seealso \code{\link{queryDropColumnsFromPostgresDbAccordingDF}},
  9. #' \code{\link{queryAddColumnsToPostgresDbAccordingDF}},
  10. #' \code{\link{queryWithoutGeom}}
  11. #' @examples \dontrun{
  12. #' # Connect with database
  13. #' tblName = "transport_tsoonid_tallinn"
  14. #' q <- queryAddColumnsToPostgresDbAccordingDF(df = tsoonAsumLosa, tbl = tblName)
  15. #' con <- myPostgresConnect(host = conf$host, port = conf$port, user = conf$user,
  16. #' password = conf$password, dbname = conf$dbname, type = "RPostgreSQL")
  17. #' res <- DBI::dbSendQuery(conn = con, statement = q)
  18. #' DBI::dbClearResult(res)
  19. #' DBI::dbDisconnect(con)
  20. #'
  21. #' }
  22. #'
  23. #' @export
  24. #'
  25. queryAddColumnsToPostgresDbAccordingDF <- function(df, tbl) {
  26. colnames(df) <- transpordiTsoonid::dfNamesToLower(df = df)
  27. # Lisame andmebaasi veerud, mida tahame DataFrame'st kopeerida.
  28. res <- sapply(1:ncol(df), function(x) {
  29. paste0("ADD COLUMN ", names(df)[x], " ", transpordiTsoonid::df2PostgresReplaceFieldsArray[typeof(df[,x])], "")
  30. })
  31. res <- paste(res, collapse = ", ")
  32. res <- paste0("ALTER TABLE ", tbl , " ", res, "")
  33. res
  34. }