write_pg.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. /*!
  2. \file lib/vector/Vlib/write_pg.c
  3. \brief Vector library - write vector feature (PostGIS format)
  4. Higher level functions for reading/writing/manipulating vectors.
  5. Write subroutine inspired by OGR PostgreSQL driver.
  6. \todo PostGIS version of V2__add_line_to_topo_nat()
  7. \todo OGR version of V2__delete_area_cats_from_cidx_nat()
  8. \todo function to delete corresponding entry in fidx
  9. \todo OGR version of V2__add_area_cats_to_cidx_nat
  10. \todo OGR version of V2__add_line_to_topo_nat
  11. (C) 2012 by Martin Landa, and the GRASS Development Team
  12. This program is free software under the GNU General Public License
  13. (>=v2). Read the file COPYING that comes with GRASS for details.
  14. \author Martin Landa <landa.martin gmail.com>
  15. */
  16. #include <string.h>
  17. #include <grass/vector.h>
  18. #include <grass/glocale.h>
  19. #include "local_proto.h"
  20. #ifdef HAVE_POSTGRES
  21. #include "pg_local_proto.h"
  22. #define WKBSRIDFLAG 0x20000000
  23. /*! Use SQL statements from PostGIS Topology extension (this options
  24. is quite slow. By default are used simple SQL statements (INSERT, UPDATE)
  25. */
  26. #define USE_TOPO_STMT 0
  27. static off_t write_line_sf(struct Map_info *, int,
  28. const struct line_pnts **, int,
  29. const struct line_cats *);
  30. static off_t write_line_tp(struct Map_info *, int, int,
  31. const struct line_pnts *,
  32. const struct line_cats *);
  33. static char *binary_to_hex(int, const unsigned char *);
  34. static unsigned char *point_to_wkb(int, const struct line_pnts *, int, int *);
  35. static unsigned char *linestring_to_wkb(int, const struct line_pnts *,
  36. int, int *);
  37. static unsigned char *polygon_to_wkb(int, const struct line_pnts **, int,
  38. int, int *);
  39. static int write_feature(struct Map_info *, int, int,
  40. const struct line_pnts **, int, int,
  41. int, const struct field_info *);
  42. static char *build_insert_stmt(const struct Format_info_pg *, const char *,
  43. int, const struct field_info *);
  44. static int insert_topo_element(struct Map_info *, int, int, const char *);
  45. static int update_next_edge(struct Map_info*, int, int);
  46. static int insert_face(struct Map_info *, int);
  47. static int delete_face(const struct Map_info *, int);
  48. static int update_topo_edge(struct Map_info *, int);
  49. static int update_topo_face(struct Map_info *, int);
  50. #endif
  51. /*!
  52. \brief Writes feature on level 1 (PostGIS interface)
  53. Note:
  54. - centroids are not supported in PostGIS, pseudotopo holds virtual
  55. centroids
  56. - boundaries are not supported in PostGIS, pseudotopo treats polygons
  57. as boundaries
  58. \param Map pointer to Map_info structure
  59. \param type feature type (GV_POINT, GV_LINE, ...)
  60. \param points pointer to line_pnts structure (feature geometry)
  61. \param cats pointer to line_cats structure (feature categories)
  62. \return feature offset into file
  63. \return -1 on error
  64. */
  65. off_t V1_write_line_pg(struct Map_info *Map, int type,
  66. const struct line_pnts *points,
  67. const struct line_cats *cats)
  68. {
  69. #ifdef HAVE_POSTGRES
  70. struct Format_info_pg *pg_info;
  71. pg_info = &(Map->fInfo.pg);
  72. if (pg_info->feature_type == SF_UNKNOWN) {
  73. /* create PostGIS table if doesn't exist */
  74. if (V2_open_new_pg(Map, type) < 0)
  75. return -1;
  76. }
  77. if (pg_info->toposchema_name) {
  78. G_warning(_("PostGIS topology not supported on level 1"));
  79. return -1;
  80. }
  81. return write_line_sf(Map, type, &points, 1, cats);
  82. #else
  83. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  84. return -1;
  85. #endif
  86. }
  87. /*!
  88. \brief Writes feature on level 2 (PostGIS interface)
  89. \param Map pointer to Map_info structure
  90. \param type feature type (GV_POINT, GV_LINE, ...)
  91. \param points pointer to line_pnts structure (feature geometry)
  92. \param cats pointer to line_cats structure (feature categories)
  93. \return feature offset into file
  94. \return -1 on error
  95. */
  96. off_t V2_write_line_pg(struct Map_info *Map, int type,
  97. const struct line_pnts *points,
  98. const struct line_cats *cats)
  99. {
  100. #ifdef HAVE_POSTGRES
  101. struct Format_info_pg *pg_info;
  102. pg_info = &(Map->fInfo.pg);
  103. if (!pg_info->toposchema_name) { /* pseudo-topology */
  104. return V2_write_line_sfa(Map, type, points, cats);
  105. }
  106. else { /* PostGIS topology */
  107. if (Map->plus.built < GV_BUILD_BASE)
  108. Map->plus.built = GV_BUILD_ALL;
  109. return write_line_tp(Map, type, FALSE, points, cats);
  110. }
  111. #else
  112. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  113. return -1;
  114. #endif
  115. }
  116. /*!
  117. \brief Rewrites feature at the given offset (level 1) (PostGIS interface)
  118. \param Map pointer to Map_info structure
  119. \param offset feature offset
  120. \param type feature type (GV_POINT, GV_LINE, ...)
  121. \param points feature geometry
  122. \param cats feature categories
  123. \return feature offset (rewriten feature)
  124. \return -1 on error
  125. */
  126. off_t V1_rewrite_line_pg(struct Map_info * Map,
  127. int line, int type, off_t offset,
  128. const struct line_pnts * points,
  129. const struct line_cats * cats)
  130. {
  131. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%lu",
  132. line, type, offset);
  133. #ifdef HAVE_POSTGRES
  134. if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
  135. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  136. return -1;
  137. }
  138. /* delete old */
  139. V1_delete_line_pg(Map, offset);
  140. return V1_write_line_pg(Map, type, points, cats);
  141. #else
  142. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  143. return -1;
  144. #endif
  145. }
  146. /*!
  147. \brief Deletes feature at the given offset (level 1)
  148. \param Map pointer Map_info structure
  149. \param offset feature offset
  150. \return 0 on success
  151. \return -1 on error
  152. */
  153. int V1_delete_line_pg(struct Map_info *Map, off_t offset)
  154. {
  155. #ifdef HAVE_POSTGRES
  156. long fid;
  157. char stmt[DB_SQL_MAX];
  158. struct Format_info_pg *pg_info;
  159. pg_info = &(Map->fInfo.pg);
  160. if (!pg_info->conn || !pg_info->table_name) {
  161. G_warning(_("No connection defined"));
  162. return -1;
  163. }
  164. if (offset >= pg_info->offset.array_num) {
  165. G_warning(_("Invalid offset (%d)"), offset);
  166. return -1;
  167. }
  168. fid = pg_info->offset.array[offset];
  169. G_debug(3, "V1_delete_line_pg(), offset = %lu -> fid = %ld",
  170. (unsigned long)offset, fid);
  171. if (!pg_info->inTransaction) {
  172. /* start transaction */
  173. pg_info->inTransaction = TRUE;
  174. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1)
  175. return -1;
  176. }
  177. sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
  178. pg_info->table_name, pg_info->fid_column, fid);
  179. G_debug(2, "SQL: %s", stmt);
  180. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  181. G_warning(_("Unable to delete feature"));
  182. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  183. return -1;
  184. }
  185. return 0;
  186. #else
  187. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  188. return -1;
  189. #endif
  190. }
  191. /*!
  192. \brief Writes node on level 2 (PostGIS Topology interface) - internal use only
  193. \param Map pointer to Map_info structure
  194. \param points pointer to line_pnts structure
  195. \return 0 on success
  196. \return -1 on error
  197. */
  198. off_t V2__write_node_pg(struct Map_info *Map, const struct line_pnts *points)
  199. {
  200. #ifdef HAVE_POSTGRES
  201. struct Format_info_pg *pg_info;
  202. pg_info = &(Map->fInfo.pg);
  203. if (!pg_info->toposchema_name)
  204. return -1; /* PostGIS Topology required */
  205. return write_line_tp(Map, GV_POINT, TRUE, points, NULL);
  206. #else
  207. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  208. return -1;
  209. #endif
  210. }
  211. /*!
  212. \brief Writes area on level 2 (PostGIS Simple Features interface) - internal use only
  213. \param Map pointer to Map_info structure
  214. \param type feature type (GV_POINT, GV_LINE, ...)
  215. \param points pointer to line_pnts structure (boundary geometry)
  216. \param cats pointer to line_cats structure (feature categories)
  217. \param ipoints pointer to line_pnts structure (isles geometry)
  218. \param nisles number of isles
  219. \return feature offset into file
  220. \return -1 on error
  221. */
  222. off_t V2__write_area_pg(struct Map_info *Map,
  223. const struct line_pnts *bpoints,
  224. const struct line_cats *cats,
  225. const struct line_pnts **ipoints, int nisles)
  226. {
  227. #ifdef HAVE_POSTGRES
  228. int i;
  229. off_t ret;
  230. const struct line_pnts **points;
  231. if (nisles > 0) {
  232. points = (const struct line_pnts **) G_calloc(nisles + 1, sizeof(struct line_pnts *));
  233. points[0] = bpoints;
  234. for (i = 0; i < nisles; i++)
  235. points[i + 1] = ipoints[i];
  236. }
  237. else {
  238. points = &bpoints;
  239. }
  240. ret = write_line_sf(Map, GV_BOUNDARY, points, nisles + 1, cats);
  241. if (nisles > 0)
  242. G_free(points);
  243. return ret;
  244. #else
  245. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  246. return -1;
  247. #endif
  248. }
  249. #ifdef HAVE_POSTGRES
  250. /*!
  251. \brief Write vector features as PostGIS simple feature element
  252. \return 0 on success
  253. \return -1 on error
  254. */
  255. off_t write_line_sf(struct Map_info *Map, int type,
  256. const struct line_pnts **points, int nparts,
  257. const struct line_cats *cats)
  258. {
  259. int cat;
  260. off_t offset;
  261. SF_FeatureType sf_type;
  262. struct field_info *Fi;
  263. struct Format_info_pg *pg_info;
  264. struct Format_info_offset *offset_info;
  265. pg_info = &(Map->fInfo.pg);
  266. offset_info = &(pg_info->offset);
  267. /* check required PG settings */
  268. if (!pg_info->conn) {
  269. G_warning(_("No connection defined"));
  270. return -1;
  271. }
  272. if (!pg_info->table_name) {
  273. G_warning(_("PostGIS feature table not defined"));
  274. return -1;
  275. }
  276. /* create PostGIS table if doesn't exist */
  277. if (pg_info->feature_type == SF_UNKNOWN) {
  278. if (V2_open_new_pg(Map, type) < 0)
  279. return -1;
  280. }
  281. Fi = NULL; /* no attributes to be written */
  282. cat = -1;
  283. if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) {
  284. /* check for attributes */
  285. Fi = Vect_get_dblink(Map, 0);
  286. if (Fi) {
  287. if (!Vect_cat_get(cats, Fi->number, &cat))
  288. G_warning(_("No category defined for layer %d"), Fi->number);
  289. if (cats->n_cats > 1) {
  290. G_warning(_("Feature has more categories, using "
  291. "category %d (from layer %d)"),
  292. cat, cats->field[0]);
  293. }
  294. }
  295. }
  296. sf_type = pg_info->feature_type;
  297. /* determine matching PostGIS feature geometry type */
  298. if (type & (GV_POINT | GV_KERNEL)) {
  299. if (sf_type != SF_POINT && sf_type != SF_POINT25D) {
  300. G_warning(_("Feature is not a point. Skipping."));
  301. return -1;
  302. }
  303. }
  304. else if (type & GV_LINE) {
  305. if (sf_type != SF_LINESTRING && sf_type != SF_LINESTRING25D) {
  306. G_warning(_("Feature is not a line. Skipping."));
  307. return -1;
  308. }
  309. }
  310. else if (type & GV_BOUNDARY || type & GV_CENTROID) {
  311. if (sf_type != SF_POLYGON) {
  312. G_warning(_("Feature is not a polygon. Skipping."));
  313. return -1;
  314. }
  315. }
  316. else if (type & GV_FACE) {
  317. if (sf_type != SF_POLYGON25D) {
  318. G_warning(_("Feature is not a face. Skipping."));
  319. return -1;
  320. }
  321. }
  322. else {
  323. G_warning(_("Unsupported feature type %d"), type);
  324. return -1;
  325. }
  326. G_debug(3, "write_line_sf(): type = %d n_points = %d cat = %d",
  327. type, points[0]->n_points, cat);
  328. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  329. /* skip this check when writing PostGIS topology */
  330. int part, npoints;
  331. for (part = 0; part < nparts; part++) {
  332. npoints = points[part]->n_points - 1;
  333. if (points[part]->x[0] != points[part]->x[npoints] ||
  334. points[part]->y[0] != points[part]->y[npoints] ||
  335. points[part]->z[0] != points[part]->z[npoints]) {
  336. G_warning(_("Boundary is not closed. Skipping."));
  337. return -1;
  338. }
  339. }
  340. }
  341. /* write feature's geometry and fid */
  342. if (-1 == write_feature(Map, -1, type, points, nparts,
  343. Vect_is_3d(Map) ? WITH_Z : WITHOUT_Z, cat, Fi)) {
  344. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  345. return -1;
  346. }
  347. /* update offset array */
  348. if (offset_info->array_num >= offset_info->array_alloc) {
  349. offset_info->array_alloc += 1000;
  350. offset_info->array = (int *)G_realloc(offset_info->array,
  351. offset_info->array_alloc *
  352. sizeof(int));
  353. }
  354. offset = offset_info->array_num;
  355. offset_info->array[offset_info->array_num++] = cat;
  356. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  357. /* register first part in offset array */
  358. offset_info->array[offset_info->array_num++] = 0;
  359. }
  360. G_debug(3, "write_line_sf(): -> offset = %lu offset_num = %d cat = %d",
  361. (unsigned long)offset, offset_info->array_num, cat);
  362. return offset;
  363. }
  364. /*!
  365. \brief Write vector feature in PostGIS topology schema and
  366. updates internal topology structures
  367. \param Map vector map
  368. \param type feature type to be written
  369. \param points feature geometry
  370. \param is_node TRUE for nodes (written as points)
  371. \return 0 on success
  372. \return -1 on error
  373. */
  374. off_t write_line_tp(struct Map_info *Map, int type, int is_node,
  375. const struct line_pnts *points,
  376. const struct line_cats *cats)
  377. {
  378. int line, cat;
  379. struct field_info *Fi;
  380. struct Format_info_pg *pg_info;
  381. struct Plus_head *plus;
  382. pg_info = &(Map->fInfo.pg);
  383. plus = &(Map->plus);
  384. /* check type for nodes */
  385. if (is_node && type != GV_POINT) {
  386. G_warning(_("Invalid type (%d) for nodes"), type);
  387. return -1;
  388. }
  389. /* check required PG settings */
  390. if (!pg_info->conn) {
  391. G_warning(_("No connection defined"));
  392. return -1;
  393. }
  394. if (!pg_info->table_name) {
  395. G_warning(_("PostGIS feature table not defined"));
  396. return -1;
  397. }
  398. if (!pg_info->toposchema_name) {
  399. G_warning(_("PostGIS topology schema not defined"));
  400. return -1;
  401. }
  402. /* create PostGIS table if doesn't exist */
  403. if (pg_info->feature_type == SF_UNKNOWN) {
  404. if (V2_open_new_pg(Map, type) < 0)
  405. return -1;
  406. }
  407. G_debug(3, "write_line_pg(): type = %d n_points = %d",
  408. type, points->n_points);
  409. line = -1; /* used only for topological access (lines, boundaries, and centroids) */
  410. Fi = NULL; /* no attributes to be written */
  411. cat = -1;
  412. if (cats && cats->n_cats > 0) {
  413. if (Vect_get_num_dblinks(Map) > 0) {
  414. /* check for attributes */
  415. Fi = Vect_get_dblink(Map, 0);
  416. if (Fi) {
  417. if (!Vect_cat_get(cats, Fi->number, &cat))
  418. G_warning(_("No category defined for layer %d"), Fi->number);
  419. if (cats->n_cats > 1) {
  420. G_warning(_("Feature has more categories, using "
  421. "category %d (from layer %d)"),
  422. cat, cats->field[0]);
  423. }
  424. }
  425. }
  426. /* assume layer=1 */
  427. Vect_cat_get(cats, 1, &cat);
  428. }
  429. /* update GRASS-like topology before writing feature */
  430. if (is_node) {
  431. dig_add_node(plus, points->x[0], points->y[0], points->z[0]);
  432. }
  433. else {
  434. off_t offset;
  435. struct bound_box box;
  436. dig_line_box(points, &box);
  437. /* better is probably to check nextval directly */
  438. if (type & GV_POINTS) {
  439. offset = Vect_get_num_primitives(Map, GV_POINTS) + 1; /* next */
  440. offset += Vect_get_num_nodes(Map); /* nodes are also stored in 'node' table */
  441. }
  442. else { /* LINES */
  443. offset = Vect_get_num_primitives(Map, GV_LINES) + 1; /* next */
  444. }
  445. line = dig_add_line(plus, type, points, &box, offset);
  446. G_debug(3, " line added to topo with id = %d", line);
  447. if (line == 1)
  448. Vect_box_copy(&(plus->box), &box);
  449. else
  450. Vect_box_extend(&(plus->box), &box);
  451. }
  452. /* write new feature to PostGIS
  453. - feature table for simple features
  454. - feature table and topo schema for topological access
  455. */
  456. if (-1 == write_feature(Map, line, type, &points, 1,
  457. Vect_is_3d(Map) ? WITH_Z : WITHOUT_Z,
  458. cat, Fi)) {
  459. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  460. return -1;
  461. }
  462. return 0;
  463. }
  464. /*!
  465. \brief Binary data to HEX
  466. Allocated buffer should be freed by G_free().
  467. \param nbytes number of bytes to allocate
  468. \param wkb_data WKB data
  469. \return allocated buffer with HEX data
  470. */
  471. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  472. {
  473. char *hex_data;
  474. int i, nlow, nhigh;
  475. static const char ach_hex[] = "0123456789ABCDEF";
  476. hex_data = (char *)G_malloc(nbytes * 2 + 1);
  477. hex_data[nbytes * 2] = '\0';
  478. for (i = 0; i < nbytes; i++) {
  479. nlow = wkb_data[i] & 0x0f;
  480. nhigh = (wkb_data[i] & 0xf0) >> 4;
  481. hex_data[i * 2] = ach_hex[nhigh];
  482. hex_data[i * 2 + 1] = ach_hex[nlow];
  483. }
  484. return hex_data;
  485. }
  486. /*!
  487. \bried Write point into WKB buffer
  488. See OGRPoint::exportToWkb from GDAL/OGR library
  489. \param byte_order byte order (ENDIAN_LITTLE or BIG_ENDIAN)
  490. \param points feature geometry
  491. \param with_z WITH_Z for 3D data
  492. \param[out] nsize buffer size
  493. \return allocated WKB buffer
  494. \return NULL on error
  495. */
  496. unsigned char *point_to_wkb(int byte_order,
  497. const struct line_pnts *points, int with_z,
  498. int *nsize)
  499. {
  500. unsigned char *wkb_data;
  501. unsigned int sf_type;
  502. if (points->n_points != 1)
  503. return NULL;
  504. /* allocate buffer */
  505. *nsize = with_z ? 29 : 21;
  506. wkb_data = G_malloc(*nsize);
  507. G_zero(wkb_data, *nsize);
  508. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  509. /* set the byte order */
  510. if (byte_order == ENDIAN_LITTLE)
  511. wkb_data[0] = '\001';
  512. else
  513. wkb_data[0] = '\000';
  514. /* set the geometry feature type */
  515. sf_type = with_z ? SF_POINT25D : SF_POINT;
  516. if (byte_order == ENDIAN_LITTLE)
  517. sf_type = LSBWORD32(sf_type);
  518. else
  519. sf_type = MSBWORD32(sf_type);
  520. memcpy(wkb_data + 1, &sf_type, 4);
  521. /* copy in the raw data */
  522. memcpy(wkb_data + 5, &(points->x[0]), 8);
  523. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  524. if (with_z) {
  525. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  526. }
  527. /* swap if needed */
  528. if (byte_order == ENDIAN_BIG) {
  529. SWAPDOUBLE(wkb_data + 5);
  530. SWAPDOUBLE(wkb_data + 5 + 8);
  531. if (with_z)
  532. SWAPDOUBLE(wkb_data + 5 + 16);
  533. }
  534. return wkb_data;
  535. }
  536. /*!
  537. \bried Write linestring into WKB buffer
  538. See OGRLineString::exportToWkb from GDAL/OGR library
  539. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  540. \param points feature geometry
  541. \param with_z WITH_Z for 3D data
  542. \param[out] nsize buffer size
  543. \return allocated WKB buffer
  544. \return NULL on error
  545. */
  546. unsigned char *linestring_to_wkb(int byte_order,
  547. const struct line_pnts *points, int with_z,
  548. int *nsize)
  549. {
  550. int i, point_size;
  551. unsigned char *wkb_data;
  552. unsigned int sf_type;
  553. if (points->n_points < 1)
  554. return NULL;
  555. /* allocate buffer */
  556. point_size = 8 * (with_z ? 3 : 2);
  557. *nsize = 5 + 4 + points->n_points * point_size;
  558. wkb_data = G_malloc(*nsize);
  559. G_zero(wkb_data, *nsize);
  560. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  561. /* set the byte order */
  562. if (byte_order == ENDIAN_LITTLE)
  563. wkb_data[0] = '\001';
  564. else
  565. wkb_data[0] = '\000';
  566. /* set the geometry feature type */
  567. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  568. if (byte_order == ENDIAN_LITTLE)
  569. sf_type = LSBWORD32(sf_type);
  570. else
  571. sf_type = MSBWORD32(sf_type);
  572. memcpy(wkb_data + 1, &sf_type, 4);
  573. /* copy in the data count */
  574. memcpy(wkb_data + 5, &(points->n_points), 4);
  575. /* copy in the raw data */
  576. for (i = 0; i < points->n_points; i++) {
  577. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  578. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  579. if (with_z) {
  580. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  581. }
  582. }
  583. /* swap if needed */
  584. if (byte_order == ENDIAN_BIG) {
  585. int npoints, nitems;
  586. npoints = SWAP32(points->n_points);
  587. memcpy(wkb_data + 5, &npoints, 4);
  588. nitems = (with_z ? 3 : 2) * points->n_points;
  589. for (i = 0; i < nitems; i++) {
  590. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  591. }
  592. }
  593. return wkb_data;
  594. }
  595. /*!
  596. \bried Write polygon into WKB buffer
  597. See OGRPolygon::exportToWkb from GDAL/OGR library
  598. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  599. \param ipoints list of ring geometries (first is outer ring)
  600. \param nrings number of rings
  601. \param with_z WITH_Z for 3D data
  602. \param[out] nsize buffer size
  603. \return allocated WKB buffer
  604. \return NULL on error
  605. */
  606. unsigned char *polygon_to_wkb(int byte_order,
  607. const struct line_pnts** points, int nrings,
  608. int with_z, int *nsize)
  609. {
  610. int i, ring, point_size, offset;
  611. unsigned char *wkb_data;
  612. unsigned int sf_type;
  613. /* check data validity */
  614. if (nrings < 1)
  615. return NULL;
  616. for (ring = 0; ring < nrings; ring++) {
  617. if (points[ring]->n_points < 3)
  618. return NULL;
  619. }
  620. /* allocate buffer */
  621. point_size = 8 * (with_z ? 3 : 2);
  622. *nsize = 9;
  623. for (ring = 0; ring < nrings; ring++)
  624. *nsize += 4 + point_size * points[ring]->n_points;
  625. wkb_data = G_malloc(*nsize);
  626. G_zero(wkb_data, *nsize);
  627. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  628. /* set the byte order */
  629. if (byte_order == ENDIAN_LITTLE)
  630. wkb_data[0] = '\001';
  631. else
  632. wkb_data[0] = '\000';
  633. /* set the geometry feature type */
  634. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  635. if (byte_order == ENDIAN_LITTLE)
  636. sf_type = LSBWORD32(sf_type);
  637. else
  638. sf_type = MSBWORD32(sf_type);
  639. memcpy(wkb_data + 1, &sf_type, 4);
  640. /* copy in the raw data */
  641. if (byte_order == ENDIAN_BIG) {
  642. int ncount;
  643. ncount = SWAP32(nrings);
  644. memcpy(wkb_data + 5, &ncount, 4);
  645. }
  646. else {
  647. memcpy(wkb_data + 5, &nrings, 4);
  648. }
  649. /* serialize rings */
  650. offset = 9;
  651. for (ring = 0; ring < nrings; ring++) {
  652. memcpy(wkb_data + offset, &(points[ring]->n_points), 4);
  653. for (i = 0; i < points[ring]->n_points; i++) {
  654. memcpy(wkb_data + offset +
  655. 4 + point_size * i, &(points[ring]->x[i]), 8);
  656. memcpy(wkb_data + offset +
  657. 4 + 8 + point_size * i, &(points[ring]->y[i]), 8);
  658. if (with_z) {
  659. memcpy(wkb_data + offset +
  660. 4 + 16 + point_size * i, &(points[ring]->z[i]), 8);
  661. }
  662. }
  663. offset += 4 + point_size * points[ring]->n_points;
  664. /* swap if needed */
  665. if (byte_order == ENDIAN_BIG) {
  666. int npoints, nitems;
  667. npoints = SWAP32(points[ring]->n_points);
  668. memcpy(wkb_data + 5, &npoints, 4);
  669. nitems = (with_z ? 3 : 2) * points[ring]->n_points;
  670. for (i = 0; i < nitems; i++) {
  671. SWAPDOUBLE(wkb_data + offset + 4 + 8 * i);
  672. }
  673. }
  674. }
  675. return wkb_data;
  676. }
  677. /*!
  678. \brief Insert feature into table
  679. \param Map pointer to Map_info structure
  680. \param line feature id (topo access only)
  681. \param type feature type (GV_POINT, GV_LINE, ...)
  682. \param points pointer to line_pnts struct
  683. \param nparts number of parts (rings for polygon)
  684. \param with_z WITH_Z for 3D data
  685. \param cat category number (-1 for no category)
  686. \param Fi pointer to field_info (attributes to copy, NULL for no attributes)
  687. \return -1 on error
  688. \retirn 0 on success
  689. */
  690. int write_feature(struct Map_info *Map, int line, int type,
  691. const struct line_pnts **points, int nparts, int with_z,
  692. int cat, const struct field_info *Fi)
  693. {
  694. int byte_order, nbytes, nsize;
  695. unsigned int sf_type;
  696. unsigned char *wkb_data;
  697. char *stmt, *text_data, *text_data_p, *hex_data;
  698. struct Format_info_pg *pg_info;
  699. pg_info = &(Map->fInfo.pg);
  700. if (with_z && pg_info->coor_dim != 3) {
  701. G_warning(_("Trying to insert 3D data into feature table "
  702. "which store 2D data only"));
  703. return -1;
  704. }
  705. if (!with_z && pg_info->coor_dim != 2) {
  706. G_warning(_("Trying to insert 2D data into feature table "
  707. "which store 3D data only"));
  708. return -1;
  709. }
  710. byte_order = dig__byte_order_out();
  711. /* get wkb data */
  712. nbytes = -1;
  713. wkb_data = NULL;
  714. if (type == GV_POINT || type == GV_CENTROID)
  715. wkb_data = point_to_wkb(byte_order, points[0], with_z, &nbytes);
  716. else if (type == GV_LINE)
  717. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  718. else if (type == GV_BOUNDARY) {
  719. if (!pg_info->toposchema_name) {
  720. /* PostGIS simple feature access */
  721. wkb_data = polygon_to_wkb(byte_order, points, nparts,
  722. with_z, &nbytes);
  723. }
  724. else {
  725. /* PostGIS topology access */
  726. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  727. }
  728. }
  729. if (!wkb_data || nbytes < 1) {
  730. G_warning(_("Unsupported feature type %d"), type);
  731. return -1;
  732. }
  733. /* When converting to hex, each byte takes 2 hex characters. In
  734. addition we add in 8 characters to represent the SRID integer
  735. in hex, and one for a null terminator */
  736. nsize = nbytes * 2 + 8 + 1;
  737. text_data = text_data_p = (char *)G_malloc(nsize);
  738. /* convert the 1st byte, which is the endianess flag, to hex */
  739. hex_data = binary_to_hex(1, wkb_data);
  740. strcpy(text_data_p, hex_data);
  741. G_free(hex_data);
  742. text_data_p += 2;
  743. /* get the geom type which is bytes 2 through 5 */
  744. memcpy(&sf_type, wkb_data + 1, 4);
  745. /* add the SRID flag if an SRID is provided */
  746. if (pg_info->srid > 0) {
  747. unsigned int srs_flag;
  748. /* change the flag to little endianess */
  749. srs_flag = LSBWORD32(WKBSRIDFLAG);
  750. /* apply the flag */
  751. sf_type = sf_type | srs_flag;
  752. }
  753. /* write the geom type which is 4 bytes */
  754. hex_data = binary_to_hex(4, (unsigned char *)&sf_type);
  755. strcpy(text_data_p, hex_data);
  756. G_free(hex_data);
  757. text_data_p += 8;
  758. /* include SRID if provided */
  759. if (pg_info->srid > 0) {
  760. unsigned int srs_id;
  761. /* force the srsid to little endianess */
  762. srs_id = LSBWORD32(pg_info->srid);
  763. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char *)&srs_id);
  764. strcpy(text_data_p, hex_data);
  765. G_free(hex_data);
  766. text_data_p += 8;
  767. }
  768. /* copy the rest of the data over - subtract 5 since we already
  769. copied 5 bytes above */
  770. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  771. strcpy(text_data_p, hex_data);
  772. G_free(hex_data);
  773. /* build INSERT statement
  774. simple feature geometry + attributes
  775. */
  776. stmt = build_insert_stmt(pg_info, text_data, cat, Fi);
  777. G_debug(2, "SQL: %s", stmt);
  778. if (!pg_info->inTransaction) {
  779. /* start transaction */
  780. pg_info->inTransaction = TRUE;
  781. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1)
  782. return -1;
  783. }
  784. /* stmt can NULL when writing PostGIS topology with no attributes
  785. * attached */
  786. if (stmt && Vect__execute_pg(pg_info->conn, stmt) == -1) {
  787. /* rollback transaction */
  788. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  789. return -1;
  790. }
  791. G_free(stmt);
  792. /* write feature in PostGIS topology schema if enabled */
  793. if (pg_info->toposchema_name) {
  794. /* insert feature into topology schema (node or edge) */
  795. if (insert_topo_element(Map, line, type, text_data) != 0) {
  796. G_warning(_("Unable to insert topological element into PostGIS Topology schema"));
  797. return -1;
  798. }
  799. /* update GRASS-like topo */
  800. if (line > 0) /* skip nodes */
  801. V2__add_line_to_topo_nat(Map, line, points[0], NULL, /* TODO: cats */
  802. delete_face);
  803. /* update PostGIS-line topo */
  804. if (type & GV_LINES)
  805. update_topo_edge(Map, line);
  806. if (type == GV_BOUNDARY)
  807. update_topo_face(Map, line);
  808. }
  809. G_free(wkb_data);
  810. G_free(text_data);
  811. return 0;
  812. }
  813. /*!
  814. \brief Build INSERT statement to add new feature to the feature
  815. table
  816. Note: Allocated string should be freed.
  817. \param pg_info pointer to Format_info_pg structure
  818. \param geom_data geometry data
  819. \param cat category number (or -1 for no category)
  820. \param Fi pointer to field_info structure (NULL for no attributes)
  821. \return allocated string with INSERT statement
  822. */
  823. char *build_insert_stmt(const struct Format_info_pg *pg_info,
  824. const char *geom_data,
  825. int cat, const struct field_info *Fi)
  826. {
  827. char *stmt, buf[DB_SQL_MAX];
  828. stmt = NULL;
  829. if (Fi && cat > -1) { /* write attributes (simple features and topology elements) */
  830. int col, ncol, more;
  831. int sqltype, ctype;
  832. char buf_val[DB_SQL_MAX], buf_tmp[DB_SQL_MAX];
  833. char *str_val;
  834. const char *colname;
  835. dbString dbstmt;
  836. dbCursor cursor;
  837. dbTable *table;
  838. dbColumn *column;
  839. dbValue *value;
  840. db_init_string(&dbstmt);
  841. buf_val[0] = '\0';
  842. /* read & set attributes */
  843. sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key,
  844. cat);
  845. G_debug(4, "SQL: %s", buf);
  846. db_set_string(&dbstmt, buf);
  847. /* prepare INSERT statement */
  848. sprintf(buf, "INSERT INTO \"%s\".\"%s\" (",
  849. pg_info->schema_name, pg_info->table_name);
  850. /* select data */
  851. if (db_open_select_cursor(pg_info->dbdriver, &dbstmt,
  852. &cursor, DB_SEQUENTIAL) != DB_OK) {
  853. G_warning(_("Unable to select attributes for category %d"), cat);
  854. }
  855. else {
  856. if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
  857. G_warning(_("Unable to fetch data from table <%s>"),
  858. Fi->table);
  859. }
  860. if (!more) {
  861. G_warning(_("No database record for category %d, "
  862. "no attributes will be written"), cat);
  863. }
  864. else {
  865. table = db_get_cursor_table(&cursor);
  866. ncol = db_get_table_number_of_columns(table);
  867. for (col = 0; col < ncol; col++) {
  868. column = db_get_table_column(table, col);
  869. colname = db_get_column_name(column);
  870. /* skip fid column */
  871. if (strcmp(pg_info->fid_column, colname) == 0)
  872. continue;
  873. /* -> columns */
  874. sprintf(buf_tmp, "%s", colname);
  875. strcat(buf, buf_tmp);
  876. if (col < ncol - 1)
  877. strcat(buf, ",");
  878. /* -> values */
  879. value = db_get_column_value(column);
  880. /* for debug only */
  881. db_convert_column_value_to_string(column, &dbstmt);
  882. G_debug(2, "col %d : val = %s", col,
  883. db_get_string(&dbstmt));
  884. sqltype = db_get_column_sqltype(column);
  885. ctype = db_sqltype_to_Ctype(sqltype);
  886. /* prevent writing NULL values */
  887. if (!db_test_value_isnull(value)) {
  888. switch (ctype) {
  889. case DB_C_TYPE_INT:
  890. sprintf(buf_tmp, "%d", db_get_value_int(value));
  891. break;
  892. case DB_C_TYPE_DOUBLE:
  893. sprintf(buf_tmp, "%.14f",
  894. db_get_value_double(value));
  895. break;
  896. case DB_C_TYPE_STRING:
  897. str_val = G_store(db_get_value_string(value));
  898. G_str_to_sql(str_val);
  899. sprintf(buf_tmp, "'%s'", str_val);
  900. G_free(str_val);
  901. break;
  902. case DB_C_TYPE_DATETIME:
  903. db_convert_column_value_to_string(column,
  904. &dbstmt);
  905. sprintf(buf_tmp, "%s", db_get_string(&dbstmt));
  906. break;
  907. default:
  908. G_warning(_("Unsupported column type %d"), ctype);
  909. sprintf(buf_tmp, "NULL");
  910. break;
  911. }
  912. }
  913. else {
  914. sprintf(buf_tmp, "NULL");
  915. }
  916. strcat(buf_val, buf_tmp);
  917. if (col < ncol - 1)
  918. strcat(buf_val, ",");
  919. }
  920. if (!pg_info->toposchema_name) {
  921. /* simple feature access */
  922. G_asprintf(&stmt, "%s,%s) VALUES (%s,'%s'::GEOMETRY)",
  923. buf, pg_info->geom_column, buf_val, geom_data);
  924. }
  925. else {
  926. /* PostGIS topology access, write geometry in
  927. * topology schema, skip geometry at this point */
  928. G_asprintf(&stmt, "%s) VALUES (%s)",
  929. buf, buf_val);
  930. }
  931. }
  932. }
  933. }
  934. else {
  935. /* no attributes */
  936. if (!pg_info->toposchema_name) {
  937. /* no attributes (simple features access) */
  938. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  939. "('%s'::GEOMETRY)",
  940. pg_info->schema_name, pg_info->table_name,
  941. pg_info->geom_column, geom_data);
  942. }
  943. else if (cat > 0)
  944. /* no attributes (topology elements) */
  945. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES (NULL)",
  946. pg_info->schema_name, pg_info->table_name,
  947. pg_info->geom_column);
  948. }
  949. return stmt;
  950. }
  951. /*!
  952. \brief Insert topological element into 'node' or 'edge' table
  953. \param Map pointer to Map_info struct
  954. \param line feature id (-1 for nodes/points)
  955. \param type feature type (GV_POINT, GV_LINE, ...)
  956. \param geom_data geometry in wkb
  957. \return 0 on success
  958. \return -1 on error
  959. */
  960. int insert_topo_element(struct Map_info *Map, int line, int type,
  961. const char *geom_data)
  962. {
  963. char *stmt;
  964. struct Format_info_pg *pg_info;
  965. struct P_line *Line;
  966. pg_info = &(Map->fInfo.pg);
  967. if (line > 0)
  968. Line = Map->plus.Line[line];
  969. stmt = NULL;
  970. switch(type) {
  971. case GV_POINT: {
  972. #if USE_TOPO_STMT
  973. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  974. pg_info->toposchema_name, geom_data);
  975. #else
  976. G_asprintf(&stmt, "INSERT INTO \"%s\".node (geom) VALUES ('%s'::GEOMETRY)",
  977. pg_info->toposchema_name, geom_data);
  978. #endif
  979. break;
  980. }
  981. case GV_LINE:
  982. case GV_BOUNDARY: {
  983. #if USE_TOPO_STMT
  984. G_asprintf(&stmt, "SELECT topology.AddEdge('%s', '%s'::GEOMETRY)",
  985. pg_info->toposchema_name, geom_data);
  986. #else
  987. int nle, nre;
  988. if (!Line) {
  989. G_warning(_("Topology not available. Unable to insert new edge."));
  990. return -1;
  991. }
  992. struct P_topo_l *topo = (struct P_topo_l *) Line->topo;
  993. /* assuming isolated lines */
  994. nle = -Line->offset;
  995. nre = Line->offset;
  996. G_debug(3, "new edge: id=%lu next_left_edge=%d next_right_edge=%d",
  997. Line->offset, nle, nre);
  998. G_asprintf(&stmt, "INSERT INTO \"%s\".edge_data (geom, start_node, end_node, "
  999. "next_left_edge, abs_next_left_edge, next_right_edge, abs_next_right_edge, "
  1000. "left_face, right_face) "
  1001. "VALUES ('%s'::GEOMETRY, %d, %d, %d, %d, %d, %d, 0, 0)",
  1002. pg_info->toposchema_name, geom_data, topo->N1, topo->N2, nle, abs(nle),
  1003. nre, abs(nre));
  1004. #endif
  1005. break;
  1006. }
  1007. case GV_CENTROID: {
  1008. #if USE_TOPO_STMT
  1009. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  1010. pg_info->toposchema_name, geom_data);
  1011. #else
  1012. if (!Line) {
  1013. G_warning(_("Topology not available. Unable to insert new node (centroid)"));
  1014. return -1;
  1015. }
  1016. struct P_topo_c *topo = (struct P_topo_c *) Line->topo;
  1017. /* get id - see write_line_tp()
  1018. sprintf(stmt_next, "SELECT nextval('\"%s\".node_node_id_seq')",
  1019. pg_info->toposchema_name);
  1020. Line->offset = Vect__execute_get_value_pg(pg_info->conn, stmt_next);
  1021. if (Line->offset < 1) {
  1022. G_warning(_("Invalid feature offset"));
  1023. return NULL;
  1024. }
  1025. */
  1026. G_asprintf(&stmt, "INSERT INTO \"%s\".node (containing_face, geom) "
  1027. "VALUES (%d, '%s'::GEOMETRY)",
  1028. pg_info->toposchema_name, topo->area, geom_data);
  1029. #endif
  1030. break;
  1031. }
  1032. default:
  1033. G_warning(_("Unsupported feature type %d"), type);
  1034. break;
  1035. }
  1036. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1037. /* rollback transaction */
  1038. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1039. return -1;
  1040. }
  1041. return 0;
  1042. }
  1043. /*!
  1044. \brief Find next line (topo only)
  1045. \param Map pointer to Map_info struct
  1046. \param nlines number of lines
  1047. \param line current line
  1048. \param[out] left left line
  1049. \param[out] right right line
  1050. \return left (line < 0) or right (line > 0) next edge
  1051. \return 0 on failure
  1052. */
  1053. int update_next_edge(struct Map_info* Map, int nlines, int line)
  1054. {
  1055. int ret, next_line, edge;
  1056. char stmt[DB_SQL_MAX];
  1057. const struct Format_info_pg *pg_info;
  1058. struct P_line *Line_next, *Line;
  1059. Line = Line_next = NULL;
  1060. pg_info = &(Map->fInfo.pg);
  1061. /* find next line
  1062. start node -> next on the left
  1063. end node -> next on the right
  1064. */
  1065. next_line = dig_angle_next_line(&(Map->plus), line, GV_LEFT, GV_LINES, NULL);
  1066. G_debug(3, "line=%d next_line=%d", line, next_line);
  1067. if (next_line == 0) {
  1068. G_warning(_("Invalid topology"));
  1069. return 0;
  1070. }
  1071. Line = Map->plus.Line[abs(line)];
  1072. Line_next = Map->plus.Line[abs(next_line)];
  1073. if (!Line || !Line_next) {
  1074. G_warning(_("Invalid topology"));
  1075. return 0;
  1076. }
  1077. if (line > 0) {
  1078. edge = Line->offset;
  1079. ret = next_line > 0 ? Line_next->offset : -Line_next->offset;
  1080. }
  1081. else {
  1082. edge = -Line->offset;
  1083. ret = next_line > 0 ? Line_next->offset : -Line_next->offset;
  1084. }
  1085. if (next_line < 0) {
  1086. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_left_edge = %d, "
  1087. "abs_next_left_edge = %d WHERE edge_id = %lu AND abs_next_left_edge = %lu",
  1088. pg_info->toposchema_name, edge, abs(edge), Line_next->offset, Line_next->offset);
  1089. G_debug(3, "update edge=%lu next_left_edge=%d (?)", Line_next->offset, edge);
  1090. }
  1091. else {
  1092. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_right_edge = %d, "
  1093. "abs_next_right_edge = %d WHERE edge_id = %lu AND abs_next_right_edge = %lu",
  1094. pg_info->toposchema_name, edge, abs(edge), Line_next->offset, Line_next->offset);
  1095. G_debug(3, "update edge=%lu next_right_edge=%d (?)", Line_next->offset, edge);
  1096. }
  1097. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1098. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1099. return 0;
  1100. }
  1101. if (nlines > 2) {
  1102. /* more lines connected to the node
  1103. start node -> next on the right
  1104. end node -> next on the left
  1105. */
  1106. next_line = dig_angle_next_line(&(Map->plus), line, GV_RIGHT, GV_LINES, NULL);
  1107. Line_next = Map->plus.Line[abs(next_line)];
  1108. if (next_line < 0) {
  1109. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_left_edge = %d, "
  1110. "abs_next_left_edge = %d WHERE edge_id = %lu",
  1111. pg_info->toposchema_name, edge, abs(edge), Line_next->offset);
  1112. G_debug(3, "update edge=%lu next_left_edge=%d", Line_next->offset, edge);
  1113. }
  1114. else {
  1115. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_right_edge = %d, "
  1116. "abs_next_right_edge = %d WHERE edge_id = %lu",
  1117. pg_info->toposchema_name, edge, abs(edge), Line_next->offset);
  1118. G_debug(3, "update edge=%lu next_right_edge=%d", Line_next->offset, edge);
  1119. }
  1120. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1121. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1122. return 0;
  1123. }
  1124. }
  1125. return ret;
  1126. }
  1127. /*!
  1128. \brief Insert new face to the 'face' table (topo only)
  1129. \param Map pointer to Map_info struct
  1130. \param area area id
  1131. \return 0 on error
  1132. \return area id on success (>0)
  1133. */
  1134. int insert_face(struct Map_info *Map, int area)
  1135. {
  1136. char *stmt;
  1137. struct Format_info_pg *pg_info;
  1138. struct bound_box box;
  1139. if (area <= 0)
  1140. return 0; /* universal face has id '0' in PostGIS Topology */
  1141. stmt = NULL;
  1142. pg_info = &(Map->fInfo.pg);
  1143. /* check if face exists */
  1144. /* get mbr of the area */
  1145. Vect_get_area_box(Map, area, &box);
  1146. /* insert face if not exists */
  1147. G_asprintf(&stmt, "INSERT INTO \"%s\".face (face_id, mbr) VALUES "
  1148. "(%d, 'POLYGON((%.12f %.12f, %.12f %.12f, %.12f %.12f, %.12f %.12f, "
  1149. "%.12f %.12f))'::GEOMETRY)", pg_info->toposchema_name, area,
  1150. box.W, box.S, box.W, box.N, box.E, box.N,
  1151. box.E, box.S, box.W, box.S);
  1152. G_debug(3, "new face id=%d", area);
  1153. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1154. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1155. return 0;
  1156. }
  1157. G_free(stmt);
  1158. return area;
  1159. }
  1160. /*!
  1161. \brief Delete existing face
  1162. \todo Set foreign keys as DEFERRABLE INITIALLY DEFERRED and use SET
  1163. CONSTRAINTS ALL DEFERRED
  1164. \param Map pointer to Map_info struct
  1165. \param area area id to delete
  1166. \return 0 on success
  1167. \return -1 on error
  1168. */
  1169. int delete_face(const struct Map_info *Map, int area)
  1170. {
  1171. char stmt[DB_SQL_MAX];
  1172. const struct Format_info_pg *pg_info;
  1173. pg_info = &(Map->fInfo.pg);
  1174. /* update centroids first */
  1175. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = 0 "
  1176. "WHERE containing_face = %d",
  1177. pg_info->toposchema_name, area);
  1178. G_debug(3, "SQL: %s", stmt);
  1179. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1180. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1181. return -1;
  1182. }
  1183. /* update also edges (left face) */
  1184. sprintf(stmt, "UPDATE \"%s\".edge_data SET left_face = 0 "
  1185. "WHERE left_face = %d",
  1186. pg_info->toposchema_name, area);
  1187. G_debug(3, "SQL: %s", stmt);
  1188. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1189. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1190. return -1;
  1191. }
  1192. /* update also edges (left face) */
  1193. sprintf(stmt, "UPDATE \"%s\".edge_data SET right_face = 0 "
  1194. "WHERE right_face = %d",
  1195. pg_info->toposchema_name, area);
  1196. G_debug(3, "SQL: %s", stmt);
  1197. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1198. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1199. return -1;
  1200. }
  1201. /* delete face */
  1202. sprintf(stmt, "DELETE FROM \"%s\".face WHERE face_id = %d",
  1203. pg_info->toposchema_name, area);
  1204. G_debug(3, "delete face id=%d", area);
  1205. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1206. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1207. return -1;
  1208. }
  1209. return 0;
  1210. }
  1211. /*!
  1212. \brief Update lines (next left and right edges)
  1213. - isolated edges
  1214. next left edge: -edge
  1215. next right edge: edge
  1216. - connected edges
  1217. next left edge: next edge or -edge
  1218. next right edge: next edge or edge
  1219. \param Map pointer to Map_info struct
  1220. \param line feature id
  1221. \return 0 on success
  1222. \return -1 on error
  1223. */
  1224. int update_topo_edge(struct Map_info *Map, int line)
  1225. {
  1226. int i, n;
  1227. int nle, nre, next_edge;
  1228. char stmt[DB_SQL_MAX];
  1229. struct Format_info_pg *pg_info;
  1230. struct P_line *Line;
  1231. pg_info = &(Map->fInfo.pg);
  1232. if (line < 1 || line > Vect_get_num_lines(Map)) {
  1233. G_warning(_("Inconsistency in topology: invalid feature id"));
  1234. return -1;
  1235. }
  1236. Line = Map->plus.Line[line];
  1237. if (!Line) {
  1238. G_warning(_("Inconsistency in topology: dead line found"));
  1239. return -1;
  1240. }
  1241. struct P_topo_l *topo = (struct P_topo_l *) Line->topo;
  1242. nre = nle = 0; /* edge = 0 is an illegal value */
  1243. /* check for line connection */
  1244. for (i = 0; i < 2; i++) {
  1245. /* first check start node then end node */
  1246. n = i == 0 ? Vect_get_node_n_lines(Map, topo->N1)
  1247. : Vect_get_node_n_lines(Map, topo->N2);
  1248. if (n < 2) /* no connection */
  1249. continue;
  1250. next_edge = update_next_edge(Map, n,
  1251. i == 0 ? line : -line);
  1252. if (next_edge != 0) {
  1253. if (i == 0)
  1254. nre = next_edge; /* update next right edge for start node */
  1255. else
  1256. nle = next_edge; /* update next left edge for end node */
  1257. }
  1258. else {
  1259. G_warning(_("Inconsistency in topology detected: "
  1260. "unable to determine next left/right edge."));
  1261. return -1;
  1262. }
  1263. }
  1264. if (nle == 0 && nre == 0) /* nothing changed */
  1265. return 0;
  1266. if (nle != 0 && nre != 0) {
  1267. /* update both next left and right edge */
  1268. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1269. "next_left_edge = %d, abs_next_left_edge = %d, "
  1270. "next_right_edge = %d, abs_next_right_edge = %d "
  1271. "WHERE edge_id = %lu", pg_info->toposchema_name,
  1272. nle, abs(nle), nre, abs(nre), Line->offset);
  1273. }
  1274. else if (nle != 0) {
  1275. /* update next left edge only */
  1276. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1277. "next_left_edge = %d, abs_next_left_edge = %d "
  1278. "WHERE edge_id = %lu", pg_info->toposchema_name,
  1279. nle, abs(nle), Line->offset);
  1280. }
  1281. else {
  1282. /* update next right edge only */
  1283. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1284. "next_right_edge = %d, abs_next_right_edge = %d "
  1285. "WHERE edge_id = %lu", pg_info->toposchema_name,
  1286. nre, abs(nre), Line->offset);
  1287. }
  1288. G_debug(3, "update edge=%lu next_left_edge=%d next_right_edge=%d",
  1289. Line->offset, nle, nre);
  1290. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1291. /* rollback transaction */
  1292. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1293. return -1;
  1294. }
  1295. return 0;
  1296. }
  1297. /*!
  1298. \brief Update lines (left and right faces)
  1299. TODO: handle isles
  1300. \param Map pointer to Map_info struct
  1301. \param line feature id
  1302. \return 0 on success
  1303. \return -1 on error
  1304. */
  1305. int update_topo_face(struct Map_info *Map, int line)
  1306. {
  1307. int i, s, area, face[2];
  1308. char stmt[DB_SQL_MAX];
  1309. struct Format_info_pg *pg_info;
  1310. struct P_line *Line, *Line_i;
  1311. struct P_area *Area;
  1312. struct P_topo_b *topo, *topo_i;
  1313. pg_info = &(Map->fInfo.pg);
  1314. if (line < 1 || line > Vect_get_num_lines(Map)) {
  1315. G_warning(_("Inconsistency in topology detected: invalid feature id"));
  1316. return -1;
  1317. }
  1318. Line = Map->plus.Line[line];
  1319. if (!Line) {
  1320. G_warning(_("Inconsistency in topology detected: dead line found"));
  1321. return -1;
  1322. }
  1323. topo = (struct P_topo_b *)Line->topo;
  1324. /* for both side on the current boundary (line) */
  1325. /* create new faces */
  1326. for (s = 0; s < 2; s++) { /* for each side */
  1327. area = s == 0 ? topo->left : topo->right;
  1328. if (area <= 0) /* no area - skip */
  1329. continue;
  1330. face[s] = insert_face(Map, area);
  1331. if (face[s] < 1) {
  1332. G_warning(_("Unable to create new face"));
  1333. return -1;
  1334. }
  1335. }
  1336. /* update edges forming faces */
  1337. for (s = 0; s < 2; s++) { /* for each side */
  1338. area = s == 0 ? topo->left : topo->right;
  1339. if (area <= 0) /* no area - skip */
  1340. continue;
  1341. Area = Map->plus.Area[area];
  1342. for (i = 0; i < Area->n_lines; i++) {
  1343. Line_i = Map->plus.Line[abs(Area->lines[i])];
  1344. topo_i = (struct P_topo_b *)Line_i->topo;
  1345. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1346. "left_face = %d, right_face = %d "
  1347. "WHERE edge_id = %lu", pg_info->toposchema_name,
  1348. topo_i->left > 0 ? topo_i->left : 0,
  1349. topo_i->right > 0 ? topo_i->right : 0,
  1350. Line_i->offset);
  1351. G_debug(2, "SQL: %s", stmt);
  1352. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1353. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1354. return -1;
  1355. }
  1356. }
  1357. /* update also centroids (stored as nodes) */
  1358. if (Area->centroid > 0) {
  1359. Line_i = Map->plus.Line[Area->centroid];
  1360. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = %d "
  1361. "WHERE node_id = %lu", pg_info->toposchema_name,
  1362. face[s], Line_i->offset);
  1363. G_debug(2, "SQL: %s", stmt);
  1364. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1365. /* rollback transaction */
  1366. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1367. return -1;
  1368. }
  1369. }
  1370. }
  1371. return 0;
  1372. }
  1373. #endif