build_pg.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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_UNKNOWN)
  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 indeces */
  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 (create_simple_feature_from_topo(Map) != 0)
  342. return 0;
  343. G_free_key_value(key_val);
  344. }
  345. return 1;
  346. }
  347. /*!
  348. \brief Build UPDATE statement for topo geometry element stored in
  349. feature table
  350. \param pg_info so pointer to Format_info_pg
  351. \param type feature type (GV_POINT, ...)
  352. \param topo_id topology element id
  353. \param fid feature id
  354. \param[out] stmt string buffer
  355. \return 1 on success
  356. \return 0 on failure
  357. */
  358. int build_topogeom_stmt(const struct Format_info_pg *pg_info,
  359. int type, int topo_id, int fid, char *stmt)
  360. {
  361. int topogeom_type;
  362. switch(type) {
  363. case GV_POINT:
  364. topogeom_type = 1;
  365. break;
  366. case GV_LINE:
  367. case GV_BOUNDARY:
  368. topogeom_type = 2;
  369. break;
  370. case GV_CENTROID:
  371. topogeom_type = 3;
  372. break;
  373. default:
  374. G_warning(_("Unsupported topo geometry type %d"), type);
  375. return 0;
  376. }
  377. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  378. "'(%d, 1, %d, %d)'::topology.TopoGeometry "
  379. "WHERE (%s).id = %d",
  380. pg_info->schema_name, pg_info->table_name,
  381. pg_info->topogeom_column, pg_info->toposchema_id,
  382. topo_id, topogeom_type, pg_info->topogeom_column, fid);
  383. return 1;
  384. }
  385. /*!
  386. \brief Store map bounding box in DB head table
  387. \param pg_info pointer to Format_info_pg struct
  388. \param box pointer to bounding box
  389. \return 1 on success
  390. \return 0 on failure
  391. */
  392. int save_map_bbox(const struct Format_info_pg *pg_info, const struct bound_box *box)
  393. {
  394. char stmt[DB_SQL_MAX];
  395. /* create if not exists */
  396. if (create_topo_grass(pg_info) == -1) {
  397. G_warning(_("Unable to create <%s.%s>"), TOPO_SCHEMA, TOPO_TABLE);
  398. return 0;
  399. }
  400. /* update bbox */
  401. if (has_topo_grass(pg_info)) {
  402. /* -> update */
  403. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  404. "'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d WHERE %s = %d",
  405. TOPO_SCHEMA, TOPO_TABLE, TOPO_BBOX,
  406. box->W, box->S, box->B, box->E, box->N, box->T,
  407. TOPO_ID, pg_info->toposchema_id);
  408. }
  409. else {
  410. /* -> insert */
  411. sprintf(stmt, "INSERT INTO \"%s\".\"%s\" (%s, %s) "
  412. "VALUES(%d, 'BOX3D(%.12f %.12f %.12f, %.12f %.12f %.12f)'::box3d)",
  413. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX, pg_info->toposchema_id,
  414. box->W, box->S, box->B, box->E, box->N, box->T);
  415. }
  416. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  417. return -1;
  418. }
  419. return 1;
  420. }
  421. /*!
  422. \brief Creates 'topology.grass' table if not exists
  423. \return 0 table already exists
  424. \return 1 table successfully added
  425. \return -1 on error
  426. */
  427. int create_topo_grass(const struct Format_info_pg *pg_info)
  428. {
  429. char stmt[DB_SQL_MAX];
  430. PGresult *result;
  431. /* check if table exists */
  432. sprintf(stmt, "SELECT COUNT(*) FROM information_schema.tables "
  433. "WHERE table_schema = '%s' AND table_name = '%s'",
  434. TOPO_SCHEMA, TOPO_TABLE);
  435. result = PQexec(pg_info->conn, stmt);
  436. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  437. PQclear(result);
  438. return -1;
  439. }
  440. if (atoi(PQgetvalue(result, 0, 0)) == 1) {
  441. /* table already exists */
  442. PQclear(result);
  443. return 1;
  444. }
  445. PQclear(result);
  446. G_debug(1, "<%s.%s> created", TOPO_SCHEMA, TOPO_TABLE);
  447. /* create table */
  448. sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s INTEGER, %s box3d)",
  449. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, TOPO_BBOX);
  450. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  451. return -1;
  452. }
  453. /* add primary key */
  454. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD PRIMARY KEY (%s)",
  455. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID);
  456. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  457. return -1;
  458. }
  459. /* add constraint */
  460. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD CONSTRAINT \"%s_%s_fkey\" "
  461. "FOREIGN KEY (%s) REFERENCES topology.topology(id) ON DELETE CASCADE",
  462. TOPO_SCHEMA, TOPO_TABLE, TOPO_TABLE, TOPO_ID, TOPO_ID);
  463. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  464. return -1;
  465. }
  466. return 1;
  467. }
  468. /*!
  469. \brief Check if 'topology_id' exists in 'topology.grass'
  470. \param pg_info pointer to Format_info_pg struct
  471. \return TRUE if exists
  472. \return FALSE otherwise
  473. \return -1 on error
  474. */
  475. int has_topo_grass(const struct Format_info_pg *pg_info)
  476. {
  477. int has_topo;
  478. char stmt[DB_SQL_MAX];
  479. PGresult *result;
  480. sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".\"%s\" "
  481. "WHERE %s = %d",
  482. TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, pg_info->toposchema_id);
  483. result = PQexec(pg_info->conn, stmt);
  484. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  485. PQclear(result);
  486. return -1;
  487. }
  488. has_topo = FALSE;
  489. if (atoi(PQgetvalue(result, 0, 0)) == 1) {
  490. /* table already exists */
  491. has_topo = TRUE;
  492. }
  493. PQclear(result);
  494. return has_topo;
  495. }
  496. /*!
  497. \brief Insert node into 'node_grass' table
  498. Writes (see P_node struct):
  499. - lines
  500. - angles
  501. Already stored in Topo-Geo:
  502. - x,y,z (geom)
  503. \param plus pointer to Plus_head struct
  504. \param pg_info pointer to Format_info_pg struct
  505. \return 0 on success
  506. \return -1 on error
  507. */
  508. int write_nodes(const struct Plus_head *plus,
  509. const struct Format_info_pg *pg_info)
  510. {
  511. int i, node_id;
  512. size_t stmt_lines_size, stmt_angles_size, stmt_size;
  513. char *stmt_lines, *stmt_angles, *stmt;
  514. const struct P_node *Node;
  515. const struct Format_info_offset *offset;
  516. offset = &(pg_info->offset);
  517. if (offset->array_num < 1) /* nothing to write */
  518. return 0;
  519. if (plus->n_nodes != offset->array_num) {
  520. G_warning(_("Unable to write nodes, offset array mismatch"));
  521. return -1;
  522. }
  523. stmt_size = 2 * DB_SQL_MAX + 512;
  524. stmt = (char *) G_malloc(stmt_size);
  525. stmt_lines = stmt_angles = NULL;
  526. for (i = 1; i <= plus->n_nodes; i++) {
  527. Node = plus->Node[i];
  528. if (!Node)
  529. continue; /* should not happen */
  530. node_id = offset->array[i-1];
  531. /* 'lines' array */
  532. build_stmt_id(Node->lines, Node->n_lines, TRUE, plus, &stmt_lines, &stmt_lines_size);
  533. /* 'angle' array */
  534. build_stmt_id(Node->angles, Node->n_lines, FALSE, NULL, &stmt_angles, &stmt_angles_size);
  535. /* build SQL statement to add new node into 'node_grass' */
  536. if (stmt_lines_size + stmt_angles_size + 512 > stmt_size) {
  537. stmt_size = stmt_lines_size + stmt_angles_size + 512;
  538. stmt = (char *) G_realloc(stmt, stmt_size);
  539. }
  540. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  541. "%d, '{%s}', '{%s}')", pg_info->toposchema_name, TOPO_TABLE_NODE,
  542. node_id, stmt_lines, stmt_angles);
  543. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  544. G_warning(_("Unable to write nodes"));
  545. return -1;
  546. }
  547. }
  548. G_free(stmt_lines);
  549. G_free(stmt_angles);
  550. G_free(stmt);
  551. return 0;
  552. }
  553. /*!
  554. \brief Insert lines into 'line_grass' table
  555. Writes (see P_line struct) - only for boundaries:
  556. - left, right area
  557. Already stored in Topo-Geo:
  558. - edge_id, left_face, right_face
  559. \param plus pointer to Plus_head struct
  560. \param pg_info pointer to Format_info_pg struct
  561. \return 0 on success
  562. \return -1 on error
  563. */
  564. int write_lines(const struct Plus_head *plus,
  565. const struct Format_info_pg *pg_info)
  566. {
  567. int i, row, offset;
  568. char stmt[DB_SQL_MAX];
  569. const struct P_line *Line;
  570. const struct P_topo_b *topo;
  571. PGresult *res;
  572. sprintf(stmt, "SELECT edge_id FROM \"%s\".edge_data WHERE "
  573. "left_face != 0 OR right_face != 0 ORDER BY edge_id",
  574. pg_info->toposchema_name);
  575. G_debug(2, "SQL: %s", stmt);
  576. res = PQexec(pg_info->conn, stmt);
  577. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  578. (PQntuples(res) > 0 && PQntuples(res) != plus->n_blines)) {
  579. G_warning(_("Inconsistency in topology: number of "
  580. "boundaries %d (should be %d)"),
  581. PQntuples(res), plus->n_blines);
  582. if (res)
  583. PQclear(res);
  584. return -1;
  585. }
  586. for (row = 0, i = 1; i <= plus->n_lines; i++) {
  587. Line = plus->Line[i];
  588. if (!Line || Line->type != GV_BOUNDARY)
  589. continue;
  590. if (Line->offset == 0L)
  591. offset = atoi(PQgetvalue(res, row++, 0));
  592. else
  593. offset = (int)Line->offset;
  594. topo = (struct P_topo_b *)Line->topo;
  595. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  596. "%d, %d, %d)", pg_info->toposchema_name, TOPO_TABLE_LINE,
  597. offset, topo->left, topo->right);
  598. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  599. G_warning(_("Unable to write lines"));
  600. return -1;
  601. }
  602. }
  603. return 0;
  604. }
  605. /*!
  606. \brief Insert area into 'area_grass' table
  607. Writes (see P_area struct):
  608. - lines
  609. - centroid
  610. - isles
  611. \param plus pointer to Plus_head struct
  612. \param pg_info pointer to Format_info_pg struct
  613. \return 0 on success
  614. \return -1 on error
  615. */
  616. int write_areas(const struct Plus_head *plus,
  617. const struct Format_info_pg *pg_info)
  618. {
  619. int area, centroid;
  620. size_t stmt_lines_size, stmt_isles_size, stmt_size;
  621. char *stmt_lines, *stmt_isles, *stmt;
  622. const struct P_line *Line;
  623. const struct P_area *Area;
  624. stmt_size = 2 * DB_SQL_MAX + 512;
  625. stmt = (char *) G_malloc(stmt_size);
  626. stmt_lines = stmt_isles = NULL;
  627. for (area = 1; area <= plus->n_areas; area++) {
  628. Area = plus->Area[area];
  629. if (!Area) {
  630. G_debug(3, "Area %d skipped (dead)", area);
  631. continue; /* should not happen */
  632. }
  633. /* 'lines' array */
  634. build_stmt_id(Area->lines, Area->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
  635. /* 'isles' array */
  636. build_stmt_id(Area->isles, Area->n_isles, TRUE, NULL, &stmt_isles, &stmt_isles_size);
  637. if (Area->centroid != 0) {
  638. Line = plus->Line[Area->centroid];
  639. if (!Line) {
  640. G_warning(_("Topology for centroid %d not available. Area %d skipped"),
  641. Area->centroid, area);
  642. continue;
  643. }
  644. centroid = (int) Line->offset;
  645. }
  646. else {
  647. centroid = 0;
  648. }
  649. /* build SQL statement to add new node into 'node_grass' */
  650. if (stmt_lines_size + stmt_isles_size + 512 > stmt_size) {
  651. stmt_size = stmt_lines_size + stmt_isles_size + 512;
  652. stmt = (char *) G_realloc(stmt, stmt_size);
  653. }
  654. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  655. "%d, '{%s}', %d, '{%s}')", pg_info->toposchema_name, TOPO_TABLE_AREA,
  656. area, stmt_lines, centroid, stmt_isles);
  657. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  658. return -1;
  659. }
  660. }
  661. G_free(stmt_lines);
  662. G_free(stmt_isles);
  663. G_free(stmt);
  664. return 0;
  665. }
  666. /*!
  667. \brief Insert isle into 'isle_grass' table
  668. Writes (see P_isle struct):
  669. - lines
  670. - area
  671. \param plus pointer to Plus_head struct
  672. \param pg_info pointer to Format_info_pg struct
  673. \return 0 on success
  674. \return -1 on error
  675. */
  676. int write_isles(const struct Plus_head *plus,
  677. const struct Format_info_pg *pg_info)
  678. {
  679. int isle;
  680. size_t stmt_lines_size, stmt_size;
  681. char *stmt_lines, *stmt;
  682. const struct P_isle *Isle;
  683. stmt_size = DB_SQL_MAX + 512;
  684. stmt = (char *) G_malloc(stmt_size);
  685. stmt_lines = NULL;
  686. for (isle = 1; isle <= plus->n_isles; isle++) {
  687. Isle = plus->Isle[isle];
  688. if (!Isle)
  689. continue; /* should not happen */
  690. /* 'lines' array */
  691. build_stmt_id(Isle->lines, Isle->n_lines, TRUE, NULL, &stmt_lines, &stmt_lines_size);
  692. /* build SQL statement to add new node into 'node_grass' */
  693. if (stmt_lines_size + 512 > stmt_size) {
  694. stmt_size = stmt_lines_size + 512;
  695. stmt = (char *) G_realloc(stmt, stmt_size);
  696. }
  697. sprintf(stmt, "INSERT INTO \"%s\".%s VALUES ("
  698. "%d, '{%s}', %d)", pg_info->toposchema_name, TOPO_TABLE_ISLE,
  699. isle, stmt_lines, Isle->area);
  700. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  701. return -1;
  702. }
  703. }
  704. G_free(stmt_lines);
  705. G_free(stmt);
  706. return 0;
  707. }
  708. /*!
  709. \brief Create PG-like array for int/float array
  710. \param array array of items
  711. \param nitems number of items in the array
  712. \param is_int TRUE for array of integers otherwise floats
  713. \param plus pointer to Plus_head struct
  714. \param[in,out] output buffer (re-used)
  715. \param[in,out] buffer size
  716. */
  717. void build_stmt_id(const void *array, int nitems, int is_int, const struct Plus_head *plus,
  718. char **stmt, size_t *stmt_size)
  719. {
  720. int i, ivalue;
  721. int *iarray;
  722. float *farray;
  723. size_t stmt_id_size;
  724. char *stmt_id, buf_id[128];
  725. struct P_line *Line;
  726. if (is_int)
  727. iarray = (int *) array;
  728. else
  729. farray = (float *) array;
  730. if (!(*stmt)) {
  731. stmt_id_size = DB_SQL_MAX;
  732. stmt_id = (char *) G_malloc(stmt_id_size);
  733. }
  734. else {
  735. stmt_id_size = *stmt_size;
  736. stmt_id = *stmt;
  737. }
  738. /* reset array */
  739. stmt_id[0] = '\0';
  740. for (i = 0; i < nitems; i++) {
  741. /* realloc array if needed */
  742. if (strlen(stmt_id) + 100 > stmt_id_size) {
  743. stmt_id_size = strlen(stmt_id) + DB_SQL_MAX;
  744. stmt_id = (char *) G_realloc(stmt_id, stmt_id_size);
  745. }
  746. if (is_int) {
  747. if (plus) {
  748. Line = plus->Line[abs(iarray[i])];
  749. ivalue = (int) Line->offset;
  750. if (iarray[i] < 0)
  751. ivalue *= -1;
  752. }
  753. else {
  754. ivalue = iarray[i];
  755. }
  756. sprintf(buf_id, "%d", ivalue);
  757. }
  758. else {
  759. sprintf(buf_id, "%f", farray[i]);
  760. }
  761. if (i > 0)
  762. strcat(stmt_id, ",");
  763. strcat(stmt_id, buf_id);
  764. }
  765. *stmt = stmt_id;
  766. *stmt_size = stmt_id_size;
  767. }
  768. /*!
  769. \brief Clean-up GRASS Topology tables
  770. \param pg_info pointer to Format_info_pg pg_info
  771. \return 0 on success
  772. \return -1 on error
  773. */
  774. int Vect__clean_grass_db_topo(struct Format_info_pg *pg_info)
  775. {
  776. char stmt[DB_SQL_MAX];
  777. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  778. pg_info->toposchema_name, TOPO_TABLE_NODE);
  779. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  780. return -1;
  781. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  782. pg_info->toposchema_name, TOPO_TABLE_LINE);
  783. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  784. return -1;
  785. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  786. pg_info->toposchema_name, TOPO_TABLE_AREA);
  787. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  788. return -1;
  789. sprintf(stmt, "DELETE FROM \"%s\".\"%s\"",
  790. pg_info->toposchema_name, TOPO_TABLE_ISLE);
  791. if (-1 == Vect__execute_pg(pg_info->conn, stmt))
  792. return -1;
  793. return 0;
  794. }
  795. /*!
  796. \brief Create simple features geometry from topogeometry data
  797. \param Map pointer to Map_info struct
  798. \return 0 on success
  799. \return -1 on error
  800. */
  801. int create_simple_feature_from_topo(struct Map_info *Map)
  802. {
  803. char stmt[DB_SQL_MAX];
  804. struct Format_info_pg *pg_info;
  805. pg_info = &(Map->fInfo.pg);
  806. G_debug(1, "build_simple_feature_from_topo(): %d", pg_info->feature_type);
  807. G_message(_("Create simple features topology from topogeometry data..."));
  808. Vect__execute_pg(pg_info->conn, "BEGIN");
  809. if (pg_info->feature_type == SF_POINT ||
  810. pg_info->feature_type == SF_LINESTRING) {
  811. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET %s = (SELECT geom FROM \"%s\".node "
  812. "WHERE node_id = (%s).id)", pg_info->schema_name, pg_info->table_name,
  813. pg_info->geom_column, pg_info->toposchema_name, pg_info->topogeom_column);
  814. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  815. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  816. return -1;
  817. }
  818. }
  819. else if (pg_info->feature_type == SF_POLYGON) {
  820. Vect__copy_areas(Map, 1, Map);
  821. }
  822. else {
  823. G_warning(_("Unable to build simple features from topogeometry data. "
  824. "Unsupported type %d."), pg_info->feature_type);
  825. }
  826. Vect__execute_pg(pg_info->conn, "COMMIT");
  827. return 0;
  828. }
  829. #endif