GRASS GIS 7 Programmer's Manual  7.9.dev(2020)-547ded6c0
build_pg.c
Go to the documentation of this file.
1 /*!
2  \file lib/vector/Vlib/build_pg.c
3 
4  \brief Vector library - Building topology for PostGIS layers
5 
6  Higher level functions for reading/writing/manipulating vectors.
7 
8  Line offset (simple features only) is
9  - centroids : FID
10  - other types : index of the first record (which is FID) in offset array.
11 
12  (C) 2012-2013 by the GRASS Development Team
13 
14  This program is free software under the GNU General Public License
15  (>=v2). Read the file COPYING that comes with GRASS for details.
16 
17  \author Martin Landa <landa.martin gmail.com>
18  */
19 
20 #include <grass/vector.h>
21 #include <grass/glocale.h>
22 
23 #include "local_proto.h"
24 
25 #ifdef HAVE_POSTGRES
26 #include "pg_local_proto.h"
27 
28 static int build_topo(struct Map_info *, int);
29 static int build_topogeom_stmt(const struct Format_info_pg *, int, int, int, char *);
30 static int save_map_bbox(const struct Format_info_pg *, const struct bound_box*);
31 static int create_topo_grass(const struct Format_info_pg *);
32 static int has_topo_grass(const struct Format_info_pg *);
33 static int write_nodes(const struct Plus_head *, const struct Format_info_pg *);
34 static int write_lines(const struct Plus_head *, const struct Format_info_pg *);
35 static int write_areas(const struct Plus_head *, const struct Format_info_pg *);
36 static int write_isles(const struct Plus_head *, const struct Format_info_pg *);
37 static void build_stmt_id(const void *, int, int, const struct Plus_head *, char **, size_t *);
38 static int create_simple_feature_from_topo(struct Map_info *);
39 #endif
40 
41 /*!
42  \brief Build topology for PostGIS layer
43 
44  Build levels:
45  - GV_BUILD_NONE
46  - GV_BUILD_BASE
47  - GV_BUILD_ATTACH_ISLES
48  - GV_BUILD_CENTROIDS
49  - GV_BUILD_ALL
50 
51  \param Map pointer to Map_info structure
52  \param build build level
53 
54  \return 1 on success
55  \return 0 on error
56  */
57 int Vect_build_pg(struct Map_info *Map, int build)
58 {
59 #ifdef HAVE_POSTGRES
60  struct Plus_head *plus;
61  struct Format_info_pg *pg_info;
62 
63  plus = &(Map->plus);
64  pg_info = &(Map->fInfo.pg);
65 
66  G_debug(1, "Vect_build_pg(): db='%s' table='%s', build=%d",
67  pg_info->db_name, pg_info->table_name, build);
68 
69  /* commit transaction block (update mode only) */
70  if (pg_info->inTransaction && Vect__execute_pg(pg_info->conn, "COMMIT") == -1)
71  return 0;
72  pg_info->inTransaction = FALSE;
73 
74  if (pg_info->feature_type == SF_GEOMETRY)
75  return 1;
76 
77  if (build == plus->built)
78  return 1; /* do nothing */
79 
80  /* TODO move this init to better place (Vect_open_ ?), because in
81  theory build may be reused on level2 */
82  if (!pg_info->toposchema_name && build >= plus->built && build > GV_BUILD_BASE) {
83  G_free(pg_info->offset.array);
84  G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
85  }
86 
87  if (!pg_info->conn) {
88  G_warning(_("No DB connection"));
89  return 0;
90  }
91 
92  if (!pg_info->fid_column && !pg_info->toposchema_name) {
93  G_warning(_("Feature table <%s> has no primary key defined"),
94  pg_info->table_name);
95  G_warning(_("Random read is not supported for this layer. "
96  "Unable to build topology."));
97  return 0;
98  }
99 
100  if (build > GV_BUILD_NONE) {
101  G_message(_("Using external data format '%s' (feature type '%s')"),
104  if (!pg_info->toposchema_name)
105  G_message(_("Building pseudo-topology over simple features..."));
106  else
107  G_message(_("Building topology from PostGIS topology schema <%s>..."),
108  pg_info->toposchema_name);
109  }
110 
111  if (!pg_info->toposchema_name) /* pseudo-topology for simple features */
112  return Vect__build_sfa(Map, build);
113 
114  /* PostGIS Topology */
115  return build_topo(Map, build);
116 #else
117  G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
118  return 0;
119 #endif
120 }
121 
122 #ifdef HAVE_POSTGRES
123 /*!
124  \brief Build from PostGIS topology schema
125 
126  \todo Attach isles
127 
128  \param Map pointer to Map_info struct
129  \param build build level
130 
131  \return 1 on success
132  \return 0 on error
133 */
134 int build_topo(struct Map_info *Map, int build)
135 {
136  int line, type, s, n_nodes;
137  int area, nareas, isle, nisles;
138  int face[2];
139  char stmt[DB_SQL_MAX];
140  char *def_file;
141 
142  struct Plus_head *plus;
143  struct Format_info_pg *pg_info;
144 
145  struct P_line *Line;
146  struct P_area *Area;
147  struct P_topo_b *topo_b;
148  struct P_isle *Isle;
149 
150  plus = &(Map->plus);
151  pg_info = &(Map->fInfo.pg);
152 
153  /* check if upgrade or downgrade */
154  if (build < plus->built) {
155  /* -> downgrade */
156  Vect__build_downgrade(Map, build);
157  return 1;
158  }
159  /* -> upgrade */
160 
161  if (build < GV_BUILD_BASE)
162  return 1; /* nothing to print */
163 
164  /* cache features to speed-up random access (when attaching isles
165  to areas) */
166  if (build >= GV_BUILD_BASE) {
167  /* clean-up GRASS topology tables in DB */
168  if (!pg_info->topo_geo_only)
169  Vect__clean_grass_db_topo(&(Map->fInfo.pg));
170 
171  if (Map->mode == GV_MODE_RW &&
172  pg_info->cache.lines_num > 0) {
173 
174  /* read line cache from scratch when map is open in update
175  * mode, before building native topology read nodes from
176  * PostGIS Topology */
177 
178  /* clean-up spatial a category indices */
179  dig_free_plus(&(Map->plus));
180  dig_init_plus(&(Map->plus));
181  plus->Spidx_new = TRUE;
182  plus->update_cidx = TRUE;
183 
184  /* reset cache for reading features */
185  Vect__free_cache(&(pg_info->cache));
186  }
187  }
188 
189  if (plus->built >= GV_BUILD_BASE &&
190  pg_info->cache.lines_num < 1) {
191  /* features are not cached, build from scratch */
193  }
194 
195  if (plus->built < GV_BUILD_BASE) {
196  /* force loading nodes from DB to get up-to-date node
197  * offsets, see write_nodes() for details */
198  Vect__free_offset(&(pg_info->offset));
199 
200  pg_info->cache.ctype = CACHE_FEATURE; /* do not cache nodes */
201  n_nodes = Map->plus.n_nodes = Vect__load_map_nodes_pg(Map, TRUE);
202  Vect__free_cache(&(pg_info->cache));
203  }
204 
205  if (build > GV_BUILD_BASE)
206  pg_info->cache.ctype = CACHE_MAP; /* cache all features */
207 
208  /* update TopoGeometry based on GRASS-like topology */
209  Vect_build_nat(Map, build);
210 
211  if (n_nodes != Map->plus.n_nodes)
212  G_warning(_("Inconsistency in topology: number of nodes %d (should be %d)"),
213  Map->plus.n_nodes, n_nodes);
214 
215  /* store map boundig box in DB */
216  save_map_bbox(pg_info, &(plus->box));
217 
218  /* begin transaction */
219  if (Vect__execute_pg(pg_info->conn, "BEGIN"))
220  return 0;
221 
222  Vect__execute_pg(pg_info->conn, "SET CONSTRAINTS ALL DEFERRED");
223 
224  /* write full node topo info to DB if requested */
225  if (!pg_info->topo_geo_only) {
226  write_nodes(plus, pg_info);
227  write_lines(plus, pg_info);
228  }
229 
230  /* update faces from GRASS Topology */
231  if (build >= GV_BUILD_AREAS) {
232  /* do clean up (1-3)
233  insert new faces (4)
234  update edges (5)
235  */
236 
237  G_message(_("Cleaning-up topology schema..."));
238  /* 1) reset centroids to '0' (universal face) */
239  sprintf(stmt, "UPDATE \"%s\".node SET containing_face = 0 WHERE "
240  "containing_face IS NOT NULL", pg_info->toposchema_name);
241  G_debug(2, "SQL: %s", stmt);
242  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
243  Vect__execute_pg(pg_info->conn, "ROLLBACK");
244  return 0;
245  }
246 
247  /* 2) reset left|right edges */
248  sprintf(stmt, "UPDATE \"%s\".edge_data SET left_face = 0, right_face = 0",
249  pg_info->toposchema_name);
250  G_debug(2, "SQL: %s", stmt);
251  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
252  Vect__execute_pg(pg_info->conn, "ROLLBACK");
253  return 0;
254  }
255 
256  /* 3) delete faces (areas/isles) */
257  sprintf(stmt, "DELETE FROM \"%s\".face WHERE "
258  "face_id != 0", pg_info->toposchema_name);
259  G_debug(2, "SQL: %s", stmt);
260  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
261  Vect__execute_pg(pg_info->conn, "ROLLBACK");
262  return 0;
263  }
264  if (!pg_info->topo_geo_only) {
265  sprintf(stmt, "DELETE FROM \"%s\".%s", pg_info->toposchema_name, TOPO_TABLE_AREA);
266  G_debug(2, "SQL: %s", stmt);
267  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
268  Vect__execute_pg(pg_info->conn, "ROLLBACK");
269  return 0;
270  }
271 
272  sprintf(stmt, "DELETE FROM \"%s\".%s", pg_info->toposchema_name, TOPO_TABLE_ISLE);
273  G_debug(2, "SQL: %s", stmt);
274  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
275  Vect__execute_pg(pg_info->conn, "ROLLBACK");
276  return 0;
277  }
278  }
279 
280  /* 4) insert faces & update nodes (containing_face) based on
281  * GRASS topology */
282  G_message(_("Updating faces..."));
283  nareas = Vect_get_num_areas(Map);
284  for (area = 1; area <= nareas; area++) {
285  G_percent(area, nareas, 5);
286  if (0 == Vect__insert_face_pg(Map, area)) {
287  Vect__execute_pg(pg_info->conn, "ROLLBACK");
288  return 0;
289  }
290 
291  if (build < GV_BUILD_CENTROIDS)
292  continue;
293 
294  /* update centroids (node -> containing_face) */
295  Area = plus->Area[area];
296  if (Area->centroid < 1) {
297  G_debug(3, "Area %d without centroid, skipped", area);
298  continue;
299  }
300 
301  Line = plus->Line[Area->centroid];
302  sprintf(stmt, "UPDATE \"%s\".node SET "
303  "containing_face = %d WHERE node_id = %d",
304  pg_info->toposchema_name, area, (int)Line->offset);
305  G_debug(2, "SQL: %s", stmt);
306 
307  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
308  Vect__execute_pg(pg_info->conn, "ROLLBACK");
309  return 0;
310  }
311  }
312 
313  /* 5) update edges (left and right face) */
314  G_message(_("Updating edges..."));
315  for (line = 1; line <= plus->n_lines; line++) {
316  G_percent(line, plus->n_lines, 5);
317  type = Vect_read_line(Map, NULL, NULL, line);
318  if (type != GV_BOUNDARY)
319  continue;
320 
321  Line = Map->plus.Line[line];
322  if (!Line) {
323  G_warning(_("Inconsistency in topology detected. "
324  "Dead line found."));
325  return 0;
326  }
327 
328  topo_b = (struct P_topo_b *) Line->topo;
329 
330  for (s = 0; s < 2; s++) { /* for both sides */
331  face[s] = s == 0 ? topo_b->left : topo_b->right;
332  if (face[s] < 0) {
333  /* isle */
334  Isle = plus->Isle[abs(face[s])];
335  face[s] = Isle->area;
336  }
337  }
338  G_debug(3, "update edge %d: left_face = %d, right_face = %d",
339  (int)Line->offset, face[0], face[1]);
340 
341  sprintf(stmt, "UPDATE \"%s\".edge_data SET "
342  "left_face = %d, right_face = %d "
343  "WHERE edge_id = %d", pg_info->toposchema_name,
344  face[0], face[1], (int) Line->offset);
345 
346  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
347  Vect__execute_pg(pg_info->conn, "ROLLBACK");
348  return 0;
349  }
350  }
351 
352  /* write full area topo info to DB if requested */
353  if (!pg_info->topo_geo_only) {
354  write_areas(plus, pg_info);
355  }
356  } /* build >= GV_BUILD_AREAS */
357 
358  if (build >= GV_BUILD_ATTACH_ISLES) {
359  /* insert isles as faces with negative face_id */
360  nisles = Vect_get_num_islands(Map);
361  for(isle = 1; isle <= nisles; isle++) {
362  Isle = plus->Isle[isle];
363  Vect__insert_face_pg(Map, -isle);
364  }
365 
366  /* write full isles topo info to DB if requested */
367  if (!pg_info->topo_geo_only) {
368  write_isles(plus, pg_info);
369  }
370  } /* build >= GV_BUILD_ISLES */
371 
372  if (pg_info->feature_type == SF_POLYGON) {
373  int centroid;
374 
375  struct P_line *Line;
376 
377  G_message(_("Updating TopoGeometry data..."));
378  for (area = 1; area <= plus->n_areas; area++) {
379  G_percent(area, plus->n_areas, 5);
380  centroid = Vect_get_area_centroid(Map, area);
381  if (centroid < 1)
382  continue;
383 
384  Line = plus->Line[centroid];
385  if (!Line)
386  continue;
387 
388  /* update topogeometry object: centroid -> face */
389  if (build_topogeom_stmt(pg_info, GV_CENTROID, area, (int) Line->offset, stmt) &&
390  Vect__execute_pg(pg_info->conn, stmt) == -1) {
391  Vect__execute_pg(pg_info->conn, "ROLLBACK");
392  return 0;
393  }
394 
395  Vect__define_topo_relation(pg_info, area, area);
396  }
397  }
398 
399  if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1)
400  return 0;
401 
402  /* check if we want to create simple features from topogeometry
403  data */
404  def_file = getenv("GRASS_VECTOR_PGFILE");
405 
406  if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
407  FILE *fp;
408  const char *p;
409 
410  struct Key_Value *key_val;
411  fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
412  if (!fp) {
413  G_fatal_error(_("Unable to open PG file"));
414  }
415  key_val = G_fread_key_value(fp);
416  fclose(fp);
417 
418  /* build simple features from topogeometry data */
419  p = G_find_key_value("simple_feature", key_val);
420  if (p && G_strcasecmp(p, "yes") == 0) {
421  if (build > GV_BUILD_BASE)
422  Map->level = LEVEL_2; /* force level to avoid errors */
423 
424  if (create_simple_feature_from_topo(Map) != 0)
425  return 0;
426  }
427 
428  G_free_key_value(key_val);
429  }
430 
431  return 1;
432 }
433 
434 /*!
435  \brief Build UPDATE statement for topo geometry element stored in
436  feature table
437 
438  \param pg_info so pointer to Format_info_pg
439  \param type feature type (GV_POINT, ...)
440  \param topo_id topology element id
441  \param fid feature id
442  \param[out] stmt string buffer
443 
444  \return 1 on success
445  \return 0 on failure
446 */
447 int build_topogeom_stmt(const struct Format_info_pg *pg_info,
448  int type, int topo_id, int fid, char *stmt)
449 {
450  int topogeom_type;
451 
452  switch(type) {
453  case GV_POINT:
454  topogeom_type = 1;
455  break;
456  case GV_LINE:
457  case GV_BOUNDARY:
458  topogeom_type = 2;
459  break;
460  case GV_CENTROID:
461  topogeom_type = 3;
462  break;
463  default:
464  G_warning(_("Unsupported topo geometry type %d"), type);
465  return 0;
466  }
467 
468  sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
469  "'(%d, 1, %d, %d)'::topology.TopoGeometry "
470  "WHERE (%s).id = %d",
471  pg_info->schema_name, pg_info->table_name,
472  pg_info->topogeom_column, pg_info->toposchema_id,
473  topo_id, topogeom_type, pg_info->topogeom_column, fid);
474 
475  return 1;
476 }
477 
478 /*!
479  \brief Store map bounding box in DB head table
480 
481  \param pg_info pointer to Format_info_pg struct
482  \param box pointer to bounding box
483 
484  \return 1 on success
485  \return 0 on failure
486 */
487 int save_map_bbox(const struct Format_info_pg *pg_info, const struct bound_box *box)
488 {
489  char stmt[DB_SQL_MAX];
490 
491  /* create if not exists */
492  if (create_topo_grass(pg_info) == -1) {
493  G_warning(_("Unable to create <%s.%s>"), TOPO_SCHEMA, TOPO_TABLE);
494  return 0;
495  }
496 
497  /* update bbox */
498  if (has_topo_grass(pg_info)) {
499  /* -> update */
500  sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
501  "'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d WHERE %s = %d",
502  TOPO_SCHEMA, TOPO_TABLE, TOPO_BBOX,
503  box->W, box->S, box->B, box->E, box->N, box->T,
504  TOPO_ID, pg_info->toposchema_id);
505  }
506  else {
507  /* -> insert */
508  sprintf(stmt, "INSERT INTO \"%s\".\"%s\" (%s, %s) "
509  "VALUES(%d, 'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d)",
510  TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX, pg_info->toposchema_id,
511  box->W, box->S, box->B, box->E, box->N, box->T);
512  }
513 
514  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
515  return -1;
516  }
517 
518  return 1;
519 }
520 
521 /*!
522  \brief Creates 'topology.grass' table if not exists
523 
524  \return 0 table already exists
525  \return 1 table successfully added
526  \return -1 on error
527 */
528 int create_topo_grass(const struct Format_info_pg *pg_info)
529 {
530  char stmt[DB_SQL_MAX];
531 
532  PGresult *result;
533 
534  /* check if table exists */
535  sprintf(stmt, "SELECT COUNT(*) FROM information_schema.tables "
536  "WHERE table_schema = '%s' AND table_name = '%s'",
537  TOPO_SCHEMA, TOPO_TABLE);
538  result = PQexec(pg_info->conn, stmt);
539  if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
540  PQclear(result);
541  return -1;
542  }
543 
544  if (atoi(PQgetvalue(result, 0, 0)) == 1) {
545  /* table already exists */
546  PQclear(result);
547  return 1;
548  }
549  PQclear(result);
550 
551  G_debug(1, "<%s.%s> created", TOPO_SCHEMA, TOPO_TABLE);
552 
553  /* create table */
554  sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s INTEGER, %s box3d)",
555  TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX);
556  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
557  return -1;
558  }
559  /* add primary key */
560  sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD PRIMARY KEY (%s)",
561  TOPO_SCHEMA, TOPO_TABLE, TOPO_ID);
562  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
563  return -1;
564  }
565 
566  /* add constraint */
567  sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD CONSTRAINT \"%s_%s_fkey\" "
568  "FOREIGN KEY (%s) REFERENCES topology.topology(id) ON DELETE CASCADE",
569  TOPO_SCHEMA, TOPO_TABLE, TOPO_TABLE, TOPO_ID, TOPO_ID);
570  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
571  return -1;
572  }
573 
574  return 1;
575 }
576 
577 /*!
578  \brief Check if 'topology_id' exists in 'topology.grass'
579 
580  \param pg_info pointer to Format_info_pg struct
581 
582  \return TRUE if exists
583  \return FALSE otherwise
584  \return -1 on error
585 */
586 int has_topo_grass(const struct Format_info_pg *pg_info)
587 {
588  int has_topo;
589  char stmt[DB_SQL_MAX];
590 
591  PGresult *result;
592 
593  sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".\"%s\" "
594  "WHERE %s = %d",
595  TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, pg_info->toposchema_id);
596  result = PQexec(pg_info->conn, stmt);
597  if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
598  PQclear(result);
599  return -1;
600  }
601 
602  has_topo = FALSE;
603  if (atoi(PQgetvalue(result, 0, 0)) == 1) {
604  /* table already exists */
605  has_topo = TRUE;
606  }
607  PQclear(result);
608 
609  return has_topo;
610 }
611 
612 /*!
613  \brief Insert node into 'node_grass' table
614 
615  Writes (see P_node struct):
616  - lines
617  - angles
618 
619  Already stored in Topo-Geo:
620  - x,y,z (geom)
621 
622  \param plus pointer to Plus_head struct
623  \param pg_info pointer to Format_info_pg struct
624 
625  \return 0 on success
626  \return -1 on error
627 */
628 int write_nodes(const struct Plus_head *plus,
629  const struct Format_info_pg *pg_info)
630 {
631  int i, node_id;
632  size_t stmt_lines_size, stmt_angles_size, stmt_size;
633  char *stmt_lines, *stmt_angles, *stmt;
634 
635  const struct P_node *Node;
636  const struct Format_info_offset *offset;
637 
638  offset = &(pg_info->offset);
639 
640  if (offset->array_num < 1) /* nothing to write */
641  return 0;
642 
643  if (plus->n_nodes != offset->array_num) {
644  G_warning(_("Unable to write nodes, offset array mismatch"));
645  return -1;
646  }
647 
648  stmt_size = 2 * DB_SQL_MAX + 512;
649  stmt = (char *) G_malloc(stmt_size);
650 
651  stmt_lines = stmt_angles = NULL;
652  for (i = 1; i <= plus->n_nodes; i++) {
653  Node = plus->Node[i];
654  if (!Node)
655  continue; /* should not happen */
656 
657  node_id = offset->array[i-1];
658 
659  /* 'lines' array */
660  build_stmt_id(Node->lines, Node->n_lines, TRUE, plus, &stmt_lines, &stmt_lines_size);
661  /* 'angle' array */
662  build_stmt_id(Node->angles, Node->n_lines, FALSE, NULL, &stmt_angles, &stmt_angles_size);
663 
664  /* build SQL statement to add new node into 'node_grass' */
665  if (stmt_lines_size + stmt_angles_size + 512 > stmt_size) {
666  stmt_size = stmt_lines_size + stmt_angles_size + 512;
667  stmt = (char *) G_realloc(stmt, stmt_size);
668  }
669  sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
670  "%d, '{%s}', '{%s}')", pg_info->toposchema_name, TOPO_TABLE_NODE,
671  node_id, stmt_lines, stmt_angles);
672  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
673  G_warning(_("Unable to write nodes"));
674  return -1;
675  }
676  }
677 
678  G_free(stmt_lines);
679  G_free(stmt_angles);
680  G_free(stmt);
681 
682  return 0;
683 }
684 
685 /*!
686  \brief Insert lines into 'line_grass' table
687 
688  Writes (see P_line struct) - only for boundaries:
689  - left, right area
690 
691  Already stored in Topo-Geo:
692  - edge_id, left_face, right_face
693 
694  \param plus pointer to Plus_head struct
695  \param pg_info pointer to Format_info_pg struct
696 
697  \return 0 on success
698  \return -1 on error
699 */
700 int write_lines(const struct Plus_head *plus,
701  const struct Format_info_pg *pg_info)
702 {
703  int i, row, offset;
704  char stmt[DB_SQL_MAX];
705 
706  const struct P_line *Line;
707  const struct P_topo_b *topo;
708 
709  PGresult *res;
710 
711  sprintf(stmt, "SELECT edge_id FROM \"%s\".edge_data WHERE "
712  "left_face != 0 OR right_face != 0 ORDER BY edge_id",
713  pg_info->toposchema_name);
714  G_debug(2, "SQL: %s", stmt);
715  res = PQexec(pg_info->conn, stmt);
716  if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
717  (PQntuples(res) > 0 && PQntuples(res) != plus->n_blines)) {
718  G_warning(_("Inconsistency in topology: number of "
719  "boundaries %d (should be %d)"),
720  PQntuples(res), plus->n_blines);
721  if (res)
722  PQclear(res);
723  return -1;
724  }
725 
726  for (row = 0, i = 1; i <= plus->n_lines; i++) {
727  Line = plus->Line[i];
728  if (!Line || Line->type != GV_BOUNDARY)
729  continue;
730 
731  if (Line->offset == 0L)
732  offset = atoi(PQgetvalue(res, row++, 0));
733  else
734  offset = (int)Line->offset;
735 
736  topo = (struct P_topo_b *)Line->topo;
737  sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
738  "%d, %d, %d)", pg_info->toposchema_name, TOPO_TABLE_LINE,
739  offset, topo->left, topo->right);
740  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
741  G_warning(_("Unable to write lines"));
742  return -1;
743  }
744  }
745 
746  return 0;
747 }
748 
749 /*!
750  \brief Insert area into 'area_grass' table
751 
752  Writes (see P_area struct):
753  - lines
754  - centroid
755  - isles
756 
757  \param plus pointer to Plus_head struct
758  \param pg_info pointer to Format_info_pg struct
759 
760  \return 0 on success
761  \return -1 on error
762 */
763 int write_areas(const struct Plus_head *plus,
764  const struct Format_info_pg *pg_info)
765 {
766  int area, centroid;
767  size_t stmt_lines_size, stmt_isles_size, stmt_size;
768  char *stmt_lines, *stmt_isles, *stmt;
769 
770  const struct P_line *Line;
771  const struct P_area *Area;
772 
773  stmt_size = 2 * DB_SQL_MAX + 512;
774  stmt = (char *) G_malloc(stmt_size);
775 
776  stmt_lines = stmt_isles = NULL;
777  for (area = 1; area <= plus->n_areas; area++) {
778  Area = plus->Area[area];
779  if (!Area) {
780  G_debug(3, "Area %d skipped (dead)", area);
781  continue; /* should not happen */
782  }
783 
784  /* 'lines' array */
785  build_stmt_id(Area->lines, Area->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
786  /* 'isles' array */
787  build_stmt_id(Area->isles, Area->n_isles, TRUE, NULL, &stmt_isles, &stmt_isles_size);
788 
789  if (Area->centroid != 0) {
790  Line = plus->Line[Area->centroid];
791  if (!Line) {
792  G_warning(_("Topology for centroid %d not available. Area %d skipped"),
793  Area->centroid, area);
794  continue;
795  }
796  centroid = (int) Line->offset;
797  }
798  else {
799  centroid = 0;
800  }
801 
802  /* build SQL statement to add new node into 'node_grass' */
803  if (stmt_lines_size + stmt_isles_size + 512 > stmt_size) {
804  stmt_size = stmt_lines_size + stmt_isles_size + 512;
805  stmt = (char *) G_realloc(stmt, stmt_size);
806  }
807  sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
808  "%d, '{%s}', %d, '{%s}')", pg_info->toposchema_name, TOPO_TABLE_AREA,
809  area, stmt_lines, centroid, stmt_isles);
810  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
811  return -1;
812  }
813  }
814 
815  G_free(stmt_lines);
816  G_free(stmt_isles);
817  G_free(stmt);
818 
819  return 0;
820 }
821 
822 /*!
823  \brief Insert isle into 'isle_grass' table
824 
825  Writes (see P_isle struct):
826  - lines
827  - area
828 
829  \param plus pointer to Plus_head struct
830  \param pg_info pointer to Format_info_pg struct
831 
832  \return 0 on success
833  \return -1 on error
834 */
835 int write_isles(const struct Plus_head *plus,
836  const struct Format_info_pg *pg_info)
837 {
838  int isle;
839  size_t stmt_lines_size, stmt_size;
840  char *stmt_lines, *stmt;
841 
842  const struct P_isle *Isle;
843 
844  stmt_size = DB_SQL_MAX + 512;
845  stmt = (char *) G_malloc(stmt_size);
846 
847  stmt_lines = NULL;
848  for (isle = 1; isle <= plus->n_isles; isle++) {
849  Isle = plus->Isle[isle];
850  if (!Isle)
851  continue; /* should not happen */
852 
853  /* 'lines' array */
854  build_stmt_id(Isle->lines, Isle->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
855 
856  /* build SQL statement to add new node into 'node_grass' */
857  if (stmt_lines_size + 512 > stmt_size) {
858  stmt_size = stmt_lines_size + 512;
859  stmt = (char *) G_realloc(stmt, stmt_size);
860  }
861  sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
862  "%d, '{%s}', %d)", pg_info->toposchema_name, TOPO_TABLE_ISLE,
863  isle, stmt_lines, Isle->area);
864  if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
865  return -1;
866  }
867  }
868 
869  G_free(stmt_lines);
870  G_free(stmt);
871 
872  return 0;
873 }
874 
875 /*!
876  \brief Create PG-like array for int/float array
877 
878  \param array array of items
879  \param nitems number of items in the array
880  \param is_int TRUE for array of integers otherwise floats
881  \param plus pointer to Plus_head struct
882  \param[in,out] output buffer (re-used)
883  \param[in,out] buffer size
884 */
885 void build_stmt_id(const void *array, int nitems, int is_int, const struct Plus_head *plus,
886  char **stmt, size_t *stmt_size)
887 {
888  int i, ivalue;
889  int *iarray;
890  float *farray;
891 
892  size_t stmt_id_size;
893  char *stmt_id, buf_id[128];
894 
895  struct P_line *Line;
896 
897  if (is_int)
898  iarray = (int *) array;
899  else
900  farray = (float *) array;
901 
902  if (!(*stmt)) {
903  stmt_id_size = DB_SQL_MAX;
904  stmt_id = (char *) G_malloc(stmt_id_size);
905  }
906  else {
907  stmt_id_size = *stmt_size;
908  stmt_id = *stmt;
909  }
910 
911  /* reset array */
912  stmt_id[0] = '\0';
913 
914  for (i = 0; i < nitems; i++) {
915  /* realloc array if needed */
916  if (strlen(stmt_id) + 100 > stmt_id_size) {
917  stmt_id_size = strlen(stmt_id) + DB_SQL_MAX;
918  stmt_id = (char *) G_realloc(stmt_id, stmt_id_size);
919  }
920 
921  if (is_int) {
922  if (plus) {
923  Line = plus->Line[abs(iarray[i])];
924  ivalue = (int) Line->offset;
925  if (iarray[i] < 0)
926  ivalue *= -1;
927  }
928  else {
929  ivalue = iarray[i];
930  }
931  sprintf(buf_id, "%d", ivalue);
932  }
933  else {
934  sprintf(buf_id, "%f", farray[i]);
935  }
936 
937  if (i > 0)
938  strcat(stmt_id, ",");
939  strcat(stmt_id, buf_id);
940  }
941 
942  *stmt = stmt_id;
943  *stmt_size = stmt_id_size;
944 }
945 
946 /*!
947  \brief Clean-up GRASS Topology tables
948 
949  \param pg_info pointer to Format_info_pg pg_info
950 
951  \return 0 on success
952  \return -1 on error
953 */
954 int Vect__clean_grass_db_topo(struct Format_info_pg *pg_info)
955 {
956  char stmt[DB_SQL_MAX];
957 
958  sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
959  pg_info->toposchema_name, TOPO_TABLE_NODE);
960  if (-1 == Vect__execute_pg(pg_info->conn, stmt))
961  return -1;
962 
963  sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
964  pg_info->toposchema_name, TOPO_TABLE_LINE);
965  if (-1 == Vect__execute_pg(pg_info->conn, stmt))
966  return -1;
967 
968 
969  sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
970  pg_info->toposchema_name, TOPO_TABLE_AREA);
971  if (-1 == Vect__execute_pg(pg_info->conn, stmt))
972  return -1;
973 
974 
975  sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
976  pg_info->toposchema_name, TOPO_TABLE_ISLE);
977  if (-1 == Vect__execute_pg(pg_info->conn, stmt))
978  return -1;
979 
980 
981  return 0;
982 }
983 
984 /*!
985  \brief Create simple features geometry from topogeometry data
986 
987  \param Map pointer to Map_info struct
988 
989  \return 0 on success
990  \return -1 on error
991 */
992 int create_simple_feature_from_topo(struct Map_info *Map)
993 {
994  char stmt[DB_SQL_MAX];
995 
996  struct Format_info_pg *pg_info;
997 
998  pg_info = &(Map->fInfo.pg);
999 
1000  G_debug(1, "build_simple_feature_from_topo(): %d", pg_info->feature_type);
1001 
1002  G_message(_("Create simple features topology from topogeometry data..."));
1003  Vect__execute_pg(pg_info->conn, "BEGIN");
1004  if (pg_info->feature_type == SF_POINT ||
1005  pg_info->feature_type == SF_LINESTRING) {
1006  sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = (SELECT geom FROM \"%s\".node "
1007  "WHERE node_id = (%s).id)", pg_info->schema_name, pg_info->table_name,
1008  pg_info->geom_column, pg_info->toposchema_name, pg_info->topogeom_column);
1009 
1010  if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
1011  Vect__execute_pg(pg_info->conn, "ROLLBACK");
1012  return -1;
1013 
1014  }
1015  }
1016  else if (pg_info->feature_type == SF_POLYGON) {
1017  Vect__copy_areas(Map, 1, Map);
1018  }
1019  else {
1020  G_warning(_("Unable to build simple features from topogeometry data. "
1021  "Unsupported type %d."), pg_info->feature_type);
1022  }
1023 
1024  Vect__execute_pg(pg_info->conn, "COMMIT");
1025 
1026  return 0;
1027 }
1028 #endif
int * array
Offset list.
Definition: dig_structs.h:446
char * toposchema_name
Topology schema name and id.
Definition: dig_structs.h:699
int Vect_build_nat(struct Map_info *Map, int build)
Build topology.
Definition: build_nat.c:33
int Spidx_new
Build new spatial index.
Definition: dig_structs.h:1059
#define TRUE
Definition: gis.h:56
plus_t n_areas
Current number of areas.
Definition: dig_structs.h:951
plus_t Vect_get_num_areas(const struct Map_info *Map)
Get number of areas in vector map.
Definition: level_two.c:86
int G_strcasecmp(const char *x, const char *y)
String compare ignoring case (upper or lower)
Definition: strings.c:46
Bounding box.
Definition: dig_structs.h:65
const char * G_find_key_value(const char *key, const struct Key_Value *kv)
Find given key (case sensitive)
Definition: key_value1.c:84
if(!(yy_init))
Definition: sqlp.yy.c:775
void G_free(void *buf)
Free allocated memory.
Definition: gis/alloc.c:149
int built
Highest level of topology currently available.
Definition: dig_structs.h:873
int Vect__build_sfa(struct Map_info *Map, int build)
Build pseudo-topology (for simple features) - internal use only.
Definition: build_sfa.c:694
double W
West.
Definition: dig_structs.h:82
off_t offset
Offset in coor file for line.
Definition: dig_structs.h:1593
Vector geometry.
Definition: dig_structs.h:1574
struct P_line ** Line
Array of vector geometries.
Definition: dig_structs.h:887
struct Key_Value * G_fread_key_value(FILE *fd)
Read key/values pairs from file.
Definition: key_value2.c:49
Isle (topology) info.
Definition: dig_structs.h:1646
SF_FeatureType feature_type
Feature type (simple feature access)
Definition: dig_structs.h:635
plus_t right
Area number to the right, negative for isle.
Definition: dig_structs.h:1526
#define GV_BUILD_BASE
Topology levels - basic level (without areas and isles)
Definition: dig_defines.h:125
struct P_area ** Area
Array of areas.
Definition: dig_structs.h:891
#define DB_SQL_MAX
Definition: dbmi.h:142
struct P_node ** Node
Array of nodes.
Definition: dig_structs.h:883
void Vect__free_cache(struct Format_info_cache *cache)
#define GV_CENTROID
Definition: dig_defines.h:185
const char * Vect_get_finfo_geometry_type(const struct Map_info *Map)
Get geometry type as string (relevant only for non-native formats)
Definition: header_finfo.c:144
plus_t n_lines
Number of attached lines (size of lines, angle)
Definition: dig_structs.h:1472
plus_t left
Area number to the left, negative for isle.
Definition: dig_structs.h:1522
struct Format_info fInfo
Format info for non-native formats.
Definition: dig_structs.h:1415
double E
East.
Definition: dig_structs.h:78
struct P_isle ** Isle
Array of isles.
Definition: dig_structs.h:895
plus_t * lines
List of connected lines.
Definition: dig_structs.h:1479
int inTransaction
Start/Finish transaction.
Definition: dig_structs.h:658
plus_t * isles
1st generation interior islands
Definition: dig_structs.h:1640
plus_t n_isles
Current number of isles.
Definition: dig_structs.h:955
plus_t centroid
Number of first centroid within area.
Definition: dig_structs.h:1628
int level
Topology level.
Definition: dig_structs.h:1313
char * table_name
Table name.
Definition: dig_structs.h:619
#define NULL
Definition: ccmath.h:32
plus_t n_lines
Number of boundary lines.
Definition: dig_structs.h:1651
char * db_name
Database name (derived from conninfo)
Definition: dig_structs.h:611
void dig_free_plus(struct Plus_head *)
Free Plus structure.
Definition: plus.c:174
#define GV_POINT
Feature types used in memory on run time (may change)
Definition: dig_defines.h:182
char * topogeom_column
TopoGeometry column (feature table)
Definition: dig_structs.h:695
void G_free_key_value(struct Key_Value *kv)
Free allocated Key_Value structure.
Definition: key_value1.c:103
#define GV_BUILD_NONE
Topology levels - nothing to build.
Definition: dig_defines.h:123
int Vect_get_area_centroid(const struct Map_info *Map, int area)
Returns centroid id for given area.
int lines_num
Number of lines which forms current feature.
Definition: dig_structs.h:489
#define GV_MODE_RW
Read-write vector map open mode.
Definition: dig_defines.h:108
plus_t n_lines
Current number of lines.
Definition: dig_structs.h:947
void G_fatal_error(const char *msg,...)
Print a fatal error message to stderr.
Definition: gis/error.c:160
#define GV_LINE
Definition: dig_defines.h:183
int Vect_build_pg(struct Map_info *Map, int build)
Build topology for PostGIS layer.
Definition: build_pg.c:57
double N
North.
Definition: dig_structs.h:70
plus_t Vect_get_num_islands(const struct Map_info *Map)
Get number of islands in vector map.
Definition: level_two.c:137
char type
Line type.
Definition: dig_structs.h:1586
plus_t * lines
List of boundary lines.
Definition: dig_structs.h:1621
void Vect__free_offset(struct Format_info_offset *offset)
int ctype
Cache type.
Definition: dig_structs.h:507
Basic topology-related info.
Definition: dig_structs.h:784
Data structure used for building pseudo-topology.
Definition: dig_structs.h:397
#define GV_BUILD_AREAS
Topology levels - build areas.
Definition: dig_defines.h:127
Non-native format info (PostGIS)
Definition: dig_structs.h:602
char * geom_column
Geometry column (simple feature access)
Definition: dig_structs.h:631
struct Format_info_cache cache
Lines cache for reading feature.
Definition: dig_structs.h:683
#define FALSE
Definition: gis.h:60
void * topo
Topology info.
Definition: dig_structs.h:1599
float * angles
List of angles of connected lines.
Definition: dig_structs.h:1488
Boundary topology.
Definition: dig_structs.h:1509
struct Format_info_pg pg
PostGIS info.
Definition: dig_structs.h:726
int G_debug(int level, const char *msg,...)
Print debugging message.
Definition: debug.c:65
#define GV_BOUNDARY
Definition: dig_defines.h:184
plus_t * lines
List of boundary lines.
Definition: dig_structs.h:1662
double B
Bottom.
Definition: dig_structs.h:90
struct Plus_head plus
Plus info (topology, version, ...)
Definition: dig_structs.h:1286
Topological feature - node.
Definition: dig_structs.h:1448
int topo_geo_only
Topology format.
Definition: dig_structs.h:707
double T
Top.
Definition: dig_structs.h:86
struct bound_box box
Bounding box of features.
Definition: dig_structs.h:877
void G_percent(long n, long d, int s)
Print percent complete messages.
Definition: percent.c:62
plus_t n_isles
Number of islands inside.
Definition: dig_structs.h:1632
#define GV_BUILD_ATTACH_ISLES
Topology levels - attach islands to areas.
Definition: dig_defines.h:129
int array_num
Number of items in offset list.
Definition: dig_structs.h:450
Definition: gis.h:498
Vector map info.
Definition: dig_structs.h:1259
Area (topology) info.
Definition: dig_structs.h:1605
struct Format_info_offset offset
Offset list used for building pseudo-topology (simple features access)
Definition: dig_structs.h:689
#define LEVEL_2
Vector level - with 2D topology.
Definition: dig_defines.h:118
double S
South.
Definition: dig_structs.h:74
#define _(str)
Definition: glocale.h:13
void G_message(const char *msg,...)
Print a message to stderr.
Definition: gis/error.c:90
int Vect_read_line(const struct Map_info *Map, struct line_pnts *line_p, struct line_cats *line_c, int line)
Read vector feature (topological level required)
#define GV_BUILD_CENTROIDS
Topology levels - assign centroids to areas.
Definition: dig_defines.h:131
const char * G_mapset(void)
Get current mapset name.
Definition: gis/mapset.c:33
void Vect__build_downgrade(struct Map_info *Map, int build)
Downgrade build level (for internal use only)
Definition: build.c:760
void G_zero(void *buf, int i)
Zero out a buffer, buf, of length i.
Definition: gis/zero.c:23
FILE * G_fopen_old(const char *element, const char *name, const char *mapset)
Open a database file for reading.
Definition: gis/open.c:253
plus_t n_blines
Current number of boundaries.
Definition: dig_structs.h:910
char * schema_name
Schema name.
Definition: dig_structs.h:615
int update_cidx
Update category index if vector is modified.
Definition: dig_structs.h:1136
char * getenv()
plus_t n_lines
Number of boundary lines.
Definition: dig_structs.h:1610
plus_t area
Area it exists w/in, if any.
Definition: dig_structs.h:1669
int Vect_build_partial(struct Map_info *Map, int build)
Build partial topology for vector map.
Definition: build.c:847
void G_warning(const char *msg,...)
Print a warning message to stderr.
Definition: gis/error.c:204
const char * G_find_file2(const char *element, const char *name, const char *mapset)
Searches for a file from the mapset search list or in a specified mapset. (look but don&#39;t touch) ...
Definition: find_file.c:247
const char * Vect_get_finfo_format_info(const struct Map_info *Map)
Get format info as string (relevant only for non-native formats)
Definition: header_finfo.c:108
int Vect__copy_areas(const struct Map_info *In, int field, struct Map_info *Out)
Copy areas as polygons (OGR/PostGIS simple features access only)
int dig_init_plus(struct Plus_head *)
Initialize Plus_head structure.
Definition: plus.c:31
char * fid_column
FID column.
Definition: dig_structs.h:627
plus_t n_nodes
Current number of topological features derived from vector geometries.
Definition: dig_structs.h:939