write_pg.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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++] = (int) cat;
  141. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  142. /* register exterior ring in offset array */
  143. offset_info->array[offset_info->array_num++] = 0;
  144. }
  145. G_debug(3, "V1_write_line_ogr(): -> offset = %lu", (unsigned long) offset);
  146. return offset;
  147. #else
  148. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  149. return -1;
  150. #endif
  151. }
  152. /*!
  153. \brief Rewrites feature at the given offset (level 1) (PostGIS interface)
  154. \param Map pointer to Map_info structure
  155. \param offset feature offset
  156. \param type feature type (GV_POINT, GV_LINE, ...)
  157. \param points feature geometry
  158. \param cats feature categories
  159. \return feature offset (rewriten feature)
  160. \return -1 on error
  161. */
  162. off_t V1_rewrite_line_pg(struct Map_info *Map,
  163. int line, int type, off_t offset,
  164. const struct line_pnts *points, const struct line_cats *cats)
  165. {
  166. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%llu",
  167. line, type, offset);
  168. #ifdef HAVE_POSTGRES
  169. if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
  170. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  171. return -1;
  172. }
  173. /* delete old */
  174. V1_delete_line_pg(Map, offset);
  175. return V1_write_line_pg(Map, type, points, cats);
  176. #else
  177. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  178. return -1;
  179. #endif
  180. }
  181. /*!
  182. \brief Deletes feature at the given offset (level 1)
  183. \param Map pointer Map_info structure
  184. \param offset feature offset
  185. \return 0 on success
  186. \return -1 on error
  187. */
  188. int V1_delete_line_pg(struct Map_info *Map, off_t offset)
  189. {
  190. #ifdef HAVE_POSTGRES
  191. long fid;
  192. char stmt[DB_SQL_MAX];
  193. struct Format_info_pg *pg_info;
  194. pg_info = &(Map->fInfo.pg);
  195. if (!pg_info->conn || !pg_info->table_name) {
  196. G_warning(_("No connection defined"));
  197. return -1;
  198. }
  199. if (offset >= pg_info->offset.array_num) {
  200. G_warning(_("Invalid offset (%d)"), offset);
  201. return -1;
  202. }
  203. fid = pg_info->offset.array[offset];
  204. G_debug(3, "V1_delete_line_pg(), offset = %lu -> fid = %ld",
  205. (unsigned long) offset, fid);
  206. if (execute(pg_info->conn, "BEGIN") == -1)
  207. return -1;
  208. sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
  209. pg_info->table_name, pg_info->fid_column, fid);
  210. G_debug(2, "SQL: %s", stmt);
  211. if (execute(pg_info->conn, stmt) == -1) {
  212. G_warning(_("Unable to delete feature"));
  213. return -1;
  214. }
  215. if (execute(pg_info->conn, "COMMIT") == -1)
  216. return -1;
  217. return 0;
  218. #else
  219. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  220. return -1;
  221. #endif
  222. }
  223. #ifdef HAVE_POSTGRES
  224. /*!
  225. \brief Binary data to HEX
  226. Allocated buffer should be freed by G_free().
  227. \param nbytes number of bytes to allocate
  228. \param wkb_data WKB data
  229. \return allocated buffer with HEX data
  230. */
  231. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  232. {
  233. char *hex_data;
  234. int i, nlow, nhigh;
  235. static const char ach_hex[] = "0123456789ABCDEF";
  236. hex_data = (char *) G_malloc(nbytes * 2 + 1);
  237. hex_data[nbytes * 2] = '\0';
  238. for (i = 0; i < nbytes; i++) {
  239. nlow = wkb_data[i] & 0x0f;
  240. nhigh = (wkb_data[i] & 0xf0) >> 4;
  241. hex_data[i * 2] = ach_hex[nhigh];
  242. hex_data[i * 2 + 1] = ach_hex[nlow];
  243. }
  244. return hex_data;
  245. }
  246. /*!
  247. \bried Write point into WKB buffer
  248. See OGRPoint::exportToWkb from GDAL/OGR library
  249. \param byte_order byte order (LITTLE_ENDIAN or BIG_ENDIAN)
  250. \param points feature geometry
  251. \param with_z WITH_Z for 3D data
  252. \param[out] nsize buffer size
  253. \return allocated WKB buffer
  254. \return NULL on error
  255. */
  256. unsigned char *point_to_wkb(int byte_order,
  257. const struct line_pnts *points, int with_z,
  258. int *nsize)
  259. {
  260. unsigned char *wkb_data;
  261. unsigned int sf_type;
  262. if (points->n_points != 1)
  263. return NULL;
  264. /* allocate buffer */
  265. *nsize = with_z ? 29 : 21;
  266. wkb_data = G_malloc(*nsize);
  267. G_zero(wkb_data, *nsize);
  268. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  269. /* set the byte order */
  270. if (byte_order == LITTLE_ENDIAN)
  271. wkb_data[0] = '\001';
  272. else
  273. wkb_data[0] = '\000';
  274. /* set the geometry feature type */
  275. sf_type = with_z ? SF_POINT25D : SF_POINT;
  276. if (byte_order == LITTLE_ENDIAN)
  277. sf_type = LSBWORD32(sf_type);
  278. else
  279. sf_type = MSBWORD32(sf_type);
  280. memcpy(wkb_data + 1, &sf_type, 4);
  281. /* copy in the raw data */
  282. memcpy(wkb_data + 5, &(points->x[0]), 8);
  283. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  284. if (with_z) {
  285. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  286. }
  287. /* swap if needed */
  288. if (byte_order == ENDIAN_BIG) {
  289. SWAPDOUBLE(wkb_data + 5);
  290. SWAPDOUBLE(wkb_data + 5 + 8);
  291. if (with_z)
  292. SWAPDOUBLE(wkb_data + 5 + 16);
  293. }
  294. return wkb_data;
  295. }
  296. /*!
  297. \bried Write linestring into WKB buffer
  298. See OGRLineString::exportToWkb from GDAL/OGR library
  299. \param byte_order byte order (LITTLE_ENDIAN or BIG_ENDIAN)
  300. \param points feature geometry
  301. \param with_z WITH_Z for 3D data
  302. \param[out] nsize buffer size
  303. \return allocated WKB buffer
  304. \return NULL on error
  305. */
  306. unsigned char *linestring_to_wkb(int byte_order,
  307. const struct line_pnts *points, int with_z,
  308. int *nsize)
  309. {
  310. int i, point_size;
  311. unsigned char *wkb_data;
  312. unsigned int sf_type;
  313. if (points->n_points < 1)
  314. return NULL;
  315. /* allocate buffer */
  316. point_size = 8 * (with_z ? 3 : 2);
  317. *nsize = 5 + 4 + points->n_points * point_size;
  318. wkb_data = G_malloc(*nsize);
  319. G_zero(wkb_data, *nsize);
  320. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  321. /* set the byte order */
  322. if (byte_order == LITTLE_ENDIAN)
  323. wkb_data[0] = '\001';
  324. else
  325. wkb_data[0] = '\000';
  326. /* set the geometry feature type */
  327. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  328. if (byte_order == LITTLE_ENDIAN)
  329. sf_type = LSBWORD32(sf_type);
  330. else
  331. sf_type = MSBWORD32(sf_type);
  332. memcpy(wkb_data + 1, &sf_type, 4);
  333. /* copy in the data count */
  334. memcpy(wkb_data + 5, &(points->n_points), 4);
  335. /* copy in the raw data */
  336. for (i = 0; i < points->n_points; i++) {
  337. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  338. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  339. if (with_z) {
  340. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  341. }
  342. }
  343. /* swap if needed */
  344. if (byte_order == ENDIAN_BIG) {
  345. int npoints, nitems;
  346. npoints = SWAP32(points->n_points);
  347. memcpy(wkb_data+5, &npoints, 4);
  348. nitems = (with_z ? 3 : 2) * points->n_points;
  349. for(i = 0; i < nitems; i++ )
  350. {
  351. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  352. }
  353. }
  354. return wkb_data;
  355. }
  356. /*!
  357. \bried Write polygon into WKB buffer
  358. See OGRPolygon::exportToWkb from GDAL/OGR library
  359. \param byte_order byte order (LITTLE_ENDIAN or BIG_ENDIAN)
  360. \param points feature geometry
  361. \param with_z WITH_Z for 3D data
  362. \param[out] nsize buffer size
  363. \return allocated WKB buffer
  364. \return NULL on error
  365. */
  366. unsigned char *polygon_to_wkb(int byte_order,
  367. const struct line_pnts *points, int with_z,
  368. int *nsize)
  369. {
  370. int i, point_size, nrings;
  371. unsigned char *wkb_data;
  372. unsigned int sf_type;
  373. if (points->n_points < 3)
  374. return NULL;
  375. /* allocate buffer */
  376. point_size = 8 * (with_z ? 3 : 2);
  377. /* one ring only */
  378. nrings = 1;
  379. *nsize = 9 + (4 + point_size * points->n_points);
  380. wkb_data = G_malloc(*nsize);
  381. G_zero(wkb_data, *nsize);
  382. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  383. /* set the byte order */
  384. if (byte_order == LITTLE_ENDIAN)
  385. wkb_data[0] = '\001';
  386. else
  387. wkb_data[0] = '\000';
  388. /* set the geometry feature type */
  389. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  390. if (byte_order == LITTLE_ENDIAN)
  391. sf_type = LSBWORD32(sf_type);
  392. else
  393. sf_type = MSBWORD32(sf_type);
  394. memcpy(wkb_data + 1, &sf_type, 4);
  395. /* copy in the raw data */
  396. if (byte_order == ENDIAN_BIG) {
  397. int ncount;
  398. ncount = SWAP32(nrings);
  399. memcpy(wkb_data + 5, &ncount, 4);
  400. }
  401. else {
  402. memcpy(wkb_data + 5, &nrings, 4);
  403. }
  404. /* serialize ring */
  405. memcpy(wkb_data + 9, &(points->n_points), 4);
  406. for (i = 0; i < points->n_points; i++) {
  407. memcpy(wkb_data + 9 + 4 + point_size * i, &(points->x[i]), 8);
  408. memcpy(wkb_data + 9 + 4 + 8 + point_size * i, &(points->y[i]), 8);
  409. if (with_z) {
  410. memcpy(wkb_data + 9 + 4 + 16 + point_size * i, &(points->z[i]), 8);
  411. }
  412. }
  413. /* swap if needed */
  414. if (byte_order == ENDIAN_BIG) {
  415. int npoints, nitems;
  416. npoints = SWAP32(points->n_points);
  417. memcpy(wkb_data+5, &npoints, 4);
  418. nitems = (with_z ? 3 : 2) * points->n_points;
  419. for(i = 0; i < nitems; i++ ) {
  420. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  421. }
  422. }
  423. return wkb_data;
  424. }
  425. /*!
  426. \brief Insert feature into table
  427. \param pg_info pointer to Format_info_pg struct
  428. \param type feature type (GV_POINT, GV_LINE, ...)
  429. \param points pointer to line_pnts struct
  430. \param with_z WITH_Z for 3D data
  431. \param fid feature id
  432. \return -1 on error
  433. \retirn 0 on success
  434. */
  435. int write_feature(const struct Format_info_pg *pg_info,
  436. int type, const struct line_pnts *points, int with_z,
  437. int fid)
  438. {
  439. int byte_order, nbytes, nsize;
  440. unsigned int sf_type;
  441. unsigned char *wkb_data;
  442. char *stmt, *text_data, *text_data_p, *hex_data;
  443. if (with_z && pg_info->coor_dim != 3) {
  444. G_warning(_("Trying to insert 3D data into feature table "
  445. "which store 2D data only"));
  446. return -1;
  447. }
  448. if (!with_z && pg_info->coor_dim != 2) {
  449. G_warning(_("Trying to insert 2D data into feature table "
  450. "which store 3D data only"));
  451. return -1;
  452. }
  453. byte_order = LITTLE_ENDIAN; /* ? */
  454. /* get wkb data */
  455. nbytes = -1;
  456. wkb_data = NULL;
  457. if (type == GV_POINT)
  458. wkb_data = point_to_wkb(byte_order, points, with_z, &nbytes);
  459. else if (type == GV_LINE)
  460. wkb_data = linestring_to_wkb(byte_order, points, with_z, &nbytes);
  461. else if (type == GV_BOUNDARY)
  462. wkb_data = polygon_to_wkb(byte_order, points, with_z, &nbytes);
  463. if (!wkb_data || nbytes < 1) {
  464. G_warning(_("Unsupported feature type %d"), type);
  465. return -1;
  466. }
  467. /* When converting to hex, each byte takes 2 hex characters. In
  468. addition we add in 8 characters to represent the SRID integer
  469. in hex, and one for a null terminator */
  470. nsize = nbytes * 2 + 8 + 1;
  471. text_data = text_data_p = (char *) G_malloc(nsize);
  472. /* convert the 1st byte, which is the endianess flag, to hex */
  473. hex_data = binary_to_hex(1, wkb_data);
  474. strcpy(text_data_p, hex_data);
  475. G_free (hex_data);
  476. text_data_p += 2;
  477. /* get the geom type which is bytes 2 through 5 */
  478. memcpy(&sf_type, wkb_data + 1, 4);
  479. /* add the SRID flag if an SRID is provided */
  480. if (pg_info->srid > 0) {
  481. unsigned int srs_flag;
  482. /* change the flag to little endianess */
  483. srs_flag = LSBWORD32(WKBSRIDFLAG);
  484. /* apply the flag */
  485. sf_type = sf_type | srs_flag;
  486. }
  487. /* write the geom type which is 4 bytes */
  488. hex_data = binary_to_hex(4, (unsigned char*) &sf_type);
  489. strcpy(text_data_p, hex_data);
  490. G_free(hex_data);
  491. text_data_p += 8;
  492. /* include SRID if provided */
  493. if (pg_info->srid > 0) {
  494. unsigned int srs_id;
  495. /* force the srsid to little endianess */
  496. srs_id = LSBWORD32(pg_info->srid);
  497. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char*) &srs_id);
  498. strcpy(text_data_p, hex_data);
  499. G_free(hex_data);
  500. text_data_p += 8;
  501. }
  502. /* copy the rest of the data over - subtract 5 since we already
  503. copied 5 bytes above */
  504. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  505. strcpy(text_data_p, hex_data);
  506. G_free(hex_data);
  507. /* build INSERT statement */
  508. stmt = NULL;
  509. G_asprintf(&stmt, "INSERT INTO %s (%s, %s) VALUES (%d, '%s'::GEOMETRY)",
  510. pg_info->table_name, pg_info->fid_column, pg_info->geom_column,
  511. fid, text_data);
  512. G_debug(2, "SQL: %s", stmt);
  513. if (execute(pg_info->conn, stmt) == -1)
  514. return -1;
  515. G_free(wkb_data);
  516. G_free(text_data);
  517. G_free(stmt);
  518. return 0;
  519. }
  520. #endif