write_pg.c 16 KB

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