write_pg.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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(struct Format_info_pg *,
  30. int, const struct line_pnts *, int,
  31. int, const struct field_info *);
  32. static char *build_insert_stmt(const struct Format_info_pg *, const char *,
  33. int, const struct field_info *);
  34. #endif
  35. /*!
  36. \brief Writes feature on level 1 (PostGIS interface)
  37. Note:
  38. - centroids are not supported in PostGIS, pseudotopo holds virtual
  39. centroids
  40. - boundaries are not supported in PostGIS, pseudotopo treats polygons
  41. as boundaries
  42. \param Map pointer to Map_info structure
  43. \param type feature type (GV_POINT, GV_LINE, ...)
  44. \param points pointer to line_pnts structure (feature geometry)
  45. \param cats pointer to line_cats structure (feature categories)
  46. \return feature offset into file
  47. \return -1 on error
  48. */
  49. off_t V1_write_line_pg(struct Map_info *Map, int type,
  50. const struct line_pnts *points,
  51. const struct line_cats *cats)
  52. {
  53. #ifdef HAVE_POSTGRES
  54. int cat;
  55. off_t offset;
  56. SF_FeatureType sf_type;
  57. struct field_info *Fi;
  58. struct Format_info_pg *pg_info;
  59. struct Format_info_offset *offset_info;
  60. pg_info = &(Map->fInfo.pg);
  61. offset_info = &(pg_info->offset);
  62. if (!pg_info->conn) {
  63. G_warning(_("No connection defined"));
  64. return -1;
  65. }
  66. if (!pg_info->table_name) {
  67. G_warning(_("PostGIS feature table not defined"));
  68. return -1;
  69. }
  70. if (pg_info->feature_type == SF_UNKNOWN) {
  71. /* create PostGIS table if doesn't exist */
  72. if (V2_open_new_pg(Map, type) < 0)
  73. return -1;
  74. }
  75. Fi = NULL; /* no attributes to be written */
  76. cat = -1;
  77. if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) {
  78. /* check for attributes */
  79. Fi = Vect_get_dblink(Map, 0);
  80. if (Fi) {
  81. if (!Vect_cat_get(cats, Fi->number, &cat))
  82. G_warning(_("No category defined for layer %d"), Fi->number);
  83. if (cats->n_cats > 1) {
  84. G_warning(_("Feature has more categories, using "
  85. "category %d (from layer %d)"),
  86. cat, cats->field[0]);
  87. }
  88. }
  89. }
  90. sf_type = pg_info->feature_type;
  91. /* determine matching PostGIS feature geometry type */
  92. if (type & (GV_POINT | GV_KERNEL)) {
  93. if (sf_type != SF_POINT &&
  94. sf_type != SF_POINT25D) {
  95. G_warning(_("Feature is not a point. Skipping."));
  96. return -1;
  97. }
  98. }
  99. else if (type & GV_LINE) {
  100. if (sf_type != SF_LINESTRING &&
  101. sf_type != SF_LINESTRING25D) {
  102. G_warning(_("Feature is not a line. Skipping."));
  103. return -1;
  104. }
  105. }
  106. else if (type & GV_BOUNDARY) {
  107. if (sf_type != SF_POLYGON) {
  108. G_warning(_("Feature is not a polygon. Skipping."));
  109. return -1;
  110. }
  111. }
  112. else if (type & GV_FACE) {
  113. if (sf_type != SF_POLYGON25D) {
  114. G_warning(_("Feature is not a face. Skipping."));
  115. return -1;
  116. }
  117. }
  118. else {
  119. G_warning(_("Unsupported feature type (%d)"), type);
  120. return -1;
  121. }
  122. G_debug(3, "V1_write_line_pg(): type = %d n_points = %d cat = %d",
  123. type, points->n_points, cat);
  124. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  125. int npoints;
  126. npoints = points->n_points - 1;
  127. if (points->x[0] != points->x[npoints] ||
  128. points->y[0] != points->y[npoints] ||
  129. points->z[0] != points->z[npoints]) {
  130. G_warning(_("Boundary is not closed. Skipping."));
  131. return -1;
  132. }
  133. }
  134. /* write feature's geometry and fid */
  135. if (-1 == write_feature(pg_info, type, points,
  136. Vect_is_3d(Map) ? WITH_Z : WITHOUT_Z,
  137. cat, Fi)) {
  138. execute(pg_info->conn, "ROLLBACK");
  139. return -1;
  140. }
  141. /* update offset array */
  142. if (offset_info->array_num >= offset_info->array_alloc) {
  143. offset_info->array_alloc += 1000;
  144. offset_info->array = (int *) G_realloc(offset_info->array,
  145. offset_info->array_alloc *
  146. sizeof(int));
  147. }
  148. offset = offset_info->array_num;
  149. offset_info->array[offset_info->array_num++] = cat;
  150. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  151. /* register first part in offset array */
  152. offset_info->array[offset_info->array_num++] = 0;
  153. }
  154. G_debug(3, "V1_write_line_pg(): -> offset = %lu offset_num = %d cat = %d",
  155. (unsigned long) offset, offset_info->array_num, cat);
  156. return offset;
  157. #else
  158. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  159. return -1;
  160. #endif
  161. }
  162. /*!
  163. \brief Rewrites feature at the given offset (level 1) (PostGIS interface)
  164. \param Map pointer to Map_info structure
  165. \param offset feature offset
  166. \param type feature type (GV_POINT, GV_LINE, ...)
  167. \param points feature geometry
  168. \param cats feature categories
  169. \return feature offset (rewriten feature)
  170. \return -1 on error
  171. */
  172. off_t V1_rewrite_line_pg(struct Map_info *Map,
  173. int line, int type, off_t offset,
  174. const struct line_pnts *points, const struct line_cats *cats)
  175. {
  176. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%llu",
  177. line, type, offset);
  178. #ifdef HAVE_POSTGRES
  179. if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
  180. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  181. return -1;
  182. }
  183. /* delete old */
  184. V1_delete_line_pg(Map, offset);
  185. return V1_write_line_pg(Map, type, points, cats);
  186. #else
  187. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  188. return -1;
  189. #endif
  190. }
  191. /*!
  192. \brief Deletes feature at the given offset (level 1)
  193. \param Map pointer Map_info structure
  194. \param offset feature offset
  195. \return 0 on success
  196. \return -1 on error
  197. */
  198. int V1_delete_line_pg(struct Map_info *Map, off_t offset)
  199. {
  200. #ifdef HAVE_POSTGRES
  201. long fid;
  202. char stmt[DB_SQL_MAX];
  203. struct Format_info_pg *pg_info;
  204. pg_info = &(Map->fInfo.pg);
  205. if (!pg_info->conn || !pg_info->table_name) {
  206. G_warning(_("No connection defined"));
  207. return -1;
  208. }
  209. if (offset >= pg_info->offset.array_num) {
  210. G_warning(_("Invalid offset (%d)"), offset);
  211. return -1;
  212. }
  213. fid = pg_info->offset.array[offset];
  214. G_debug(3, "V1_delete_line_pg(), offset = %lu -> fid = %ld",
  215. (unsigned long) offset, fid);
  216. if (!pg_info->inTransaction) {
  217. /* start transaction */
  218. pg_info->inTransaction = TRUE;
  219. if (execute(pg_info->conn, "BEGIN") == -1)
  220. return -1;
  221. }
  222. sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
  223. pg_info->table_name, pg_info->fid_column, fid);
  224. G_debug(2, "SQL: %s", stmt);
  225. if (execute(pg_info->conn, stmt) == -1) {
  226. G_warning(_("Unable to delete feature"));
  227. execute(pg_info->conn, "ROLLBACK");
  228. return -1;
  229. }
  230. return 0;
  231. #else
  232. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  233. return -1;
  234. #endif
  235. }
  236. #ifdef HAVE_POSTGRES
  237. /*!
  238. \brief Binary data to HEX
  239. Allocated buffer should be freed by G_free().
  240. \param nbytes number of bytes to allocate
  241. \param wkb_data WKB data
  242. \return allocated buffer with HEX data
  243. */
  244. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  245. {
  246. char *hex_data;
  247. int i, nlow, nhigh;
  248. static const char ach_hex[] = "0123456789ABCDEF";
  249. hex_data = (char *) G_malloc(nbytes * 2 + 1);
  250. hex_data[nbytes * 2] = '\0';
  251. for (i = 0; i < nbytes; i++) {
  252. nlow = wkb_data[i] & 0x0f;
  253. nhigh = (wkb_data[i] & 0xf0) >> 4;
  254. hex_data[i * 2] = ach_hex[nhigh];
  255. hex_data[i * 2 + 1] = ach_hex[nlow];
  256. }
  257. return hex_data;
  258. }
  259. /*!
  260. \bried Write point into WKB buffer
  261. See OGRPoint::exportToWkb from GDAL/OGR library
  262. \param byte_order byte order (ENDIAN_LITTLE or BIG_ENDIAN)
  263. \param points feature geometry
  264. \param with_z WITH_Z for 3D data
  265. \param[out] nsize buffer size
  266. \return allocated WKB buffer
  267. \return NULL on error
  268. */
  269. unsigned char *point_to_wkb(int byte_order,
  270. const struct line_pnts *points, int with_z,
  271. int *nsize)
  272. {
  273. unsigned char *wkb_data;
  274. unsigned int sf_type;
  275. if (points->n_points != 1)
  276. return NULL;
  277. /* allocate buffer */
  278. *nsize = with_z ? 29 : 21;
  279. wkb_data = G_malloc(*nsize);
  280. G_zero(wkb_data, *nsize);
  281. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  282. /* set the byte order */
  283. if (byte_order == ENDIAN_LITTLE)
  284. wkb_data[0] = '\001';
  285. else
  286. wkb_data[0] = '\000';
  287. /* set the geometry feature type */
  288. sf_type = with_z ? SF_POINT25D : SF_POINT;
  289. if (byte_order == ENDIAN_LITTLE)
  290. sf_type = LSBWORD32(sf_type);
  291. else
  292. sf_type = MSBWORD32(sf_type);
  293. memcpy(wkb_data + 1, &sf_type, 4);
  294. /* copy in the raw data */
  295. memcpy(wkb_data + 5, &(points->x[0]), 8);
  296. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  297. if (with_z) {
  298. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  299. }
  300. /* swap if needed */
  301. if (byte_order == ENDIAN_BIG) {
  302. SWAPDOUBLE(wkb_data + 5);
  303. SWAPDOUBLE(wkb_data + 5 + 8);
  304. if (with_z)
  305. SWAPDOUBLE(wkb_data + 5 + 16);
  306. }
  307. return wkb_data;
  308. }
  309. /*!
  310. \bried Write linestring into WKB buffer
  311. See OGRLineString::exportToWkb from GDAL/OGR library
  312. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  313. \param points feature geometry
  314. \param with_z WITH_Z for 3D data
  315. \param[out] nsize buffer size
  316. \return allocated WKB buffer
  317. \return NULL on error
  318. */
  319. unsigned char *linestring_to_wkb(int byte_order,
  320. const struct line_pnts *points, int with_z,
  321. int *nsize)
  322. {
  323. int i, point_size;
  324. unsigned char *wkb_data;
  325. unsigned int sf_type;
  326. if (points->n_points < 1)
  327. return NULL;
  328. /* allocate buffer */
  329. point_size = 8 * (with_z ? 3 : 2);
  330. *nsize = 5 + 4 + points->n_points * point_size;
  331. wkb_data = G_malloc(*nsize);
  332. G_zero(wkb_data, *nsize);
  333. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  334. /* set the byte order */
  335. if (byte_order == ENDIAN_LITTLE)
  336. wkb_data[0] = '\001';
  337. else
  338. wkb_data[0] = '\000';
  339. /* set the geometry feature type */
  340. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  341. if (byte_order == ENDIAN_LITTLE)
  342. sf_type = LSBWORD32(sf_type);
  343. else
  344. sf_type = MSBWORD32(sf_type);
  345. memcpy(wkb_data + 1, &sf_type, 4);
  346. /* copy in the data count */
  347. memcpy(wkb_data + 5, &(points->n_points), 4);
  348. /* copy in the raw data */
  349. for (i = 0; i < points->n_points; i++) {
  350. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  351. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  352. if (with_z) {
  353. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  354. }
  355. }
  356. /* swap if needed */
  357. if (byte_order == ENDIAN_BIG) {
  358. int npoints, nitems;
  359. npoints = SWAP32(points->n_points);
  360. memcpy(wkb_data+5, &npoints, 4);
  361. nitems = (with_z ? 3 : 2) * points->n_points;
  362. for(i = 0; i < nitems; i++ )
  363. {
  364. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  365. }
  366. }
  367. return wkb_data;
  368. }
  369. /*!
  370. \bried Write polygon into WKB buffer
  371. See OGRPolygon::exportToWkb from GDAL/OGR library
  372. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  373. \param points feature geometry
  374. \param with_z WITH_Z for 3D data
  375. \param[out] nsize buffer size
  376. \return allocated WKB buffer
  377. \return NULL on error
  378. */
  379. unsigned char *polygon_to_wkb(int byte_order,
  380. const struct line_pnts *points, int with_z,
  381. int *nsize)
  382. {
  383. int i, point_size, nrings;
  384. unsigned char *wkb_data;
  385. unsigned int sf_type;
  386. if (points->n_points < 3)
  387. return NULL;
  388. /* allocate buffer */
  389. point_size = 8 * (with_z ? 3 : 2);
  390. /* one ring only */
  391. nrings = 1;
  392. *nsize = 9 + (4 + point_size * points->n_points);
  393. wkb_data = G_malloc(*nsize);
  394. G_zero(wkb_data, *nsize);
  395. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  396. /* set the byte order */
  397. if (byte_order == ENDIAN_LITTLE)
  398. wkb_data[0] = '\001';
  399. else
  400. wkb_data[0] = '\000';
  401. /* set the geometry feature type */
  402. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  403. if (byte_order == ENDIAN_LITTLE)
  404. sf_type = LSBWORD32(sf_type);
  405. else
  406. sf_type = MSBWORD32(sf_type);
  407. memcpy(wkb_data + 1, &sf_type, 4);
  408. /* copy in the raw data */
  409. if (byte_order == ENDIAN_BIG) {
  410. int ncount;
  411. ncount = SWAP32(nrings);
  412. memcpy(wkb_data + 5, &ncount, 4);
  413. }
  414. else {
  415. memcpy(wkb_data + 5, &nrings, 4);
  416. }
  417. /* serialize ring */
  418. memcpy(wkb_data + 9, &(points->n_points), 4);
  419. for (i = 0; i < points->n_points; i++) {
  420. memcpy(wkb_data + 9 + 4 + point_size * i, &(points->x[i]), 8);
  421. memcpy(wkb_data + 9 + 4 + 8 + point_size * i, &(points->y[i]), 8);
  422. if (with_z) {
  423. memcpy(wkb_data + 9 + 4 + 16 + point_size * i, &(points->z[i]), 8);
  424. }
  425. }
  426. /* swap if needed */
  427. if (byte_order == ENDIAN_BIG) {
  428. int npoints, nitems;
  429. npoints = SWAP32(points->n_points);
  430. memcpy(wkb_data+5, &npoints, 4);
  431. nitems = (with_z ? 3 : 2) * points->n_points;
  432. for(i = 0; i < nitems; i++ ) {
  433. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  434. }
  435. }
  436. return wkb_data;
  437. }
  438. /*!
  439. \brief Insert feature into table
  440. \param pg_info pointer to Format_info_pg struct
  441. \param type feature type (GV_POINT, GV_LINE, ...)
  442. \param points pointer to line_pnts struct
  443. \param with_z WITH_Z for 3D data
  444. \param cat category number (-1 for no category)
  445. \param Fi pointer to field_info (attributes to copy, NULL for no attributes)
  446. \return -1 on error
  447. \retirn 0 on success
  448. */
  449. int write_feature(struct Format_info_pg *pg_info,
  450. int type, const struct line_pnts *points, int with_z,
  451. int cat, const struct field_info *Fi)
  452. {
  453. int byte_order, nbytes, nsize;
  454. unsigned int sf_type;
  455. unsigned char *wkb_data;
  456. char *stmt, *text_data, *text_data_p, *hex_data;
  457. if (with_z && pg_info->coor_dim != 3) {
  458. G_warning(_("Trying to insert 3D data into feature table "
  459. "which store 2D data only"));
  460. return -1;
  461. }
  462. if (!with_z && pg_info->coor_dim != 2) {
  463. G_warning(_("Trying to insert 2D data into feature table "
  464. "which store 3D data only"));
  465. return -1;
  466. }
  467. byte_order = ENDIAN_LITTLE; /* TODO: get endianness for system from dig__byte_order_out()? */
  468. /* get wkb data */
  469. nbytes = -1;
  470. wkb_data = NULL;
  471. if (type == GV_POINT)
  472. wkb_data = point_to_wkb(byte_order, points, with_z, &nbytes);
  473. else if (type == GV_LINE)
  474. wkb_data = linestring_to_wkb(byte_order, points, with_z, &nbytes);
  475. else if (type == GV_BOUNDARY)
  476. wkb_data = polygon_to_wkb(byte_order, points, with_z, &nbytes);
  477. if (!wkb_data || nbytes < 1) {
  478. G_warning(_("Unsupported feature type %d"), type);
  479. return -1;
  480. }
  481. /* When converting to hex, each byte takes 2 hex characters. In
  482. addition we add in 8 characters to represent the SRID integer
  483. in hex, and one for a null terminator */
  484. nsize = nbytes * 2 + 8 + 1;
  485. text_data = text_data_p = (char *) G_malloc(nsize);
  486. /* convert the 1st byte, which is the endianess flag, to hex */
  487. hex_data = binary_to_hex(1, wkb_data);
  488. strcpy(text_data_p, hex_data);
  489. G_free (hex_data);
  490. text_data_p += 2;
  491. /* get the geom type which is bytes 2 through 5 */
  492. memcpy(&sf_type, wkb_data + 1, 4);
  493. /* add the SRID flag if an SRID is provided */
  494. if (pg_info->srid > 0) {
  495. unsigned int srs_flag;
  496. /* change the flag to little endianess */
  497. srs_flag = LSBWORD32(WKBSRIDFLAG);
  498. /* apply the flag */
  499. sf_type = sf_type | srs_flag;
  500. }
  501. /* write the geom type which is 4 bytes */
  502. hex_data = binary_to_hex(4, (unsigned char*) &sf_type);
  503. strcpy(text_data_p, hex_data);
  504. G_free(hex_data);
  505. text_data_p += 8;
  506. /* include SRID if provided */
  507. if (pg_info->srid > 0) {
  508. unsigned int srs_id;
  509. /* force the srsid to little endianess */
  510. srs_id = LSBWORD32(pg_info->srid);
  511. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char*) &srs_id);
  512. strcpy(text_data_p, hex_data);
  513. G_free(hex_data);
  514. text_data_p += 8;
  515. }
  516. /* copy the rest of the data over - subtract 5 since we already
  517. copied 5 bytes above */
  518. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  519. strcpy(text_data_p, hex_data);
  520. G_free(hex_data);
  521. /* build INSERT statement */
  522. stmt = build_insert_stmt(pg_info, text_data, cat, Fi);
  523. G_debug(2, "SQL: %s", stmt);
  524. if (!pg_info->inTransaction) {
  525. /* start transaction */
  526. pg_info->inTransaction = TRUE;
  527. if (execute(pg_info->conn, "BEGIN") == -1)
  528. return -1;
  529. }
  530. if (execute(pg_info->conn, stmt) == -1) {
  531. /* rollback transaction */
  532. execute(pg_info->conn, "ROLLBACK");
  533. return -1;
  534. }
  535. G_free(wkb_data);
  536. G_free(text_data);
  537. G_free(stmt);
  538. return 0;
  539. }
  540. /*!
  541. \brief Build INSERT statement to insert new feature to the table
  542. \param pg_info pointer to Format_info_pg structure
  543. \param cat category number (or -1 for no category)
  544. \param Fi pointer to field_info structure (NULL for no attributes)
  545. \return allocated string with INSERT statement
  546. */
  547. char *build_insert_stmt(const struct Format_info_pg *pg_info,
  548. const char *geom_data,
  549. int cat, const struct field_info *Fi)
  550. {
  551. char *stmt, buf[DB_SQL_MAX];
  552. stmt = NULL;
  553. if (Fi && cat > -1) {
  554. int col, ncol, more;
  555. int sqltype, ctype;
  556. char buf_val[DB_SQL_MAX], buf_tmp[DB_SQL_MAX];
  557. char *str_val;
  558. const char *colname;
  559. dbString dbstmt;
  560. dbCursor cursor;
  561. dbTable *table;
  562. dbColumn *column;
  563. dbValue *value;
  564. db_init_string(&dbstmt);
  565. buf_val[0] = '\0';
  566. /* read & set attributes */
  567. sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key,
  568. cat);
  569. G_debug(4, "SQL: %s", buf);
  570. db_set_string(&dbstmt, buf);
  571. /* prepare INSERT statement */
  572. sprintf(buf, "INSERT INTO \"%s\".\"%s\" (%s",
  573. pg_info->schema_name, pg_info->table_name,
  574. pg_info->geom_column);
  575. /* select data */
  576. if (db_open_select_cursor(pg_info->dbdriver, &dbstmt,
  577. &cursor, DB_SEQUENTIAL) != DB_OK) {
  578. G_warning(_("Unable to select attributes for category %d"),
  579. cat);
  580. }
  581. else {
  582. if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
  583. G_warning(_("Unable to fetch data from table <%s>"),
  584. Fi->table);
  585. }
  586. if (!more) {
  587. G_warning(_("No database record for category %d, "
  588. "no attributes will be written"), cat);
  589. }
  590. else {
  591. table = db_get_cursor_table(&cursor);
  592. ncol = db_get_table_number_of_columns(table);
  593. for (col = 0; col < ncol; col++) {
  594. column = db_get_table_column(table, col);
  595. colname = db_get_column_name(column);
  596. /* skip fid column */
  597. if (strcmp(pg_info->fid_column, colname) == 0)
  598. continue;
  599. /* -> columns */
  600. sprintf(buf_tmp, ",%s", colname);
  601. strcat(buf, buf_tmp);
  602. /* -> values */
  603. value = db_get_column_value(column);
  604. /* for debug only */
  605. db_convert_column_value_to_string(column, &dbstmt);
  606. G_debug(2, "col %d : val = %s", col,
  607. db_get_string(&dbstmt));
  608. sqltype = db_get_column_sqltype(column);
  609. ctype = db_sqltype_to_Ctype(sqltype);
  610. /* prevent writing NULL values */
  611. if (!db_test_value_isnull(value)) {
  612. switch (ctype) {
  613. case DB_C_TYPE_INT:
  614. sprintf(buf_tmp, ",%d", db_get_value_int(value));
  615. break;
  616. case DB_C_TYPE_DOUBLE:
  617. sprintf(buf_tmp, ",%.14f", db_get_value_double(value));
  618. break;
  619. case DB_C_TYPE_STRING:
  620. str_val = G_store(db_get_value_string(value));
  621. G_str_to_sql(str_val);
  622. sprintf(buf_tmp, ",'%s'", str_val);
  623. G_free(str_val);
  624. break;
  625. case DB_C_TYPE_DATETIME:
  626. db_convert_column_value_to_string(column,
  627. &dbstmt);
  628. sprintf(buf_tmp, ",%s", db_get_string(&dbstmt));
  629. break;
  630. default:
  631. G_warning(_("Unsupported column type %d"), ctype);
  632. sprintf(buf_tmp, ",NULL");
  633. break;
  634. }
  635. }
  636. else {
  637. sprintf(buf_tmp, ",NULL");
  638. }
  639. strcat(buf_val, buf_tmp);
  640. }
  641. G_asprintf(&stmt, "%s) VALUES ('%s'::GEOMETRY%s)",
  642. buf, geom_data, buf_val);
  643. }
  644. }
  645. }
  646. if (!stmt) {
  647. /* no attributes */
  648. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  649. "('%s'::GEOMETRY)",
  650. pg_info->schema_name, pg_info->table_name,
  651. pg_info->geom_column, geom_data);
  652. }
  653. return stmt;
  654. }
  655. #endif