write_pg.c 47 KB

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