build_pg.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /*!
  2. \file lib/vector/Vlib/build_pg.c
  3. \brief Vector library - Building topology for PostGIS layers
  4. Higher level functions for reading/writing/manipulating vectors.
  5. Line offset (simple features only) is
  6. - centroids : FID
  7. - other types : index of the first record (which is FID) in offset array.
  8. (C) 2012-2013 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. \author Martin Landa <landa.martin gmail.com>
  12. */
  13. #include <grass/vector.h>
  14. #include <grass/glocale.h>
  15. #include "local_proto.h"
  16. #ifdef HAVE_POSTGRES
  17. #include "pg_local_proto.h"
  18. static int build_topo(struct Map_info *, int);
  19. static int build_topogeom_stmt(const struct Format_info_pg *, int, int, int, char *);
  20. static int save_map_bbox(const struct Format_info_pg *, const struct bound_box*);
  21. static int create_topo_grass(const struct Format_info_pg *);
  22. static int has_topo_grass(const struct Format_info_pg *);
  23. static int write_nodes(const struct Plus_head *, const struct Format_info_pg *);
  24. static int write_lines(const struct Plus_head *, const struct Format_info_pg *);
  25. static int write_areas(const struct Plus_head *, const struct Format_info_pg *);
  26. static int write_isles(const struct Plus_head *, const struct Format_info_pg *);
  27. static void build_stmt_id(const void *, int, int, const struct Plus_head *, char **, size_t *);
  28. static int create_simple_feature_from_topo(struct Map_info *);
  29. #endif
  30. /*!
  31. \brief Build topology for PostGIS layer
  32. Build levels:
  33. - GV_BUILD_NONE
  34. - GV_BUILD_BASE
  35. - GV_BUILD_ATTACH_ISLES
  36. - GV_BUILD_CENTROIDS
  37. - GV_BUILD_ALL
  38. \param Map pointer to Map_info structure
  39. \param build build level
  40. \return 1 on success
  41. \return 0 on error
  42. */
  43. int Vect_build_pg(struct Map_info *Map, int build)
  44. {
  45. #ifdef HAVE_POSTGRES
  46. struct Plus_head *plus;
  47. struct Format_info_pg *pg_info;
  48. plus = &(Map->plus);
  49. pg_info = &(Map->fInfo.pg);
  50. G_debug(1, "Vect_build_pg(): db='%s' table='%s', build=%d",
  51. pg_info->db_name, pg_info->table_name, build);
  52. /* commit transaction block (update mode only) */
  53. if (pg_info->inTransaction && Vect__execute_pg(pg_info->conn, "COMMIT") == -1)
  54. return 0;
  55. pg_info->inTransaction = FALSE;
  56. if (pg_info->feature_type == SF_GEOMETRY)
  57. return 1;
  58. if (build == plus->built)
  59. return 1; /* do nothing */
  60. /* TODO move this init to better place (Vect_open_ ?), because in
  61. theory build may be reused on level2 */
  62. if (!pg_info->toposchema_name && build >= plus->built && build > GV_BUILD_BASE) {
  63. G_free(pg_info->offset.array);
  64. G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
  65. }
  66. if (!pg_info->conn) {
  67. G_warning(_("No DB connection"));
  68. return 0;
  69. }
  70. if (!pg_info->fid_column && !pg_info->toposchema_name) {
  71. G_warning(_("Feature table <%s> has no primary key defined"),
  72. pg_info->table_name);
  73. G_warning(_("Random read is not supported for this layer. "
  74. "Unable to build topology."));
  75. return 0;
  76. }
  77. if (build > GV_BUILD_NONE) {
  78. G_message(_("Using external data format '%s' (feature type '%s')"),
  79. Vect_get_finfo_format_info(Map),
  80. Vect_get_finfo_geometry_type(Map));
  81. if (!pg_info->toposchema_name)
  82. G_message(_("Building pseudo-topology over simple features..."));
  83. else
  84. G_message(_("Building topology from PostGIS topology schema <%s>..."),
  85. pg_info->toposchema_name);
  86. }
  87. if (!pg_info->toposchema_name) /* pseudo-topology for simple features */
  88. return Vect__build_sfa(Map, build);
  89. /* PostGIS Topology */
  90. return build_topo(Map, build);
  91. #else
  92. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  93. return 0;
  94. #endif
  95. }
  96. #ifdef HAVE_POSTGRES
  97. /*!
  98. \brief Build from PostGIS topology schema
  99. \todo Attach isles
  100. \param Map pointer to Map_info struct
  101. \param build build level
  102. \return 1 on success
  103. \return 0 on error
  104. */
  105. int build_topo(struct Map_info *Map, int build)
  106. {
  107. int line, type, s, n_nodes;
  108. int area, nareas, isle, nisles;
  109. int face[2];
  110. char stmt[DB_SQL_MAX];
  111. char *def_file;
  112. struct Plus_head *plus;
  113. struct Format_info_pg *pg_info;
  114. struct P_line *Line;
  115. struct P_area *Area;
  116. struct P_topo_b *topo_b;
  117. struct P_isle *Isle;
  118. plus = &(Map->plus);
  119. pg_info = &(Map->fInfo.pg);
  120. /* check if upgrade or downgrade */
  121. if (build < plus->built) {
  122. /* -> downgrade */
  123. Vect__build_downgrade(Map, build);
  124. return 1;
  125. }
  126. /* -> upgrade */
  127. if (build < GV_BUILD_BASE)
  128. return 1; /* nothing to print */
  129. /* cache features to speed-up random access (when attaching isles
  130. to areas) */
  131. if (build >= GV_BUILD_BASE) {
  132. /* clean-up GRASS topology tables in DB */
  133. if (!pg_info->topo_geo_only)
  134. Vect__clean_grass_db_topo(&(Map->fInfo.pg));
  135. if (Map->mode == GV_MODE_RW &&
  136. pg_info->cache.lines_num > 0) {
  137. /* read line cache from scratch when map is open in update
  138. * mode, before building native topology read nodes from
  139. * PostGIS Topology */
  140. /* clean-up spatial a category indices */
  141. dig_free_plus(&(Map->plus));
  142. dig_init_plus(&(Map->plus));
  143. plus->Spidx_new = TRUE;
  144. plus->update_cidx = TRUE;
  145. /* reset cache for reading features */
  146. Vect__free_cache(&(pg_info->cache));
  147. }
  148. }
  149. if (plus->built >= GV_BUILD_BASE &&
  150. pg_info->cache.lines_num < 1) {
  151. /* features are not cached, build from scratch */
  152. Vect_build_partial(Map, GV_BUILD_NONE);
  153. }
  154. if (plus->built < GV_BUILD_BASE) {
  155. /* force loading nodes from DB to get up-to-date node
  156. * offsets, see write_nodes() for details */
  157. Vect__free_offset(&(pg_info->offset));
  158. pg_info->cache.ctype = CACHE_FEATURE; /* do not cache nodes */
  159. n_nodes = Map->plus.n_nodes = Vect__load_map_nodes_pg(Map, TRUE);
  160. Vect__free_cache(&(pg_info->cache));
  161. }
  162. if (build > GV_BUILD_BASE)
  163. pg_info->cache.ctype = CACHE_MAP; /* cache all features */
  164. /* update TopoGeometry based on GRASS-like topology */
  165. Vect_build_nat(Map, build);
  166. if (n_nodes != Map->plus.n_nodes)
  167. G_warning(_("Inconsistency in topology: number of nodes %d (should be %d)"),
  168. Map->plus.n_nodes, n_nodes);
  169. /* store map boundig box in DB */
  170. save_map_bbox(pg_info, &(plus->box));
  171. /* begin transaction */
  172. if (Vect__execute_pg(pg_info->conn, "BEGIN"))
  173. return 0;
  174. Vect__execute_pg(pg_info->conn, "SET CONSTRAINTS ALL DEFERRED");
  175. /* write full node topo info to DB if requested */
  176. if (!pg_info->topo_geo_only) {
  177. write_nodes(plus, pg_info);
  178. write_lines(plus, pg_info);
  179. }
  180. /* update faces from GRASS Topology */
  181. if (build >= GV_BUILD_AREAS) {
  182. /* do clean up (1-3)
  183. insert new faces (4)
  184. update edges (5)
  185. */
  186. G_message(_("Cleaning-up topology schema..."));
  187. /* 1) reset centroids to '0' (universal face) */
  188. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = 0 WHERE "
  189. "containing_face IS NOT NULL", pg_info->toposchema_name);
  190. G_debug(2, "SQL: %s", stmt);
  191. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  192. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  193. return 0;
  194. }
  195. /* 2) reset left|right edges */
  196. sprintf(stmt, "UPDATE \"%s\".edge_data SET left_face = 0, right_face = 0",
  197. pg_info->toposchema_name);
  198. G_debug(2, "SQL: %s", stmt);
  199. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  200. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  201. return 0;
  202. }
  203. /* 3) delete faces (areas/isles) */
  204. sprintf(stmt, "DELETE FROM \"%s\".face WHERE "
  205. "face_id != 0", pg_info->toposchema_name);
  206. G_debug(2, "SQL: %s", stmt);
  207. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  208. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  209. return 0;
  210. }
  211. if (!pg_info->topo_geo_only) {
  212. sprintf(stmt, "DELETE FROM \"%s\".%s", pg_info->toposchema_name, TOPO_TABLE_AREA);
  213. G_debug(2, "SQL: %s", stmt);
  214. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  215. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  216. return 0;
  217. }
  218. sprintf(stmt, "DELETE FROM \"%s\".%s", pg_info->toposchema_name, TOPO_TABLE_ISLE);
  219. G_debug(2, "SQL: %s", stmt);
  220. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  221. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  222. return 0;
  223. }
  224. }
  225. /* 4) insert faces & update nodes (containing_face) based on
  226. * GRASS topology */
  227. G_message(_("Updating faces..."));
  228. nareas = Vect_get_num_areas(Map);
  229. for (area = 1; area <= nareas; area++) {
  230. G_percent(area, nareas, 5);
  231. if (0 == Vect__insert_face_pg(Map, area)) {
  232. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  233. return 0;
  234. }
  235. if (build < GV_BUILD_CENTROIDS)
  236. continue;
  237. /* update centroids (node -> containing_face) */
  238. Area = plus->Area[area];
  239. if (Area->centroid < 1) {
  240. G_debug(3, "Area %d without centroid, skipped", area);
  241. continue;
  242. }
  243. Line = plus->Line[Area->centroid];
  244. sprintf(stmt, "UPDATE \"%s\".node SET "
  245. "containing_face = %d WHERE node_id = %d",
  246. pg_info->toposchema_name, area, (int)Line->offset);
  247. G_debug(2, "SQL: %s", stmt);
  248. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  249. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  250. return 0;
  251. }
  252. }
  253. /* 5) update edges (left and right face) */
  254. G_message(_("Updating edges..."));
  255. for (line = 1; line <= plus->n_lines; line++) {
  256. G_percent(line, plus->n_lines, 5);
  257. type = Vect_read_line(Map, NULL, NULL, line);
  258. if (type != GV_BOUNDARY)
  259. continue;
  260. Line = Map->plus.Line[line];
  261. if (!Line) {
  262. G_warning(_("Inconsistency in topology detected. "
  263. "Dead line found."));
  264. return 0;
  265. }
  266. topo_b = (struct P_topo_b *) Line->topo;
  267. for (s = 0; s < 2; s++) { /* for both sides */
  268. face[s] = s == 0 ? topo_b->left : topo_b->right;
  269. if (face[s] < 0) {
  270. /* isle */
  271. Isle = plus->Isle[abs(face[s])];
  272. face[s] = Isle->area;
  273. }
  274. }
  275. G_debug(3, "update edge %d: left_face = %d, right_face = %d",
  276. (int)Line->offset, face[0], face[1]);
  277. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  278. "left_face = %d, right_face = %d "
  279. "WHERE edge_id = %d", pg_info->toposchema_name,
  280. face[0], face[1], (int) Line->offset);
  281. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  282. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  283. return 0;
  284. }
  285. }
  286. /* write full area topo info to DB if requested */
  287. if (!pg_info->topo_geo_only) {
  288. write_areas(plus, pg_info);
  289. }
  290. } /* build >= GV_BUILD_AREAS */
  291. if (build >= GV_BUILD_ATTACH_ISLES) {
  292. /* insert isles as faces with negative face_id */
  293. nisles = Vect_get_num_islands(Map);
  294. for(isle = 1; isle <= nisles; isle++) {
  295. Isle = plus->Isle[isle];
  296. Vect__insert_face_pg(Map, -isle);
  297. }
  298. /* write full isles topo info to DB if requested */
  299. if (!pg_info->topo_geo_only) {
  300. write_isles(plus, pg_info);
  301. }
  302. } /* build >= GV_BUILD_ISLES */
  303. if (pg_info->feature_type == SF_POLYGON) {
  304. int centroid;
  305. struct P_line *Line;
  306. G_message(_("Updating TopoGeometry data..."));
  307. for (area = 1; area <= plus->n_areas; area++) {
  308. G_percent(area, plus->n_areas, 5);
  309. centroid = Vect_get_area_centroid(Map, area);
  310. if (centroid < 1)
  311. continue;
  312. Line = plus->Line[centroid];
  313. if (!Line)
  314. continue;
  315. /* update topogeometry object: centroid -> face */
  316. if (build_topogeom_stmt(pg_info, GV_CENTROID, area, (int) Line->offset, stmt) &&
  317. Vect__execute_pg(pg_info->conn, stmt) == -1) {
  318. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  319. return 0;
  320. }
  321. }
  322. }
  323. if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1)
  324. return 0;
  325. /* check if we want to create simple features from topogeometry
  326. data */
  327. def_file = getenv("GRASS_VECTOR_PGFILE");
  328. if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
  329. FILE *fp;
  330. const char *p;
  331. struct Key_Value *key_val;
  332. fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
  333. if (!fp) {
  334. G_fatal_error(_("Unable to open PG file"));
  335. }
  336. key_val = G_fread_key_value(fp);
  337. fclose(fp);
  338. /* build simple features from topogeometry data */
  339. p = G_find_key_value("simple_feature", key_val);
  340. if (p && G_strcasecmp(p, "yes") == 0) {
  341. if (build > GV_BUILD_BASE)
  342. Map->level = LEVEL_2; /* force level to avoid errors */
  343. if (create_simple_feature_from_topo(Map) != 0)
  344. return 0;
  345. }
  346. G_free_key_value(key_val);
  347. }
  348. return 1;
  349. }
  350. /*!
  351. \brief Build UPDATE statement for topo geometry element stored in
  352. feature table
  353. \param pg_info so pointer to Format_info_pg
  354. \param type feature type (GV_POINT, ...)
  355. \param topo_id topology element id
  356. \param fid feature id
  357. \param[out] stmt string buffer
  358. \return 1 on success
  359. \return 0 on failure
  360. */
  361. int build_topogeom_stmt(const struct Format_info_pg *pg_info,
  362. int type, int topo_id, int fid, char *stmt)
  363. {
  364. int topogeom_type;
  365. switch(type) {
  366. case GV_POINT:
  367. topogeom_type = 1;
  368. break;
  369. case GV_LINE:
  370. case GV_BOUNDARY:
  371. topogeom_type = 2;
  372. break;
  373. case GV_CENTROID:
  374. topogeom_type = 3;
  375. break;
  376. default:
  377. G_warning(_("Unsupported topo geometry type %d"), type);
  378. return 0;
  379. }
  380. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  381. "'(%d, 1, %d, %d)'::topology.TopoGeometry "
  382. "WHERE (%s).id = %d",
  383. pg_info->schema_name, pg_info->table_name,
  384. pg_info->topogeom_column, pg_info->toposchema_id,
  385. topo_id, topogeom_type, pg_info->topogeom_column, fid);
  386. return 1;
  387. }
  388. /*!
  389. \brief Store map bounding box in DB head table
  390. \param pg_info pointer to Format_info_pg struct
  391. \param box pointer to bounding box
  392. \return 1 on success
  393. \return 0 on failure
  394. */
  395. int save_map_bbox(const struct Format_info_pg *pg_info, const struct bound_box *box)
  396. {
  397. char stmt[DB_SQL_MAX];
  398. /* create if not exists */
  399. if (create_topo_grass(pg_info) == -1) {
  400. G_warning(_("Unable to create <%s.%s>"), TOPO_SCHEMA, TOPO_TABLE);
  401. return 0;
  402. }
  403. /* update bbox */
  404. if (has_topo_grass(pg_info)) {
  405. /* -> update */
  406. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  407. "'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d WHERE %s = %d",
  408. TOPO_SCHEMA, TOPO_TABLE, TOPO_BBOX,
  409. box->W, box->S, box->B, box->E, box->N, box->T,
  410. TOPO_ID, pg_info->toposchema_id);
  411. }
  412. else {
  413. /* -> insert */
  414. sprintf(stmt, "INSERT INTO \"%s\".\"%s\" (%s, %s) "
  415. "VALUES(%d, 'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d)",
  416. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX, pg_info->toposchema_id,
  417. box->W, box->S, box->B, box->E, box->N, box->T);
  418. }
  419. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  420. return -1;
  421. }
  422. return 1;
  423. }
  424. /*!
  425. \brief Creates 'topology.grass' table if not exists
  426. \return 0 table already exists
  427. \return 1 table successfully added
  428. \return -1 on error
  429. */
  430. int create_topo_grass(const struct Format_info_pg *pg_info)
  431. {
  432. char stmt[DB_SQL_MAX];
  433. PGresult *result;
  434. /* check if table exists */
  435. sprintf(stmt, "SELECT COUNT(*) FROM information_schema.tables "
  436. "WHERE table_schema = '%s' AND table_name = '%s'",
  437. TOPO_SCHEMA, TOPO_TABLE);
  438. result = PQexec(pg_info->conn, stmt);
  439. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  440. PQclear(result);
  441. return -1;
  442. }
  443. if (atoi(PQgetvalue(result, 0, 0)) == 1) {
  444. /* table already exists */
  445. PQclear(result);
  446. return 1;
  447. }
  448. PQclear(result);
  449. G_debug(1, "<%s.%s> created", TOPO_SCHEMA, TOPO_TABLE);
  450. /* create table */
  451. sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s INTEGER, %s box3d)",
  452. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX);
  453. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  454. return -1;
  455. }
  456. /* add primary key */
  457. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD PRIMARY KEY (%s)",
  458. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID);
  459. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  460. return -1;
  461. }
  462. /* add constraint */
  463. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD CONSTRAINT \"%s_%s_fkey\" "
  464. "FOREIGN KEY (%s) REFERENCES topology.topology(id) ON DELETE CASCADE",
  465. TOPO_SCHEMA, TOPO_TABLE, TOPO_TABLE, TOPO_ID, TOPO_ID);
  466. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  467. return -1;
  468. }
  469. return 1;
  470. }
  471. /*!
  472. \brief Check if 'topology_id' exists in 'topology.grass'
  473. \param pg_info pointer to Format_info_pg struct
  474. \return TRUE if exists
  475. \return FALSE otherwise
  476. \return -1 on error
  477. */
  478. int has_topo_grass(const struct Format_info_pg *pg_info)
  479. {
  480. int has_topo;
  481. char stmt[DB_SQL_MAX];
  482. PGresult *result;
  483. sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".\"%s\" "
  484. "WHERE %s = %d",
  485. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, pg_info->toposchema_id);
  486. result = PQexec(pg_info->conn, stmt);
  487. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  488. PQclear(result);
  489. return -1;
  490. }
  491. has_topo = FALSE;
  492. if (atoi(PQgetvalue(result, 0, 0)) == 1) {
  493. /* table already exists */
  494. has_topo = TRUE;
  495. }
  496. PQclear(result);
  497. return has_topo;
  498. }
  499. /*!
  500. \brief Insert node into 'node_grass' table
  501. Writes (see P_node struct):
  502. - lines
  503. - angles
  504. Already stored in Topo-Geo:
  505. - x,y,z (geom)
  506. \param plus pointer to Plus_head struct
  507. \param pg_info pointer to Format_info_pg struct
  508. \return 0 on success
  509. \return -1 on error
  510. */
  511. int write_nodes(const struct Plus_head *plus,
  512. const struct Format_info_pg *pg_info)
  513. {
  514. int i, node_id;
  515. size_t stmt_lines_size, stmt_angles_size, stmt_size;
  516. char *stmt_lines, *stmt_angles, *stmt;
  517. const struct P_node *Node;
  518. const struct Format_info_offset *offset;
  519. offset = &(pg_info->offset);
  520. if (offset->array_num < 1) /* nothing to write */
  521. return 0;
  522. if (plus->n_nodes != offset->array_num) {
  523. G_warning(_("Unable to write nodes, offset array mismatch"));
  524. return -1;
  525. }
  526. stmt_size = 2 * DB_SQL_MAX + 512;
  527. stmt = (char *) G_malloc(stmt_size);
  528. stmt_lines = stmt_angles = NULL;
  529. for (i = 1; i <= plus->n_nodes; i++) {
  530. Node = plus->Node[i];
  531. if (!Node)
  532. continue; /* should not happen */
  533. node_id = offset->array[i-1];
  534. /* 'lines' array */
  535. build_stmt_id(Node->lines, Node->n_lines, TRUE, plus, &stmt_lines, &stmt_lines_size);
  536. /* 'angle' array */
  537. build_stmt_id(Node->angles, Node->n_lines, FALSE, NULL, &stmt_angles, &stmt_angles_size);
  538. /* build SQL statement to add new node into 'node_grass' */
  539. if (stmt_lines_size + stmt_angles_size + 512 > stmt_size) {
  540. stmt_size = stmt_lines_size + stmt_angles_size + 512;
  541. stmt = (char *) G_realloc(stmt, stmt_size);
  542. }
  543. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  544. "%d, '{%s}', '{%s}')", pg_info->toposchema_name, TOPO_TABLE_NODE,
  545. node_id, stmt_lines, stmt_angles);
  546. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  547. G_warning(_("Unable to write nodes"));
  548. return -1;
  549. }
  550. }
  551. G_free(stmt_lines);
  552. G_free(stmt_angles);
  553. G_free(stmt);
  554. return 0;
  555. }
  556. /*!
  557. \brief Insert lines into 'line_grass' table
  558. Writes (see P_line struct) - only for boundaries:
  559. - left, right area
  560. Already stored in Topo-Geo:
  561. - edge_id, left_face, right_face
  562. \param plus pointer to Plus_head struct
  563. \param pg_info pointer to Format_info_pg struct
  564. \return 0 on success
  565. \return -1 on error
  566. */
  567. int write_lines(const struct Plus_head *plus,
  568. const struct Format_info_pg *pg_info)
  569. {
  570. int i, row, offset;
  571. char stmt[DB_SQL_MAX];
  572. const struct P_line *Line;
  573. const struct P_topo_b *topo;
  574. PGresult *res;
  575. sprintf(stmt, "SELECT edge_id FROM \"%s\".edge_data WHERE "
  576. "left_face != 0 OR right_face != 0 ORDER BY edge_id",
  577. pg_info->toposchema_name);
  578. G_debug(2, "SQL: %s", stmt);
  579. res = PQexec(pg_info->conn, stmt);
  580. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  581. (PQntuples(res) > 0 && PQntuples(res) != plus->n_blines)) {
  582. G_warning(_("Inconsistency in topology: number of "
  583. "boundaries %d (should be %d)"),
  584. PQntuples(res), plus->n_blines);
  585. if (res)
  586. PQclear(res);
  587. return -1;
  588. }
  589. for (row = 0, i = 1; i <= plus->n_lines; i++) {
  590. Line = plus->Line[i];
  591. if (!Line || Line->type != GV_BOUNDARY)
  592. continue;
  593. if (Line->offset == 0L)
  594. offset = atoi(PQgetvalue(res, row++, 0));
  595. else
  596. offset = (int)Line->offset;
  597. topo = (struct P_topo_b *)Line->topo;
  598. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  599. "%d, %d, %d)", pg_info->toposchema_name, TOPO_TABLE_LINE,
  600. offset, topo->left, topo->right);
  601. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  602. G_warning(_("Unable to write lines"));
  603. return -1;
  604. }
  605. }
  606. return 0;
  607. }
  608. /*!
  609. \brief Insert area into 'area_grass' table
  610. Writes (see P_area struct):
  611. - lines
  612. - centroid
  613. - isles
  614. \param plus pointer to Plus_head struct
  615. \param pg_info pointer to Format_info_pg struct
  616. \return 0 on success
  617. \return -1 on error
  618. */
  619. int write_areas(const struct Plus_head *plus,
  620. const struct Format_info_pg *pg_info)
  621. {
  622. int area, centroid;
  623. size_t stmt_lines_size, stmt_isles_size, stmt_size;
  624. char *stmt_lines, *stmt_isles, *stmt;
  625. const struct P_line *Line;
  626. const struct P_area *Area;
  627. stmt_size = 2 * DB_SQL_MAX + 512;
  628. stmt = (char *) G_malloc(stmt_size);
  629. stmt_lines = stmt_isles = NULL;
  630. for (area = 1; area <= plus->n_areas; area++) {
  631. Area = plus->Area[area];
  632. if (!Area) {
  633. G_debug(3, "Area %d skipped (dead)", area);
  634. continue; /* should not happen */
  635. }
  636. /* 'lines' array */
  637. build_stmt_id(Area->lines, Area->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
  638. /* 'isles' array */
  639. build_stmt_id(Area->isles, Area->n_isles, TRUE, NULL, &stmt_isles, &stmt_isles_size);
  640. if (Area->centroid != 0) {
  641. Line = plus->Line[Area->centroid];
  642. if (!Line) {
  643. G_warning(_("Topology for centroid %d not available. Area %d skipped"),
  644. Area->centroid, area);
  645. continue;
  646. }
  647. centroid = (int) Line->offset;
  648. }
  649. else {
  650. centroid = 0;
  651. }
  652. /* build SQL statement to add new node into 'node_grass' */
  653. if (stmt_lines_size + stmt_isles_size + 512 > stmt_size) {
  654. stmt_size = stmt_lines_size + stmt_isles_size + 512;
  655. stmt = (char *) G_realloc(stmt, stmt_size);
  656. }
  657. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  658. "%d, '{%s}', %d, '{%s}')", pg_info->toposchema_name, TOPO_TABLE_AREA,
  659. area, stmt_lines, centroid, stmt_isles);
  660. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  661. return -1;
  662. }
  663. }
  664. G_free(stmt_lines);
  665. G_free(stmt_isles);
  666. G_free(stmt);
  667. return 0;
  668. }
  669. /*!
  670. \brief Insert isle into 'isle_grass' table
  671. Writes (see P_isle struct):
  672. - lines
  673. - area
  674. \param plus pointer to Plus_head struct
  675. \param pg_info pointer to Format_info_pg struct
  676. \return 0 on success
  677. \return -1 on error
  678. */
  679. int write_isles(const struct Plus_head *plus,
  680. const struct Format_info_pg *pg_info)
  681. {
  682. int isle;
  683. size_t stmt_lines_size, stmt_size;
  684. char *stmt_lines, *stmt;
  685. const struct P_isle *Isle;
  686. stmt_size = DB_SQL_MAX + 512;
  687. stmt = (char *) G_malloc(stmt_size);
  688. stmt_lines = NULL;
  689. for (isle = 1; isle <= plus->n_isles; isle++) {
  690. Isle = plus->Isle[isle];
  691. if (!Isle)
  692. continue; /* should not happen */
  693. /* 'lines' array */
  694. build_stmt_id(Isle->lines, Isle->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
  695. /* build SQL statement to add new node into 'node_grass' */
  696. if (stmt_lines_size + 512 > stmt_size) {
  697. stmt_size = stmt_lines_size + 512;
  698. stmt = (char *) G_realloc(stmt, stmt_size);
  699. }
  700. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  701. "%d, '{%s}', %d)", pg_info->toposchema_name, TOPO_TABLE_ISLE,
  702. isle, stmt_lines, Isle->area);
  703. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  704. return -1;
  705. }
  706. }
  707. G_free(stmt_lines);
  708. G_free(stmt);
  709. return 0;
  710. }
  711. /*!
  712. \brief Create PG-like array for int/float array
  713. \param array array of items
  714. \param nitems number of items in the array
  715. \param is_int TRUE for array of integers otherwise floats
  716. \param plus pointer to Plus_head struct
  717. \param[in,out] output buffer (re-used)
  718. \param[in,out] buffer size
  719. */
  720. void build_stmt_id(const void *array, int nitems, int is_int, const struct Plus_head *plus,
  721. char **stmt, size_t *stmt_size)
  722. {
  723. int i, ivalue;
  724. int *iarray;
  725. float *farray;
  726. size_t stmt_id_size;
  727. char *stmt_id, buf_id[128];
  728. struct P_line *Line;
  729. if (is_int)
  730. iarray = (int *) array;
  731. else
  732. farray = (float *) array;
  733. if (!(*stmt)) {
  734. stmt_id_size = DB_SQL_MAX;
  735. stmt_id = (char *) G_malloc(stmt_id_size);
  736. }
  737. else {
  738. stmt_id_size = *stmt_size;
  739. stmt_id = *stmt;
  740. }
  741. /* reset array */
  742. stmt_id[0] = '\0';
  743. for (i = 0; i < nitems; i++) {
  744. /* realloc array if needed */
  745. if (strlen(stmt_id) + 100 > stmt_id_size) {
  746. stmt_id_size = strlen(stmt_id) + DB_SQL_MAX;
  747. stmt_id = (char *) G_realloc(stmt_id, stmt_id_size);
  748. }
  749. if (is_int) {
  750. if (plus) {
  751. Line = plus->Line[abs(iarray[i])];
  752. ivalue = (int) Line->offset;
  753. if (iarray[i] < 0)
  754. ivalue *= -1;
  755. }
  756. else {
  757. ivalue = iarray[i];
  758. }
  759. sprintf(buf_id, "%d", ivalue);
  760. }
  761. else {
  762. sprintf(buf_id, "%f", farray[i]);
  763. }
  764. if (i > 0)
  765. strcat(stmt_id, ",");
  766. strcat(stmt_id, buf_id);
  767. }
  768. *stmt = stmt_id;
  769. *stmt_size = stmt_id_size;
  770. }
  771. /*!
  772. \brief Clean-up GRASS Topology tables
  773. \param pg_info pointer to Format_info_pg pg_info
  774. \return 0 on success
  775. \return -1 on error
  776. */
  777. int Vect__clean_grass_db_topo(struct Format_info_pg *pg_info)
  778. {
  779. char stmt[DB_SQL_MAX];
  780. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  781. pg_info->toposchema_name, TOPO_TABLE_NODE);
  782. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  783. return -1;
  784. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  785. pg_info->toposchema_name, TOPO_TABLE_LINE);
  786. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  787. return -1;
  788. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  789. pg_info->toposchema_name, TOPO_TABLE_AREA);
  790. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  791. return -1;
  792. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  793. pg_info->toposchema_name, TOPO_TABLE_ISLE);
  794. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  795. return -1;
  796. return 0;
  797. }
  798. /*!
  799. \brief Create simple features geometry from topogeometry data
  800. \param Map pointer to Map_info struct
  801. \return 0 on success
  802. \return -1 on error
  803. */
  804. int create_simple_feature_from_topo(struct Map_info *Map)
  805. {
  806. char stmt[DB_SQL_MAX];
  807. struct Format_info_pg *pg_info;
  808. pg_info = &(Map->fInfo.pg);
  809. G_debug(1, "build_simple_feature_from_topo(): %d", pg_info->feature_type);
  810. G_message(_("Create simple features topology from topogeometry data..."));
  811. Vect__execute_pg(pg_info->conn, "BEGIN");
  812. if (pg_info->feature_type == SF_POINT ||
  813. pg_info->feature_type == SF_LINESTRING) {
  814. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = (SELECT geom FROM \"%s\".node "
  815. "WHERE node_id = (%s).id)", pg_info->schema_name, pg_info->table_name,
  816. pg_info->geom_column, pg_info->toposchema_name, pg_info->topogeom_column);
  817. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  818. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  819. return -1;
  820. }
  821. }
  822. else if (pg_info->feature_type == SF_POLYGON) {
  823. Vect__copy_areas(Map, 1, Map);
  824. }
  825. else {
  826. G_warning(_("Unable to build simple features from topogeometry data. "
  827. "Unsupported type %d."), pg_info->feature_type);
  828. }
  829. Vect__execute_pg(pg_info->conn, "COMMIT");
  830. return 0;
  831. }
  832. #endif