Explorar el Código

Polügoonidega seotud muudatused.

Ardo Kubjas hace 3 años
padre
commit
007ceb03a7
Se han modificado 3 ficheros con 628 adiciones y 204 borrados
  1. 255 59
      R/pk_lisame_polygoonid.R
  2. 198 92
      R/pk_sellest_alustame_db_loomist.R
  3. 175 53
      R/pk_teisendame_polygoone.R

+ 255 - 59
R/pk_lisame_polygoonid.R

@@ -25,7 +25,9 @@ pk_lisame_polygoonid <- function(obj = NULL, conf = NULL) {
   conf <- vars$conf
   ## Konfiguratsiooni muutujale väärtuste omistamine, kui seda pole antud.
   if (!any("a00_piir" %in% ruut::db_schema_tablenames(conf = conf))) {
-    cat("\nAndmebaas loomata. Palun funktsiooniga ruut::pk_sellest_alustame_db_loomist() andmebaasi loomist.\n")
+    cat(
+      "\nAndmebaas loomata. Palun funktsiooniga ruut::pk_sellest_alustame_db_loomist() andmebaasi loomist.\n"
+    )
     return(NULL)
   }
 
@@ -36,68 +38,147 @@ pk_lisame_polygoonid <- function(obj = NULL, conf = NULL) {
 
   ## -------------------- Loop -----------------------
   intersect_layers <- c("a00_bb2") # c("piir", "bb", "bb2")
-  andmed <- data.frame("schema" = character(0), "table" = character(0))
-  andmed <- rbind(andmed, data.frame("schema" = "maaamet", "table" = "asustusyksus"))
-  andmed <- rbind(andmed, data.frame("schema" = "maaamet", "table" = "shp_katastriyksus"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "buildings_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "landuse_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "natural_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "places_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "pofw_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "pois_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "traffic_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "transport_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "osm_shp", "table" = "water_a"))
+  andmed <-
+    data.frame("schema" = character(0), "table" = character(0))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "maaamet", "table" = "asustusyksus"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "maaamet", "table" = "shp_katastriyksus"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "osm_shp", "table" = "buildings_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "osm_shp", "table" = "landuse_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "osm_shp", "table" = "natural_a"))
+  andmed <-
+    rbind(andmed, data.frame("schema" = "osm_shp", "table" = "places_a"))
+  andmed <-
+    rbind(andmed, data.frame("schema" = "osm_shp", "table" = "pofw_a"))
+  andmed <-
+    rbind(andmed, data.frame("schema" = "osm_shp", "table" = "pois_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "osm_shp", "table" = "traffic_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "osm_shp", "table" = "transport_a"))
+  andmed <-
+    rbind(andmed, data.frame("schema" = "osm_shp", "table" = "water_a"))
   # andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_201_meri_a_dissolved"))
   # andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_202_seisuveekogu_a_dissolved"))
   # andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_203_vooluveekogu_a_dissolved"))
   # andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_305_puittaimestik_a_dissolved"))
   # andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_306_margala_a_dissolved"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_201_meri_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_202_seisuveekogu_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_203_vooluveekogu_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_301_muu_kolvik_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_301_muu_kolvik_ka"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_302_ou_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_303_haritav_maa_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_304_lage_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_305_puittaimestik_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_306_margala_ka"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_307_turbavali_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_401_hoone_ka"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_403_muu_rajatis_ka"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_404_maaalune_hoone_ka"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_501_tee_a"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "e_505_liikluskorralduslik_rajatis_ka"))
-  andmed <- rbind(andmed, data.frame("schema" = "eesti", "table" = "mullakaart"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_201_meri_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_202_seisuveekogu_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_203_vooluveekogu_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_301_muu_kolvik_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_301_muu_kolvik_ka"))
+  andmed <-
+    rbind(andmed, data.frame("schema" = "eesti", "table" = "e_302_ou_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_303_haritav_maa_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_304_lage_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_305_puittaimestik_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_306_margala_ka"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_307_turbavali_a"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_401_hoone_ka"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_403_muu_rajatis_ka"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_404_maaalune_hoone_ka"))
+  andmed <-
+    rbind(andmed,
+          data.frame("schema" = "eesti", "table" = "e_501_tee_a"))
+  andmed <-
+    rbind(
+      andmed,
+      data.frame("schema" = "eesti", "table" = "e_505_liikluskorralduslik_rajatis_ka")
+    )
+  andmed <-
+    rbind(andmed, data.frame("schema" = "eesti", "table" = "mullakaart"))
 
 
   for (intersect in intersect_layers) {
     conf$table <- intersect
     conf$schema <- obj
-    intersect_layer <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_type = "Polygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
+    intersect_layer <-
+      ruut::construct_to_gpkg_output_postgres_str(
+        conf = conf,
+        geometry_type = "Polygon",
+        srid = 3301,
+        checkPrimaryKeyUnicity = TRUE,
+        key = "id"
+      )
 
     for (i in 1:nrow(andmed)) {
-      if (andmed$schema[i] %in% c("teeregister_wfs")) geom <- "geometry" else geom <- "geom"
+      if (andmed$schema[i] %in% c("teeregister_wfs"))
+        geom <- "geometry"
+      else
+        geom <- "geom"
       conf$table <- andmed$table[i]
       conf$schema <- andmed$schema[i]
       input <- ruut::construct_to_gpkg_output_postgres_str(
-        conf = conf, geometry_type = "Polygon", srid = 3301,
-        checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = geom
+        conf = conf,
+        geometry_type = "Polygon",
+        srid = 3301,
+        checkPrimaryKeyUnicity = TRUE,
+        key = "id",
+        geometry_field = geom
       )
       # Geomeetria parandamine
       # ruut::qgis_algorithm_search_by_word("fix")
       algorithm <- "native:fixgeometries"
       output <- vars$tmp_gpkg_file_output_1 # ajutine fail
-      str <-  sprintf("{ 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        sprintf("{ 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd)
       # Ühisosa leidmine ja salvestamine ajutiseks failiks.
       algorithm <- "native:intersection"
       input <- vars$tmp_gpkg_file_input_1
       output <- vars$tmp_gpkg_file_output_2 # ajutine fail
-      str <- paste0("{ 'INPUT' : '", input, "', 'INPUT_FIELDS' : [], 'OUTPUT' : '", output, "', 'OVERLAY' : '", intersect_layer, "', 'OVERLAY_FIELDS' : [], 'OVERLAY_FIELDS_PREFIX' : '' }")
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        paste0(
+          "{ 'INPUT' : '",
+          input,
+          "', 'INPUT_FIELDS' : [], 'OUTPUT' : '",
+          output,
+          "', 'OVERLAY' : '",
+          intersect_layer,
+          "', 'OVERLAY_FIELDS' : [], 'OVERLAY_FIELDS_PREFIX' : '' }"
+        )
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       cat(sprintf("\n%s\n\n", cmd))
       system(cmd)
       ## Andmebaasi tabeli nimi: 2 esimest tähte tuleb schema nimest millest on andmed võetud, siis '_a_' s.o 'area' mis tähistab polügoone.
@@ -105,28 +186,80 @@ pk_lisame_polygoonid <- function(obj = NULL, conf = NULL) {
       # ruut::qgis_algorithm_search_by_word("Drop")
       algorithm <- "native:deletecolumn"
       input <- vars$tmp_gpkg_file_input_2
-      conf$table <- sprintf("data_a_%s_%s", strtrim(as.character(andmed$schema[i]), 2), andmed$table[i])
+      conf$table <-
+        sprintf("data_a_%s_%s",
+                strtrim(as.character(andmed$schema[i]), 2),
+                andmed$table[i])
       conf$schema <- obj
-      output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = NULL, srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-      cmd <- sprintf("qgis_process run %s --COLUMN='fid' --COLUMN='id_2' --COLUMN='left' --COLUMN='top' --COLUMN='right' --COLUMN='bottom' --INPUT='%s' --OUTPUT='%s' ", algorithm, input, output)
+      output <-
+        ruut::construct_to_gpkg_output_postgres_str(
+          conf = conf,
+          geometry_field = "geom",
+          geometry_type = NULL,
+          srid = 3301,
+          checkPrimaryKeyUnicity = FALSE,
+          key = "id"
+        )
+      cmd <-
+        sprintf(
+          "qgis_process run %s --COLUMN='fid' --COLUMN='id_2' --COLUMN='left' --COLUMN='top' --COLUMN='right' --COLUMN='bottom' --INPUT='%s' --OUTPUT='%s' ",
+          algorithm,
+          input,
+          output
+        )
       system(cmd)
 
       ## Filtreerime mõned andmetabelid eraldi alamkihtideks
       if (andmed$table[i] == "landuse_a") {
-        parent_table <- sprintf("data_a_%s_%s", strtrim(as.character(andmed$schema[i]), 2), andmed$table[i])
+        parent_table <-
+          sprintf("data_a_%s_%s",
+                  strtrim(as.character(andmed$schema[i]), 2),
+                  andmed$table[i])
         conn <- ruut::db_connect(conf = conf)
-        landuse_a <- unique(as.data.frame(sf::st_read(dsn = conn, layer = c(conf$schema, parent_table), as_tibble = T))[, c("code", "fclass")])
+        landuse_a <-
+          unique(as.data.frame(sf::st_read(
+            dsn = conn,
+            layer = c(conf$schema, parent_table),
+            as_tibble = T
+          ))[, c("code", "fclass")])
         for (k in 1:nrow(landuse_a)) {
           table_suffix <- landuse_a$fclass[k]
           conf$table <- parent_table
           conf$schema <- obj
-          input <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
+          input <-
+            ruut::construct_to_gpkg_output_postgres_str(
+              conf = conf,
+              geometry_type = "MultiPolygon",
+              srid = 3301,
+              checkPrimaryKeyUnicity = TRUE,
+              key = "id"
+            )
           # sf::st_read(dsn = conn, layer = c(conf$schema, parent_table))
           conf$table <- sprintf("%s_%s", parent_table, table_suffix)
-          output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-          str <- paste0("{ 'INPUT' : '", input, "', 'INTERSECT' : '", intersect_layer, "', 'OUTPUT' : '", output, "', FIELD : 'code', OPERATOR : 0, VALUE : '", landuse_a$code[k], "' }")
+          output <-
+            ruut::construct_to_gpkg_output_postgres_str(
+              conf = conf,
+              geometry_field = "geom",
+              geometry_type = "MultiPolygon",
+              srid = 3301,
+              checkPrimaryKeyUnicity = FALSE,
+              key = "id"
+            )
+          str <-
+            paste0(
+              "{ 'INPUT' : '",
+              input,
+              "', 'INTERSECT' : '",
+              intersect_layer,
+              "', 'OUTPUT' : '",
+              output,
+              "', FIELD : 'code', OPERATOR : 0, VALUE : '",
+              landuse_a$code[k],
+              "' }"
+            )
           algorithm <- "native:extractbyattribute"
-          cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+          cmd <-
+            ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
           cat(sprintf("\n%s\n", cmd))
           system(cmd)
         }
@@ -134,36 +267,99 @@ pk_lisame_polygoonid <- function(obj = NULL, conf = NULL) {
 
       ## Filtreerime mõned andmetabelid eraldi alamkihtideks
       if (andmed$table[i] == "e_401_hoone_ka") {
-        parent_table <- sprintf("data_a_%s_%s", strtrim(as.character(andmed$schema[i]), 2), andmed$table[i])
+        parent_table <-
+          sprintf("data_a_%s_%s",
+                  strtrim(as.character(andmed$schema[i]), 2),
+                  andmed$table[i])
         conn <- ruut::db_connect(conf = conf)
-        alamobjektid <- unique(as.data.frame(sf::st_read(dsn = conn, layer = c(conf$schema, parent_table), as_tibble = T))[, c("kood", "tyyp")])
+        alamobjektid <-
+          unique(as.data.frame(sf::st_read(
+            dsn = conn,
+            layer = c(conf$schema, parent_table),
+            as_tibble = T
+          ))[, c("kood", "tyyp")])
         for (k in 1:nrow(alamobjektid)) {
           table_suffix <- alamobjektid$tyyp[k]
           conf$table <- parent_table
           conf$schema <- obj
-          input <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
+          input <-
+            ruut::construct_to_gpkg_output_postgres_str(
+              conf = conf,
+              geometry_type = "MultiPolygon",
+              srid = 3301,
+              checkPrimaryKeyUnicity = TRUE,
+              key = "id"
+            )
           # sf::st_read(dsn = conn, layer = c(conf$schema, parent_table))
           conf$table <- sprintf("%s_%s", parent_table, table_suffix)
-          output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-          str <- paste0("{ 'INPUT' : '", input, "', 'INTERSECT' : '", intersect_layer, "', 'OUTPUT' : '", output, "', FIELD : 'tyyp', OPERATOR : 0, VALUE : '", alamobjektid$tyyp[k], "' }")
+          output <-
+            ruut::construct_to_gpkg_output_postgres_str(
+              conf = conf,
+              geometry_field = "geom",
+              geometry_type = "MultiPolygon",
+              srid = 3301,
+              checkPrimaryKeyUnicity = FALSE,
+              key = "id"
+            )
+          str <-
+            paste0(
+              "{ 'INPUT' : '",
+              input,
+              "', 'INTERSECT' : '",
+              intersect_layer,
+              "', 'OUTPUT' : '",
+              output,
+              "', FIELD : 'tyyp', OPERATOR : 0, VALUE : '",
+              alamobjektid$tyyp[k],
+              "' }"
+            )
           algorithm <- "native:extractbyattribute"
-          cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+          cmd <-
+            ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
           cat(sprintf("\n%s\n", cmd))
           system(cmd)
 
           ## ----------- lisame tsentroidid -----------
-          parent_table <- sprintf("data_a_%s_%s", strtrim(as.character(andmed$schema[i]), 2), andmed$table[i])
+          parent_table <-
+            sprintf("data_a_%s_%s",
+                    strtrim(as.character(andmed$schema[i]), 2),
+                    andmed$table[i])
 
           conf$table <- sprintf("%s_%s", parent_table, table_suffix)
           conf$schema <- obj
-          input <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
-          conf$table <- sprintf("data_p_%s_%s_%s", strtrim(as.character(andmed$schema[i]), 2), andmed$table[i], table_suffix)
-          output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "Point", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-          str <- sprintf("{ 'ALL_PARTS' : False, 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
+          input <-
+            ruut::construct_to_gpkg_output_postgres_str(
+              conf = conf,
+              geometry_type = "MultiPolygon",
+              srid = 3301,
+              checkPrimaryKeyUnicity = TRUE,
+              key = "id"
+            )
+          conf$table <-
+            sprintf(
+              "data_p_%s_%s_%s",
+              strtrim(as.character(andmed$schema[i]), 2),
+              andmed$table[i],
+              table_suffix
+            )
+          output <-
+            ruut::construct_to_gpkg_output_postgres_str(
+              conf = conf,
+              geometry_field = "geom",
+              geometry_type = "Point",
+              srid = 3301,
+              checkPrimaryKeyUnicity = FALSE,
+              key = "id"
+            )
+          str <-
+            sprintf("{ 'ALL_PARTS' : False, 'INPUT' : '%s', 'OUTPUT' : '%s' }",
+                    input,
+                    output)
           # ruut::qgis_algorithm_search_by_word("centroid")
           algorithm <- "native:centroids"
           # ruut::qgis_show_help(algorithm = algorithm)
-          cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+          cmd <-
+            ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
           cat(sprintf("\n%s\n", cmd))
           system(cmd)
         }

+ 198 - 92
R/pk_sellest_alustame_db_loomist.R

@@ -29,103 +29,209 @@
 #' # Layers list.
 #' ruut::db_schema_tablenames(conf = conf)
 #' }
-pk_sellest_alustame_db_loomist <- function(pk = NULL, obj = NULL, conf = NULL) {
-  ## ----------- argumentide vastavuse kontroll -----------
-  if (is.null(pk) || !sf::st_is_valid(pk)) {
-    cat("\nPalun kontrolli geomeetrilise kujundi \u00F%igsust.\n")
-    # return(NULL)
-  }
-  if (is.null(obj)) {
-    cat("\nPalun sisesta objekti nimi.\n")
-    # return(NULL)
-  }
-  vars <- ajutised_muutujad(pk, obj, conf)
-  obj <- vars$obj
-  pk <- vars$pk
-  conf <- vars$conf
-  attributes(pk)$names <- attributes(pk)$sf_column <- "geom"
+pk_sellest_alustame_db_loomist <-
+  function(pk = NULL,
+           obj = NULL,
+           conf = NULL) {
+    ## ----------- argumentide vastavuse kontroll -----------
+    if (is.null(pk) || !sf::st_is_valid(pk)) {
+      cat("\nPalun kontrolli geomeetrilise kujundi \u00F%igsust.\n")
+      # return(NULL)
+    }
+    if (is.null(obj)) {
+      cat("\nPalun sisesta objekti nimi.\n")
+      # return(NULL)
+    }
+    vars <- ajutised_muutujad(pk, obj, conf)
+    obj <- vars$obj
+    pk <- vars$pk
+    conf <- vars$conf
+    # attributes(pk)$names <- attributes(pk)$sf_column <- "geom"
 
 
-  ## --------------------- programmi osa ------------------------
+    ## --------------------- programmi osa ------------------------
 
-  ## 1. Piirjoone salvestamine
-  pk <- sf::st_transform(pk, 3301)
-  # Write to gpkg and check validity
-  sf::write_sf(pk, dsn = vars$tmp_gpkg_file, layer = vars$conf$gpkg_table, driver = "gpkg", fid_column_name = "fid", delete_dsn = T)
-  # Geomeetria parandamine
-  # ruut::qgis_algorithm_search_by_word("fix")
-  algorithm <- "native:fixgeometries"
-  input <- vars$tmp_gpkg_file_input_1 # ajutine fail
-  output <- vars$tmp_gpkg_file_output_2 # ajutine fail
-  str <-  sprintf("{ 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
-  cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
-  system(cmd)
-  # Write to postgis
-  ruut::db_create_new_schema(conf = conf)
-  conn <- ruut::db_connect(conf = conf)
-  # Eemaldame üleliigsed veerud
-  # ruut::qgis_algorithm_search_by_word("Drop")
-  algorithm <- "native:deletecolumn"
-  input <- vars$tmp_gpkg_file_input_2
-  conf$table <- "a00_piir"
-  output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-  cmd <- sprintf("qgis_process run %s --COLUMN='fid' --INPUT='%s' --OUTPUT='%s' ", algorithm, input, output)
-  system(cmd)
-  # sf::write_sf(pk, dsn = conn, layer = c(conf$schema, "a00_piir"), driver = "PostgreSQL", fid_column_name = "id", delete_dsn = F)
+    ## 1. Piirjoone salvestamine
+    pk <- sf::st_transform(pk, 3301)
+    # Write to gpkg and check validity
+    sf::write_sf(
+      pk,
+      dsn = vars$tmp_gpkg_file,
+      layer = vars$conf$gpkg_table,
+      driver = "gpkg",
+      fid_column_name = "fid",
+      delete_dsn = T
+    )
+    # Geomeetria parandamine
+    # ruut::qgis_algorithm_search_by_word("fix")
+    algorithm <- "native:fixgeometries"
+    input <- vars$tmp_gpkg_file_input_1 # ajutine fail
+    output <- vars$tmp_gpkg_file_output_2 # ajutine fail
+    str <-
+      sprintf("{ 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
+    cmd <-
+      ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+    system(cmd)
+    ## Multipart to singlepart
+    # ruut::qgis_algorithm_search_by_word("singlepart")
+    algorithm <- "native:multiparttosingleparts"
+    input <- vars$tmp_gpkg_file_input_2 # ajutine fail
+    output <- vars$tmp_gpkg_file_output_1 # ajutine fail
+    str <-  sprintf("{
+  'INPUT' : '%s',
+  'OUTPUT' : '%s'
+}", input, output)
+    cmd <-
+      ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+    system(cmd)
+    # Write to postgis
+    ruut::db_create_new_schema(conf = conf)
+    conn <- ruut::db_connect(conf = conf)
+    # Eemaldame üleliigsed veerud
+    # ruut::qgis_algorithm_search_by_word("Drop")
+    algorithm <- "native:deletecolumn"
+    input <- vars$tmp_gpkg_file_input_1
+    conf$table <- "a00_piir"
+    output <-
+      ruut::construct_to_gpkg_output_postgres_str(
+        conf = conf,
+        geometry_field = "geom",
+        geometry_type = "Polygon",
+        srid = 3301,
+        checkPrimaryKeyUnicity = FALSE,
+        key = "id"
+      )
+    cmd <-
+      sprintf(
+        "qgis_process run %s --COLUMN='fid' --INPUT='%s' --OUTPUT='%s' ",
+        algorithm,
+        input,
+        output
+      )
+    system(cmd)
 
-  ## 2. Piirikasti salvestamine
-  ## konstrueerime EXTENT, HSPACING ja VSPACING väärtused piirikasti konstrueerimiseks.
-  pk_attributes <- attributes(pk$geom)
-  extent <- sprintf("%s,%s,%s,%s [EPSG:3301]", round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["xmax"] / 100)) * 100, round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["ymax"] / 100)) * 100)
-  hspacing <- (ceiling((pk_attributes$bbox["xmax"] / 100)) * 100) - (round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100)
-  vspacing <- (ceiling((pk_attributes$bbox["ymax"] / 100)) * 100) - (round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100)
-  conf$table <- "a00_piir_bb"
-  output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = NULL, srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-  # ruut::qgis_algorithm_search_by_word(str = "grid")
-  algorithm <- "native:creategrid"
-  # cat(ruut::qgis_show_help(algorithm = algorithm))
-  cmd <- sprintf("qgis_process run %s --CRS=\"EPSG:3301\" --EXTENT=\"%s\" --HOVERLAY=0 --HSPACING=%s --TYPE=2 --VOVERLAY=0 --VSPACING=%s --OUTPUT=\"%s\"", algorithm, extent, hspacing, vspacing, output)
-  cat(sprintf("\n%s\n", cmd))
-  system(cmd)
+    ## 2. Piirikasti salvestamine
+    ## konstrueerime EXTENT, HSPACING ja VSPACING väärtused piirikasti konstrueerimiseks.
+    pk_attributes <- attributes(pk$geom)
+    extent <-
+      sprintf(
+        "%s,%s,%s,%s [EPSG:3301]",
+        round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100,
+        ceiling((pk_attributes$bbox["xmax"] / 100)) * 100,
+        round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100,
+        ceiling((pk_attributes$bbox["ymax"] / 100)) * 100
+      )
+    hspacing <-
+      (ceiling((pk_attributes$bbox["xmax"] / 100)) * 100) - (round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100)
+    vspacing <-
+      (ceiling((pk_attributes$bbox["ymax"] / 100)) * 100) - (round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100)
+    conf$table <- "a00_piir_bb"
+    output <-
+      ruut::construct_to_gpkg_output_postgres_str(
+        conf = conf,
+        geometry_field = "geom",
+        geometry_type = NULL,
+        srid = 3301,
+        checkPrimaryKeyUnicity = FALSE,
+        key = "id"
+      )
+    # ruut::qgis_algorithm_search_by_word(str = "grid")
+    algorithm <- "native:creategrid"
+    # cat(ruut::qgis_show_help(algorithm = algorithm))
+    cmd <-
+      sprintf(
+        "qgis_process run %s --CRS=\"EPSG:3301\" --EXTENT=\"%s\" --HOVERLAY=0 --HSPACING=%s --TYPE=2 --VOVERLAY=0 --VSPACING=%s --OUTPUT=\"%s\"",
+        algorithm,
+        extent,
+        hspacing,
+        vspacing,
+        output
+      )
+    cat(sprintf("\n%s\n", cmd))
+    system(cmd)
 
-  ## 3. epk2t piirikasti konstrueerimine ja salvestamine s.t kuhu mahuvad sisse
-  ## meie piirkonna epk2t (1x1km) ruudud.
+    ## 3. epk2t piirikasti konstrueerimine ja salvestamine s.t kuhu mahuvad sisse
+    ## meie piirkonna epk2t (1x1km) ruudud.
 
-  ## 3.1 Leiame piirikastiga seotud epk2t ruudud
-  # ruut::qgis_algorithm_search_by_word(str = "extract")
-  algorithm <- "native:extractbylocation"
-  # cat(ruut::qgis_show_help(algorithm = algorithm))
-  conf$table <- "epk2t_grid"
-  conf$schema <- "maaamet"
-  input <- ruut::construct_to_gpkg_output_postgres_str(
-    conf = conf, geometry_type = "Polygon", srid = 3301,
-    checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
-  )
-  conf$table <- "a00_piir_bb"
-  conf$schema <- obj
-  intersect <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_type = "Polygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
-  output <- vars$tmp_gpkg_file_output_1 # ajutine fail
-  str <- sprintf("{ 'INPUT' : '%s', 'INTERSECT' : '%s', 'OUTPUT' : '%s', 'PREDICATE' : [5,6] }", input, intersect, output)
-  cmd <- ruut::construct_qgis_output_result_to_better_format(str, algorithm)
-  system(cmd)
+    ## 3.1 Leiame piirikastiga seotud epk2t ruudud
+    # ruut::qgis_algorithm_search_by_word(str = "extract")
+    algorithm <- "native:extractbylocation"
+    # cat(ruut::qgis_show_help(algorithm = algorithm))
+    conf$table <- "epk2t_grid"
+    conf$schema <- "maaamet"
+    input <- ruut::construct_to_gpkg_output_postgres_str(
+      conf = conf,
+      geometry_type = "Polygon",
+      srid = 3301,
+      checkPrimaryKeyUnicity = TRUE,
+      key = "id",
+      geometry_field = "geom"
+    )
+    conf$table <- "a00_piir_bb"
+    conf$schema <- obj
+    intersect <-
+      ruut::construct_to_gpkg_output_postgres_str(
+        conf = conf,
+        geometry_type = "Polygon",
+        srid = 3301,
+        checkPrimaryKeyUnicity = TRUE,
+        key = "id"
+      )
+    output <- vars$tmp_gpkg_file_output_1 # ajutine fail
+    str <-
+      sprintf(
+        "{ 'INPUT' : '%s', 'INTERSECT' : '%s', 'OUTPUT' : '%s', 'PREDICATE' : [5,6] }",
+        input,
+        intersect,
+        output
+      )
+    cmd <-
+      ruut::construct_qgis_output_result_to_better_format(str, algorithm)
+    system(cmd)
 
-  ## 3.2 Ajutise faili abil epk2t piirikasti konstrueerimine
-  test_layer_obj <- sf::read_sf(dsn = vars$tmp_gpkg_file, layer = "test_layer_1")
-  pk_attributes <- attributes(test_layer_obj$geom)
-  extent <- sprintf("%s,%s,%s,%s [EPSG:3301]", round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["xmax"] / 100)) * 100, round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["ymax"] / 100)) * 100)
-  hspacing <- (ceiling((pk_attributes$bbox["xmax"] / 100)) * 100) - (round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100)
-  vspacing <- (ceiling((pk_attributes$bbox["ymax"] / 100)) * 100) - (round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100)
-  conf$table <- "a00_bb2"
-  output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = NULL, srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-  # ruut::qgis_algorithm_search_by_word(str = "grid")
-  algorithm <- "native:creategrid"
-  # cat(ruut::qgis_show_help(algorithm = algorithm))
-  cmd <- sprintf("qgis_process run %s --CRS=\"EPSG:3301\" --EXTENT=\"%s\" --HOVERLAY=0 --HSPACING=%s --TYPE=2 --VOVERLAY=0 --VSPACING=%s --OUTPUT=\"%s\"", algorithm, extent, hspacing, vspacing, output)
-  cat(sprintf("\n%s\n", cmd))
-  system(cmd)
+    ## 3.2 Ajutise faili abil epk2t piirikasti konstrueerimine
+    test_layer_obj <-
+      sf::read_sf(dsn = vars$tmp_gpkg_file, layer = "test_layer_1")
+    pk_attributes <- attributes(test_layer_obj$geom)
+    extent <-
+      sprintf(
+        "%s,%s,%s,%s [EPSG:3301]",
+        round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100,
+        ceiling((pk_attributes$bbox["xmax"] / 100)) * 100,
+        round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100,
+        ceiling((pk_attributes$bbox["ymax"] / 100)) * 100
+      )
+    hspacing <-
+      (ceiling((pk_attributes$bbox["xmax"] / 100)) * 100) - (round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100)
+    vspacing <-
+      (ceiling((pk_attributes$bbox["ymax"] / 100)) * 100) - (round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100)
+    conf$table <- "a00_bb2"
+    output <-
+      ruut::construct_to_gpkg_output_postgres_str(
+        conf = conf,
+        geometry_field = "geom",
+        geometry_type = NULL,
+        srid = 3301,
+        checkPrimaryKeyUnicity = FALSE,
+        key = "id"
+      )
+    # ruut::qgis_algorithm_search_by_word(str = "grid")
+    algorithm <- "native:creategrid"
+    # cat(ruut::qgis_show_help(algorithm = algorithm))
+    cmd <-
+      sprintf(
+        "qgis_process run %s --CRS=\"EPSG:3301\" --EXTENT=\"%s\" --HOVERLAY=0 --HSPACING=%s --TYPE=2 --VOVERLAY=0 --VSPACING=%s --OUTPUT=\"%s\"",
+        algorithm,
+        extent,
+        hspacing,
+        vspacing,
+        output
+      )
+    cat(sprintf("\n%s\n", cmd))
+    system(cmd)
 
-  ## Layers list
-  conf$schema <- obj
-  ruut::db_schema_tablenames(conf = conf)
-  sf::st_layers(dsn = vars$tmp_gpkg_file)
-}
+    ## Layers list
+    conf$schema <- obj
+    ruut::db_schema_tablenames(conf = conf)
+    sf::st_layers(dsn = vars$tmp_gpkg_file)
+  }

+ 175 - 53
R/pk_teisendame_polygoone.R

@@ -25,40 +25,70 @@ pk_teisendame_polygoone <- function(obj = NULL, conf = NULL) {
   conf <- vars$conf
   ## Konfiguratsiooni muutujale väärtuste omistamine, kui seda pole antud.
   if (!any("a00_piir" %in% ruut::db_schema_tablenames(conf = conf))) {
-    cat("\nAndmebaas loomata. Palun funktsiooniga ruut::pk_sellest_alustame_db_loomist() andmebaasi loomist.\n")
+    cat(
+      "\nAndmebaas loomata. Palun funktsiooniga ruut::pk_sellest_alustame_db_loomist() andmebaasi loomist.\n"
+    )
     return(NULL)
   }
 
   ## ====================== teisendused =====================
-  conn <- ruut::db_connect(conf = conf)
   # Layers list
   layer_names <- ruut::db_schema_tablenames(conf = conf)
-  layer_names <- layer_names[!layer_names %in% c("a00_bb2", "a00_piir_bb", "bb2_epk10t_grid", "bb2_epk02t_grid", "bb2_epk2t_grid")]
-  layer_names <- c("a00_piir", layer_names[grepl("^data_", layer_names)])
+  layer_names <-
+    layer_names[!layer_names %in% c("a00_bb2",
+                                    "a00_piir_bb",
+                                    "bb2_epk10t_grid",
+                                    "bb2_epk02t_grid",
+                                    "bb2_epk2t_grid")]
+  # layer_names <-
+  #   c("a00_piir", layer_names[grepl("^data_", layer_names)])
+  layer_names <-
+    c(layer_names[grepl("^data_", layer_names)])
   for (layer_name in layer_names) {
-    try(ruumiline_obj <- sf::st_read(dsn = conn, layer = c(conf$schema, layer_name)))
+    conn <- ruut::db_connect(conf = conf)
+    try(ruumiline_obj <-
+          sf::st_read(dsn = conn,
+                      layer = c(conf$schema, layer_name)))
+    DBI::dbDisconnect(conn)
     ## Kontlrollime kas geomeetriline objekt on polügoon.
     ## Arvutame sel juhul pindala.
-    is_polygon <- any(grepl("polygon", tolower(attributes(ruumiline_obj$geom)$class), fixed = TRUE))
+    is_polygon <-
+      any(grepl("polygon", tolower(
+        attributes(ruumiline_obj$geom)$class
+      ), fixed = TRUE))
     if (is_polygon) {
-
       ## 1. Lõikame objekti ruudistikga tükkideks. Ühte ruutu võib jääda mitu tükki.
       ## Peame need pärast ühendama
       # ruut::qgis_algorithm_search_by_word("Intersection")
       algorithm <- "native:intersection"
       conf$table <- sprintf("%s", layer_name)
       input <- ruut::construct_to_gpkg_output_postgres_str(
-        conf = conf, geometry_type = "MultiPolygon", srid = 3301,
-        checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
+        conf = conf,
+        geometry_type = "MultiPolygon",
+        srid = 3301,
+        checkPrimaryKeyUnicity = TRUE,
+        key = "id",
+        geometry_field = "geom"
       )
       conf$table <- sprintf("%s", "bb2_epk02t_grid")
       overlay <- ruut::construct_to_gpkg_output_postgres_str(
-        conf = conf, geometry_type = "Polygon", srid = 3301,
-        checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
+        conf = conf,
+        geometry_type = "Polygon",
+        srid = 3301,
+        checkPrimaryKeyUnicity = TRUE,
+        key = "id",
+        geometry_field = "geom"
       )
       output <- vars$tmp_gpkg_file_output_1 # ajutine fail
-      str <- sprintf("{ 'INPUT' : '%s', 'INPUT_FIELDS' : ['fid'], 'OUTPUT' : '%s', 'OVERLAY' : '%s', 'OVERLAY_FIELDS' : [], 'OVERLAY_FIELDS_PREFIX' : '' }", input, output, overlay)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        sprintf(
+          "{ 'INPUT' : '%s', 'INPUT_FIELDS' : ['fid'], 'OUTPUT' : '%s', 'OVERLAY' : '%s', 'OVERLAY_FIELDS' : [], 'OVERLAY_FIELDS_PREFIX' : '' }",
+          input,
+          output,
+          overlay
+        )
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd)
 
       ## 2. Ühendame ruudus olevad pinnad
@@ -66,8 +96,13 @@ pk_teisendame_polygoone <- function(obj = NULL, conf = NULL) {
       algorithm <- "native:dissolve"
       input <- vars$tmp_gpkg_file_input_1 # ajutine fail
       output <- vars$tmp_gpkg_file_output_2 # ajutine fail
-      str <- sprintf("{ 'FIELD' : ['%s'], 'INPUT' : '%s', 'OUTPUT' : '%s' }", "id", input, output)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        sprintf("{ 'FIELD' : ['%s'], 'INPUT' : '%s', 'OUTPUT' : '%s' }",
+                "id",
+                input,
+                output)
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd)
 
       ## 3. Lisame pindade pindalad ja perimeetri
@@ -75,8 +110,12 @@ pk_teisendame_polygoone <- function(obj = NULL, conf = NULL) {
       algorithm <- "qgis:exportaddgeometrycolumns"
       input <- vars$tmp_gpkg_file_input_2 # ajutine fail
       output <- vars$tmp_gpkg_file_output_1 # ajutine fail
-      str <- sprintf("{ 'CALC_METHOD' : 0, 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        sprintf("{ 'CALC_METHOD' : 0, 'INPUT' : '%s', 'OUTPUT' : '%s' }",
+                input,
+                output)
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd)
 
       ## 4. Add field
@@ -84,11 +123,15 @@ pk_teisendame_polygoone <- function(obj = NULL, conf = NULL) {
       # ruut::qgis_algorithm_search_by_word("pythonfield")
       algorithm <- "qgis:advancedpythonfieldcalculator"
       input <- vars$tmp_gpkg_file_input_1 # ajutine fail
-      epk02t_table_name <- sprintf("epk02t_%s", gsub("^data_", "", layer_name))
-      conf$table <- epk02t_table_name
-      output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "id")
-      str <- sprintf("{ 'FIELD_NAME' : 'area_pc', 'FIELD_TYPE' : 1, 'FIELD_LENGTH' : 4, 'FIELD_PRECISION' : 2, 'GLOBAL' : '', 'FORMULA' : 'value = round($geom.area()/10000,3)', 'INPUT' : '%s', 'OUTPUT' : '%s' }", input, output)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      output <- vars$tmp_gpkg_file_output_2 # ajutine fail
+      str <-
+        sprintf(
+          "{ 'FIELD_NAME' : 'area_pc', 'FIELD_TYPE' : 1, 'FIELD_LENGTH' : 4, 'FIELD_PRECISION' : 2, 'GLOBAL' : '', 'FORMULA' : 'value = round($geom.area()/10000,3)', 'INPUT' : '%s', 'OUTPUT' : '%s' }",
+          input,
+          output
+        )
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd)
 
       ## ------------- TIFF ----------------
@@ -96,60 +139,139 @@ pk_teisendame_polygoone <- function(obj = NULL, conf = NULL) {
       # ruut::qgis_algorithm_search_by_word("attributes")
       algorithm <- "native:joinattributesbylocation"
       conf$table <- "bb2_epk02t_grid"
-      input <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
-      conf$table <- epk02t_table_name
-      join <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = TRUE, key = "id")
+      input <-
+        ruut::construct_to_gpkg_output_postgres_str(
+          conf = conf,
+          geometry_field = "geom",
+          geometry_type = "MultiPolygon",
+          srid = 3301,
+          checkPrimaryKeyUnicity = TRUE,
+          key = "id"
+        )
+      join <- vars$tmp_gpkg_file_input_2 # ajutine fail
       output <- vars$tmp_gpkg_file_output_1
-      str <- sprintf("{ 'DISCARD_NONMATCHING' : False, 'INPUT' : '%s', 'JOIN' : '%s', 'JOIN_FIELDS' : ['area_pc'], 'METHOD' : 0, 'OUTPUT' : '%s', 'PREDICATE' : [1], 'PREFIX' : '' }", input, join, output)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        sprintf(
+          "{ 'DISCARD_NONMATCHING' : False, 'INPUT' : '%s', 'JOIN' : '%s', 'JOIN_FIELDS' : ['area_pc'], 'METHOD' : 0, 'OUTPUT' : '%s', 'PREDICATE' : [1], 'PREFIX' : '' }",
+          input,
+          join,
+          output
+        )
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd)
 
       ## 6. Asendame NULL väärtustega 0.
       algorithm <- "qgis:advancedpythonfieldcalculator"
       input <- vars$tmp_gpkg_file_input_1 # ajutine fail
       output <- vars$tmp_gpkg_file_output_2
-      cmd <- sprintf("qgis_process run %s --FIELD_NAME='value' --FIELD_TYPE=1 --FIELD_LENGTH=4 --FIELD_PRECISION=2 --GLOBAL=\"def getValue(x):
+      cmd <-
+        sprintf(
+          "qgis_process run %s --FIELD_NAME='value' --FIELD_TYPE=1 --FIELD_LENGTH=4 --FIELD_PRECISION=2 --GLOBAL=\"def getValue(x):
     if not x:
         value = 0
     else:
         value = x
-    return value\" --FORMULA='value = getValue( <area_pc> )' --INPUT='%s' --OUTPUT='%s' ", algorithm, input, output)
+    return value\" --FORMULA='value = getValue( <area_pc> )' --INPUT='%s' --OUTPUT='%s' ",
+          algorithm,
+          input,
+          output
+        )
       system(cmd)
 
-      ## 7. Eemaldame üleliigsed veerud
-      # ruut::qgis_algorithm_search_by_word("Drop ")
-      algorithm <- "native:deletecolumn"
-      input <- vars$tmp_gpkg_file_input_2
-      conf$table <- sprintf("grid_%s", gsub("^data_", "", layer_name))
-      output <- ruut::construct_to_gpkg_output_postgres_str(conf = conf, geometry_field = "geom", geometry_type = "MultiPolygon", srid = 3301, checkPrimaryKeyUnicity = FALSE, key = "fid")
-      cmd <- sprintf("qgis_process run %s --COLUMN='area_pc' --INPUT='%s' --OUTPUT='%s' ", algorithm, input, output)
-      system(cmd)
-
-      ## 8. tif salvestamine tmp kataloogi
-      grid_layer <- sf::read_sf(dsn = conn, layer = c(conf$schema, "bb2_epk02t_grid"))
+      ## 7. tif salvestamine tmp kataloogi
+      conn <- ruut::db_connect(conf = conf)
+      grid_layer <-
+        sf::read_sf(dsn = conn,
+                    layer = c(conf$schema, "bb2_epk02t_grid"))
+      DBI::dbDisconnect(conn)
       # sf::st_crs(grid_layer) <- 3301
       pk_attributes <- attributes(grid_layer$geom)
-      extent <- sprintf("%s,%s,%s,%s [EPSG:3301]", round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["xmax"] / 100)) * 100, round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100, ceiling((pk_attributes$bbox["ymax"] / 100)) * 100)
+      extent <-
+        sprintf(
+          "%s,%s,%s,%s [EPSG:3301]",
+          round((pk_attributes$bbox["xmin"] / 100), digits = 0) * 100,
+          ceiling((pk_attributes$bbox["xmax"] / 100)) * 100,
+          round((pk_attributes$bbox["ymin"] / 100), digits = 0) * 100,
+          ceiling((pk_attributes$bbox["ymax"] / 100)) * 100
+        )
       # ruut::qgis_algorithm_search_by_word("Rasterize")
       algorithm <- "gdal:rasterize"
       # ruut::qgis_show_help(algorithm = algorithm)
-      input <- ruut::construct_to_gpkg_output_postgres_str(
-        conf = conf, geometry_type = "MultiPolygon", srid = 3301,
-        checkPrimaryKeyUnicity = TRUE, key = "id", geometry_field = "geom"
-      )
-      tif_file_name <- sprintf("tif_%s", gsub("^data_", "", layer_name))
+      input <- vars$tmp_gpkg_file_input_2
+      tif_file_name <-
+        sprintf("tif_%s", gsub("^data_", "", layer_name))
       output <- sprintf("%s/%s.tif", vars$tmp_dir, tif_file_name)
-      str <- sprintf("{ 'BURN' : 0, 'DATA_TYPE' : 5, 'EXTENT' : '%s', 'EXTRA' : '-a_srs epsg:3301', 'FIELD' : 'value', 'HEIGHT' : 100, 'INIT' : None, 'INPUT' : '%s', 'INVERT' : False, 'NODATA' : -1, 'OPTIONS' : '', 'OUTPUT' : '%s', 'UNITS' : 1, 'WIDTH' : 100 }", extent, input, output)
-      cmd <- ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
+      str <-
+        sprintf(
+          "{ 'BURN' : 0, 'DATA_TYPE' : 5, 'EXTENT' : '%s', 'EXTRA' : '-a_srs epsg:3301', 'FIELD' : 'value', 'HEIGHT' : 100, 'INIT' : None, 'INPUT' : '%s', 'INVERT' : False, 'NODATA' : -1, 'OPTIONS' : '', 'OUTPUT' : '%s', 'UNITS' : 1, 'WIDTH' : 100 }",
+          extent,
+          input,
+          output
+        )
+      cmd <-
+        ruut::construct_qgis_output_result_to_better_format(str = str, algorithm = algorithm)
       system(cmd) # Salvestame kataloogi
 
-      ## 9. ----------- TIF TO POSTGIS -------------
+      ## 8. ----------- TIF TO POSTGIS -------------
       # Installi eelnevalt andmebaasi laiendus: create extension postgis_raster;
-      (cmd <- sprintf(
-        "export PGPASSWORD=%s && raster2pgsql -s 3301 -d -I -C -M %s %s.%s_tif | psql -U %s -d %s -h %s -p %s",
-        conf$password, output, conf$schema, tif_file_name, conf$user, conf$dbname, conf$host, conf$port
-      ))
+      (
+        cmd <- sprintf(
+          "export PGPASSWORD=%s && raster2pgsql -s 3301 -d -I -C -M %s %s.%s_tif | psql -U %s -d %s -h %s -p %s",
+          conf$password,
+          output,
+          conf$schema,
+          tif_file_name,
+          conf$user,
+          conf$dbname,
+          conf$host,
+          conf$port
+        )
+      )
+      system(cmd)
+
+      ## 9. Eemaldame üleliigsed veerud ja salvestame tiff alusfaili andmebaasi
+      # ruut::qgis_algorithm_search_by_word("Drop ")
+      algorithm <- "native:deletecolumn"
+      input <- vars$tmp_gpkg_file_input_2
+      conf$table <-
+        sprintf("grid_%s", gsub("^data_", "", layer_name))
+      output <-
+        ruut::construct_to_gpkg_output_postgres_str(
+          conf = conf,
+          geometry_field = "geom",
+          geometry_type = "MultiPolygon",
+          srid = 3301,
+          checkPrimaryKeyUnicity = FALSE,
+          key = "id"
+        )
+      cmd <-
+        sprintf(
+          "qgis_process run %s --COLUMN='area_pc' --COLUMN='fid' --COLUMN='left' --COLUMN='top' --COLUMN='right' --COLUMN='bottom' --INPUT='%s' --OUTPUT='%s' ",
+          algorithm,
+          input,
+          output
+        )
       system(cmd)
+
+      ## 10. Kustutame geom veeru.
+      conn <- ruut::db_connect(conf = conf)
+      q <-
+        sprintf("ALTER TABLE %s.%s DROP COLUMN geom;",
+                conf$schema,
+                conf$table)
+      cat(sprintf("\n-----------------\n%s\n\n", q))
+      DBI::dbSendQuery(conn, q)
+      ## 11. Vaakum.
+      q <-
+        sprintf(
+          "VACUUM (FULL, FREEZE, VERBOSE, ANALYZE, INDEX_CLEANUP) %s.%s;",
+          conf$schema,
+          conf$table
+        )
+      cat(sprintf("\n-----------------\n%s\n\n", q))
+      DBI::dbSendQuery(conn, q)
+      DBI::dbDisconnect(conn)
     }
   }
   ## Layers list