queryWithGeom.R 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #' Get query string with geom column representations to Spatial objects.
  2. #' @details Päringu stringi koostamine geomeetria veeruga Spatial objektina.
  3. #' @param con An PostgreSQLConnection object as produced by dbConnect.
  4. #' @param tbl The database table name.
  5. #' @param geom The array with postgresql geom column names.
  6. #' @param where Other conditions in request.
  7. #' @return query string.
  8. #' @seealso \code{\link{queryDropColumnsFromPostgresDbAccordingDF}},
  9. #' \code{\link{queryAddColumnsToPostgresDbAccordingDF}},
  10. #' \code{\link{queryWithoutGeom}},
  11. #' \code{\link{queryWithGeom}}
  12. #' @examples \dontrun{
  13. #' # Connect with database
  14. #' con <- myPostgresConnect(host = conf$host, port = conf$port, user = conf$user,
  15. #' password = conf$password, dbname = conf$dbname, type = "RPostgreSQL")
  16. #' tblName = "transport_tsoonid_tallinn"
  17. #' q <- queryWithGeom(con = con, tbl = tblName, geom = 'geom', where = "LIMIT 100")
  18. #' df <- dbGetQuery(con, q)
  19. #' df
  20. #' DBI::dbClearResult(res)
  21. #' DBI::dbDisconnect(con)
  22. #'
  23. #' }
  24. #'
  25. #' @export
  26. #'
  27. queryWithGeom <- function(con, tbl, geom = 'geom', where = NULL) {
  28. ## All columns without geom as shp@data
  29. # geom = paste(paste0("'", geom, "'"), collapse = ", ")
  30. q <- paste0("SELECT 'SELECT ' ||
  31. ARRAY_TO_STRING(ARRAY(SELECT COLUMN_NAME::VARCHAR(50)
  32. FROM INFORMATION_SCHEMA.COLUMNS
  33. WHERE TABLE_NAME='", tbl, "' AND
  34. COLUMN_NAME NOT IN ('", geom,"')
  35. ORDER BY ORDINAL_POSITION
  36. ), ', ') || ', ST_AsText(", geom,") AS ", geom," FROM ", tbl, "'")
  37. q <- DBI::dbGetQuery(con,q)[1,1]
  38. q <- paste(q, where)
  39. q
  40. }