write_pg.c 51 KB

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