write_pg.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 char *binary_to_hex(int, const unsigned char *);
  23. static unsigned char *point_to_wkb(int, const struct line_pnts *,
  24. int, int*);
  25. static unsigned char *linestring_to_wkb(int, const struct line_pnts *,
  26. int, int*);
  27. static unsigned char *polygon_to_wkb(int, const struct line_pnts *,
  28. int, int*);
  29. static int write_feature(const struct Format_info_pg *,
  30. int, const struct line_pnts *, int, int);
  31. #endif
  32. /*!
  33. \brief Writes feature on level 1 (PostGIS interface)
  34. Note:
  35. - centroids are not supported in PostGIS, pseudotopo holds virtual
  36. centroids
  37. - boundaries are not supported in PostGIS, pseudotopo treats polygons
  38. as boundaries
  39. \param Map pointer to Map_info structure
  40. \param type feature type (GV_POINT, GV_LINE, ...)
  41. \param points pointer to line_pnts structure (feature geometry)
  42. \param cats pointer to line_cats structure (feature categories)
  43. \return feature offset into file
  44. \return -1 on error
  45. */
  46. off_t V1_write_line_pg(struct Map_info *Map, int type,
  47. const struct line_pnts *points,
  48. const struct line_cats *cats)
  49. {
  50. #ifdef HAVE_POSTGRES
  51. int cat;
  52. off_t offset;
  53. SF_FeatureType sf_type;
  54. struct field_info *Fi;
  55. struct Format_info_pg *pg_info;
  56. struct Format_info_offset *offset_info;
  57. pg_info = &(Map->fInfo.pg);
  58. offset_info = &(pg_info->offset);
  59. if (!pg_info->conn || !pg_info->table_name) {
  60. G_warning(_("No connection defined"));
  61. return -1;
  62. }
  63. /* create PostGIS layer if doesn't exist ? */
  64. cat = -1; /* no attributes to be written */
  65. if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) {
  66. /* check for attributes */
  67. Fi = Vect_get_dblink(Map, 0);
  68. if (Fi) {
  69. if (!Vect_cat_get(cats, Fi->number, &cat))
  70. G_warning(_("No category defined for layer %d"), Fi->number);
  71. if (cats->n_cats > 1) {
  72. G_warning(_("Feature has more categories, using "
  73. "category %d (from layer %d)"),
  74. cat, cats->field[0]);
  75. }
  76. }
  77. }
  78. sf_type = pg_info->feature_type;
  79. /* determine matching PostGIS feature geometry type */
  80. if (type & (GV_POINT | GV_KERNEL)) {
  81. if (sf_type != SF_POINT &&
  82. sf_type != SF_POINT25D) {
  83. G_warning(_("Feature is not a point. Skipping."));
  84. return -1;
  85. }
  86. }
  87. else if (type & GV_LINE) {
  88. if (sf_type != SF_LINESTRING &&
  89. sf_type != SF_LINESTRING25D) {
  90. G_warning(_("Feature is not a line. Skipping."));
  91. return -1;
  92. }
  93. }
  94. else if (type & GV_BOUNDARY) {
  95. if (sf_type != SF_POLYGON) {
  96. G_warning(_("Feature is not a polygon. Skipping."));
  97. return -1;
  98. }
  99. }
  100. else if (type & GV_FACE) {
  101. if (sf_type != SF_POLYGON25D) {
  102. G_warning(_("Feature is not a face. Skipping."));
  103. return -1;
  104. }
  105. }
  106. else {
  107. G_warning(_("Unsupported feature type (%d)"), type);
  108. return -1;
  109. }
  110. G_debug(3, "V1_write_line_pg(): type = %d n_points = %d cat = %d",
  111. type, points->n_points, cat);
  112. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  113. int npoints;
  114. npoints = points->n_points - 1;
  115. if (points->x[0] != points->x[npoints] ||
  116. points->y[0] != points->y[npoints] ||
  117. points->z[0] != points->z[npoints]) {
  118. G_warning(_("Boundary is not closed. Skipping."));
  119. return -1;
  120. }
  121. }
  122. if (execute(pg_info->conn, "BEGIN") == -1)
  123. return -1;
  124. /* write feature's geometry and fid */
  125. if (-1 == write_feature(pg_info, type, points,
  126. Vect_is_3d(Map) ? WITH_Z : WITHOUT_Z, cat))
  127. return -1;
  128. /* write attributes */
  129. /* ? */
  130. if (execute(pg_info->conn, "COMMIT") == -1)
  131. return -1;
  132. /* update offset array */
  133. if (offset_info->array_num >= offset_info->array_alloc) {
  134. offset_info->array_alloc += 1000;
  135. offset_info->array = (int *) G_realloc(offset_info->array,
  136. offset_info->array_alloc *
  137. sizeof(int));
  138. }
  139. offset = offset_info->array_num;
  140. offset_info->array[offset_info->array_num++] = cat;
  141. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  142. /* register first part in offset array */
  143. offset_info->array[offset_info->array_num++] = 0;
  144. }
  145. G_debug(3, "V1_write_line_pg(): -> offset = %lu offset_num = %d cat = %d",
  146. (unsigned long) offset, offset_info->array_num, cat);
  147. return offset;
  148. #else
  149. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  150. return -1;
  151. #endif
  152. }
  153. /*!
  154. \brief Rewrites feature at the given offset (level 1) (PostGIS interface)
  155. \param Map pointer to Map_info structure
  156. \param offset feature offset
  157. \param type feature type (GV_POINT, GV_LINE, ...)
  158. \param points feature geometry
  159. \param cats feature categories
  160. \return feature offset (rewriten feature)
  161. \return -1 on error
  162. */
  163. off_t V1_rewrite_line_pg(struct Map_info *Map,
  164. int line, int type, off_t offset,
  165. const struct line_pnts *points, const struct line_cats *cats)
  166. {
  167. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%llu",
  168. line, type, offset);
  169. #ifdef HAVE_POSTGRES
  170. if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
  171. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  172. return -1;
  173. }
  174. /* delete old */
  175. V1_delete_line_pg(Map, offset);
  176. return V1_write_line_pg(Map, type, points, cats);
  177. #else
  178. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  179. return -1;
  180. #endif
  181. }
  182. /*!
  183. \brief Deletes feature at the given offset (level 1)
  184. \param Map pointer Map_info structure
  185. \param offset feature offset
  186. \return 0 on success
  187. \return -1 on error
  188. */
  189. int V1_delete_line_pg(struct Map_info *Map, off_t offset)
  190. {
  191. #ifdef HAVE_POSTGRES
  192. long fid;
  193. char stmt[DB_SQL_MAX];
  194. struct Format_info_pg *pg_info;
  195. pg_info = &(Map->fInfo.pg);
  196. if (!pg_info->conn || !pg_info->table_name) {
  197. G_warning(_("No connection defined"));
  198. return -1;
  199. }
  200. if (offset >= pg_info->offset.array_num) {
  201. G_warning(_("Invalid offset (%d)"), offset);
  202. return -1;
  203. }
  204. fid = pg_info->offset.array[offset];
  205. G_debug(3, "V1_delete_line_pg(), offset = %lu -> fid = %ld",
  206. (unsigned long) offset, fid);
  207. if (execute(pg_info->conn, "BEGIN") == -1)
  208. return -1;
  209. sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
  210. pg_info->table_name, pg_info->fid_column, fid);
  211. G_debug(2, "SQL: %s", stmt);
  212. if (execute(pg_info->conn, stmt) == -1) {
  213. G_warning(_("Unable to delete feature"));
  214. return -1;
  215. }
  216. if (execute(pg_info->conn, "COMMIT") == -1)
  217. return -1;
  218. return 0;
  219. #else
  220. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  221. return -1;
  222. #endif
  223. }
  224. #ifdef HAVE_POSTGRES
  225. /*!
  226. \brief Binary data to HEX
  227. Allocated buffer should be freed by G_free().
  228. \param nbytes number of bytes to allocate
  229. \param wkb_data WKB data
  230. \return allocated buffer with HEX data
  231. */
  232. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  233. {
  234. char *hex_data;
  235. int i, nlow, nhigh;
  236. static const char ach_hex[] = "0123456789ABCDEF";
  237. hex_data = (char *) G_malloc(nbytes * 2 + 1);
  238. hex_data[nbytes * 2] = '\0';
  239. for (i = 0; i < nbytes; i++) {
  240. nlow = wkb_data[i] & 0x0f;
  241. nhigh = (wkb_data[i] & 0xf0) >> 4;
  242. hex_data[i * 2] = ach_hex[nhigh];
  243. hex_data[i * 2 + 1] = ach_hex[nlow];
  244. }
  245. return hex_data;
  246. }
  247. /*!
  248. \bried Write point into WKB buffer
  249. See OGRPoint::exportToWkb from GDAL/OGR library
  250. \param byte_order byte order (LITTLE_ENDIAN or BIG_ENDIAN)
  251. \param points feature geometry
  252. \param with_z WITH_Z for 3D data
  253. \param[out] nsize buffer size
  254. \return allocated WKB buffer
  255. \return NULL on error
  256. */
  257. unsigned char *point_to_wkb(int byte_order,
  258. const struct line_pnts *points, int with_z,
  259. int *nsize)
  260. {
  261. unsigned char *wkb_data;
  262. unsigned int sf_type;
  263. if (points->n_points != 1)
  264. return NULL;
  265. /* allocate buffer */
  266. *nsize = with_z ? 29 : 21;
  267. wkb_data = G_malloc(*nsize);
  268. G_zero(wkb_data, *nsize);
  269. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  270. /* set the byte order */
  271. if (byte_order == LITTLE_ENDIAN)
  272. wkb_data[0] = '\001';
  273. else
  274. wkb_data[0] = '\000';
  275. /* set the geometry feature type */
  276. sf_type = with_z ? SF_POINT25D : SF_POINT;
  277. if (byte_order == LITTLE_ENDIAN)
  278. sf_type = LSBWORD32(sf_type);
  279. else
  280. sf_type = MSBWORD32(sf_type);
  281. memcpy(wkb_data + 1, &sf_type, 4);
  282. /* copy in the raw data */
  283. memcpy(wkb_data + 5, &(points->x[0]), 8);
  284. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  285. if (with_z) {
  286. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  287. }
  288. /* swap if needed */
  289. if (byte_order == ENDIAN_BIG) {
  290. SWAPDOUBLE(wkb_data + 5);
  291. SWAPDOUBLE(wkb_data + 5 + 8);
  292. if (with_z)
  293. SWAPDOUBLE(wkb_data + 5 + 16);
  294. }
  295. return wkb_data;
  296. }
  297. /*!
  298. \bried Write linestring into WKB buffer
  299. See OGRLineString::exportToWkb from GDAL/OGR library
  300. \param byte_order byte order (LITTLE_ENDIAN or BIG_ENDIAN)
  301. \param points feature geometry
  302. \param with_z WITH_Z for 3D data
  303. \param[out] nsize buffer size
  304. \return allocated WKB buffer
  305. \return NULL on error
  306. */
  307. unsigned char *linestring_to_wkb(int byte_order,
  308. const struct line_pnts *points, int with_z,
  309. int *nsize)
  310. {
  311. int i, point_size;
  312. unsigned char *wkb_data;
  313. unsigned int sf_type;
  314. if (points->n_points < 1)
  315. return NULL;
  316. /* allocate buffer */
  317. point_size = 8 * (with_z ? 3 : 2);
  318. *nsize = 5 + 4 + points->n_points * point_size;
  319. wkb_data = G_malloc(*nsize);
  320. G_zero(wkb_data, *nsize);
  321. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  322. /* set the byte order */
  323. if (byte_order == LITTLE_ENDIAN)
  324. wkb_data[0] = '\001';
  325. else
  326. wkb_data[0] = '\000';
  327. /* set the geometry feature type */
  328. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  329. if (byte_order == LITTLE_ENDIAN)
  330. sf_type = LSBWORD32(sf_type);
  331. else
  332. sf_type = MSBWORD32(sf_type);
  333. memcpy(wkb_data + 1, &sf_type, 4);
  334. /* copy in the data count */
  335. memcpy(wkb_data + 5, &(points->n_points), 4);
  336. /* copy in the raw data */
  337. for (i = 0; i < points->n_points; i++) {
  338. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  339. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  340. if (with_z) {
  341. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  342. }
  343. }
  344. /* swap if needed */
  345. if (byte_order == ENDIAN_BIG) {
  346. int npoints, nitems;
  347. npoints = SWAP32(points->n_points);
  348. memcpy(wkb_data+5, &npoints, 4);
  349. nitems = (with_z ? 3 : 2) * points->n_points;
  350. for(i = 0; i < nitems; i++ )
  351. {
  352. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  353. }
  354. }
  355. return wkb_data;
  356. }
  357. /*!
  358. \bried Write polygon into WKB buffer
  359. See OGRPolygon::exportToWkb from GDAL/OGR library
  360. \param byte_order byte order (LITTLE_ENDIAN or BIG_ENDIAN)
  361. \param points feature geometry
  362. \param with_z WITH_Z for 3D data
  363. \param[out] nsize buffer size
  364. \return allocated WKB buffer
  365. \return NULL on error
  366. */
  367. unsigned char *polygon_to_wkb(int byte_order,
  368. const struct line_pnts *points, int with_z,
  369. int *nsize)
  370. {
  371. int i, point_size, nrings;
  372. unsigned char *wkb_data;
  373. unsigned int sf_type;
  374. if (points->n_points < 3)
  375. return NULL;
  376. /* allocate buffer */
  377. point_size = 8 * (with_z ? 3 : 2);
  378. /* one ring only */
  379. nrings = 1;
  380. *nsize = 9 + (4 + point_size * points->n_points);
  381. wkb_data = G_malloc(*nsize);
  382. G_zero(wkb_data, *nsize);
  383. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  384. /* set the byte order */
  385. if (byte_order == LITTLE_ENDIAN)
  386. wkb_data[0] = '\001';
  387. else
  388. wkb_data[0] = '\000';
  389. /* set the geometry feature type */
  390. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  391. if (byte_order == LITTLE_ENDIAN)
  392. sf_type = LSBWORD32(sf_type);
  393. else
  394. sf_type = MSBWORD32(sf_type);
  395. memcpy(wkb_data + 1, &sf_type, 4);
  396. /* copy in the raw data */
  397. if (byte_order == ENDIAN_BIG) {
  398. int ncount;
  399. ncount = SWAP32(nrings);
  400. memcpy(wkb_data + 5, &ncount, 4);
  401. }
  402. else {
  403. memcpy(wkb_data + 5, &nrings, 4);
  404. }
  405. /* serialize ring */
  406. memcpy(wkb_data + 9, &(points->n_points), 4);
  407. for (i = 0; i < points->n_points; i++) {
  408. memcpy(wkb_data + 9 + 4 + point_size * i, &(points->x[i]), 8);
  409. memcpy(wkb_data + 9 + 4 + 8 + point_size * i, &(points->y[i]), 8);
  410. if (with_z) {
  411. memcpy(wkb_data + 9 + 4 + 16 + point_size * i, &(points->z[i]), 8);
  412. }
  413. }
  414. /* swap if needed */
  415. if (byte_order == ENDIAN_BIG) {
  416. int npoints, nitems;
  417. npoints = SWAP32(points->n_points);
  418. memcpy(wkb_data+5, &npoints, 4);
  419. nitems = (with_z ? 3 : 2) * points->n_points;
  420. for(i = 0; i < nitems; i++ ) {
  421. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  422. }
  423. }
  424. return wkb_data;
  425. }
  426. /*!
  427. \brief Insert feature into table
  428. \param pg_info pointer to Format_info_pg struct
  429. \param type feature type (GV_POINT, GV_LINE, ...)
  430. \param points pointer to line_pnts struct
  431. \param with_z WITH_Z for 3D data
  432. \param fid feature id
  433. \return -1 on error
  434. \retirn 0 on success
  435. */
  436. int write_feature(const struct Format_info_pg *pg_info,
  437. int type, const struct line_pnts *points, int with_z,
  438. int fid)
  439. {
  440. int byte_order, nbytes, nsize;
  441. unsigned int sf_type;
  442. unsigned char *wkb_data;
  443. char *stmt, *text_data, *text_data_p, *hex_data;
  444. if (with_z && pg_info->coor_dim != 3) {
  445. G_warning(_("Trying to insert 3D data into feature table "
  446. "which store 2D data only"));
  447. return -1;
  448. }
  449. if (!with_z && pg_info->coor_dim != 2) {
  450. G_warning(_("Trying to insert 2D data into feature table "
  451. "which store 3D data only"));
  452. return -1;
  453. }
  454. byte_order = LITTLE_ENDIAN; /* ? */
  455. /* get wkb data */
  456. nbytes = -1;
  457. wkb_data = NULL;
  458. if (type == GV_POINT)
  459. wkb_data = point_to_wkb(byte_order, points, with_z, &nbytes);
  460. else if (type == GV_LINE)
  461. wkb_data = linestring_to_wkb(byte_order, points, with_z, &nbytes);
  462. else if (type == GV_BOUNDARY)
  463. wkb_data = polygon_to_wkb(byte_order, points, with_z, &nbytes);
  464. if (!wkb_data || nbytes < 1) {
  465. G_warning(_("Unsupported feature type %d"), type);
  466. return -1;
  467. }
  468. /* When converting to hex, each byte takes 2 hex characters. In
  469. addition we add in 8 characters to represent the SRID integer
  470. in hex, and one for a null terminator */
  471. nsize = nbytes * 2 + 8 + 1;
  472. text_data = text_data_p = (char *) G_malloc(nsize);
  473. /* convert the 1st byte, which is the endianess flag, to hex */
  474. hex_data = binary_to_hex(1, wkb_data);
  475. strcpy(text_data_p, hex_data);
  476. G_free (hex_data);
  477. text_data_p += 2;
  478. /* get the geom type which is bytes 2 through 5 */
  479. memcpy(&sf_type, wkb_data + 1, 4);
  480. /* add the SRID flag if an SRID is provided */
  481. if (pg_info->srid > 0) {
  482. unsigned int srs_flag;
  483. /* change the flag to little endianess */
  484. srs_flag = LSBWORD32(WKBSRIDFLAG);
  485. /* apply the flag */
  486. sf_type = sf_type | srs_flag;
  487. }
  488. /* write the geom type which is 4 bytes */
  489. hex_data = binary_to_hex(4, (unsigned char*) &sf_type);
  490. strcpy(text_data_p, hex_data);
  491. G_free(hex_data);
  492. text_data_p += 8;
  493. /* include SRID if provided */
  494. if (pg_info->srid > 0) {
  495. unsigned int srs_id;
  496. /* force the srsid to little endianess */
  497. srs_id = LSBWORD32(pg_info->srid);
  498. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char*) &srs_id);
  499. strcpy(text_data_p, hex_data);
  500. G_free(hex_data);
  501. text_data_p += 8;
  502. }
  503. /* copy the rest of the data over - subtract 5 since we already
  504. copied 5 bytes above */
  505. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  506. strcpy(text_data_p, hex_data);
  507. G_free(hex_data);
  508. /* build INSERT statement */
  509. stmt = NULL;
  510. G_asprintf(&stmt, "INSERT INTO %s (%s, %s) VALUES (%d, '%s'::GEOMETRY)",
  511. pg_info->table_name, pg_info->fid_column, pg_info->geom_column,
  512. fid, text_data);
  513. G_debug(2, "SQL: %s", stmt);
  514. if (execute(pg_info->conn, stmt) == -1) {
  515. /* close transaction */
  516. execute(pg_info->conn, "COMMIT");
  517. return -1;
  518. }
  519. G_free(wkb_data);
  520. G_free(text_data);
  521. G_free(stmt);
  522. return 0;
  523. }
  524. #endif