copy_shp_to_db.R 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #' ESRI Shapefile kopeerimine andmebaasi
  2. #'
  3. #' Funktsioon kopeerib ESRI Shapefile objeketi postgis andmebaasi. Andmebaasi parameetri muutmiseks muuda konfiguratsiooni muutujat conf <- ruut::get_conf().
  4. #' @param dir path directory of the shape files.
  5. #' @param layer str layer name.
  6. #' @param conf list database confuration. Default get_conf()
  7. #' @param id field andmebaasi unikaalne id veerg. Default 'fid'
  8. #' @param crs_source CRS source CRS for example 'EPSG:3301' (Estonia). Default is 'EPSG:4326'.
  9. #' @param crs_target CRS target CRS for example 'EPSG:4326'. Default is 'EPSG:4326'.
  10. #' @param geometry_type str Force a geometry type for new layer. One of: NONE, GEOMETRY, POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT, MULTIPOLYGON, or MULTILINESTRING, or PROMOTE_TO_MULTI or CONVERT_TO_LINEAR. Add "25D" for 3D layers.
  11. #' @keywords postgis, ESRI Shapefile
  12. #' @export
  13. #' @examples
  14. #' ## Not run:
  15. #' ##
  16. #' ## copy_qgis_object_to_db()
  17. #' ##
  18. #' ## End(**Not run**)
  19. copy_shp_to_db <- function(dir = NULL, layer = NULL, conf = NULL, id = "fid",
  20. crs_source = "EPSG:4326",
  21. crs_target = "EPSG:4326",
  22. geometry_type = "PROMOTE_TO_MULTI") {
  23. # Command 'ogr2ogr' help
  24. # system("ogr2ogr --long-usage")
  25. # Kontrollime kas etteantud kataloogis paiknevad failid
  26. if (length(list.files(path = dir, pattern = sprintf("%s*", layer))) > 0) {
  27. source <- sprintf('"%s" "%s"', dir, layer)
  28. cmd <- sprintf(
  29. paste0(
  30. "ogr2ogr -progress --config PG_USE_COPY YES -f PostgreSQL ",
  31. "PG:\" dbname='%s' host=%s port=%d user='%s' password='%s' ",
  32. "sslmode=%s active_schema=%s \" -lco DIM=2 %s -overwrite -nlt GEOMETRY ",
  33. "-lco GEOMETRY_NAME=geometry -lco FID=%s -nln %s.%s ",
  34. "-s_srs %s -t_srs %s -nlt %s"
  35. ),
  36. conf$dbname, conf$host, conf$port, conf$user, conf$password,
  37. conf$sslmode, conf$schema, source, id, conf$schema, conf$table,
  38. crs_source, crs_target, geometry_type
  39. )
  40. ruut::db_create_new_schema(conf)
  41. Sys.sleep(1)
  42. system(cmd)
  43. } else {
  44. cat("\nEi leitud antud kataloogist faile.")
  45. return(NULL)
  46. }
  47. }