build_pg.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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_areas(const struct Plus_head *, const struct Format_info_pg *);
  25. static int write_isles(const struct Plus_head *, const struct Format_info_pg *);
  26. static void build_stmt_id(const void *, int, int, const struct Plus_head *, char **, size_t *);
  27. #endif
  28. /*!
  29. \brief Build topology for PostGIS layer
  30. Build levels:
  31. - GV_BUILD_NONE
  32. - GV_BUILD_BASE
  33. - GV_BUILD_ATTACH_ISLES
  34. - GV_BUILD_CENTROIDS
  35. - GV_BUILD_ALL
  36. \param Map pointer to Map_info structure
  37. \param build build level
  38. \return 1 on success
  39. \return 0 on error
  40. */
  41. int Vect_build_pg(struct Map_info *Map, int build)
  42. {
  43. #ifdef HAVE_POSTGRES
  44. struct Plus_head *plus;
  45. struct Format_info_pg *pg_info;
  46. plus = &(Map->plus);
  47. pg_info = &(Map->fInfo.pg);
  48. G_debug(1, "Vect_build_pg(): db='%s' table='%s', build=%d",
  49. pg_info->db_name, pg_info->table_name, build);
  50. /* commit transaction block (update mode only) */
  51. if (pg_info->inTransaction && Vect__execute_pg(pg_info->conn, "COMMIT") == -1)
  52. return 0;
  53. pg_info->inTransaction = FALSE;
  54. if (pg_info->feature_type == SF_UNKNOWN)
  55. return 1;
  56. if (build == plus->built)
  57. return 1; /* do nothing */
  58. /* TODO move this init to better place (Vect_open_ ?), because in
  59. theory build may be reused on level2 */
  60. if (!pg_info->toposchema_name && build >= plus->built && build > GV_BUILD_BASE) {
  61. G_free(pg_info->offset.array);
  62. G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
  63. }
  64. if (!pg_info->conn) {
  65. G_warning(_("No DB connection"));
  66. return 0;
  67. }
  68. if (!pg_info->fid_column && !pg_info->toposchema_name) {
  69. G_warning(_("Feature table <%s> has no primary key defined"),
  70. pg_info->table_name);
  71. G_warning(_("Random read is not supported for this layer. "
  72. "Unable to build topology."));
  73. return 0;
  74. }
  75. if (build > GV_BUILD_NONE) {
  76. G_message(_("Using external data format '%s' (feature type '%s')"),
  77. Vect_get_finfo_format_info(Map),
  78. Vect_get_finfo_geometry_type(Map));
  79. if (!pg_info->toposchema_name)
  80. G_message(_("Building pseudo-topology over simple features..."));
  81. else
  82. G_message(_("Building topology from PostGIS topology schema <%s>..."),
  83. pg_info->toposchema_name);
  84. }
  85. if (!pg_info->toposchema_name) /* pseudo-topology for simple features */
  86. return Vect__build_sfa(Map, build);
  87. /* PostGIS Topology */
  88. return build_topo(Map, build);
  89. #else
  90. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  91. return 0;
  92. #endif
  93. }
  94. #ifdef HAVE_POSTGRES
  95. /*!
  96. \brief Build from PostGIS topology schema
  97. \todo Attach isles
  98. \param Map pointer to Map_info struct
  99. \param build build level
  100. \return 1 on success
  101. \return 0 on error
  102. */
  103. int build_topo(struct Map_info *Map, int build)
  104. {
  105. int line, type, s;
  106. int area, nareas, isle, nisles;
  107. int face[2];
  108. char stmt[DB_SQL_MAX];
  109. struct Plus_head *plus;
  110. struct Format_info_pg *pg_info;
  111. struct P_line *Line;
  112. struct P_area *Area;
  113. struct P_topo_b *topo_b;
  114. struct P_isle *Isle;
  115. plus = &(Map->plus);
  116. pg_info = &(Map->fInfo.pg);
  117. /* check if upgrade or downgrade */
  118. if (build < plus->built) {
  119. /* -> downgrade */
  120. Vect__build_downgrade(Map, build);
  121. return 1;
  122. }
  123. /* -> upgrade */
  124. if (build < GV_BUILD_BASE)
  125. return 1; /* nothing to print */
  126. /* cache features to speed-up random access (when attaching isles
  127. to areas) */
  128. if (build >= GV_BUILD_BASE)
  129. pg_info->cache.ctype = CACHE_MAP;
  130. /* update TopoGeometry based on GRASS-like topology */
  131. Vect_build_nat(Map, build);
  132. /* store map boundig box in DB */
  133. save_map_bbox(pg_info, &(plus->box));
  134. /* begin transaction */
  135. if (Vect__execute_pg(pg_info->conn, "BEGIN"))
  136. return 0;
  137. /* write full node topo info to DB if requested */
  138. if (!pg_info->topo_geo_only) {
  139. write_nodes(plus, pg_info);
  140. }
  141. /* update faces from GRASS Topology */
  142. if (build >= GV_BUILD_AREAS) {
  143. /* do clean up (1-3)
  144. insert new faces (4)
  145. update edges (5)
  146. */
  147. G_message(_("Cleaning-up topology schema..."));
  148. /* 1) reset centroids to '0' (universal face) */
  149. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = 0 WHERE "
  150. "containing_face IS NOT NULL", pg_info->toposchema_name);
  151. G_debug(2, "SQL: %s", stmt);
  152. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  153. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  154. return 0;
  155. }
  156. /* 2) reset left|right edges */
  157. sprintf(stmt, "UPDATE \"%s\".edge_data SET left_face = 0, right_face = 0",
  158. pg_info->toposchema_name);
  159. G_debug(2, "SQL: %s", stmt);
  160. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  161. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  162. return 0;
  163. }
  164. /* 3) delete faces (areas/isles) */
  165. sprintf(stmt, "DELETE FROM \"%s\".face WHERE "
  166. "face_id != 0", pg_info->toposchema_name);
  167. G_debug(2, "SQL: %s", stmt);
  168. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  169. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  170. return 0;
  171. }
  172. if (!pg_info->topo_geo_only) {
  173. sprintf(stmt, "DELETE FROM \"%s\".%s", pg_info->toposchema_name, TOPO_TABLE_AREA);
  174. G_debug(2, "SQL: %s", stmt);
  175. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  176. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  177. return 0;
  178. }
  179. sprintf(stmt, "DELETE FROM \"%s\".%s", pg_info->toposchema_name, TOPO_TABLE_ISLE);
  180. G_debug(2, "SQL: %s", stmt);
  181. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  182. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  183. return 0;
  184. }
  185. }
  186. /* 4) insert faces & update nodes (containing_face) based on
  187. * GRASS topology */
  188. G_message(_("Updating faces..."));
  189. nareas = Vect_get_num_areas(Map);
  190. for (area = 1; area <= nareas; area++) {
  191. G_percent(area, nareas, 5);
  192. if (0 == Vect__insert_face_pg(Map, area)) {
  193. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  194. return 0;
  195. }
  196. if (build < GV_BUILD_CENTROIDS)
  197. continue;
  198. /* update centroids (node -> containing_face) */
  199. Area = plus->Area[area];
  200. if (Area->centroid < 1) {
  201. G_debug(3, "Area %d without centroid, skipped", area);
  202. continue;
  203. }
  204. Line = plus->Line[Area->centroid];
  205. sprintf(stmt, "UPDATE \"%s\".node SET "
  206. "containing_face = %d WHERE node_id = %d",
  207. pg_info->toposchema_name, area, (int)Line->offset);
  208. G_debug(2, "SQL: %s", stmt);
  209. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  210. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  211. return 0;
  212. }
  213. }
  214. /* 5) update edges (left and right face) */
  215. G_message(_("Updating edges..."));
  216. for (line = 1; line <= plus->n_lines; line++) {
  217. G_percent(line, plus->n_lines, 5);
  218. type = Vect_read_line(Map, NULL, NULL, line);
  219. if (type != GV_BOUNDARY)
  220. continue;
  221. Line = Map->plus.Line[line];
  222. if (!Line) {
  223. G_warning(_("Inconsistency in topology detected. "
  224. "Dead line found."));
  225. return 0;
  226. }
  227. topo_b = (struct P_topo_b *) Line->topo;
  228. for (s = 0; s < 2; s++) { /* for both sides */
  229. face[s] = s == 0 ? topo_b->left : topo_b->right;
  230. if (face[s] < 0) {
  231. /* isle */
  232. Isle = plus->Isle[abs(face[s])];
  233. face[s] = Isle->area;
  234. }
  235. }
  236. G_debug(3, "update edge %d: left_face = %d, right_face = %d",
  237. (int)Line->offset, face[0], face[1]);
  238. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  239. "left_face = %d, right_face = %d "
  240. "WHERE edge_id = %d", pg_info->toposchema_name,
  241. face[0], face[1], (int) Line->offset);
  242. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  243. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  244. return 0;
  245. }
  246. }
  247. /* write full area topo info to DB if requested */
  248. if (!pg_info->topo_geo_only) {
  249. write_areas(plus, pg_info);
  250. }
  251. } /* build >= GV_BUILD_AREAS */
  252. if (build >= GV_BUILD_ATTACH_ISLES) {
  253. /* insert isles as faces with negative face_id */
  254. nisles = Vect_get_num_islands(Map);
  255. for(isle = 1; isle <= nisles; isle++) {
  256. Isle = plus->Isle[isle];
  257. Vect__insert_face_pg(Map, -isle);
  258. }
  259. /* write full isles topo info to DB if requested */
  260. if (!pg_info->topo_geo_only) {
  261. write_isles(plus, pg_info);
  262. }
  263. } /* build >= GV_BUILD_ISLES */
  264. if (pg_info->feature_type == SF_POLYGON) {
  265. int centroid;
  266. struct P_line *Line;
  267. G_message(_("Updating TopoGeometry data..."));
  268. for (area = 1; area <= plus->n_areas; area++) {
  269. G_percent(area, plus->n_areas, 5);
  270. centroid = Vect_get_area_centroid(Map, area);
  271. if (centroid < 1)
  272. continue;
  273. Line = plus->Line[centroid];
  274. if (!Line)
  275. continue;
  276. /* update topogeometry object: centroid -> face */
  277. if (build_topogeom_stmt(pg_info, GV_CENTROID, area, (int) Line->offset, stmt) &&
  278. Vect__execute_pg(pg_info->conn, stmt) == -1) {
  279. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  280. return 0;
  281. }
  282. }
  283. }
  284. if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1)
  285. return 0;
  286. return 1;
  287. }
  288. /*!
  289. \brief Build UPDATE statement for topo geometry element stored in
  290. feature table
  291. \param pg_info so pointer to Format_info_pg
  292. \param type feature type (GV_POINT, ...)
  293. \param topo_id topology element id
  294. \param fid feature id
  295. \param[out] stmt string buffer
  296. \return 1 on success
  297. \return 0 on failure
  298. */
  299. int build_topogeom_stmt(const struct Format_info_pg *pg_info,
  300. int type, int topo_id, int fid, char *stmt)
  301. {
  302. int topogeom_type;
  303. switch(type) {
  304. case GV_POINT:
  305. topogeom_type = 1;
  306. break;
  307. case GV_LINE:
  308. case GV_BOUNDARY:
  309. topogeom_type = 2;
  310. break;
  311. case GV_CENTROID:
  312. topogeom_type = 3;
  313. break;
  314. default:
  315. G_warning(_("Unsupported topo geometry type %d"), type);
  316. return 0;
  317. }
  318. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  319. "'(%d, 1, %d, %d)'::topology.TopoGeometry "
  320. "WHERE (%s).id = %d",
  321. pg_info->schema_name, pg_info->table_name,
  322. pg_info->topogeom_column, pg_info->toposchema_id,
  323. topo_id, topogeom_type, pg_info->topogeom_column, fid);
  324. return 1;
  325. }
  326. /*!
  327. \brief Store map bounding box in DB head table
  328. \param pg_info pointer to Format_info_pg struct
  329. \param box pointer to bounding box
  330. \return 1 on success
  331. \return 0 on failure
  332. */
  333. int save_map_bbox(const struct Format_info_pg *pg_info, const struct bound_box *box)
  334. {
  335. char stmt[DB_SQL_MAX];
  336. /* create if not exists */
  337. if (create_topo_grass(pg_info) == -1) {
  338. G_warning(_("Unable to create <%s.%s>"), TOPO_SCHEMA, TOPO_TABLE);
  339. return 0;
  340. }
  341. /* update bbox */
  342. if (has_topo_grass(pg_info)) {
  343. /* -> update */
  344. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  345. "'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d WHERE %s = %d",
  346. TOPO_SCHEMA, TOPO_TABLE, TOPO_BBOX,
  347. box->W, box->S, box->B, box->E, box->N, box->T,
  348. TOPO_ID, pg_info->toposchema_id);
  349. }
  350. else {
  351. /* -> insert */
  352. sprintf(stmt, "INSERT INTO \"%s\".\"%s\" (%s, %s) "
  353. "VALUES(%d, 'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d)",
  354. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX, pg_info->toposchema_id,
  355. box->W, box->S, box->B, box->E, box->N, box->T);
  356. }
  357. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  358. return -1;
  359. }
  360. return 1;
  361. }
  362. /*!
  363. \brief Creates 'topology.grass' table if not exists
  364. \return 0 table already exists
  365. \return 1 table successfully added
  366. \return -1 on error
  367. */
  368. int create_topo_grass(const struct Format_info_pg *pg_info)
  369. {
  370. char stmt[DB_SQL_MAX];
  371. PGresult *result;
  372. /* check if table exists */
  373. sprintf(stmt, "SELECT COUNT(*) FROM information_schema.tables "
  374. "WHERE table_schema = '%s' AND table_name = '%s'",
  375. TOPO_SCHEMA, TOPO_TABLE);
  376. result = PQexec(pg_info->conn, stmt);
  377. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  378. PQclear(result);
  379. return -1;
  380. }
  381. if (atoi(PQgetvalue(result, 0, 0)) == 1) {
  382. /* table already exists */
  383. PQclear(result);
  384. return 1;
  385. }
  386. PQclear(result);
  387. G_debug(1, "<%s.%s> created", TOPO_SCHEMA, TOPO_TABLE);
  388. /* create table */
  389. sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s INTEGER, %s box3d)",
  390. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX);
  391. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  392. return -1;
  393. }
  394. /* add primary key */
  395. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD PRIMARY KEY (%s)",
  396. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID);
  397. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  398. return -1;
  399. }
  400. /* add constraint */
  401. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD CONSTRAINT \"%s_%s_fkey\" "
  402. "FOREIGN KEY (%s) REFERENCES topology.topology(id) ON DELETE CASCADE",
  403. TOPO_SCHEMA, TOPO_TABLE, TOPO_TABLE, TOPO_ID, TOPO_ID);
  404. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  405. return -1;
  406. }
  407. return 1;
  408. }
  409. /*!
  410. \brief Check if 'topology_id' exists in 'topology.grass'
  411. \param pg_info pointer to Format_info_pg struct
  412. \return TRUE if exists
  413. \return FALSE otherwise
  414. \return -1 on error
  415. */
  416. int has_topo_grass(const struct Format_info_pg *pg_info)
  417. {
  418. int has_topo;
  419. char stmt[DB_SQL_MAX];
  420. PGresult *result;
  421. sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".\"%s\" "
  422. "WHERE %s = %d",
  423. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, pg_info->toposchema_id);
  424. result = PQexec(pg_info->conn, stmt);
  425. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  426. PQclear(result);
  427. return -1;
  428. }
  429. has_topo = FALSE;
  430. if (atoi(PQgetvalue(result, 0, 0)) == 1) {
  431. /* table already exists */
  432. has_topo = TRUE;
  433. }
  434. PQclear(result);
  435. return has_topo;
  436. }
  437. /*!
  438. \brief Insert node into 'node_grass' table
  439. Writes (see P_node struct):
  440. - lines
  441. - angles
  442. Already stored in Topo-Geo:
  443. - x,y,z (geom)
  444. \param plus pointer to Plus_head struct
  445. \param pg_info pointer to Format_info_pg struct
  446. \return 0 on success
  447. \return -1 on error
  448. */
  449. int write_nodes(const struct Plus_head *plus,
  450. const struct Format_info_pg *pg_info)
  451. {
  452. int i, node_id;
  453. size_t stmt_lines_size, stmt_angles_size, stmt_size;
  454. char *stmt_lines, *stmt_angles, *stmt;
  455. const struct P_node *Node;
  456. const struct Format_info_offset *offset;
  457. offset = &(pg_info->offset);
  458. if (offset->array_num < 1) /* nothing to write */
  459. return 0;
  460. if (plus->n_nodes != offset->array_num) {
  461. G_warning(_("Unable to write nodes, offset array mismatch"));
  462. return -1;
  463. }
  464. stmt_size = 2 * DB_SQL_MAX + 512;
  465. stmt = (char *) G_malloc(stmt_size);
  466. stmt_lines = stmt_angles = NULL;
  467. for (i = 1; i <= plus->n_nodes; i++) {
  468. Node = plus->Node[i];
  469. if (!Node)
  470. continue; /* should not happen */
  471. node_id = offset->array[i-1];
  472. /* 'lines' array */
  473. build_stmt_id(Node->lines, Node->n_lines, TRUE, plus, &stmt_lines, &stmt_lines_size);
  474. /* 'angle' array */
  475. build_stmt_id(Node->angles, Node->n_lines, FALSE, NULL, &stmt_angles, &stmt_angles_size);
  476. /* build SQL statement to add new node into 'node_grass' */
  477. if (stmt_lines_size + stmt_angles_size + 512 > stmt_size) {
  478. stmt_size = stmt_lines_size + stmt_angles_size + 512;
  479. stmt = (char *) G_realloc(stmt, stmt_size);
  480. }
  481. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  482. "%d, '{%s}', '{%s}')", pg_info->toposchema_name, TOPO_TABLE_NODE,
  483. node_id, stmt_lines, stmt_angles);
  484. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  485. G_warning(_("Unable to write nodes"));
  486. return -1;
  487. }
  488. }
  489. G_free(stmt_lines);
  490. G_free(stmt_angles);
  491. G_free(stmt);
  492. return 0;
  493. }
  494. /*!
  495. \brief Insert area into 'area_grass' table
  496. Writes (see P_area struct):
  497. - lines
  498. - centroid
  499. - isles
  500. \param plus pointer to Plus_head struct
  501. \param pg_info pointer to Format_info_pg struct
  502. \return 0 on success
  503. \return -1 on error
  504. */
  505. int write_areas(const struct Plus_head *plus,
  506. const struct Format_info_pg *pg_info)
  507. {
  508. int area, centroid;
  509. size_t stmt_lines_size, stmt_isles_size, stmt_size;
  510. char *stmt_lines, *stmt_isles, *stmt;
  511. const struct P_line *Line;
  512. const struct P_area *Area;
  513. stmt_size = 2 * DB_SQL_MAX + 512;
  514. stmt = (char *) G_malloc(stmt_size);
  515. stmt_lines = stmt_isles = NULL;
  516. for (area = 1; area <= plus->n_areas; area++) {
  517. Area = plus->Area[area];
  518. if (!Area) {
  519. G_debug(3, "Area %d skipped (dead)", area);
  520. continue; /* should not happen */
  521. }
  522. /* 'lines' array */
  523. build_stmt_id(Area->lines, Area->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
  524. /* 'isles' array */
  525. build_stmt_id(Area->isles, Area->n_isles, TRUE, NULL, &stmt_isles, &stmt_isles_size);
  526. if (Area->centroid != 0) {
  527. Line = plus->Line[Area->centroid];
  528. if (!Line) {
  529. G_warning(_("Topology for centroid %d not available. Area %d skipped"),
  530. Area->centroid, area);
  531. continue;
  532. }
  533. centroid = (int) Line->offset;
  534. }
  535. else {
  536. centroid = 0;
  537. }
  538. /* build SQL statement to add new node into 'node_grass' */
  539. if (stmt_lines_size + stmt_isles_size + 512 > stmt_size) {
  540. stmt_size = stmt_lines_size + stmt_isles_size + 512;
  541. stmt = (char *) G_realloc(stmt, stmt_size);
  542. }
  543. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  544. "%d, '{%s}', %d, '{%s}')", pg_info->toposchema_name, TOPO_TABLE_AREA,
  545. area, stmt_lines, centroid, stmt_isles);
  546. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  547. return -1;
  548. }
  549. }
  550. G_free(stmt_lines);
  551. G_free(stmt_isles);
  552. G_free(stmt);
  553. return 0;
  554. }
  555. /*!
  556. \brief Insert isle into 'isle_grass' table
  557. Writes (see P_isle struct):
  558. - lines
  559. - area
  560. \param plus pointer to Plus_head struct
  561. \param pg_info pointer to Format_info_pg struct
  562. \return 0 on success
  563. \return -1 on error
  564. */
  565. int write_isles(const struct Plus_head *plus,
  566. const struct Format_info_pg *pg_info)
  567. {
  568. int isle;
  569. size_t stmt_lines_size, stmt_size;
  570. char *stmt_lines, *stmt;
  571. const struct P_isle *Isle;
  572. stmt_size = DB_SQL_MAX + 512;
  573. stmt = (char *) G_malloc(stmt_size);
  574. stmt_lines = NULL;
  575. for (isle = 1; isle <= plus->n_isles; isle++) {
  576. Isle = plus->Isle[isle];
  577. if (!Isle)
  578. continue; /* should not happen */
  579. /* 'lines' array */
  580. build_stmt_id(Isle->lines, Isle->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
  581. /* build SQL statement to add new node into 'node_grass' */
  582. if (stmt_lines_size + 512 > stmt_size) {
  583. stmt_size = stmt_lines_size + 512;
  584. stmt = (char *) G_realloc(stmt, stmt_size);
  585. }
  586. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  587. "%d, '{%s}', %d)", pg_info->toposchema_name, TOPO_TABLE_ISLE,
  588. isle, stmt_lines, Isle->area);
  589. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  590. return -1;
  591. }
  592. }
  593. G_free(stmt_lines);
  594. G_free(stmt);
  595. return 0;
  596. }
  597. /*!
  598. \brief Create PG-like array for int/float array
  599. \param array array of items
  600. \param nitems number of items in the array
  601. \param is_int TRUE for array of integers otherwise floats
  602. \param plus pointer to Plus_head struct
  603. \param[in,out] output buffer (re-used)
  604. \param[in,out] buffer size
  605. */
  606. void build_stmt_id(const void *array, int nitems, int is_int, const struct Plus_head *plus,
  607. char **stmt, size_t *stmt_size)
  608. {
  609. int i, ivalue;
  610. int *iarray;
  611. float *farray;
  612. size_t stmt_id_size;
  613. char *stmt_id, buf_id[128];
  614. struct P_line *Line;
  615. if (is_int)
  616. iarray = (int *) array;
  617. else
  618. farray = (float *) array;
  619. if (!(*stmt)) {
  620. stmt_id_size = DB_SQL_MAX;
  621. stmt_id = (char *) G_malloc(stmt_id_size);
  622. }
  623. else {
  624. stmt_id_size = *stmt_size;
  625. stmt_id = *stmt;
  626. }
  627. /* reset array */
  628. stmt_id[0] = '\0';
  629. for (i = 0; i < nitems; i++) {
  630. /* realloc array if needed */
  631. if (strlen(stmt_id) + 100 > stmt_id_size) {
  632. stmt_id_size = strlen(stmt_id) + DB_SQL_MAX;
  633. stmt_id = (char *) G_realloc(stmt_id, stmt_id_size);
  634. }
  635. if (is_int) {
  636. if (plus) {
  637. Line = plus->Line[abs(iarray[i])];
  638. ivalue = (int) Line->offset;
  639. if (iarray[i] < 0)
  640. ivalue *= -1;
  641. }
  642. else {
  643. ivalue = iarray[i];
  644. }
  645. sprintf(buf_id, "%d", ivalue);
  646. }
  647. else {
  648. sprintf(buf_id, "%f", farray[i]);
  649. }
  650. if (i > 0)
  651. strcat(stmt_id, ",");
  652. strcat(stmt_id, buf_id);
  653. }
  654. *stmt = stmt_id;
  655. *stmt_size = stmt_id_size;
  656. }
  657. #endif