read_pg.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. /*!
  2. \file lib/vector/Vlib/read_pg.c
  3. \brief Vector library - reading features (PostGIS format)
  4. Higher level functions for reading/writing/manipulating vectors.
  5. \todo Currently only points, linestrings and polygons are supported,
  6. implement also other types
  7. (C) 2011-2012 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. \author Martin Landa <landa.martin gmail.com>
  11. */
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <limits.h>
  15. #include <grass/vector.h>
  16. #include <grass/dbmi.h>
  17. #include <grass/glocale.h>
  18. #ifdef HAVE_POSTGRES
  19. #include "pg_local_proto.h"
  20. static unsigned char *wkb_data;
  21. static unsigned int wkb_data_length;
  22. static int read_next_line_pg(struct Map_info *,
  23. struct line_pnts *, struct line_cats *, int);
  24. SF_FeatureType get_feature(struct Format_info_pg *, int, const char *);
  25. static unsigned char *hex_to_wkb(const char *, int *);
  26. static int point_from_wkb(const unsigned char *, int, int, int,
  27. struct line_pnts *);
  28. static int linestring_from_wkb(const unsigned char *, int, int, int,
  29. struct line_pnts *, int);
  30. static int polygon_from_wkb(const unsigned char *, int, int, int,
  31. struct Format_info_cache *, int *);
  32. static int geometry_collection_from_wkb(const unsigned char *, int, int, int,
  33. struct Format_info_cache *,
  34. struct feat_parts *);
  35. static int error_corrupted_data(const char *);
  36. static int set_initial_query();
  37. static void reallocate_cache(struct Format_info_cache *, int);
  38. static void add_fpart(struct feat_parts *, SF_FeatureType, int, int);
  39. static int read_centroid_pg(struct Format_info_pg *, int, struct line_pnts *);
  40. #endif
  41. /*!
  42. \brief Read next feature from PostGIS layer. Skip
  43. empty features (level 1 without topology).
  44. t
  45. This function implements sequential access.
  46. The action of this routine can be modified by:
  47. - Vect_read_constraint_region()
  48. - Vect_read_constraint_type()
  49. - Vect_remove_constraints()
  50. \param Map pointer to Map_info structure
  51. \param[out] line_p container used to store line points within
  52. (pointer to line_pnts struct)
  53. \param[out] line_c container used to store line categories within
  54. (pointer line_cats struct)
  55. \return feature type
  56. \return -2 no more features (EOF)
  57. \return -1 out of memory
  58. */
  59. int V1_read_next_line_pg(struct Map_info *Map,
  60. struct line_pnts *line_p, struct line_cats *line_c)
  61. {
  62. #ifdef HAVE_POSTGRES
  63. G_debug(3, "V1_read_next_line_pg()");
  64. /* constraints not ignored */
  65. return read_next_line_pg(Map, line_p, line_c, FALSE);
  66. #else
  67. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  68. return -1;
  69. #endif
  70. }
  71. /*!
  72. \brief Read next feature from PostGIS layer on topological level.
  73. This function implements sequential access.
  74. \param Map pointer to Map_info structure
  75. \param[out] line_p container used to store line points within
  76. (pointer to line_pnts struct)
  77. \param[out] line_c container used to store line categories within
  78. (pointer to line_cats struct)
  79. \return feature type
  80. \return -2 no more features (EOF)
  81. \return -1 on failure
  82. */
  83. int V2_read_next_line_pg(struct Map_info *Map, struct line_pnts *line_p,
  84. struct line_cats *line_c)
  85. {
  86. #ifdef HAVE_POSTGRES
  87. int line, ret;
  88. struct P_line *Line;
  89. struct bound_box lbox, mbox;
  90. G_debug(3, "V2_read_next_line_pg()");
  91. if (Map->constraint.region_flag)
  92. Vect_get_constraint_box(Map, &mbox);
  93. ret = -1;
  94. while (TRUE) {
  95. line = Map->next_line;
  96. if (Map->next_line > Map->plus.n_lines)
  97. return -2;
  98. Line = Map->plus.Line[line];
  99. if (Line == NULL) { /* skip dead features */
  100. Map->next_line++;
  101. continue;
  102. }
  103. if (Map->constraint.type_flag) {
  104. /* skip by type */
  105. if (!(Line->type & Map->constraint.type)) {
  106. Map->next_line++;
  107. continue;
  108. }
  109. }
  110. if (Line->type == GV_CENTROID) {
  111. G_debug(4, "Centroid");
  112. Map->next_line++;
  113. if (line_p != NULL) {
  114. int i, found;
  115. struct bound_box box;
  116. struct boxlist list;
  117. struct P_topo_c *topo = (struct P_topo_c *)Line->topo;
  118. /* get area bbox */
  119. Vect_get_area_box(Map, topo->area, &box);
  120. /* search in spatial index for centroid with area bbox */
  121. dig_init_boxlist(&list, TRUE);
  122. Vect_select_lines_by_box(Map, &box, Line->type, &list);
  123. found = -1;
  124. for (i = 0; i < list.n_values; i++) {
  125. if (list.id[i] == line) {
  126. found = i;
  127. break;
  128. }
  129. }
  130. if (found > -1) {
  131. Vect_reset_line(line_p);
  132. Vect_append_point(line_p, list.box[found].E,
  133. list.box[found].N, 0.0);
  134. }
  135. }
  136. if (line_c != NULL) {
  137. /* cat = FID and offset = FID for centroid */
  138. Vect_reset_cats(line_c);
  139. Vect_cat_set(line_c, 1, (int)Line->offset);
  140. }
  141. ret = GV_CENTROID;
  142. }
  143. else {
  144. /* ignore constraints, Map->next_line incremented */
  145. ret = read_next_line_pg(Map, line_p, line_c, TRUE);
  146. if (ret != Line->type)
  147. G_fatal_error(_("Unexpected feature type (%s) - should be (%d)"),
  148. ret, Line->type);
  149. }
  150. if (Map->constraint.region_flag) {
  151. /* skip by region */
  152. Vect_line_box(line_p, &lbox);
  153. if (!Vect_box_overlap(&lbox, &mbox)) {
  154. continue;
  155. }
  156. }
  157. /* skip by field ignored */
  158. return ret;
  159. }
  160. #else
  161. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  162. #endif
  163. return -1; /* not reached */
  164. }
  165. /*!
  166. \brief Read feature from PostGIS layer at given offset (level 1 without topology)
  167. This function implements random access on level 1.
  168. \param Map pointer to Map_info structure
  169. \param[out] line_p container used to store line points within
  170. (pointer line_pnts struct)
  171. \param[out] line_c container used to store line categories within
  172. (pointer line_cats struct)
  173. \param offset given offset
  174. \return line type
  175. \return 0 dead line
  176. \return -2 no more features
  177. \return -1 out of memory
  178. */
  179. int V1_read_line_pg(struct Map_info *Map,
  180. struct line_pnts *line_p, struct line_cats *line_c,
  181. off_t offset)
  182. {
  183. #ifdef HAVE_POSTGRES
  184. long fid;
  185. int ipart, type;
  186. struct Format_info_pg *pg_info;
  187. pg_info = &(Map->fInfo.pg);
  188. G_debug(3, "V1_read_line_pg(): offset = %lu offset_num = %lu",
  189. (long)offset, (long)pg_info->offset.array_num);
  190. if (offset >= pg_info->offset.array_num)
  191. return -2; /* nothing to read */
  192. if (line_p != NULL)
  193. Vect_reset_line(line_p);
  194. if (line_c != NULL)
  195. Vect_reset_cats(line_c);
  196. fid = pg_info->offset.array[offset];
  197. G_debug(4, " fid = %ld", fid);
  198. /* read feature to cache if necessary */
  199. if (pg_info->cache.fid != fid) {
  200. int type;
  201. G_debug(3, "read (%s) feature (fid = %ld) to cache",
  202. pg_info->table_name, fid);
  203. get_feature(pg_info, fid, NULL);
  204. if (pg_info->cache.sf_type == SF_NONE) {
  205. G_warning(_("Feature %d without geometry skipped"), fid);
  206. return -1;
  207. }
  208. type = (int)pg_info->cache.sf_type;
  209. if (type < 0) /* -1 || - 2 */
  210. return type;
  211. }
  212. /* get data from cache */
  213. if (pg_info->cache.sf_type == SF_POINT ||
  214. pg_info->cache.sf_type == SF_LINESTRING)
  215. ipart = 0;
  216. else
  217. ipart = pg_info->offset.array[offset + 1];
  218. type = pg_info->cache.lines_types[ipart];
  219. G_debug(3, "read feature part: %d -> type = %d", ipart, type);
  220. if (line_p)
  221. Vect_append_points(line_p, pg_info->cache.lines[ipart], GV_FORWARD);
  222. if (line_c)
  223. Vect_cat_set(line_c, 1, (int)fid);
  224. return type;
  225. #else
  226. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  227. return -1;
  228. #endif
  229. }
  230. int V3_read_line_pg(struct Map_info *Map, struct line_pnts *line_p,
  231. struct line_cats *line_c, int line)
  232. {
  233. #ifdef HAVE_POSTGRES
  234. int type;
  235. char *topotable_name;
  236. struct Format_info_pg *pg_info;
  237. struct P_line *Line;
  238. pg_info = &(Map->fInfo.pg);
  239. Line = Map->plus.Line[line];
  240. if (Line == NULL) {
  241. G_warning(_("Attempt to read dead feature %d"), line);
  242. return -1;
  243. }
  244. G_debug(4, "V3_read_line_pg() line = %d type = %d offset = %llu",
  245. line, Line->type, Line->offset);
  246. if (!line_p && !line_c)
  247. return Line->type;
  248. if (line_p != NULL)
  249. Vect_reset_line(line_p);
  250. if (line_c != NULL)
  251. Vect_reset_cats(line_c);
  252. if (line_c)
  253. Vect_cat_set(line_c, 1, (int) Line->offset);
  254. if (Line->type == GV_POINT)
  255. topotable_name = "node";
  256. else if (Line->type & GV_LINES)
  257. topotable_name = "edge";
  258. else if (Line->type == GV_CENTROID) {
  259. return read_centroid_pg(pg_info, (int) Line->offset, line_p);
  260. }
  261. else {
  262. G_warning(_("Unsupported feature type %d"), Line->type);
  263. return -1;
  264. }
  265. get_feature(pg_info, Line->offset, topotable_name);
  266. if (pg_info->cache.sf_type == SF_NONE) {
  267. G_warning(_("Feature %d without geometry skipped"), Line->offset);
  268. return -1;
  269. }
  270. type = (int)pg_info->cache.sf_type;
  271. if (type < 0) /* -1 || - 2 */
  272. return type;
  273. if (Line->type == GV_BOUNDARY && type == GV_LINE)
  274. type = GV_BOUNDARY;
  275. if (line_p)
  276. Vect_append_points(line_p, pg_info->cache.lines[0], GV_FORWARD);
  277. return type;
  278. #else
  279. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  280. return -1;
  281. #endif
  282. }
  283. #ifdef HAVE_POSTGRES
  284. /*!
  285. \brief Read next feature from PostGIS layer.
  286. \param Map pointer to Map_info structure
  287. \param[out] line_p container used to store line points within
  288. (pointer to line_pnts struct)
  289. \param[out] line_c container used to store line categories within
  290. (pointer line_cats struct)
  291. \param ignore_constraints TRUE to ignore constraints (type, region)
  292. \return feature type
  293. \return -2 no more features (EOF)
  294. \return -1 out of memory
  295. */
  296. int read_next_line_pg(struct Map_info *Map,
  297. struct line_pnts *line_p, struct line_cats *line_c,
  298. int ignore_constraints)
  299. {
  300. int line, itype;
  301. SF_FeatureType sf_type;
  302. struct Format_info_pg *pg_info;
  303. struct bound_box mbox, lbox;
  304. struct line_pnts *iline;
  305. pg_info = &(Map->fInfo.pg);
  306. if (Map->constraint.region_flag && !ignore_constraints)
  307. Vect_get_constraint_box(Map, &mbox);
  308. while (TRUE) {
  309. line = Map->next_line++; /* level 2 only */
  310. /* reset data structures */
  311. if (line_p != NULL)
  312. Vect_reset_line(line_p);
  313. if (line_c != NULL)
  314. Vect_reset_cats(line_c);
  315. /* read feature to cache if necessary */
  316. while (pg_info->cache.lines_next == pg_info->cache.lines_num) {
  317. /* cache feature -> line_p & line_c */
  318. sf_type = get_feature(pg_info, -1, NULL);
  319. if (sf_type == SF_NONE) {
  320. G_warning(_("Feature %d without geometry skipped"), line);
  321. return -1;
  322. }
  323. if ((int)sf_type < 0) /* -1 || - 2 */
  324. return (int)sf_type;
  325. if (sf_type == SF_UNKNOWN || sf_type == SF_NONE) {
  326. G_warning(_("Feature without geometry. Skipped."));
  327. pg_info->cache.lines_next = pg_info->cache.lines_num = 0;
  328. continue;
  329. }
  330. G_debug(4, "%d lines read to cache", pg_info->cache.lines_num);
  331. }
  332. /* get data from cache */
  333. itype = pg_info->cache.lines_types[pg_info->cache.lines_next];
  334. iline = pg_info->cache.lines[pg_info->cache.lines_next];
  335. G_debug(4, "read next cached line %d (type = %d)",
  336. pg_info->cache.lines_next, itype);
  337. /* apply constraints */
  338. if (Map->constraint.type_flag && !ignore_constraints) {
  339. /* skip feature by type */
  340. if (!(itype & Map->constraint.type))
  341. continue;
  342. }
  343. if (line_p && Map->constraint.region_flag && !ignore_constraints) {
  344. /* skip feature by region */
  345. Vect_line_box(iline, &lbox);
  346. if (!Vect_box_overlap(&lbox, &mbox))
  347. continue;
  348. }
  349. /* skip feature by field ignored */
  350. if (line_p)
  351. Vect_append_points(line_p, iline, GV_FORWARD);
  352. if (line_c)
  353. Vect_cat_set(line_c, 1, (int)pg_info->cache.fid);
  354. pg_info->cache.lines_next++;
  355. return itype;
  356. }
  357. return -1; /* not reached */
  358. }
  359. /*!
  360. \brief Read feature geometry
  361. Geometry is stored in lines cache.
  362. \param[in,out] pg_info pointer to Format_info_pg struct
  363. \param fid feature id to be read (-1 for next)
  364. \param topotable_name table name for topological access (NULL for pseudo-topological access) - "node" or "edge"
  365. \return simple feature type (SF_POINT, SF_LINESTRING, ...)
  366. \return -1 on error
  367. */
  368. SF_FeatureType get_feature(struct Format_info_pg *pg_info, int fid,
  369. const char *topotable_name)
  370. {
  371. char *data;
  372. char stmt[DB_SQL_MAX];
  373. if (!topotable_name && !pg_info->geom_column) {
  374. G_warning(_("No geometry column defined"));
  375. return -1;
  376. }
  377. if (fid < 1) {
  378. /* next (read n features) */
  379. if (!pg_info->res) {
  380. if (set_initial_query(pg_info) == -1)
  381. return -1;
  382. }
  383. }
  384. else {
  385. if (!topotable_name && !pg_info->fid_column) {
  386. G_warning(_("Random access not supported. "
  387. "Primary key not defined."));
  388. return -1;
  389. }
  390. if (execute(pg_info->conn, "BEGIN") == -1)
  391. return -1;
  392. if (!topotable_name) {
  393. /* simple feature access */
  394. sprintf(stmt,
  395. "DECLARE %s_%s%p CURSOR FOR SELECT %s FROM \"%s\".\"%s\" "
  396. "WHERE %s = %d", pg_info->schema_name, pg_info->table_name,
  397. pg_info->conn, pg_info->geom_column, pg_info->schema_name,
  398. pg_info->table_name, pg_info->fid_column, fid);
  399. }
  400. else {
  401. /* topological access */
  402. sprintf(stmt,
  403. "DECLARE %s_%s%p CURSOR FOR SELECT geom FROM \"%s\".\"%s\" "
  404. "WHERE %s_id = %d", pg_info->schema_name, pg_info->table_name,
  405. pg_info->conn, pg_info->toposchema_name,
  406. topotable_name, topotable_name, fid);
  407. }
  408. if (execute(pg_info->conn, stmt) == -1)
  409. return -1;
  410. sprintf(stmt, "FETCH ALL in %s_%s%p",
  411. pg_info->schema_name, pg_info->table_name, pg_info->conn);
  412. pg_info->res = PQexec(pg_info->conn, stmt);
  413. pg_info->next_line = 0;
  414. }
  415. if (!pg_info->res || PQresultStatus(pg_info->res) != PGRES_TUPLES_OK) {
  416. PQclear(pg_info->res);
  417. G_warning(_("Reading failed: %s"), PQerrorMessage(pg_info->conn));
  418. pg_info->res = NULL;
  419. return -1; /* reading failed */
  420. }
  421. /* do we need to fetch more records ? */
  422. if (PQntuples(pg_info->res) == CURSOR_PAGE &&
  423. PQntuples(pg_info->res) == pg_info->next_line) {
  424. char stmt[DB_SQL_MAX];
  425. PQclear(pg_info->res);
  426. sprintf(stmt, "FETCH %d in %s_%s%p", CURSOR_PAGE,
  427. pg_info->schema_name, pg_info->table_name, pg_info->conn);
  428. pg_info->res = PQexec(pg_info->conn, stmt);
  429. if (!pg_info->res) {
  430. execute(pg_info->conn, "ROLLBACK");
  431. return -1;
  432. }
  433. pg_info->next_line = 0;
  434. }
  435. /* out of results ? */
  436. if (PQntuples(pg_info->res) == pg_info->next_line) {
  437. if (pg_info->res) {
  438. PQclear(pg_info->res);
  439. pg_info->res = NULL;
  440. sprintf(stmt, "CLOSE %s_%s%p",
  441. pg_info->schema_name, pg_info->table_name, pg_info->conn);
  442. if (execute(pg_info->conn, stmt) == -1) {
  443. execute(pg_info->conn, "ROLLBACK");
  444. G_warning(_("Unable to close cursor"));
  445. return -1;
  446. }
  447. execute(pg_info->conn, "COMMIT");
  448. }
  449. return -2;
  450. }
  451. data = (char *)PQgetvalue(pg_info->res, pg_info->next_line, 0);
  452. pg_info->cache.sf_type =
  453. cache_feature(data, FALSE, &(pg_info->cache), NULL);
  454. if (fid < 0) {
  455. pg_info->cache.fid =
  456. atoi(PQgetvalue(pg_info->res, pg_info->next_line, 1));
  457. pg_info->next_line++;
  458. }
  459. else {
  460. pg_info->cache.fid = fid;
  461. PQclear(pg_info->res);
  462. pg_info->res = NULL;
  463. sprintf(stmt, "CLOSE %s_%s%p",
  464. pg_info->schema_name, pg_info->table_name, pg_info->conn);
  465. if (execute(pg_info->conn, stmt) == -1) {
  466. G_warning(_("Unable to close cursor"));
  467. return -1;
  468. }
  469. if (execute(pg_info->conn, "COMMIT") == -1)
  470. return -1;
  471. }
  472. return pg_info->cache.sf_type;
  473. }
  474. /*!
  475. \brief Convert HEX to WKB data
  476. \param hex_data HEX data
  477. \param[out] nbytes number of bytes in output buffer
  478. \return pointer to WKB data buffer
  479. */
  480. unsigned char *hex_to_wkb(const char *hex_data, int *nbytes)
  481. {
  482. unsigned int length;
  483. int i;
  484. length = strlen(hex_data) / 2 + 1;
  485. if (length > wkb_data_length) {
  486. wkb_data_length = length;
  487. wkb_data = G_realloc(wkb_data, wkb_data_length);
  488. }
  489. *nbytes = length - 1;
  490. for (i = 0; i < (*nbytes); i++) {
  491. wkb_data[i] =
  492. (unsigned
  493. char)((hex_data[2 * i] >
  494. 'F' ? hex_data[2 * i] - 0x57 : hex_data[2 * i] >
  495. '9' ? hex_data[2 * i] - 0x37 : hex_data[2 * i] -
  496. 0x30) << 4);
  497. wkb_data[i] |=
  498. (unsigned char)(hex_data[2 * i + 1] >
  499. 'F' ? hex_data[2 * i + 1] -
  500. 0x57 : hex_data[2 * i + 1] >
  501. '9' ? hex_data[2 * i + 1] -
  502. 0x37 : hex_data[2 * i + 1] - 0x30);
  503. }
  504. wkb_data[(*nbytes)] = 0;
  505. return wkb_data;
  506. }
  507. /*!
  508. \brief Read geometry from HEX data
  509. This code is inspired by OGRGeometryFactory::createFromWkb() from
  510. GDAL/OGR library.
  511. \param data HEX data
  512. \param skip_polygon skip polygons (level 1)
  513. \param[out] cache lines cache
  514. \param[out] fparts used for building pseudo-topology (or NULL)
  515. \return simple feature type
  516. \return SF_UNKNOWN on error
  517. */
  518. SF_FeatureType cache_feature(const char *data, int skip_polygon,
  519. struct Format_info_cache * cache,
  520. struct feat_parts * fparts)
  521. {
  522. int ret, byte_order, nbytes, is3D;
  523. unsigned char *wkb_data;
  524. unsigned int wkb_flags;
  525. SF_FeatureType ftype;
  526. /* reset cache */
  527. cache->lines_num = 0;
  528. cache->fid = -1;
  529. /* next to be read from cache */
  530. cache->lines_next = 0;
  531. if (fparts)
  532. fparts->n_parts = 0;
  533. wkb_flags = 0;
  534. wkb_data = hex_to_wkb(data, &nbytes);
  535. if (nbytes < 5) {
  536. /* G_free(wkb_data); */
  537. if (nbytes > 0) {
  538. G_debug(3, "cache_feature(): invalid geometry");
  539. G_warning(_("Invalid WKB content: %d bytes"), nbytes);
  540. return SF_UNKNOWN;
  541. }
  542. else {
  543. G_debug(3, "cache_feature(): no geometry");
  544. return SF_NONE;
  545. }
  546. }
  547. /* parsing M coordinate not supported */
  548. memcpy(&wkb_flags, wkb_data + 1, 4);
  549. byte_order = (wkb_data[0] == 0 ? ENDIAN_BIG : ENDIAN_LITTLE);
  550. if (byte_order == ENDIAN_BIG)
  551. wkb_flags = SWAP32(wkb_flags);
  552. if (wkb_flags & 0x40000000) {
  553. G_warning(_("Reading EWKB with 4-dimensional coordinates (XYZM) "
  554. "is not supported"));
  555. /* G_free(wkb_data); */
  556. return SF_UNKNOWN;
  557. }
  558. /* PostGIS EWKB format includes an SRID, but this won't be
  559. understood by OGR, so if the SRID flag is set, we remove the
  560. SRID (bytes at offset 5 to 8).
  561. */
  562. if (nbytes > 9 &&
  563. ((byte_order == ENDIAN_BIG && (wkb_data[1] & 0x20)) ||
  564. (byte_order == ENDIAN_LITTLE && (wkb_data[4] & 0x20)))) {
  565. memmove(wkb_data + 5, wkb_data + 9, nbytes - 9);
  566. nbytes -= 4;
  567. if (byte_order == ENDIAN_BIG)
  568. wkb_data[1] &= (~0x20);
  569. else
  570. wkb_data[4] &= (~0x20);
  571. }
  572. if (nbytes < 9 && nbytes != -1) {
  573. /* G_free(wkb_data); */
  574. return SF_UNKNOWN;
  575. }
  576. /* Get the geometry feature type. For now we assume that geometry
  577. type is between 0 and 255 so we only have to fetch one byte.
  578. */
  579. if (byte_order == ENDIAN_LITTLE) {
  580. ftype = (SF_FeatureType) wkb_data[1];
  581. is3D = wkb_data[4] & 0x80 || wkb_data[2] & 0x80;
  582. }
  583. else {
  584. ftype = (SF_FeatureType) wkb_data[4];
  585. is3D = wkb_data[1] & 0x80 || wkb_data[3] & 0x80;
  586. }
  587. G_debug(3, "cache_feature(): sf_type = %d", ftype);
  588. /* allocate space in lines cache - be minimalistic
  589. more lines require eg. polygon with more rings, multi-features
  590. or geometry collections
  591. */
  592. if (!cache->lines) {
  593. reallocate_cache(cache, 1);
  594. }
  595. ret = -1;
  596. if (ftype == SF_POINT) {
  597. cache->lines_num = 1;
  598. cache->lines_types[0] = GV_POINT;
  599. ret = point_from_wkb(wkb_data, nbytes, byte_order,
  600. is3D, cache->lines[0]);
  601. add_fpart(fparts, ftype, 0, 1);
  602. }
  603. else if (ftype == SF_LINESTRING) {
  604. cache->lines_num = 1;
  605. cache->lines_types[0] = GV_LINE;
  606. ret = linestring_from_wkb(wkb_data, nbytes, byte_order,
  607. is3D, cache->lines[0], FALSE);
  608. add_fpart(fparts, ftype, 0, 1);
  609. }
  610. else if (ftype == SF_POLYGON && !skip_polygon) {
  611. int nrings;
  612. ret = polygon_from_wkb(wkb_data, nbytes, byte_order,
  613. is3D, cache, &nrings);
  614. add_fpart(fparts, ftype, 0, nrings);
  615. }
  616. else if (ftype == SF_MULTIPOINT ||
  617. ftype == SF_MULTILINESTRING ||
  618. ftype == SF_MULTIPOLYGON || ftype == SF_GEOMETRYCOLLECTION) {
  619. ret = geometry_collection_from_wkb(wkb_data, nbytes, byte_order,
  620. is3D, cache, fparts);
  621. }
  622. else {
  623. G_warning(_("Unsupported feature type %d"), ftype);
  624. }
  625. /* read next feature from cache */
  626. cache->lines_next = 0;
  627. /* G_free(wkb_data); */
  628. return ret > 0 ? ftype : SF_UNKNOWN;
  629. }
  630. /*!
  631. \brief Read point for WKB data
  632. See OGRPoint::importFromWkb() from GDAL/OGR library
  633. \param wkb_data WKB data
  634. \param nbytes number of bytes (WKB data buffer)
  635. \param byte_order byte order (ENDIAN_LITTLE, ENDIAN_BIG)
  636. \param with_z WITH_Z for 3D data
  637. \param[out] line_p point geometry (pointer to line_pnts struct)
  638. \return wkb size
  639. \return -1 on error
  640. */
  641. int point_from_wkb(const unsigned char *wkb_data, int nbytes, int byte_order,
  642. int with_z, struct line_pnts *line_p)
  643. {
  644. double x, y, z;
  645. if (nbytes < 21 && nbytes != -1)
  646. return -1;
  647. /* get vertex */
  648. memcpy(&x, wkb_data + 5, 8);
  649. memcpy(&y, wkb_data + 5 + 8, 8);
  650. if (byte_order == ENDIAN_BIG) {
  651. SWAPDOUBLE(&x);
  652. SWAPDOUBLE(&y);
  653. }
  654. if (with_z) {
  655. if (nbytes < 29 && nbytes != -1)
  656. return -1;
  657. memcpy(&z, wkb_data + 5 + 16, 8);
  658. if (byte_order == ENDIAN_BIG) {
  659. SWAPDOUBLE(&z);
  660. }
  661. }
  662. else {
  663. z = 0.0;
  664. }
  665. if (line_p) {
  666. Vect_reset_line(line_p);
  667. Vect_append_point(line_p, x, y, z);
  668. }
  669. return 5 + 8 * (with_z == WITH_Z ? 3 : 2);
  670. }
  671. /*!
  672. \brief Read line for WKB data
  673. See OGRLineString::importFromWkb() from GDAL/OGR library
  674. \param wkb_data WKB data
  675. \param nbytes number of bytes (WKB data buffer)
  676. \param byte_order byte order (ENDIAN_LITTLE, ENDIAN_BIG)
  677. \param with_z WITH_Z for 3D data
  678. \param[out] line_p line geometry (pointer to line_pnts struct)
  679. \return wkb size
  680. \return -1 on error
  681. */
  682. int linestring_from_wkb(const unsigned char *wkb_data, int nbytes,
  683. int byte_order, int with_z, struct line_pnts *line_p,
  684. int is_ring)
  685. {
  686. int npoints, point_size, buff_min_size, offset;
  687. int i;
  688. double x, y, z;
  689. if (is_ring)
  690. offset = 5;
  691. else
  692. offset = 0;
  693. if (is_ring && nbytes < 4 && nbytes != -1)
  694. return error_corrupted_data(NULL);
  695. /* get the vertex count */
  696. memcpy(&npoints, wkb_data + (5 - offset), 4);
  697. if (byte_order == ENDIAN_BIG) {
  698. npoints = SWAP32(npoints);
  699. }
  700. /* check if the wkb stream buffer is big enough to store fetched
  701. number of points. 16 or 24 - size of point structure
  702. */
  703. point_size = with_z ? 24 : 16;
  704. if (npoints < 0 || npoints > INT_MAX / point_size)
  705. return error_corrupted_data(NULL);
  706. buff_min_size = point_size * npoints;
  707. if (nbytes != -1 && buff_min_size > nbytes - (9 - offset))
  708. return error_corrupted_data(_("Length of input WKB is too small"));
  709. if (line_p)
  710. Vect_reset_line(line_p);
  711. /* get the vertex */
  712. for (i = 0; i < npoints; i++) {
  713. memcpy(&x, wkb_data + (9 - offset) + i * point_size, 8);
  714. memcpy(&y, wkb_data + (9 - offset) + 8 + i * point_size, 8);
  715. if (with_z)
  716. memcpy(&z, wkb_data + (9 - offset) + 16 + i * point_size, 8);
  717. else
  718. z = 0.0;
  719. if (byte_order == ENDIAN_BIG) {
  720. SWAPDOUBLE(&x);
  721. SWAPDOUBLE(&y);
  722. if (with_z)
  723. SWAPDOUBLE(&z);
  724. }
  725. if (line_p)
  726. Vect_append_point(line_p, x, y, z);
  727. }
  728. return (9 - offset) + (with_z == WITH_Z ? 3 : 2) * 8 * line_p->n_points;
  729. }
  730. /*!
  731. \brief Read polygon for WKB data
  732. See OGRPolygon::importFromWkb() from GDAL/OGR library
  733. \param wkb_data WKB data
  734. \param nbytes number of bytes (WKB data buffer)
  735. \param byte_order byte order (ENDIAN_LITTLE, ENDIAN_BIG)
  736. \param with_z WITH_Z for 3D data
  737. \param[out] line_p array of rings (pointer to line_pnts struct)
  738. \param[out] nrings number of rings
  739. \return wkb size
  740. \return -1 on error
  741. */
  742. int polygon_from_wkb(const unsigned char *wkb_data, int nbytes,
  743. int byte_order, int with_z,
  744. struct Format_info_cache *cache, int *nrings)
  745. {
  746. int data_offset, i, nsize, isize;
  747. struct line_pnts *line_i;
  748. if (nbytes < 9 && nbytes != -1)
  749. return -1;
  750. /* get the ring count */
  751. memcpy(nrings, wkb_data + 5, 4);
  752. if (byte_order == ENDIAN_BIG) {
  753. *nrings = SWAP32(*nrings);
  754. }
  755. if (*nrings < 0) {
  756. return -1;
  757. }
  758. /* reallocate space for islands if needed */
  759. reallocate_cache(cache, *nrings);
  760. cache->lines_num += *nrings;
  761. /* each ring has a minimum of 4 bytes (point count) */
  762. if (nbytes != -1 && nbytes - 9 < (*nrings) * 4) {
  763. return error_corrupted_data(_("Length of input WKB is too small"));
  764. }
  765. data_offset = 9;
  766. if (nbytes != -1)
  767. nbytes -= data_offset;
  768. /* get the rings */
  769. nsize = 9;
  770. for (i = 0; i < (*nrings); i++) {
  771. if (cache->lines_next >= cache->lines_num)
  772. G_fatal_error(_("Invalid cache index %d (max: %d)"),
  773. cache->lines_next, cache->lines_num);
  774. line_i = cache->lines[cache->lines_next];
  775. cache->lines_types[cache->lines_next++] = GV_BOUNDARY;
  776. linestring_from_wkb(wkb_data + data_offset, nbytes, byte_order,
  777. with_z, line_i, TRUE);
  778. if (nbytes != -1) {
  779. isize = 4 + 8 * (with_z == WITH_Z ? 3 : 2) * line_i->n_points;
  780. nbytes -= isize;
  781. }
  782. nsize += isize;
  783. data_offset += isize;
  784. }
  785. return nsize;
  786. }
  787. /*!
  788. \brief Read geometry collection for WKB data
  789. See OGRGeometryCollection::importFromWkbInternal() from GDAL/OGR library
  790. \param wkb_data WKB data
  791. \param nbytes number of bytes (WKB data buffer)
  792. \param byte_order byte order (ENDIAN_LITTLE, ENDIAN_BIG)
  793. \param with_z WITH_Z for 3D data
  794. \param ipart part to cache (starts at 0)
  795. \param[out] cache lines cache
  796. \param[in,out] fparts feature parts (required for building pseudo-topology)
  797. \return number of parts
  798. \return -1 on error
  799. */
  800. int geometry_collection_from_wkb(const unsigned char *wkb_data, int nbytes,
  801. int byte_order, int with_z,
  802. struct Format_info_cache *cache,
  803. struct feat_parts *fparts)
  804. {
  805. int ipart, nparts, data_offset, nsize;
  806. unsigned char *wkb_subdata;
  807. SF_FeatureType ftype;
  808. if (nbytes < 9 && nbytes != -1)
  809. return error_corrupted_data(NULL);
  810. /* get the geometry count */
  811. memcpy(&nparts, wkb_data + 5, 4);
  812. if (byte_order == ENDIAN_BIG) {
  813. nparts = SWAP32(nparts);
  814. }
  815. if (nparts < 0 || nparts > INT_MAX / 9) {
  816. return error_corrupted_data(NULL);
  817. }
  818. G_debug(5, "\t(geometry collections) parts: %d", nparts);
  819. /* each geometry has a minimum of 9 bytes */
  820. if (nbytes != -1 && nbytes - 9 < nparts * 9) {
  821. return error_corrupted_data(_("Length of input WKB is too small"));
  822. }
  823. data_offset = 9;
  824. if (nbytes != -1)
  825. nbytes -= data_offset;
  826. /* reallocate space for parts if needed */
  827. reallocate_cache(cache, nparts);
  828. /* get parts */
  829. for (ipart = 0; ipart < nparts; ipart++) {
  830. wkb_subdata = (unsigned char *)wkb_data + data_offset;
  831. if (nbytes < 9 && nbytes != -1)
  832. return error_corrupted_data(NULL);
  833. if (byte_order == ENDIAN_LITTLE) {
  834. ftype = (SF_FeatureType) wkb_subdata[1];
  835. }
  836. else {
  837. ftype = (SF_FeatureType) wkb_subdata[4];
  838. }
  839. if (ftype == SF_POINT) {
  840. cache->lines_types[cache->lines_next] = GV_POINT;
  841. nsize = point_from_wkb(wkb_subdata, nbytes, byte_order, with_z,
  842. cache->lines[cache->lines_next]);
  843. cache->lines_num++;
  844. add_fpart(fparts, ftype, cache->lines_next, 1);
  845. cache->lines_next++;
  846. }
  847. else if (ftype == SF_LINESTRING) {
  848. cache->lines_types[cache->lines_next] = GV_LINE;
  849. nsize =
  850. linestring_from_wkb(wkb_subdata, nbytes, byte_order, with_z,
  851. cache->lines[cache->lines_next], FALSE);
  852. cache->lines_num++;
  853. add_fpart(fparts, ftype, cache->lines_next, 1);
  854. cache->lines_next++;
  855. }
  856. else if (ftype == SF_POLYGON) {
  857. int idx, nrings;
  858. idx = cache->lines_next;
  859. nsize = polygon_from_wkb(wkb_subdata, nbytes, byte_order,
  860. with_z, cache, &nrings);
  861. add_fpart(fparts, ftype, idx, nrings);
  862. }
  863. else if (ftype == SF_GEOMETRYCOLLECTION ||
  864. ftype == SF_MULTIPOLYGON ||
  865. ftype == SF_MULTILINESTRING || ftype == SF_MULTIPOLYGON) {
  866. geometry_collection_from_wkb(wkb_subdata, nbytes, byte_order,
  867. with_z, cache, fparts);
  868. }
  869. else {
  870. G_warning(_("Unsupported feature type %d"), ftype);
  871. }
  872. if (nbytes != -1) {
  873. nbytes -= nsize;
  874. }
  875. data_offset += nsize;
  876. }
  877. return nparts;
  878. }
  879. /*!
  880. \brief Report error message
  881. \param msg message (NULL)
  882. \return -1
  883. */
  884. int error_corrupted_data(const char *msg)
  885. {
  886. if (msg)
  887. G_warning(_("Corrupted data. %s."), msg);
  888. else
  889. G_warning(_("Corrupted data"));
  890. return -1;
  891. }
  892. /*!
  893. \brief Set initial SQL query for sequential access
  894. \param pg_info pointer to Format_info_pg struct
  895. \return 0 on success
  896. \return -1 on error
  897. */
  898. int set_initial_query(struct Format_info_pg *pg_info)
  899. {
  900. char stmt[DB_SQL_MAX];
  901. if (execute(pg_info->conn, "BEGIN") == -1)
  902. return -1;
  903. sprintf(stmt,
  904. "DECLARE %s_%s%p CURSOR FOR SELECT %s,%s FROM \"%s\".\"%s\"",
  905. pg_info->schema_name, pg_info->table_name, pg_info->conn,
  906. pg_info->geom_column, pg_info->fid_column, pg_info->schema_name,
  907. pg_info->table_name);
  908. G_debug(2, "SQL: %s", stmt);
  909. if (execute(pg_info->conn, stmt) == -1) {
  910. execute(pg_info->conn, "ROLLBACK");
  911. return -1;
  912. }
  913. sprintf(stmt, "FETCH %d in %s_%s%p", CURSOR_PAGE,
  914. pg_info->schema_name, pg_info->table_name, pg_info->conn);
  915. pg_info->res = PQexec(pg_info->conn, stmt);
  916. if (!pg_info->res) {
  917. execute(pg_info->conn, "ROLLBACK");
  918. return -1;
  919. }
  920. pg_info->next_line = 0;
  921. return 0;
  922. }
  923. /*!
  924. \brief Execute SQL statement
  925. See pg_local_proto.h
  926. \param conn pointer to PGconn
  927. \param stmt query
  928. \return 0 on success
  929. \return -1 on error
  930. */
  931. int execute(PGconn * conn, const char *stmt)
  932. {
  933. PGresult *result;
  934. result = NULL;
  935. G_debug(3, "execute(): %s", stmt);
  936. result = PQexec(conn, stmt);
  937. if (!result || PQresultStatus(result) != PGRES_COMMAND_OK) {
  938. PQclear(result);
  939. G_warning(_("Execution failed: %s"), PQerrorMessage(conn));
  940. return -1;
  941. }
  942. PQclear(result);
  943. return 0;
  944. }
  945. /*!
  946. \brief Reallocate lines cache
  947. */
  948. void reallocate_cache(struct Format_info_cache *cache, int num)
  949. {
  950. int i;
  951. if (cache->lines_alloc >= num)
  952. return;
  953. if (!cache->lines) {
  954. /* most of features requires only one line cache */
  955. cache->lines_alloc = 1;
  956. }
  957. else {
  958. cache->lines_alloc += 20;
  959. }
  960. cache->lines = (struct line_pnts **)G_realloc(cache->lines,
  961. cache->lines_alloc *
  962. sizeof(struct line_pnts *));
  963. cache->lines_types = (int *)G_realloc(cache->lines_types,
  964. cache->lines_alloc * sizeof(int));
  965. if (cache->lines_alloc > 1) {
  966. for (i = cache->lines_alloc - 20; i < cache->lines_alloc; i++) {
  967. cache->lines[i] = Vect_new_line_struct();
  968. cache->lines_types[i] = -1;
  969. }
  970. }
  971. else {
  972. cache->lines[0] = Vect_new_line_struct();
  973. cache->lines_types[0] = -1;
  974. }
  975. }
  976. void add_fpart(struct feat_parts *fparts, SF_FeatureType ftype,
  977. int idx, int nlines)
  978. {
  979. if (!fparts)
  980. return;
  981. if (fparts->a_parts == 0 || fparts->n_parts >= fparts->a_parts) {
  982. if (fparts->a_parts == 0)
  983. fparts->a_parts = 1;
  984. else
  985. fparts->a_parts += 20;
  986. fparts->ftype = (SF_FeatureType *) G_realloc(fparts->ftype,
  987. fparts->a_parts *
  988. sizeof(SF_FeatureType));
  989. fparts->nlines =
  990. (int *)G_realloc(fparts->nlines, fparts->a_parts * sizeof(int));
  991. fparts->idx =
  992. (int *)G_realloc(fparts->idx, fparts->a_parts * sizeof(int));
  993. }
  994. fparts->ftype[fparts->n_parts] = ftype;
  995. fparts->idx[fparts->n_parts] = idx;
  996. fparts->nlines[fparts->n_parts] = nlines;
  997. fparts->n_parts++;
  998. }
  999. int read_centroid_pg(struct Format_info_pg *pg_info,
  1000. int centroid, struct line_pnts *line_p)
  1001. {
  1002. char stmt[DB_SQL_MAX];
  1003. char *data;
  1004. PGresult *res;
  1005. sprintf(stmt,
  1006. "SELECT ST_PointOnSurface(geom) AS geom FROM "
  1007. "ST_GetFaceGeometry('%s', %d) as geom",
  1008. pg_info->toposchema_name, centroid);
  1009. res = PQexec(pg_info->conn, stmt);
  1010. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1011. PQntuples(res) != 1) {
  1012. G_warning(_("Unable to read centroid %d: %s"),
  1013. centroid, PQerrorMessage(pg_info->conn));
  1014. if (res)
  1015. PQclear(res);
  1016. return -1;
  1017. }
  1018. data = (char *)PQgetvalue(res, 0, 0);
  1019. PQclear(res);
  1020. if (GV_POINT != cache_feature(data, FALSE, &(pg_info->cache), NULL))
  1021. return -1;
  1022. Vect_append_points(line_p, pg_info->cache.lines[0], GV_FORWARD);
  1023. return GV_CENTROID;
  1024. }
  1025. #endif