write_pg.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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 *, 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(struct Format_info_pg *,
  29. int, const struct line_pnts *, int,
  30. int, const struct field_info *);
  31. static char *build_insert_stmt(const struct Format_info_pg *, const char *,
  32. int, const struct field_info *);
  33. static char *build_topo_stmt(const struct Format_info_pg *, int, const char *);
  34. static char *build_topogeom_stmt(const struct Format_info_pg *, int, int, int);
  35. static int execute_topo(PGconn *, const char *);
  36. #endif
  37. /*!
  38. \brief Writes feature on level 1 (PostGIS interface)
  39. Note:
  40. - centroids are not supported in PostGIS, pseudotopo holds virtual
  41. centroids
  42. - boundaries are not supported in PostGIS, pseudotopo treats polygons
  43. as boundaries
  44. \param Map pointer to Map_info structure
  45. \param type feature type (GV_POINT, GV_LINE, ...)
  46. \param points pointer to line_pnts structure (feature geometry)
  47. \param cats pointer to line_cats structure (feature categories)
  48. \return feature offset into file
  49. \return -1 on error
  50. */
  51. off_t V1_write_line_pg(struct Map_info *Map, int type,
  52. const struct line_pnts *points,
  53. const struct line_cats *cats)
  54. {
  55. #ifdef HAVE_POSTGRES
  56. int cat;
  57. off_t offset;
  58. SF_FeatureType sf_type;
  59. struct field_info *Fi;
  60. struct Format_info_pg *pg_info;
  61. struct Format_info_offset *offset_info;
  62. pg_info = &(Map->fInfo.pg);
  63. offset_info = &(pg_info->offset);
  64. if (!pg_info->conn) {
  65. G_warning(_("No connection defined"));
  66. return -1;
  67. }
  68. if (!pg_info->table_name) {
  69. G_warning(_("PostGIS feature table not defined"));
  70. return -1;
  71. }
  72. if (pg_info->feature_type == SF_UNKNOWN) {
  73. /* create PostGIS table if doesn't exist */
  74. if (V2_open_new_pg(Map, type) < 0)
  75. return -1;
  76. }
  77. Fi = NULL; /* no attributes to be written */
  78. cat = -1;
  79. if (cats->n_cats > 0 && Vect_get_num_dblinks(Map) > 0) {
  80. /* check for attributes */
  81. Fi = Vect_get_dblink(Map, 0);
  82. if (Fi) {
  83. if (!Vect_cat_get(cats, Fi->number, &cat))
  84. G_warning(_("No category defined for layer %d"), Fi->number);
  85. if (cats->n_cats > 1) {
  86. G_warning(_("Feature has more categories, using "
  87. "category %d (from layer %d)"),
  88. cat, cats->field[0]);
  89. }
  90. }
  91. }
  92. sf_type = pg_info->feature_type;
  93. /* determine matching PostGIS feature geometry type */
  94. if (type & (GV_POINT | GV_KERNEL)) {
  95. if (sf_type != SF_POINT && sf_type != SF_POINT25D) {
  96. G_warning(_("Feature is not a point. Skipping."));
  97. return -1;
  98. }
  99. }
  100. else if (type & GV_LINE) {
  101. if (sf_type != SF_LINESTRING && 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, cat, Fi)) {
  137. execute(pg_info->conn, "ROLLBACK");
  138. return -1;
  139. }
  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,
  174. const struct line_cats * cats)
  175. {
  176. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%lu",
  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. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  364. }
  365. }
  366. return wkb_data;
  367. }
  368. /*!
  369. \bried Write polygon into WKB buffer
  370. See OGRPolygon::exportToWkb from GDAL/OGR library
  371. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  372. \param points feature geometry
  373. \param with_z WITH_Z for 3D data
  374. \param[out] nsize buffer size
  375. \return allocated WKB buffer
  376. \return NULL on error
  377. */
  378. unsigned char *polygon_to_wkb(int byte_order,
  379. const struct line_pnts *points, int with_z,
  380. int *nsize)
  381. {
  382. int i, point_size, nrings;
  383. unsigned char *wkb_data;
  384. unsigned int sf_type;
  385. if (points->n_points < 3)
  386. return NULL;
  387. /* allocate buffer */
  388. point_size = 8 * (with_z ? 3 : 2);
  389. /* one ring only */
  390. nrings = 1;
  391. *nsize = 9 + (4 + point_size * points->n_points);
  392. wkb_data = G_malloc(*nsize);
  393. G_zero(wkb_data, *nsize);
  394. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  395. /* set the byte order */
  396. if (byte_order == ENDIAN_LITTLE)
  397. wkb_data[0] = '\001';
  398. else
  399. wkb_data[0] = '\000';
  400. /* set the geometry feature type */
  401. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  402. if (byte_order == ENDIAN_LITTLE)
  403. sf_type = LSBWORD32(sf_type);
  404. else
  405. sf_type = MSBWORD32(sf_type);
  406. memcpy(wkb_data + 1, &sf_type, 4);
  407. /* copy in the raw data */
  408. if (byte_order == ENDIAN_BIG) {
  409. int ncount;
  410. ncount = SWAP32(nrings);
  411. memcpy(wkb_data + 5, &ncount, 4);
  412. }
  413. else {
  414. memcpy(wkb_data + 5, &nrings, 4);
  415. }
  416. /* serialize ring */
  417. memcpy(wkb_data + 9, &(points->n_points), 4);
  418. for (i = 0; i < points->n_points; i++) {
  419. memcpy(wkb_data + 9 + 4 + point_size * i, &(points->x[i]), 8);
  420. memcpy(wkb_data + 9 + 4 + 8 + point_size * i, &(points->y[i]), 8);
  421. if (with_z) {
  422. memcpy(wkb_data + 9 + 4 + 16 + point_size * i, &(points->z[i]),
  423. 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 = 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. simple feature geometry + attributes
  523. */
  524. stmt = build_insert_stmt(pg_info, text_data, cat, Fi);
  525. G_debug(2, "SQL: %s", stmt);
  526. if (!pg_info->inTransaction) {
  527. /* start transaction */
  528. pg_info->inTransaction = TRUE;
  529. if (execute(pg_info->conn, "BEGIN") == -1)
  530. return -1;
  531. }
  532. /* stmt can NULL when writing PostGIS topology with no attributes
  533. * attached */
  534. if (stmt && execute(pg_info->conn, stmt) == -1) {
  535. /* rollback transaction */
  536. execute(pg_info->conn, "ROLLBACK");
  537. return -1;
  538. }
  539. G_free(stmt);
  540. /* write feature in PostGIS topology schema if enabled */
  541. if (pg_info->toposchema_name) {
  542. int id, do_update;
  543. do_update = stmt ? TRUE : FALSE; /* update or insert new record
  544. to the feature table */
  545. /* insert feature into topology schema (node or edge) */
  546. stmt = build_topo_stmt(pg_info, type, text_data);
  547. id = execute_topo(pg_info->conn, stmt);
  548. if (id == -1) {
  549. /* rollback transaction */
  550. execute(pg_info->conn, "ROLLBACK");
  551. return -1;
  552. }
  553. G_free(stmt);
  554. /* insert topoelement into feature table) */
  555. stmt = build_topogeom_stmt(pg_info, id, type, do_update);
  556. if (execute(pg_info->conn, stmt) == -1) {
  557. /* rollback transaction */
  558. execute(pg_info->conn, "ROLLBACK");
  559. return -1;
  560. }
  561. G_free(stmt);
  562. }
  563. G_free(wkb_data);
  564. G_free(text_data);
  565. return 0;
  566. }
  567. /*!
  568. \brief Build INSERT statement to insert new feature to the table
  569. \param pg_info pointer to Format_info_pg structure
  570. \param cat category number (or -1 for no category)
  571. \param Fi pointer to field_info structure (NULL for no attributes)
  572. \return allocated string with INSERT statement
  573. */
  574. char *build_insert_stmt(const struct Format_info_pg *pg_info,
  575. const char *geom_data,
  576. int cat, const struct field_info *Fi)
  577. {
  578. char *stmt, buf[DB_SQL_MAX];
  579. stmt = NULL;
  580. if (Fi && cat > -1) {
  581. int col, ncol, more;
  582. int sqltype, ctype;
  583. char buf_val[DB_SQL_MAX], buf_tmp[DB_SQL_MAX];
  584. char *str_val;
  585. const char *colname;
  586. dbString dbstmt;
  587. dbCursor cursor;
  588. dbTable *table;
  589. dbColumn *column;
  590. dbValue *value;
  591. db_init_string(&dbstmt);
  592. buf_val[0] = '\0';
  593. /* read & set attributes */
  594. sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key,
  595. cat);
  596. G_debug(4, "SQL: %s", buf);
  597. db_set_string(&dbstmt, buf);
  598. /* prepare INSERT statement */
  599. sprintf(buf, "INSERT INTO \"%s\".\"%s\" (",
  600. pg_info->schema_name, pg_info->table_name);
  601. /* select data */
  602. if (db_open_select_cursor(pg_info->dbdriver, &dbstmt,
  603. &cursor, DB_SEQUENTIAL) != DB_OK) {
  604. G_warning(_("Unable to select attributes for category %d"), cat);
  605. }
  606. else {
  607. if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
  608. G_warning(_("Unable to fetch data from table <%s>"),
  609. Fi->table);
  610. }
  611. if (!more) {
  612. G_warning(_("No database record for category %d, "
  613. "no attributes will be written"), cat);
  614. }
  615. else {
  616. table = db_get_cursor_table(&cursor);
  617. ncol = db_get_table_number_of_columns(table);
  618. for (col = 0; col < ncol; col++) {
  619. column = db_get_table_column(table, col);
  620. colname = db_get_column_name(column);
  621. /* skip fid column */
  622. if (strcmp(pg_info->fid_column, colname) == 0)
  623. continue;
  624. /* -> columns */
  625. sprintf(buf_tmp, "%s", colname);
  626. strcat(buf, buf_tmp);
  627. if (col < ncol - 1)
  628. strcat(buf, ",");
  629. /* -> values */
  630. value = db_get_column_value(column);
  631. /* for debug only */
  632. db_convert_column_value_to_string(column, &dbstmt);
  633. G_debug(2, "col %d : val = %s", col,
  634. db_get_string(&dbstmt));
  635. sqltype = db_get_column_sqltype(column);
  636. ctype = db_sqltype_to_Ctype(sqltype);
  637. /* prevent writing NULL values */
  638. if (!db_test_value_isnull(value)) {
  639. switch (ctype) {
  640. case DB_C_TYPE_INT:
  641. sprintf(buf_tmp, "%d", db_get_value_int(value));
  642. break;
  643. case DB_C_TYPE_DOUBLE:
  644. sprintf(buf_tmp, "%.14f",
  645. db_get_value_double(value));
  646. break;
  647. case DB_C_TYPE_STRING:
  648. str_val = G_store(db_get_value_string(value));
  649. G_str_to_sql(str_val);
  650. sprintf(buf_tmp, "'%s'", str_val);
  651. G_free(str_val);
  652. break;
  653. case DB_C_TYPE_DATETIME:
  654. db_convert_column_value_to_string(column,
  655. &dbstmt);
  656. sprintf(buf_tmp, "%s", db_get_string(&dbstmt));
  657. break;
  658. default:
  659. G_warning(_("Unsupported column type %d"), ctype);
  660. sprintf(buf_tmp, "NULL");
  661. break;
  662. }
  663. }
  664. else {
  665. sprintf(buf_tmp, "NULL");
  666. }
  667. strcat(buf_val, buf_tmp);
  668. if (col < ncol - 1)
  669. strcat(buf_val, ",");
  670. }
  671. if (!pg_info->toposchema_name) {
  672. /* simple feature access */
  673. G_asprintf(&stmt, "%s,%s) VALUES (%s,'%s'::GEOMETRY)",
  674. buf, pg_info->geom_column, buf_val, geom_data);
  675. }
  676. else {
  677. /* PostGIS topology access, write geometry in
  678. * topology schema, skip geometry at this point */
  679. G_asprintf(&stmt, "%s) VALUES (%s)",
  680. buf, buf_val);
  681. }
  682. }
  683. }
  684. }
  685. else if (pg_info->toposchema_name)
  686. return NULL; /* don't write simple feature element */
  687. if (!stmt) {
  688. /* no attributes */
  689. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  690. "('%s'::GEOMETRY)",
  691. pg_info->schema_name, pg_info->table_name,
  692. pg_info->geom_column, geom_data);
  693. }
  694. return stmt;
  695. }
  696. /*!
  697. \brief Build SELECT statement to insert new element into PostGIS
  698. topology schema
  699. \param pg_info so pointer to Format_info_pg
  700. \param type feature type (GV_POINT, ...)
  701. \param geom_data geometry in wkb
  702. \return pointer to allocated string buffer with SQL statement
  703. \return NULL on error
  704. */
  705. char *build_topo_stmt(const struct Format_info_pg *pg_info,
  706. int type, const char *geom_data)
  707. {
  708. char *stmt;
  709. stmt = NULL;
  710. if (type == GV_POINT) {
  711. G_asprintf(&stmt, "SELECT AddNode('%s', '%s'::GEOMETRY)",
  712. pg_info->toposchema_name, geom_data);
  713. }
  714. return stmt;
  715. }
  716. /*!
  717. \brief Build INSERT / UPDATE statement to insert topo geometry
  718. object into feature table
  719. Allocated string should be freed by G_free()
  720. \param pg_info so pointer to Format_info_pg
  721. \param type feature type (GV_POINT, ...)
  722. \param id topology element id
  723. \param do_update TRUE for UPDATE otherwise build SELECT statement
  724. \return pointer to allocated string buffer with SQL statement
  725. \return NULL on error
  726. */
  727. char *build_topogeom_stmt(const struct Format_info_pg *pg_info,
  728. int id, int type, int do_update)
  729. {
  730. int topogeom_type;
  731. char *stmt;
  732. stmt = NULL;
  733. if (type == GV_POINT)
  734. topogeom_type = 1;
  735. else if (type == GV_LINES)
  736. topogeom_type = 2;
  737. else {
  738. G_warning(_("Unsupported topo geometry type %d"), type);
  739. return NULL;
  740. }
  741. if (!do_update)
  742. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  743. "(topology.CreateTopoGeom('%s', 1, %d, "
  744. "'{{%d, %d}}'::topology.topoelementarray))",
  745. pg_info->schema_name, pg_info->table_name,
  746. pg_info->topogeom_column, pg_info->toposchema_name,
  747. topogeom_type, id, topogeom_type);
  748. else
  749. G_asprintf(&stmt, "UPDATE \"%s\".\"%s\" SET %s = "
  750. "topology.CreateTopoGeom('%s', 1, %d, "
  751. "'{{%d, %d}}'::topology.topoelementarray) "
  752. "WHERE %s = %d",
  753. pg_info->schema_name, pg_info->table_name,
  754. pg_info->topogeom_column, pg_info->toposchema_name,
  755. topogeom_type, id, topogeom_type,
  756. pg_info->fid_column, id);
  757. return stmt;
  758. }
  759. /*!
  760. \brief Execute SQL topo select statement
  761. \param conn pointer to PGconn
  762. \param stmt query
  763. \return value on success
  764. \return -1 on error
  765. */
  766. int execute_topo(PGconn *conn, const char *stmt)
  767. {
  768. int ret;
  769. PGresult *result;
  770. result = NULL;
  771. G_debug(3, "execute_topo(): %s", stmt);
  772. result = PQexec(conn, stmt);
  773. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK ||
  774. PQntuples(result) != 1) {
  775. PQclear(result);
  776. G_warning(_("Execution failed: %s"), PQerrorMessage(conn));
  777. return -1;
  778. }
  779. ret = atoi(PQgetvalue(result, 0, 0));
  780. PQclear(result);
  781. return ret;
  782. }
  783. #endif