Last active
August 29, 2015 14:23
-
-
Save Quiri/e5020012446b5eb0fd97 to your computer and use it in GitHub Desktop.
Wrapper to insert data in PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Wrapper to insert to a PostgreSQL table | |
#' @description | |
#' This function checks the scheme on Postgres and adopts the data.frame to the scheme, then inserts it. | |
#' If there is no table with the provided name, it will generate one. Adds inserted column to data.frame with a specified time stamp. | |
#' @param logs DATA:FRAME The data to insert to db | |
#' @param conn POSTGRES CONNECTION OBJECT A valid connection to the DB | |
#' @param table STRING The name of the table to insert | |
#' @param inserted_at TIMESTAMP default is current time | |
#' @keywords postgresql, db | |
#' @export | |
#' @import RPostgreSQL data.table | |
#' @examples | |
#' library(RPostgreSQL) | |
#' conn <- dbConnect("PostgreSQL", db = "test") | |
#' data <- data.frame(a = 1:10, b = letters[1:10]) | |
#' inserted <- insertDB(data, conn, "letters") | |
#' if(inserted) cat("Successfulle inserted") | |
insertDB <- function(logs, conn, table, inserted_at = Sys.time()) { | |
logs$inserted <- inserted_at | |
logs <- data.table(logs) | |
if (dbExistsTable(conn, table)) { | |
scheme <- dbGetQuery(conn, sprintf( | |
"SELECT attnum, attname | |
FROM pg_attribute | |
WHERE attrelid = '%s'::regclass | |
AND attnum > 0 | |
AND NOT attisdropped | |
ORDER BY attnum;", table)) | |
logs <- logs[, scheme$attname, with = F] | |
inserted <- dbWriteTable(conn, table, logs, overwrite = FALSE, append = TRUE, row.names = FALSE) | |
} else { | |
inserted <- dbWriteTable(conn, table, logs, overwrite = FALSE, append = FALSE, row.names = FALSE) | |
} | |
if(inserted) { | |
cat("Successfully inserted to table", table, "\n") | |
} else { | |
cat("Could not insert to", table, "\n") | |
} | |
return(inserted) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment