write_pg.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. 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. #ifdef HAVE_POSTGRES
  20. #include "pg_local_proto.h"
  21. #define WKBSRIDFLAG 0x20000000
  22. static off_t write_line_sf(struct Map_info *, int,
  23. const struct line_pnts **, int,
  24. const struct line_cats *);
  25. static off_t write_line_tp(struct Map_info *, int,
  26. const struct line_pnts *);
  27. static char *binary_to_hex(int, const unsigned char *);
  28. static unsigned char *point_to_wkb(int, const struct line_pnts *, int, int *);
  29. static unsigned char *linestring_to_wkb(int, const struct line_pnts *,
  30. int, int *);
  31. static unsigned char *polygon_to_wkb(int, const struct line_pnts **, int,
  32. int, int *);
  33. static int write_feature(struct Format_info_pg *,
  34. int, const struct line_pnts **, int, int,
  35. int, const struct field_info *);
  36. static char *build_insert_stmt(const struct Format_info_pg *, const char *,
  37. int, const struct field_info *);
  38. static char *build_topo_stmt(const struct Format_info_pg *, int,
  39. const struct P_line *, const char *);
  40. static char *build_topogeom_stmt(const struct Format_info_pg *, int, int, int);
  41. static int execute_topo(PGconn *, const char *);
  42. #endif
  43. /*!
  44. \brief Writes feature on level 1 (PostGIS interface)
  45. Note:
  46. - centroids are not supported in PostGIS, pseudotopo holds virtual
  47. centroids
  48. - boundaries are not supported in PostGIS, pseudotopo treats polygons
  49. as boundaries
  50. \param Map pointer to Map_info structure
  51. \param type feature type (GV_POINT, GV_LINE, ...)
  52. \param points pointer to line_pnts structure (feature geometry)
  53. \param cats pointer to line_cats structure (feature categories)
  54. \return feature offset into file
  55. \return -1 on error
  56. */
  57. off_t V1_write_line_pg(struct Map_info *Map, int type,
  58. const struct line_pnts *points,
  59. const struct line_cats *cats)
  60. {
  61. #ifdef HAVE_POSTGRES
  62. if (!Map->fInfo.pg.toposchema_name)
  63. return write_line_sf(Map, type, &points, 1, cats);
  64. else
  65. return write_line_tp(Map, type, points);
  66. #else
  67. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  68. return -1;
  69. #endif
  70. }
  71. /*!
  72. \brief Rewrites feature at the given offset (level 1) (PostGIS interface)
  73. \param Map pointer to Map_info structure
  74. \param offset feature offset
  75. \param type feature type (GV_POINT, GV_LINE, ...)
  76. \param points feature geometry
  77. \param cats feature categories
  78. \return feature offset (rewriten feature)
  79. \return -1 on error
  80. */
  81. off_t V1_rewrite_line_pg(struct Map_info * Map,
  82. int line, int type, off_t offset,
  83. const struct line_pnts * points,
  84. const struct line_cats * cats)
  85. {
  86. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%lu",
  87. line, type, offset);
  88. #ifdef HAVE_POSTGRES
  89. if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
  90. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  91. return -1;
  92. }
  93. /* delete old */
  94. V1_delete_line_pg(Map, offset);
  95. return V1_write_line_pg(Map, type, points, cats);
  96. #else
  97. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  98. return -1;
  99. #endif
  100. }
  101. /*!
  102. \brief Deletes feature at the given offset (level 1)
  103. \param Map pointer Map_info structure
  104. \param offset feature offset
  105. \return 0 on success
  106. \return -1 on error
  107. */
  108. int V1_delete_line_pg(struct Map_info *Map, off_t offset)
  109. {
  110. #ifdef HAVE_POSTGRES
  111. long fid;
  112. char stmt[DB_SQL_MAX];
  113. struct Format_info_pg *pg_info;
  114. pg_info = &(Map->fInfo.pg);
  115. if (!pg_info->conn || !pg_info->table_name) {
  116. G_warning(_("No connection defined"));
  117. return -1;
  118. }
  119. if (offset >= pg_info->offset.array_num) {
  120. G_warning(_("Invalid offset (%d)"), offset);
  121. return -1;
  122. }
  123. fid = pg_info->offset.array[offset];
  124. G_debug(3, "V1_delete_line_pg(), offset = %lu -> fid = %ld",
  125. (unsigned long)offset, fid);
  126. if (!pg_info->inTransaction) {
  127. /* start transaction */
  128. pg_info->inTransaction = TRUE;
  129. if (execute(pg_info->conn, "BEGIN") == -1)
  130. return -1;
  131. }
  132. sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
  133. pg_info->table_name, pg_info->fid_column, fid);
  134. G_debug(2, "SQL: %s", stmt);
  135. if (execute(pg_info->conn, stmt) == -1) {
  136. G_warning(_("Unable to delete feature"));
  137. execute(pg_info->conn, "ROLLBACK");
  138. return -1;
  139. }
  140. return 0;
  141. #else
  142. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  143. return -1;
  144. #endif
  145. }
  146. /*!
  147. \brief Writes area on level 2 (PostGIS interface)
  148. \param Map pointer to Map_info structure
  149. \param type feature type (GV_POINT, GV_LINE, ...)
  150. \param points pointer to line_pnts structure (boundary geometry)
  151. \param cats pointer to line_cats structure (feature categories)
  152. \param ipoints pointer to line_pnts structure (isles geometry)
  153. \param nisles number of isles
  154. \return feature offset into file
  155. \return -1 on error
  156. */
  157. off_t V2_write_area_pg(struct Map_info *Map,
  158. const struct line_pnts *bpoints,
  159. const struct line_cats *cats,
  160. const struct line_pnts **ipoints, int nisles)
  161. {
  162. #ifdef HAVE_POSTGRES
  163. int i;
  164. off_t ret;
  165. const struct line_pnts **points;
  166. if (nisles > 0) {
  167. points = (const struct line_pnts **) G_calloc(nisles + 1, sizeof(struct line_pnts *));
  168. points[0] = bpoints;
  169. for (i = 0; i < nisles; i++)
  170. points[i + 1] = ipoints[i];
  171. }
  172. else {
  173. points = &bpoints;
  174. }
  175. ret = write_line_sf(Map, GV_BOUNDARY, points, nisles + 1, cats);
  176. if (nisles > 0)
  177. G_free(points);
  178. return ret;
  179. #else
  180. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  181. return -1;
  182. #endif
  183. }
  184. #ifdef HAVE_POSTGRES
  185. off_t write_line_sf(struct Map_info *Map, int type,
  186. const struct line_pnts **points, int nparts,
  187. const struct line_cats *cats)
  188. {
  189. int cat;
  190. off_t offset;
  191. SF_FeatureType sf_type;
  192. struct field_info *Fi;
  193. struct Format_info_pg *pg_info;
  194. struct Format_info_offset *offset_info;
  195. pg_info = &(Map->fInfo.pg);
  196. offset_info = &(pg_info->offset);
  197. if (!pg_info->conn) {
  198. G_warning(_("No connection defined"));
  199. return -1;
  200. }
  201. if (!pg_info->table_name) {
  202. G_warning(_("PostGIS feature table not defined"));
  203. return -1;
  204. }
  205. if (pg_info->feature_type == SF_UNKNOWN) {
  206. /* create PostGIS table if doesn't exist */
  207. if (V2_open_new_pg(Map, type) < 0)
  208. return -1;
  209. }
  210. Fi = NULL; /* no attributes to be written */
  211. cat = -1;
  212. if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) {
  213. /* check for attributes */
  214. Fi = Vect_get_dblink(Map, 0);
  215. if (Fi) {
  216. if (!Vect_cat_get(cats, Fi->number, &cat))
  217. G_warning(_("No category defined for layer %d"), Fi->number);
  218. if (cats->n_cats > 1) {
  219. G_warning(_("Feature has more categories, using "
  220. "category %d (from layer %d)"),
  221. cat, cats->field[0]);
  222. }
  223. }
  224. }
  225. sf_type = pg_info->feature_type;
  226. /* determine matching PostGIS feature geometry type */
  227. if (type & (GV_POINT | GV_KERNEL)) {
  228. if (sf_type != SF_POINT && sf_type != SF_POINT25D) {
  229. G_warning(_("Feature is not a point. Skipping."));
  230. return -1;
  231. }
  232. }
  233. else if (type & GV_LINE) {
  234. if (sf_type != SF_LINESTRING && sf_type != SF_LINESTRING25D) {
  235. G_warning(_("Feature is not a line. Skipping."));
  236. return -1;
  237. }
  238. }
  239. else if (type & GV_BOUNDARY || type & GV_CENTROID) {
  240. if (sf_type != SF_POLYGON) {
  241. G_warning(_("Feature is not a polygon. Skipping."));
  242. return -1;
  243. }
  244. }
  245. else if (type & GV_FACE) {
  246. if (sf_type != SF_POLYGON25D) {
  247. G_warning(_("Feature is not a face. Skipping."));
  248. return -1;
  249. }
  250. }
  251. else {
  252. G_warning(_("Unsupported feature type (%d)"), type);
  253. return -1;
  254. }
  255. G_debug(3, "write_line_sf(): type = %d n_points = %d cat = %d",
  256. type, points[0]->n_points, cat);
  257. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  258. /* skip this check when writing PostGIS topology */
  259. int part, npoints;
  260. for (part = 0; part < nparts; part++) {
  261. npoints = points[part]->n_points - 1;
  262. if (points[part]->x[0] != points[part]->x[npoints] ||
  263. points[part]->y[0] != points[part]->y[npoints] ||
  264. points[part]->z[0] != points[part]->z[npoints]) {
  265. G_warning(_("Boundary is not closed. Skipping."));
  266. return -1;
  267. }
  268. }
  269. }
  270. /* write feature's geometry and fid */
  271. if (-1 == write_feature(pg_info, type, points, nparts,
  272. Vect_is_3d(Map) ? WITH_Z : WITHOUT_Z, cat, Fi)) {
  273. execute(pg_info->conn, "ROLLBACK");
  274. return -1;
  275. }
  276. /* update offset array */
  277. if (offset_info->array_num >= offset_info->array_alloc) {
  278. offset_info->array_alloc += 1000;
  279. offset_info->array = (int *)G_realloc(offset_info->array,
  280. offset_info->array_alloc *
  281. sizeof(int));
  282. }
  283. offset = offset_info->array_num;
  284. offset_info->array[offset_info->array_num++] = cat;
  285. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  286. /* register first part in offset array */
  287. offset_info->array[offset_info->array_num++] = 0;
  288. }
  289. G_debug(3, "write_line_sf(): -> offset = %lu offset_num = %d cat = %d",
  290. (unsigned long)offset, offset_info->array_num, cat);
  291. return offset;
  292. }
  293. off_t write_line_tp(struct Map_info *Map, int type,
  294. const struct line_pnts *points)
  295. {
  296. struct Format_info_pg *pg_info;
  297. pg_info = &(Map->fInfo.pg);
  298. if (!pg_info->conn) {
  299. G_warning(_("No connection defined"));
  300. return -1;
  301. }
  302. if (!pg_info->table_name) {
  303. G_warning(_("PostGIS feature table not defined"));
  304. return -1;
  305. }
  306. if (pg_info->feature_type == SF_UNKNOWN) {
  307. /* create PostGIS table if doesn't exist */
  308. if (V2_open_new_pg(Map, type) < 0)
  309. return -1;
  310. }
  311. G_debug(3, "write_line_pg(): type = %d n_points = %d",
  312. type, points->n_points);
  313. /* write feature's geometry and fid */
  314. if (-1 == write_feature(pg_info, type, &points, 1,
  315. Vect_is_3d(Map) ? WITH_Z : WITHOUT_Z, -1, NULL)) {
  316. execute(pg_info->conn, "ROLLBACK");
  317. return -1;
  318. }
  319. return 0;
  320. }
  321. /*!
  322. \brief Binary data to HEX
  323. Allocated buffer should be freed by G_free().
  324. \param nbytes number of bytes to allocate
  325. \param wkb_data WKB data
  326. \return allocated buffer with HEX data
  327. */
  328. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  329. {
  330. char *hex_data;
  331. int i, nlow, nhigh;
  332. static const char ach_hex[] = "0123456789ABCDEF";
  333. hex_data = (char *)G_malloc(nbytes * 2 + 1);
  334. hex_data[nbytes * 2] = '\0';
  335. for (i = 0; i < nbytes; i++) {
  336. nlow = wkb_data[i] & 0x0f;
  337. nhigh = (wkb_data[i] & 0xf0) >> 4;
  338. hex_data[i * 2] = ach_hex[nhigh];
  339. hex_data[i * 2 + 1] = ach_hex[nlow];
  340. }
  341. return hex_data;
  342. }
  343. /*!
  344. \bried Write point into WKB buffer
  345. See OGRPoint::exportToWkb from GDAL/OGR library
  346. \param byte_order byte order (ENDIAN_LITTLE or BIG_ENDIAN)
  347. \param points feature geometry
  348. \param with_z WITH_Z for 3D data
  349. \param[out] nsize buffer size
  350. \return allocated WKB buffer
  351. \return NULL on error
  352. */
  353. unsigned char *point_to_wkb(int byte_order,
  354. const struct line_pnts *points, int with_z,
  355. int *nsize)
  356. {
  357. unsigned char *wkb_data;
  358. unsigned int sf_type;
  359. if (points->n_points != 1)
  360. return NULL;
  361. /* allocate buffer */
  362. *nsize = with_z ? 29 : 21;
  363. wkb_data = G_malloc(*nsize);
  364. G_zero(wkb_data, *nsize);
  365. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  366. /* set the byte order */
  367. if (byte_order == ENDIAN_LITTLE)
  368. wkb_data[0] = '\001';
  369. else
  370. wkb_data[0] = '\000';
  371. /* set the geometry feature type */
  372. sf_type = with_z ? SF_POINT25D : SF_POINT;
  373. if (byte_order == ENDIAN_LITTLE)
  374. sf_type = LSBWORD32(sf_type);
  375. else
  376. sf_type = MSBWORD32(sf_type);
  377. memcpy(wkb_data + 1, &sf_type, 4);
  378. /* copy in the raw data */
  379. memcpy(wkb_data + 5, &(points->x[0]), 8);
  380. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  381. if (with_z) {
  382. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  383. }
  384. /* swap if needed */
  385. if (byte_order == ENDIAN_BIG) {
  386. SWAPDOUBLE(wkb_data + 5);
  387. SWAPDOUBLE(wkb_data + 5 + 8);
  388. if (with_z)
  389. SWAPDOUBLE(wkb_data + 5 + 16);
  390. }
  391. return wkb_data;
  392. }
  393. /*!
  394. \bried Write linestring into WKB buffer
  395. See OGRLineString::exportToWkb from GDAL/OGR library
  396. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  397. \param points feature geometry
  398. \param with_z WITH_Z for 3D data
  399. \param[out] nsize buffer size
  400. \return allocated WKB buffer
  401. \return NULL on error
  402. */
  403. unsigned char *linestring_to_wkb(int byte_order,
  404. const struct line_pnts *points, int with_z,
  405. int *nsize)
  406. {
  407. int i, point_size;
  408. unsigned char *wkb_data;
  409. unsigned int sf_type;
  410. if (points->n_points < 1)
  411. return NULL;
  412. /* allocate buffer */
  413. point_size = 8 * (with_z ? 3 : 2);
  414. *nsize = 5 + 4 + points->n_points * point_size;
  415. wkb_data = G_malloc(*nsize);
  416. G_zero(wkb_data, *nsize);
  417. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  418. /* set the byte order */
  419. if (byte_order == ENDIAN_LITTLE)
  420. wkb_data[0] = '\001';
  421. else
  422. wkb_data[0] = '\000';
  423. /* set the geometry feature type */
  424. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  425. if (byte_order == ENDIAN_LITTLE)
  426. sf_type = LSBWORD32(sf_type);
  427. else
  428. sf_type = MSBWORD32(sf_type);
  429. memcpy(wkb_data + 1, &sf_type, 4);
  430. /* copy in the data count */
  431. memcpy(wkb_data + 5, &(points->n_points), 4);
  432. /* copy in the raw data */
  433. for (i = 0; i < points->n_points; i++) {
  434. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  435. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  436. if (with_z) {
  437. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  438. }
  439. }
  440. /* swap if needed */
  441. if (byte_order == ENDIAN_BIG) {
  442. int npoints, nitems;
  443. npoints = SWAP32(points->n_points);
  444. memcpy(wkb_data + 5, &npoints, 4);
  445. nitems = (with_z ? 3 : 2) * points->n_points;
  446. for (i = 0; i < nitems; i++) {
  447. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  448. }
  449. }
  450. return wkb_data;
  451. }
  452. /*!
  453. \bried Write polygon into WKB buffer
  454. See OGRPolygon::exportToWkb from GDAL/OGR library
  455. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  456. \param ipoints list of ring geometries (first is outer ring)
  457. \param nrings number of rings
  458. \param with_z WITH_Z for 3D data
  459. \param[out] nsize buffer size
  460. \return allocated WKB buffer
  461. \return NULL on error
  462. */
  463. unsigned char *polygon_to_wkb(int byte_order,
  464. const struct line_pnts** points, int nrings,
  465. int with_z, int *nsize)
  466. {
  467. int i, ring, point_size, offset;
  468. unsigned char *wkb_data;
  469. unsigned int sf_type;
  470. /* check data validity */
  471. if (nrings < 1)
  472. return NULL;
  473. for (ring = 0; ring < nrings; ring++) {
  474. if (points[ring]->n_points < 3)
  475. return NULL;
  476. }
  477. /* allocate buffer */
  478. point_size = 8 * (with_z ? 3 : 2);
  479. *nsize = 9;
  480. for (ring = 0; ring < nrings; ring++)
  481. *nsize += 4 + point_size * points[ring]->n_points;
  482. wkb_data = G_malloc(*nsize);
  483. G_zero(wkb_data, *nsize);
  484. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  485. /* set the byte order */
  486. if (byte_order == ENDIAN_LITTLE)
  487. wkb_data[0] = '\001';
  488. else
  489. wkb_data[0] = '\000';
  490. /* set the geometry feature type */
  491. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  492. if (byte_order == ENDIAN_LITTLE)
  493. sf_type = LSBWORD32(sf_type);
  494. else
  495. sf_type = MSBWORD32(sf_type);
  496. memcpy(wkb_data + 1, &sf_type, 4);
  497. /* copy in the raw data */
  498. if (byte_order == ENDIAN_BIG) {
  499. int ncount;
  500. ncount = SWAP32(nrings);
  501. memcpy(wkb_data + 5, &ncount, 4);
  502. }
  503. else {
  504. memcpy(wkb_data + 5, &nrings, 4);
  505. }
  506. /* serialize rings */
  507. offset = 9;
  508. for (ring = 0; ring < nrings; ring++) {
  509. memcpy(wkb_data + offset, &(points[ring]->n_points), 4);
  510. for (i = 0; i < points[ring]->n_points; i++) {
  511. memcpy(wkb_data + offset +
  512. 4 + point_size * i, &(points[ring]->x[i]), 8);
  513. memcpy(wkb_data + offset +
  514. 4 + 8 + point_size * i, &(points[ring]->y[i]), 8);
  515. if (with_z) {
  516. memcpy(wkb_data + offset +
  517. 4 + 16 + point_size * i, &(points[ring]->z[i]), 8);
  518. }
  519. }
  520. offset += 4 + point_size * points[ring]->n_points;
  521. /* swap if needed */
  522. if (byte_order == ENDIAN_BIG) {
  523. int npoints, nitems;
  524. npoints = SWAP32(points[ring]->n_points);
  525. memcpy(wkb_data + 5, &npoints, 4);
  526. nitems = (with_z ? 3 : 2) * points[ring]->n_points;
  527. for (i = 0; i < nitems; i++) {
  528. SWAPDOUBLE(wkb_data + offset + 4 + 8 * i);
  529. }
  530. }
  531. }
  532. return wkb_data;
  533. }
  534. /*!
  535. \brief Insert feature into table
  536. \param pg_info pointer to Format_info_pg struct
  537. \param type feature type (GV_POINT, GV_LINE, ...)
  538. \param points pointer to line_pnts struct
  539. \param nparts number of parts (rings for polygon)
  540. \param with_z WITH_Z for 3D data
  541. \param cat category number (-1 for no category)
  542. \param Fi pointer to field_info (attributes to copy, NULL for no attributes)
  543. \return -1 on error
  544. \retirn 0 on success
  545. */
  546. int write_feature(struct Format_info_pg *pg_info, int type,
  547. const struct line_pnts **points, int nparts,
  548. int with_z, int cat, const struct field_info *Fi)
  549. {
  550. int byte_order, nbytes, nsize;
  551. unsigned int sf_type;
  552. unsigned char *wkb_data;
  553. char *stmt, *text_data, *text_data_p, *hex_data;
  554. if (with_z && pg_info->coor_dim != 3) {
  555. G_warning(_("Trying to insert 3D data into feature table "
  556. "which store 2D data only"));
  557. return -1;
  558. }
  559. if (!with_z && pg_info->coor_dim != 2) {
  560. G_warning(_("Trying to insert 2D data into feature table "
  561. "which store 3D data only"));
  562. return -1;
  563. }
  564. byte_order = dig__byte_order_out();
  565. /* get wkb data */
  566. nbytes = -1;
  567. wkb_data = NULL;
  568. if (type == GV_POINT || type == GV_CENTROID)
  569. wkb_data = point_to_wkb(byte_order, points[0], with_z, &nbytes);
  570. else if (type == GV_LINE)
  571. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  572. else if (type == GV_BOUNDARY) {
  573. if (!pg_info->toposchema_name) {
  574. /* PostGIS simple feature access */
  575. wkb_data = polygon_to_wkb(byte_order, points, nparts,
  576. with_z, &nbytes);
  577. }
  578. else {
  579. /* PostGIS topology access */
  580. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  581. }
  582. }
  583. if (!wkb_data || nbytes < 1) {
  584. G_warning(_("Unsupported feature type %d"), type);
  585. return -1;
  586. }
  587. /* When converting to hex, each byte takes 2 hex characters. In
  588. addition we add in 8 characters to represent the SRID integer
  589. in hex, and one for a null terminator */
  590. nsize = nbytes * 2 + 8 + 1;
  591. text_data = text_data_p = (char *)G_malloc(nsize);
  592. /* convert the 1st byte, which is the endianess flag, to hex */
  593. hex_data = binary_to_hex(1, wkb_data);
  594. strcpy(text_data_p, hex_data);
  595. G_free(hex_data);
  596. text_data_p += 2;
  597. /* get the geom type which is bytes 2 through 5 */
  598. memcpy(&sf_type, wkb_data + 1, 4);
  599. /* add the SRID flag if an SRID is provided */
  600. if (pg_info->srid > 0) {
  601. unsigned int srs_flag;
  602. /* change the flag to little endianess */
  603. srs_flag = LSBWORD32(WKBSRIDFLAG);
  604. /* apply the flag */
  605. sf_type = sf_type | srs_flag;
  606. }
  607. /* write the geom type which is 4 bytes */
  608. hex_data = binary_to_hex(4, (unsigned char *)&sf_type);
  609. strcpy(text_data_p, hex_data);
  610. G_free(hex_data);
  611. text_data_p += 8;
  612. /* include SRID if provided */
  613. if (pg_info->srid > 0) {
  614. unsigned int srs_id;
  615. /* force the srsid to little endianess */
  616. srs_id = LSBWORD32(pg_info->srid);
  617. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char *)&srs_id);
  618. strcpy(text_data_p, hex_data);
  619. G_free(hex_data);
  620. text_data_p += 8;
  621. }
  622. /* copy the rest of the data over - subtract 5 since we already
  623. copied 5 bytes above */
  624. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  625. strcpy(text_data_p, hex_data);
  626. G_free(hex_data);
  627. /* build INSERT statement
  628. simple feature geometry + attributes
  629. */
  630. stmt = build_insert_stmt(pg_info, text_data, cat, Fi);
  631. G_debug(2, "SQL: %s", stmt);
  632. if (!pg_info->inTransaction) {
  633. /* start transaction */
  634. pg_info->inTransaction = TRUE;
  635. if (execute(pg_info->conn, "BEGIN") == -1)
  636. return -1;
  637. }
  638. /* stmt can NULL when writing PostGIS topology with no attributes
  639. * attached */
  640. if (stmt && execute(pg_info->conn, stmt) == -1) {
  641. /* rollback transaction */
  642. execute(pg_info->conn, "ROLLBACK");
  643. return -1;
  644. }
  645. G_free(stmt);
  646. /* write feature in PostGIS topology schema if enabled */
  647. if (pg_info->toposchema_name) {
  648. int id, do_update;
  649. do_update = stmt ? TRUE : FALSE; /* update or insert new record
  650. to the feature table */
  651. /* insert feature into topology schema (node or edge) */
  652. stmt = build_topo_stmt(pg_info, type, NULL, text_data);
  653. id = execute_topo(pg_info->conn, stmt);
  654. if (id == -1) {
  655. /* rollback transaction */
  656. execute(pg_info->conn, "ROLLBACK");
  657. return -1;
  658. }
  659. G_free(stmt);
  660. /* insert topoelement into feature table) */
  661. stmt = build_topogeom_stmt(pg_info, id, type, do_update);
  662. if (execute(pg_info->conn, stmt) == -1) {
  663. execute(pg_info->conn, "ROLLBACK");
  664. return -1;
  665. }
  666. G_free(stmt);
  667. }
  668. G_free(wkb_data);
  669. G_free(text_data);
  670. return 0;
  671. }
  672. /*!
  673. \brief Build INSERT statement to insert new feature to the table
  674. \param pg_info pointer to Format_info_pg structure
  675. \param cat category number (or -1 for no category)
  676. \param Fi pointer to field_info structure (NULL for no attributes)
  677. \return allocated string with INSERT statement
  678. */
  679. char *build_insert_stmt(const struct Format_info_pg *pg_info,
  680. const char *geom_data,
  681. int cat, const struct field_info *Fi)
  682. {
  683. char *stmt, buf[DB_SQL_MAX];
  684. stmt = NULL;
  685. if (Fi && cat > -1) {
  686. int col, ncol, more;
  687. int sqltype, ctype;
  688. char buf_val[DB_SQL_MAX], buf_tmp[DB_SQL_MAX];
  689. char *str_val;
  690. const char *colname;
  691. dbString dbstmt;
  692. dbCursor cursor;
  693. dbTable *table;
  694. dbColumn *column;
  695. dbValue *value;
  696. db_init_string(&dbstmt);
  697. buf_val[0] = '\0';
  698. /* read & set attributes */
  699. sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key,
  700. cat);
  701. G_debug(4, "SQL: %s", buf);
  702. db_set_string(&dbstmt, buf);
  703. /* prepare INSERT statement */
  704. sprintf(buf, "INSERT INTO \"%s\".\"%s\" (",
  705. pg_info->schema_name, pg_info->table_name);
  706. /* select data */
  707. if (db_open_select_cursor(pg_info->dbdriver, &dbstmt,
  708. &cursor, DB_SEQUENTIAL) != DB_OK) {
  709. G_warning(_("Unable to select attributes for category %d"), cat);
  710. }
  711. else {
  712. if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
  713. G_warning(_("Unable to fetch data from table <%s>"),
  714. Fi->table);
  715. }
  716. if (!more) {
  717. G_warning(_("No database record for category %d, "
  718. "no attributes will be written"), cat);
  719. }
  720. else {
  721. table = db_get_cursor_table(&cursor);
  722. ncol = db_get_table_number_of_columns(table);
  723. for (col = 0; col < ncol; col++) {
  724. column = db_get_table_column(table, col);
  725. colname = db_get_column_name(column);
  726. /* skip fid column */
  727. if (strcmp(pg_info->fid_column, colname) == 0)
  728. continue;
  729. /* -> columns */
  730. sprintf(buf_tmp, "%s", colname);
  731. strcat(buf, buf_tmp);
  732. if (col < ncol - 1)
  733. strcat(buf, ",");
  734. /* -> values */
  735. value = db_get_column_value(column);
  736. /* for debug only */
  737. db_convert_column_value_to_string(column, &dbstmt);
  738. G_debug(2, "col %d : val = %s", col,
  739. db_get_string(&dbstmt));
  740. sqltype = db_get_column_sqltype(column);
  741. ctype = db_sqltype_to_Ctype(sqltype);
  742. /* prevent writing NULL values */
  743. if (!db_test_value_isnull(value)) {
  744. switch (ctype) {
  745. case DB_C_TYPE_INT:
  746. sprintf(buf_tmp, "%d", db_get_value_int(value));
  747. break;
  748. case DB_C_TYPE_DOUBLE:
  749. sprintf(buf_tmp, "%.14f",
  750. db_get_value_double(value));
  751. break;
  752. case DB_C_TYPE_STRING:
  753. str_val = G_store(db_get_value_string(value));
  754. G_str_to_sql(str_val);
  755. sprintf(buf_tmp, "'%s'", str_val);
  756. G_free(str_val);
  757. break;
  758. case DB_C_TYPE_DATETIME:
  759. db_convert_column_value_to_string(column,
  760. &dbstmt);
  761. sprintf(buf_tmp, "%s", db_get_string(&dbstmt));
  762. break;
  763. default:
  764. G_warning(_("Unsupported column type %d"), ctype);
  765. sprintf(buf_tmp, "NULL");
  766. break;
  767. }
  768. }
  769. else {
  770. sprintf(buf_tmp, "NULL");
  771. }
  772. strcat(buf_val, buf_tmp);
  773. if (col < ncol - 1)
  774. strcat(buf_val, ",");
  775. }
  776. if (!pg_info->toposchema_name) {
  777. /* simple feature access */
  778. G_asprintf(&stmt, "%s,%s) VALUES (%s,'%s'::GEOMETRY)",
  779. buf, pg_info->geom_column, buf_val, geom_data);
  780. }
  781. else {
  782. /* PostGIS topology access, write geometry in
  783. * topology schema, skip geometry at this point */
  784. G_asprintf(&stmt, "%s) VALUES (%s)",
  785. buf, buf_val);
  786. }
  787. }
  788. }
  789. }
  790. else if (pg_info->toposchema_name)
  791. return NULL; /* don't write simple feature element */
  792. if (!stmt) {
  793. /* no attributes */
  794. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  795. "('%s'::GEOMETRY)",
  796. pg_info->schema_name, pg_info->table_name,
  797. pg_info->geom_column, geom_data);
  798. }
  799. return stmt;
  800. }
  801. /*!
  802. \brief Build SELECT statement to insert new element into PostGIS
  803. topology schema
  804. \param pg_info so pointer to Format_info_pg
  805. \param Line pointer to P_line struct (topo)
  806. \param geom_data geometry in wkb
  807. \return pointer to allocated string buffer with SQL statement
  808. \return NULL on error
  809. */
  810. char *build_topo_stmt(const struct Format_info_pg *pg_info, int type,
  811. const struct P_line *Line, const char *geom_data)
  812. {
  813. char *stmt;
  814. stmt = NULL;
  815. switch(type) {
  816. case GV_POINT: {
  817. #if 0
  818. G_asprintf(&stmt, "INSERT INTO \"%s\".node (geom) VALUES ('%s'::GEOMETRY)",
  819. pg_info->toposchema_name, geom_data);
  820. #else
  821. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  822. pg_info->toposchema_name, geom_data);
  823. #endif
  824. break;
  825. }
  826. case GV_LINE: {
  827. struct P_topo_l *topo;
  828. topo = (struct P_topo_l *) Line->topo;
  829. G_asprintf(&stmt, "INSERT INTO \"%s\".edge_data (geom,"
  830. "start_node,end_node,"
  831. "next_left_edge,abs_next_left_edge,"
  832. "next_right_edge,abs_next_right_edge,"
  833. "left_face,right_face) "
  834. "VALUES ('%s'::GEOMETRY,%d,%d,0,0,0,0,0,0)",
  835. pg_info->toposchema_name, geom_data,
  836. topo->N1, topo->N2);
  837. break;
  838. }
  839. case GV_CENTROID: {
  840. /* TopoGeo_AddPoint ? */
  841. G_asprintf(&stmt, "SELECT AddNode('%s', '%s'::GEOMETRY)",
  842. pg_info->toposchema_name, geom_data);
  843. break;
  844. }
  845. case GV_BOUNDARY: {
  846. /* TopoGeo_AddLineString ? */
  847. G_asprintf(&stmt, "SELECT AddEdge('%s', '%s'::GEOMETRY)",
  848. pg_info->toposchema_name, geom_data);
  849. break;
  850. }
  851. default:
  852. G_warning(_("Unsupported feature type %d"), Line->type);
  853. break;
  854. }
  855. return stmt;
  856. }
  857. /*!
  858. \brief Build INSERT / UPDATE statement to insert topo geometry
  859. object into feature table
  860. Allocated string should be freed by G_free()
  861. \param pg_info so pointer to Format_info_pg
  862. \param type feature type (GV_POINT, ...)
  863. \param id topology element id
  864. \param do_update TRUE for UPDATE otherwise build SELECT statement
  865. \return pointer to allocated string buffer with SQL statement
  866. \return NULL on error
  867. */
  868. char *build_topogeom_stmt(const struct Format_info_pg *pg_info,
  869. int id, int type, int do_update)
  870. {
  871. int topogeom_type;
  872. char *stmt;
  873. stmt = NULL;
  874. if (type == GV_POINT)
  875. topogeom_type = 1;
  876. else if (type & GV_LINES)
  877. topogeom_type = 2;
  878. else {
  879. G_warning(_("Unsupported topo geometry type %d"), type);
  880. return NULL;
  881. }
  882. if (!do_update)
  883. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  884. "(topology.CreateTopoGeom('%s', 1, %d, "
  885. "'{{%d, %d}}'::topology.topoelementarray))",
  886. pg_info->schema_name, pg_info->table_name,
  887. pg_info->topogeom_column, pg_info->toposchema_name,
  888. topogeom_type, id, topogeom_type);
  889. else
  890. G_asprintf(&stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  891. "topology.CreateTopoGeom('%s', 1, %d, "
  892. "'{{%d, %d}}'::topology.topoelementarray) "
  893. "WHERE %s = %d",
  894. pg_info->schema_name, pg_info->table_name,
  895. pg_info->topogeom_column, pg_info->toposchema_name,
  896. topogeom_type, id, topogeom_type,
  897. pg_info->fid_column, id);
  898. return stmt;
  899. }
  900. /*!
  901. \brief Execute SQL topo select statement
  902. \param conn pointer to PGconn
  903. \param stmt query
  904. \return value on success
  905. \return -1 on error
  906. */
  907. int execute_topo(PGconn *conn, const char *stmt)
  908. {
  909. int ret;
  910. PGresult *result;
  911. result = NULL;
  912. G_debug(3, "execute_topo(): %s", stmt);
  913. result = PQexec(conn, stmt);
  914. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK ||
  915. PQntuples(result) != 1) {
  916. PQclear(result);
  917. G_warning(_("Execution failed: %s"), PQerrorMessage(conn));
  918. return -1;
  919. }
  920. ret = atoi(PQgetvalue(result, 0, 0));
  921. PQclear(result);
  922. return ret;
  923. }
  924. #endif