myPostgresImprotShp.R 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #' PostgreSQL - Automatic ESRI shp file import into postgis table
  2. #' @details ESRI shape failide automaatne importimine postgis tabeliks. Eelnevalt peab olema loodud postgis andmebaas
  3. #' \code{\link{myPostgresCreateGisDb}} ja defineeritud tabeli nimi. Andmed salvestatakse WGS4326 projektsioonis.
  4. #' Kui parameeter 'shp' on määramata, siis tuleb *.shp fail valida failide kataloogist.
  5. #' @param host Name or the numeric IPaddress of the host to connect to.
  6. #' @param dbname The database name.
  7. #' @param user PostgreSQL user name to connect as. Defaults to be the same as the operating system name of the user running the application.
  8. #' @param password Password to be used if the server demands password authentication.
  9. #' @param port Port number to connect to at the server host.
  10. #' @param shpFile ESRI shp file.
  11. #' @param tbl Postgis table name.
  12. #' @return return message.
  13. #' @seealso \code{\link{myPostgresConnect}}, \code{\link{myPostgresDropTable}},
  14. #' \code{\link{myPostgresCreateGisDb}}, \code{\link{myPostgresImprotShp}}
  15. #' @examples \dontrun{
  16. #' myPostgresImprotShp(host = '192.168.255.26', port = 5432,
  17. #' user = 'osm', password = 'osm', shpFile = NULL, dbname = 'xxxxx', tbl = 'table_xxx')
  18. #'
  19. #' }
  20. #'
  21. #' @export
  22. #'
  23. myPostgresImprotShp <- function(host = '192.168.255.26', port = 5432, user = 'osm', password = 'osm', dbname = 'shp',
  24. shpFile = NULL, tbl = NULL) {
  25. '%>%' <- magrittr::`%>%`
  26. if(is.null(tbl)) {message("Postgis tabeli nimi on puudu!"); return(NULL)}
  27. if(is.null(shpFile) || !file.exists(shpFile)) shpFile <- file.choose()
  28. system(paste0("shp2pgsql -s 4326 -I '", shpFile, "' ", tbl, " > /tmp/tmp.sql"))
  29. queries <- readLines("/tmp/tmp.sql")
  30. # class(queries)
  31. # Ühe tekstmuutuja moodustamine
  32. d0 = paste(queries,collapse=" ")
  33. # Tekstmuutuja jagamine osadeks semikooloni järele.
  34. d1 = strsplit(d0, split = ";", fixed = TRUE) %>% unlist()
  35. # semikooloni lisamine veeru lõppu
  36. d2 = paste(paste0(d1, ";"))
  37. write(d2, file = "/tmp/tmp1.sql")
  38. system(paste0("export PGPASSWORD='", password, "' && psql -U ", user, " -d ", dbname, " -h ", host, " -p ", port, " -f /tmp/tmp1.sql"))
  39. message("Shp faili importimine postgis andmebaasi lopetati.")
  40. }