write_pg.c 17 KB

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