R/pgBuffer.R

#' This function obtains the buffer of a geometry in a postgreSQL database.
#' @export
#' @title Obtains the buffer of a geometry
#' @name pgBuffer
#' @param con An object of class "pgConnect" generated by pgConnect()
#' @param vecTable Name of vectorial table in the database
#' @param geom A string with the name of a geometry type column. Only required if the table has more than 1 geometry columns
#' @param dist Integer indicating the radius. Units of radius are measured in units of the spatial reference system. Measured in the same units has
#' @param newTable TRUE or FALSE. Indicates if a table with the buffer should be permanently added to the database
#' @return A SpatialPolygonsDataFrame object with the buffer of each object
#' @author Bruno Silva
pgBuffer <- function(con, vecTable, geom = NULL, dist, newTable = NULL) { 
  if (is.null(geom)) geom <- checkGeom(con, vecTable)     
  if(length(geom) > 1) stop(paste0("Multiple geometries found. Please choose between: ",
                                   geom))
  if (is.null(newTable))  {
    sprintf("SELECT ST_Buffer(%s, %i, 'quad_segs=8') INTO temptable FROM %s",
            geom, dist, vecTable) %>%
      RPostgreSQL::dbSendQuery(con[[1]], .)
    shape <- rgdal::readOGR(dsn = con[[2]], 'temptable')
    RPostgreSQL::dbRemoveTable(con[[1]], 'temptable')
  } else {
    sprintf("SELECT ST_Buffer(%s, %i, 'quad_segs=8') INTO %s FROM %s",
            geom, dist, newTable, vecTable) %>%
      RPostgreSQL::dbSendQuery(con[[1]], .)
    shape <- rgdal::readOGR(dsn = con[[2]], newTable)
  }
  return(shape)
}
berdinazzi/easyPostgreSQL documentation built on May 12, 2019, 3:04 p.m.