open_pg.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. /*!
  2. \file lib/vector/Vlib/open_pg.c
  3. \brief Vector library - Open PostGIS layer as vector map layer
  4. Higher level functions for reading/writing/manipulating vectors.
  5. (C) 2011-2013 by the GRASS Development Team
  6. This program is free software under the GNU General Public License
  7. (>=v2). Read the file COPYING that comes with GRASS for details.
  8. \author Martin Landa <landa.martin gmail.com>
  9. */
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <grass/vector.h>
  13. #include <grass/dbmi.h>
  14. #include <grass/glocale.h>
  15. #ifdef HAVE_POSTGRES
  16. #include "pg_local_proto.h"
  17. struct edge_data {
  18. int id;
  19. int start_node;
  20. int end_node;
  21. int left_face;
  22. int right_face;
  23. char *wkb_geom;
  24. };
  25. static char *get_key_column(struct Format_info_pg *);
  26. static SF_FeatureType ftype_from_string(const char *);
  27. static int drop_table(struct Format_info_pg *);
  28. static void connect_db(struct Format_info_pg *);
  29. static int check_topo(struct Format_info_pg *, struct Plus_head *);
  30. static int parse_bbox(const char *, struct bound_box *);
  31. static struct P_node *read_p_node(struct Plus_head *, int, int,
  32. const char *, struct Format_info_pg *);
  33. static struct P_line *read_p_line(struct Plus_head *, int,
  34. const struct edge_data *,
  35. struct Format_info_cache *);
  36. static int load_plus_head(struct Format_info_pg *, struct Plus_head *);
  37. static void notice_processor(void *, const char *);
  38. #endif
  39. /*!
  40. \brief Open vector map - PostGIS feature table on non-topological
  41. level
  42. \param[in,out] Map pointer to Map_info structure
  43. \param update TRUE for write mode, otherwise read-only
  44. \return 0 success
  45. \return -1 error
  46. */
  47. int V1_open_old_pg(struct Map_info *Map, int update)
  48. {
  49. #ifdef HAVE_POSTGRES
  50. int found;
  51. char stmt[DB_SQL_MAX];
  52. PGresult *res;
  53. struct Format_info_pg *pg_info;
  54. G_debug(2, "V1_open_old_pg(): update = %d", update);
  55. pg_info = &(Map->fInfo.pg);
  56. if (!pg_info->conninfo) {
  57. G_warning(_("Connection string not defined"));
  58. return -1;
  59. }
  60. if (!pg_info->table_name) {
  61. G_warning(_("PostGIS feature table not defined"));
  62. return -1;
  63. }
  64. G_debug(1, "V1_open_old_pg(): conninfo='%s' table='%s'",
  65. pg_info->conninfo, pg_info->table_name);
  66. /* connect database */
  67. if (!pg_info->conn)
  68. connect_db(pg_info);
  69. /* get DB name */
  70. pg_info->db_name = G_store(PQdb(pg_info->conn));
  71. if (!pg_info->db_name) {
  72. G_warning(_("Unable to get database name"));
  73. return -1;
  74. }
  75. /* get fid and geometry column */
  76. sprintf(stmt, "SELECT f_geometry_column, coord_dimension, srid, type "
  77. "FROM geometry_columns WHERE f_table_schema = '%s' AND "
  78. "f_table_name = '%s'", pg_info->schema_name, pg_info->table_name);
  79. G_debug(2, "SQL: %s", stmt);
  80. res = PQexec(pg_info->conn, stmt);
  81. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  82. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  83. PQresultErrorMessage(res));
  84. found = PQntuples(res) > 0 ? TRUE : FALSE;
  85. if (found) {
  86. /* geometry column */
  87. pg_info->geom_column = G_store(PQgetvalue(res, 0, 0));
  88. G_debug(3, "\t-> table = %s column = %s", pg_info->table_name,
  89. pg_info->geom_column);
  90. /* fid column */
  91. pg_info->fid_column = get_key_column(pg_info);
  92. /* coordinates dimension */
  93. pg_info->coor_dim = atoi(PQgetvalue(res, 0, 1));
  94. /* SRS ID */
  95. pg_info->srid = atoi(PQgetvalue(res, 0, 2));
  96. /* feature type */
  97. pg_info->feature_type = ftype_from_string(PQgetvalue(res, 0, 3));
  98. }
  99. PQclear(res);
  100. /* no feature in cache */
  101. pg_info->cache.fid = -1;
  102. if (!found) {
  103. G_warning(_("Feature table <%s> not found in 'geometry_columns'"),
  104. pg_info->table_name);
  105. return -1;
  106. }
  107. /* check for topo schema */
  108. check_topo(pg_info, &(Map->plus));
  109. return 0;
  110. #else
  111. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  112. return -1;
  113. #endif
  114. }
  115. /*!
  116. \brief Open vector map - PostGIS feature table on topological level
  117. Simple feature access:
  118. - open feature index file
  119. PostGIS Topology:
  120. - check if topological schema exists
  121. \param[in,out] Map pointer to Map_info structure
  122. \return 0 success
  123. \return -1 error
  124. */
  125. int V2_open_old_pg(struct Map_info *Map)
  126. {
  127. #ifdef HAVE_POSTGRES
  128. struct Format_info_pg *pg_info;
  129. PGresult *res;
  130. G_debug(3, "V2_open_old_pg(): name = %s mapset = %s", Map->name,
  131. Map->mapset);
  132. pg_info = &(Map->fInfo.pg);
  133. if (pg_info->toposchema_name) {
  134. char stmt[DB_SQL_MAX];
  135. /* get topo schema id */
  136. sprintf(stmt, "SELECT id FROM topology.topology WHERE name = '%s'",
  137. pg_info->toposchema_name);
  138. res = PQexec(pg_info->conn, stmt);
  139. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  140. G_warning("%s\n%s", _("Topology schema not found."),
  141. PQresultErrorMessage(res));
  142. if (res)
  143. PQclear(res);
  144. return -1;
  145. }
  146. pg_info->toposchema_id = atoi(PQgetvalue(res, 0, 0));
  147. PQclear(res);
  148. }
  149. else {
  150. /* fidx file needed only for simple features access */
  151. if (Vect_open_fidx(Map, &(pg_info->offset)) != 0) {
  152. G_warning(_("Unable to open feature index file for vector map <%s>"),
  153. Vect_get_full_name(Map));
  154. G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
  155. }
  156. }
  157. return 0;
  158. #else
  159. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  160. return -1;
  161. #endif
  162. }
  163. /*!
  164. \brief Prepare PostGIS database for creating new feature table
  165. (level 1)
  166. New PostGIS table is created when writing features by
  167. Vect_wrile_line().
  168. \param[out] Map pointer to Map_info structure
  169. \param name name of PostGIS feature table to create
  170. \param with_z WITH_Z for 3D vector data otherwise WITHOUT_Z
  171. \return 0 success
  172. \return -1 error
  173. */
  174. int V1_open_new_pg(struct Map_info *Map, const char *name, int with_z)
  175. {
  176. #ifdef HAVE_POSTGRES
  177. char stmt[DB_SQL_MAX];
  178. struct Format_info_pg *pg_info;
  179. PGresult *res;
  180. G_debug(2, "V1_open_new_pg(): name = %s with_z = %d", name, with_z);
  181. pg_info = &(Map->fInfo.pg);
  182. if (!pg_info->conninfo) {
  183. G_warning(_("Connection string not defined"));
  184. return -1;
  185. }
  186. if (!pg_info->table_name) {
  187. G_warning(_("PostGIS feature table not defined"));
  188. return -1;
  189. }
  190. G_debug(1, "V1_open_new_pg(): conninfo='%s' table='%s'",
  191. pg_info->conninfo, pg_info->table_name);
  192. /* connect database */
  193. connect_db(pg_info);
  194. /* get DB name */
  195. pg_info->db_name = G_store(PQdb(pg_info->conn));
  196. if (!pg_info->db_name) {
  197. G_warning(_("Unable to get database name"));
  198. return -1;
  199. }
  200. /* if schema not defined, use 'public' */
  201. if (!pg_info->schema_name)
  202. pg_info->schema_name = G_store("public");
  203. /* if fid_column not defined, use 'fid' */
  204. if (!pg_info->fid_column)
  205. pg_info->fid_column = G_store(GV_PG_FID_COLUMN);
  206. /* if geom_column not defined, use 'geom' */
  207. if (!pg_info->geom_column)
  208. pg_info->geom_column = G_store(GV_PG_GEOMETRY_COLUMN);
  209. /* check if feature table already exists */
  210. sprintf(stmt, "SELECT * FROM pg_tables "
  211. "WHERE schemaname = '%s' AND tablename = '%s'",
  212. pg_info->schema_name, pg_info->table_name);
  213. G_debug(2, "SQL: %s", stmt);
  214. res = PQexec(pg_info->conn, stmt);
  215. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  216. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  217. PQresultErrorMessage(res));
  218. if (PQntuples(res) > 0) {
  219. /* table found */
  220. if (G_get_overwrite()) {
  221. G_warning(_("PostGIS layer <%s.%s> already exists and will be overwritten"),
  222. pg_info->schema_name, pg_info->table_name);
  223. if (drop_table(pg_info) == -1) {
  224. G_warning(_("Unable to delete PostGIS layer <%s>"),
  225. pg_info->table_name);
  226. return -1;
  227. }
  228. }
  229. else {
  230. G_warning(_("PostGIS layer <%s.%s> already exists in database '%s'"),
  231. pg_info->schema_name, pg_info->table_name,
  232. pg_info->db_name);
  233. return -1;
  234. }
  235. }
  236. /* no feature in cache */
  237. pg_info->cache.fid = -1;
  238. /* unknown feature type */
  239. pg_info->feature_type = SF_UNKNOWN;
  240. PQclear(res);
  241. return 0;
  242. #else
  243. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  244. return -1;
  245. #endif
  246. }
  247. /*!
  248. \brief Read full-topology for PostGIS links
  249. Note: Only 2D topological primitives are currently supported
  250. \param[in,out] Map pointer to Map_info structure
  251. \param head_only TRUE to read only header
  252. \return 0 on success
  253. \return 1 topology layer does not exist
  254. \return -1 on error
  255. */
  256. int Vect_open_topo_pg(struct Map_info *Map, int head_only)
  257. {
  258. #ifdef HAVE_POSTGRES
  259. struct Plus_head *plus;
  260. struct Format_info_pg *pg_info;
  261. Map->open = VECT_OPEN_CODE; /* needed by load_plus */
  262. plus = &(Map->plus);
  263. pg_info = &(Map->fInfo.pg);
  264. /* check for topo schema */
  265. if (check_topo(pg_info, plus) != 0)
  266. return 1;
  267. /* free and init plus structure */
  268. dig_init_plus(plus);
  269. plus->Spidx_new = TRUE;
  270. return Vect__load_plus_pg(Map, head_only);
  271. #else
  272. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  273. return -1;
  274. #endif
  275. }
  276. #ifdef HAVE_POSTGRES
  277. /*!
  278. \brief Get key column for feature table
  279. \param pg_info pointer to Format_info_pg
  280. \return string buffer with key column name
  281. \return NULL on missing key column
  282. */
  283. char *get_key_column(struct Format_info_pg *pg_info)
  284. {
  285. char *key_column;
  286. char stmt[DB_SQL_MAX];
  287. PGresult *res;
  288. sprintf(stmt,
  289. "SELECT kcu.column_name "
  290. "FROM INFORMATION_SCHEMA.TABLES t "
  291. "LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc "
  292. "ON tc.table_catalog = t.table_catalog "
  293. "AND tc.table_schema = t.table_schema "
  294. "AND tc.table_name = t.table_name "
  295. "AND tc.constraint_type = 'PRIMARY KEY' "
  296. "LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu "
  297. "ON kcu.table_catalog = tc.table_catalog "
  298. "AND kcu.table_schema = tc.table_schema "
  299. "AND kcu.table_name = tc.table_name "
  300. "AND kcu.constraint_name = tc.constraint_name "
  301. "WHERE t.table_schema = '%s' AND t.table_name = '%s'",
  302. pg_info->schema_name, pg_info->table_name);
  303. G_debug(2, "SQL: %s", stmt);
  304. res = PQexec(pg_info->conn, stmt);
  305. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  306. PQntuples(res) != 1 || strlen(PQgetvalue(res, 0, 0)) < 1) {
  307. G_warning(_("No key column detected."));
  308. if (res)
  309. PQclear(res);
  310. return NULL;
  311. }
  312. key_column = G_store(PQgetvalue(res, 0, 0));
  313. PQclear(res);
  314. return key_column;
  315. }
  316. /*!
  317. \brief Get simple feature type from string
  318. \param type string
  319. \return SF type
  320. */
  321. SF_FeatureType ftype_from_string(const char *type)
  322. {
  323. SF_FeatureType sf_type;
  324. if (G_strcasecmp(type, "POINT") == 0)
  325. return SF_POINT;
  326. else if (G_strcasecmp(type, "LINESTRING") == 0)
  327. return SF_LINESTRING;
  328. else if (G_strcasecmp(type, "POLYGON") == 0)
  329. return SF_POLYGON;
  330. else if (G_strcasecmp(type, "MULTIPOINT") == 0)
  331. return SF_MULTIPOINT;
  332. else if (G_strcasecmp(type, "MULTILINESTRING") == 0)
  333. return SF_MULTILINESTRING;
  334. else if (G_strcasecmp(type, "MULTIPOLYGON") == 0)
  335. return SF_MULTIPOLYGON;
  336. else if (G_strcasecmp(type, "GEOMETRYCOLLECTION") == 0)
  337. return SF_GEOMETRYCOLLECTION;
  338. else
  339. return SF_UNKNOWN;
  340. G_debug(3, "ftype_from_string(): type='%s' -> %d", type, sf_type);
  341. return sf_type;
  342. }
  343. /*!
  344. \brief Drop feature table and topology schema if exists
  345. \param pg_info pointer to Format_info_pg
  346. \return -1 on error
  347. \return 0 on success
  348. */
  349. int drop_table(struct Format_info_pg *pg_info)
  350. {
  351. int i;
  352. char stmt[DB_SQL_MAX];
  353. char *topo_schema;
  354. PGresult *result, *result_drop;
  355. /* drop topology schema(s) related to the feature table */
  356. sprintf(stmt, "SELECT t.name FROM topology.layer AS l JOIN "
  357. "topology.topology AS t ON l.topology_id = t.id "
  358. "WHERE l.table_name = '%s'", pg_info->table_name);
  359. G_debug(2, "SQL: %s", stmt);
  360. result = PQexec(pg_info->conn, stmt);
  361. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  362. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  363. PQclear(result);
  364. return -1;
  365. }
  366. for (i = 0; i < PQntuples(result); i++) {
  367. topo_schema = PQgetvalue(result, i, 0);
  368. sprintf(stmt, "SELECT topology.DropTopology('%s')",
  369. topo_schema);
  370. G_debug(2, "SQL: %s", stmt);
  371. result_drop = PQexec(pg_info->conn, stmt);
  372. if (!result_drop || PQresultStatus(result_drop) != PGRES_TUPLES_OK)
  373. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  374. G_verbose_message(_("PostGIS topology schema <%s> dropped"),
  375. topo_schema);
  376. PQclear(result_drop);
  377. }
  378. PQclear(result);
  379. /* drop feature table */
  380. sprintf(stmt, "DROP TABLE \"%s\".\"%s\"",
  381. pg_info->schema_name, pg_info->table_name);
  382. G_debug(2, "SQL: %s", stmt);
  383. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  384. return -1;
  385. }
  386. return 0;
  387. }
  388. /*!
  389. \brief Establish PG connection (pg_info->conninfo)
  390. \param pg_info pointer to Format_info_pg
  391. */
  392. void connect_db(struct Format_info_pg *pg_info)
  393. {
  394. pg_info->conn = PQconnectdb(pg_info->conninfo);
  395. G_debug(2, " PQconnectdb(): %s", pg_info->conninfo);
  396. if (PQstatus(pg_info->conn) == CONNECTION_BAD)
  397. G_fatal_error("%s\n%s",
  398. _("Connection ton PostgreSQL database failed."),
  399. PQerrorMessage(pg_info->conn));
  400. /* print notice messages only on verbose level */
  401. PQsetNoticeProcessor(pg_info->conn, notice_processor, NULL);
  402. }
  403. /*!
  404. \brief Check for topology schema (pg_info->toposchema_name)
  405. \param pg_info pointer to Format_info_pg
  406. \return 0 schema exists
  407. \return 1 schema doesn't exists
  408. */
  409. int check_topo(struct Format_info_pg *pg_info, struct Plus_head *plus)
  410. {
  411. char stmt[DB_SQL_MAX];
  412. PGresult *res;
  413. /* connect database */
  414. if (!pg_info->conn)
  415. connect_db(pg_info);
  416. if (pg_info->toposchema_name)
  417. return 0;
  418. /* check if topology layer/schema exists */
  419. sprintf(stmt,
  420. "SELECT t.id,t.name,t.hasz,l.feature_column FROM topology.layer "
  421. "AS l JOIN topology.topology AS t ON l.topology_id = t.id "
  422. "WHERE schema_name = '%s' AND table_name = '%s'",
  423. pg_info->schema_name, pg_info->table_name);
  424. G_debug(2, "SQL: %s", stmt);
  425. res = PQexec(pg_info->conn, stmt);
  426. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  427. PQntuples(res) != 1) {
  428. G_debug(1, "Topology layers for '%s.%s' not found (%s)",
  429. pg_info->schema_name, pg_info->table_name,
  430. PQerrorMessage(pg_info->conn));
  431. if (res)
  432. PQclear(res);
  433. return 1;
  434. }
  435. pg_info->toposchema_id = atoi(PQgetvalue(res, 0, 0));
  436. pg_info->toposchema_name = G_store(PQgetvalue(res, 0, 1));
  437. pg_info->topogeom_column = G_store(PQgetvalue(res, 0, 3));
  438. G_debug(1, "PostGIS topology detected: schema = %s column = %s",
  439. pg_info->toposchema_name, pg_info->topogeom_column);
  440. /* check for 3D */
  441. if (strcmp(PQgetvalue(res, 0, 2), "t") == 0)
  442. plus->with_z = WITH_Z;
  443. PQclear(res);
  444. return 0;
  445. }
  446. /*!
  447. \brief Parse BBOX string
  448. \param value string buffer
  449. \param[out] bbox pointer to output bound_box struct
  450. \return 0 on success
  451. \return -1 on error
  452. */
  453. int parse_bbox(const char *value, struct bound_box *bbox)
  454. {
  455. unsigned int i;
  456. size_t length, prefix_length;
  457. char **tokens, **tokens_coord, *coord;
  458. if (strlen(value) < 1) {
  459. G_warning(_("Empty bounding box"));
  460. return -1;
  461. }
  462. prefix_length = strlen("box3d(");
  463. if (G_strncasecmp(value, "box3d(", prefix_length) != 0)
  464. return -1;
  465. /* strip off "bbox3d(...)" */
  466. length = strlen(value);
  467. coord = G_malloc(length - prefix_length);
  468. for (i = prefix_length; i < length; i++)
  469. coord[i-prefix_length] = value[i];
  470. coord[length-prefix_length-1] = '\0';
  471. tokens = G_tokenize(coord, ",");
  472. G_free(coord);
  473. if (G_number_of_tokens(tokens) != 2) {
  474. G_free_tokens(tokens);
  475. return -1;
  476. }
  477. /* parse bbox LL corner */
  478. tokens_coord = G_tokenize(tokens[0], " ");
  479. if (G_number_of_tokens(tokens_coord) != 3) {
  480. G_free_tokens(tokens);
  481. G_free_tokens(tokens_coord);
  482. }
  483. bbox->W = atof(tokens_coord[0]);
  484. bbox->S = atof(tokens_coord[1]);
  485. bbox->B = atof(tokens_coord[2]);
  486. G_free_tokens(tokens_coord);
  487. /* parse bbox UR corner */
  488. tokens_coord = G_tokenize(tokens[1], " ");
  489. if (G_number_of_tokens(tokens_coord) != 3) {
  490. G_free_tokens(tokens);
  491. G_free_tokens(tokens_coord);
  492. }
  493. bbox->E = atof(tokens_coord[0]);
  494. bbox->N = atof(tokens_coord[1]);
  495. bbox->T = atof(tokens_coord[2]);
  496. G_free_tokens(tokens_coord);
  497. G_free_tokens(tokens);
  498. return 0;
  499. }
  500. /*!
  501. \brief Read P_node structure
  502. See dig_Rd_P_node() for reference.
  503. \param plus pointer to Plus_head structure
  504. \param n index (starts at 1)
  505. \param id node id (table "node")
  506. \param wkb_data geometry data (wkb)
  507. \param pg_info pointer to Format_info_pg sttucture
  508. \return pointer to new P_node struct
  509. \return NULL on error
  510. */
  511. struct P_node *read_p_node(struct Plus_head *plus, int n,
  512. int id, const char *wkb_data,
  513. struct Format_info_pg *pg_info)
  514. {
  515. int i, cnt;
  516. char stmt[DB_SQL_MAX];
  517. struct P_node *node;
  518. struct line_pnts *points;
  519. PGresult *res;
  520. /* get lines connected to the node */
  521. sprintf(stmt,
  522. "SELECT edge_id,'s' as node,"
  523. "ST_Azimuth(ST_StartPoint(geom), ST_PointN(geom, 2)) AS angle"
  524. " FROM \"%s\".edge WHERE start_node = %d UNION ALL "
  525. "SELECT edge_id,'e' as node,"
  526. "ST_Azimuth(ST_EndPoint(geom), ST_PointN(geom, ST_NumPoints(geom) - 1)) AS angle"
  527. " FROM \"%s\".edge WHERE end_node = %d"
  528. " ORDER BY angle DESC",
  529. pg_info->toposchema_name, id,
  530. pg_info->toposchema_name, id);
  531. G_debug(2, "SQL: %s", stmt);
  532. res = PQexec(pg_info->conn, stmt);
  533. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  534. G_warning(_("Inconsistency in topology: unable to read node %d"), id);
  535. if (res)
  536. PQclear(res);
  537. return NULL;
  538. }
  539. cnt = PQntuples(res);
  540. if (cnt == 0) { /* dead ??? */
  541. plus->Node[n] = NULL;
  542. return NULL;
  543. }
  544. node = dig_alloc_node();
  545. node->n_lines = cnt;
  546. G_debug(4, "read_p_node(): id = %d, n_lines = %d", id, cnt);
  547. if (dig_node_alloc_line(node, node->n_lines) == -1)
  548. return NULL;
  549. /* lines / angles */
  550. for (i = 0; i < node->n_lines; i++) {
  551. node->lines[i] = atoi(PQgetvalue(res, i, 0));
  552. if (strcmp(PQgetvalue(res, i, 1), "s") != 0) {
  553. /* end node */
  554. node->lines[i] *= -1;
  555. }
  556. node->angles[i] = M_PI / 2 - atof(PQgetvalue(res, i, 2));
  557. /* angles range <-PI; PI> */
  558. if (node->angles[i] > M_PI)
  559. node->angles[i] = node->angles[i] - 2 * M_PI;
  560. if (node->angles[i] < -1.0 * M_PI)
  561. node->angles[i] = node->angles[i] + 2 * M_PI;
  562. G_debug(5, "\tline = %d angle = %f", node->lines[i],
  563. node->angles[i]);
  564. }
  565. PQclear(res);
  566. /* get node coordinates */
  567. if (SF_POINT != Vect__cache_feature_pg(wkb_data, FALSE, FALSE,
  568. &(pg_info->cache), NULL))
  569. G_warning(_("Inconsistency in topology: node %d - unexpected feature type %d"),
  570. n, pg_info->cache.sf_type);
  571. points = pg_info->cache.lines[0];
  572. node->x = points->x[0];
  573. node->y = points->y[0];
  574. if (plus->with_z)
  575. node->z = points->z[0];
  576. else
  577. node->z = 0.0;
  578. /* update spatial index */
  579. dig_spidx_add_node(plus, n, node->x, node->y, node->z);
  580. if (plus->uplist.do_uplist)
  581. /* collect updated nodes if requested */
  582. dig_node_add_updated(plus, n);
  583. plus->Node[n] = node;
  584. return node;
  585. }
  586. /*!
  587. \brief Read P_line structure
  588. See dig_Rd_P_line() for reference.
  589. Supported feature types:
  590. - GV_POINT
  591. - GV_LINE
  592. - GV_BOUNDARY
  593. \param plus pointer to Plus_head structure
  594. \param n index (starts at 1)
  595. \param data edge data (id, start/end node, left/right face, ...)
  596. \param pg_info pointer to Format_info_pg sttucture
  597. \return pointer to P_line struct
  598. \return NULL on error
  599. */
  600. struct P_line *read_p_line(struct Plus_head *plus, int n,
  601. const struct edge_data *data,
  602. struct Format_info_cache *cache)
  603. {
  604. int tp, itype;
  605. struct P_line *line;
  606. struct line_pnts *points;
  607. struct bound_box box;
  608. if (data->start_node == 0 && data->end_node == 0) {
  609. if (data->left_face == 0)
  610. tp = GV_POINT;
  611. else
  612. tp = GV_CENTROID;
  613. }
  614. else if (data->left_face == 0 && data->right_face == 0) {
  615. tp = GV_LINE;
  616. }
  617. else {
  618. tp = GV_BOUNDARY;
  619. }
  620. if (tp == 0) { /* dead ??? */
  621. plus->Line[n] = NULL;
  622. return NULL;
  623. }
  624. line = dig_alloc_line();
  625. /* type & offset ( = id) */
  626. line->type = tp;
  627. line->offset = data->id;
  628. G_debug(4, "read_p_line(): id/offset = %d type = %d", data->id, line->type);
  629. /* topo */
  630. if (line->type == GV_POINT) {
  631. line->topo = NULL;
  632. }
  633. else {
  634. line->topo = dig_alloc_topo(line->type);
  635. /* lines */
  636. if (line->type == GV_LINE) {
  637. struct P_topo_l *topo = (struct P_topo_l *)line->topo;
  638. topo->N1 = data->start_node;
  639. topo->N2 = data->end_node;
  640. }
  641. /* boundaries */
  642. else if (line->type == GV_BOUNDARY) {
  643. struct P_topo_b *topo = (struct P_topo_b *)line->topo;
  644. topo->N1 = data->start_node;
  645. topo->N2 = data->end_node;
  646. /* skip left/right area - will be detected when building
  647. areas/isles */
  648. topo->left = topo->right = 0;
  649. }
  650. /* centroids */
  651. else if (line->type == GV_CENTROID) {
  652. struct P_topo_c *topo = (struct P_topo_c *)line->topo;
  653. topo->area = data->left_face;
  654. }
  655. }
  656. /* update spatial index */
  657. Vect__cache_feature_pg(data->wkb_geom, FALSE, FALSE, cache, NULL);
  658. itype = cache->lines_types[0];
  659. if ((line->type & GV_POINTS && itype != GV_POINT) ||
  660. (line->type & GV_LINES && itype != GV_LINE))
  661. G_warning(_("Inconsistency in topology: line %d - unexpected feature type"), n);
  662. points = cache->lines[0];
  663. dig_line_box(points, &box);
  664. dig_spidx_add_line(plus, n, &box);
  665. if (plus->uplist.do_uplist) {
  666. /* collect updated lines if requested */
  667. dig_line_add_updated(plus, n);
  668. plus->uplist.uplines_offset[plus->uplist.n_uplines - 1] = line->offset;
  669. }
  670. plus->Line[n] = line;
  671. return line;
  672. }
  673. /*!
  674. \brief Read topo from PostGIS topology schema -- header info only
  675. \param[in,out] plus pointer to Plus_head struct
  676. \return 0 on success
  677. \return -1 on error
  678. */
  679. int load_plus_head(struct Format_info_pg *pg_info, struct Plus_head *plus)
  680. {
  681. char stmt[DB_SQL_MAX];
  682. PGresult *res;
  683. plus->off_t_size = -1;
  684. /* get map bounding box
  685. fisrt try to get info from 'topology.grass' table */
  686. sprintf(stmt,
  687. "SELECT %s FROM \"%s\".\"%s\" WHERE %s = %d",
  688. TOPO_BBOX, TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, pg_info->toposchema_id);
  689. G_debug(2, "SQL: %s", stmt);
  690. res = PQexec(pg_info->conn, stmt);
  691. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  692. PQntuples(res) != 1) {
  693. PQclear(res);
  694. /* otherwise try to calculate bbox from TopoGeometry elements */
  695. sprintf(stmt,
  696. "SELECT ST_3DExtent(%s) FROM \"%s\".\"%s\"",
  697. pg_info->topogeom_column, pg_info->schema_name, pg_info->table_name);
  698. G_debug(2, "SQL: %s", stmt);
  699. res = PQexec(pg_info->conn, stmt);
  700. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  701. PQntuples(res) != 1 || strlen(PQgetvalue(res, 0, 0)) < 1) {
  702. G_warning(_("Unable to get map bounding box from topology"));
  703. PQclear(res);
  704. return -1;
  705. }
  706. }
  707. if (parse_bbox(PQgetvalue(res, 0, 0), &(plus->box)) != 0) {
  708. G_warning(_("Unable to parse map bounding box:\n%s"),
  709. PQgetvalue(res, 0, 0));
  710. return -1;
  711. }
  712. PQclear(res);
  713. /* get number of topological elements */
  714. /* nodes
  715. note: isolated nodes are registered in GRASS Topology model */
  716. sprintf(stmt,
  717. "SELECT COUNT(DISTINCT node) FROM (SELECT start_node AS node "
  718. "FROM \"%s\".edge GROUP BY start_node UNION ALL SELECT end_node "
  719. "AS node FROM \"%s\".edge GROUP BY end_node) AS foo",
  720. pg_info->toposchema_name, pg_info->toposchema_name);
  721. plus->n_nodes = Vect__execute_get_value_pg(pg_info->conn, stmt);
  722. G_debug(3, "Vect_open_topo_pg(): n_nodes=%d", plus->n_nodes);
  723. /* lines (edges in PostGIS Topology model) */
  724. sprintf(stmt,
  725. "SELECT COUNT(*) FROM \"%s\".edge",
  726. pg_info->toposchema_name);
  727. /* + isolated nodes as points
  728. + centroids */
  729. plus->n_lines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  730. /* areas (faces with face_id > 0 in PostGIS Topology model) */
  731. sprintf(stmt,
  732. "SELECT COUNT(*) FROM \"%s\".face WHERE face_id > 0",
  733. pg_info->toposchema_name);
  734. plus->n_areas = Vect__execute_get_value_pg(pg_info->conn, stmt);
  735. G_debug(3, "Vect_open_topo_pg(): n_areas=%d", plus->n_areas);
  736. /* isles (faces with face_id <=0 in PostGIS Topology model)
  737. note: universal face is represented in GRASS Topology model as isle (area=0)
  738. */
  739. sprintf(stmt,
  740. "SELECT COUNT(*) FROM \"%s\".face WHERE face_id < 0",
  741. pg_info->toposchema_name);
  742. plus->n_isles = Vect__execute_get_value_pg(pg_info->conn, stmt);
  743. G_debug(3, "Vect_open_topo_pg(): n_isles=%d", plus->n_isles);
  744. /* number of features according the type */
  745. /* points */
  746. sprintf(stmt,
  747. "SELECT COUNT(*) FROM \"%s\".node WHERE containing_face "
  748. "IS NULL AND node_id NOT IN "
  749. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  750. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  751. "\"%s\".edge GROUP BY end_node) AS foo)",
  752. pg_info->toposchema_name, pg_info->toposchema_name,
  753. pg_info->toposchema_name);
  754. plus->n_plines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  755. G_debug(3, "Vect_open_topo_pg(): n_plines=%d", plus->n_plines);
  756. /* lines */
  757. sprintf(stmt,
  758. "SELECT COUNT(*) FROM \"%s\".edge WHERE "
  759. "left_face = 0 AND right_face = 0",
  760. pg_info->toposchema_name);
  761. plus->n_llines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  762. G_debug(3, "Vect_open_topo_pg(): n_llines=%d", plus->n_llines);
  763. /* boundaries */
  764. sprintf(stmt,
  765. "SELECT COUNT(*) FROM \"%s\".edge WHERE "
  766. "left_face != 0 OR right_face != 0",
  767. pg_info->toposchema_name);
  768. plus->n_blines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  769. G_debug(3, "Vect_open_topo_pg(): n_blines=%d", plus->n_blines);
  770. /* centroids */
  771. sprintf(stmt,
  772. "SELECT COUNT(*) FROM \"%s\".node WHERE containing_face "
  773. "IS NOT NULL AND node_id NOT IN "
  774. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  775. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  776. "\"%s\".edge GROUP BY end_node) AS foo)",
  777. pg_info->toposchema_name, pg_info->toposchema_name,
  778. pg_info->toposchema_name);
  779. plus->n_clines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  780. G_debug(3, "Vect_open_topo_pg(): n_clines=%d", plus->n_clines);
  781. /* update number of lines - add points and centroids */
  782. plus->n_lines += plus->n_plines + plus->n_clines;
  783. G_debug(3, "Vect_open_topo_pg(): n_lines=%d", plus->n_lines);
  784. return 0;
  785. }
  786. /*!
  787. \brief Read topo info from PostGIS topology schema
  788. \param pg_info pointer to Format_info_pg
  789. \param[in,out] plus pointer to Plus_head struct
  790. \param head_only TRUE to read only header info
  791. \return 0 on success
  792. \return -1 on error
  793. */
  794. int Vect__load_plus_pg(struct Map_info *Map, int head_only)
  795. {
  796. int i, side, line, id, ntuples, area;
  797. char stmt[DB_SQL_MAX];
  798. struct edge_data line_data;
  799. struct Format_info_pg *pg_info;
  800. struct Plus_head *plus;
  801. struct P_line *Line;
  802. struct P_area *Area;
  803. struct line_pnts *Points;
  804. struct ilist *List;
  805. PGresult *res;
  806. pg_info = &(Map->fInfo.pg);
  807. plus = &(Map->plus);
  808. if (load_plus_head(pg_info, plus) != 0)
  809. return -1;
  810. if (head_only)
  811. return 0;
  812. Points = Vect_new_line_struct();
  813. List = Vect_new_list();
  814. /* read nodes (GRASS Topo)
  815. note: standalone nodes (ie. points/centroids) are ignored
  816. */
  817. sprintf(stmt,
  818. "SELECT node_id,geom FROM \"%s\".node WHERE node_id IN "
  819. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  820. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  821. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  822. pg_info->toposchema_name, pg_info->toposchema_name,
  823. pg_info->toposchema_name);
  824. G_debug(2, "SQL: %s", stmt);
  825. res = PQexec(pg_info->conn, stmt);
  826. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  827. PQntuples(res) != plus->n_nodes) {
  828. G_warning(_("Inconsistency in topology: number of "
  829. "nodes %d (should be %d)"),
  830. PQntuples(res), plus->n_nodes);
  831. if (res)
  832. PQclear(res);
  833. return -1;
  834. }
  835. G_debug(3, "load_plus(): n_nodes = %d", plus->n_nodes);
  836. dig_alloc_nodes(plus, plus->n_nodes);
  837. for (i = 0; i < plus->n_nodes; i++) {
  838. id = atoi(PQgetvalue(res, i, 0));
  839. read_p_node(plus, i + 1, /* node index starts at 1 */
  840. id, (const char *) PQgetvalue(res, i, 1), pg_info);
  841. }
  842. PQclear(res);
  843. /* read lines (GRASS Topo)
  844. - standalone nodes -> points|centroids
  845. - edges -> lines/boundaries
  846. */
  847. G_debug(3, "load_plus(): n_lines = %d", plus->n_lines);
  848. dig_alloc_lines(plus, plus->n_lines);
  849. G_zero(plus->Line, sizeof(struct P_line *) * (plus->n_lines + 1)); /* index starts at 1 */
  850. /* read PostGIS Topo standalone nodes (containing_face is null)
  851. -> points
  852. */
  853. sprintf(stmt,
  854. "SELECT node_id,geom FROM \"%s\".node WHERE containing_face "
  855. "IS NULL AND node_id NOT IN "
  856. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  857. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  858. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  859. pg_info->toposchema_name, pg_info->toposchema_name,
  860. pg_info->toposchema_name);
  861. G_debug(2, "SQL: %s", stmt);
  862. res = PQexec(pg_info->conn, stmt);
  863. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  864. PQntuples(res) > plus->n_plines) {
  865. G_warning(_("Inconsistency in topology: number of "
  866. "points %d (should be %d)"),
  867. PQntuples(res), plus->n_plines);
  868. if (res)
  869. PQclear(res);
  870. return -1;
  871. }
  872. ntuples = PQntuples(res); /* plus->n_plines */
  873. G_zero(&line_data, sizeof(struct edge_data));
  874. for (i = 0; i < ntuples; i++) {
  875. /* process standalone nodes (PostGIS Topo) */
  876. line_data.id = atoi(PQgetvalue(res, i, 0));
  877. line_data.wkb_geom = (char *) PQgetvalue(res, i, 1);
  878. read_p_line(plus, i + 1, &line_data, &(pg_info->cache));
  879. }
  880. PQclear(res);
  881. /* read PostGIS Topo edges
  882. -> lines
  883. -> boundaries
  884. */
  885. sprintf(stmt,
  886. "SELECT edge_id,start_node,end_node,left_face,right_face,geom "
  887. "FROM \"%s\".edge ORDER BY edge_id",
  888. pg_info->toposchema_name);
  889. G_debug(2, "SQL: %s", stmt);
  890. res = PQexec(pg_info->conn, stmt);
  891. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  892. PQntuples(res) > plus->n_lines) {
  893. G_warning(_("Inconsistency in topology: number of "
  894. "lines %d (should be %d)"),
  895. PQntuples(res), plus->n_lines);
  896. if (res)
  897. PQclear(res);
  898. return -1;
  899. }
  900. /* process edges (PostGIS Topo) */
  901. ntuples = PQntuples(res);
  902. for (i = 0; i < ntuples; i++) {
  903. line_data.id = atoi(PQgetvalue(res, i, 0));
  904. line_data.start_node = atoi(PQgetvalue(res, i, 1));
  905. line_data.end_node = atoi(PQgetvalue(res, i, 2));
  906. line_data.left_face = atoi(PQgetvalue(res, i, 3));
  907. line_data.right_face = atoi(PQgetvalue(res, i, 4));
  908. line_data.wkb_geom = (char *) PQgetvalue(res, i, 5);
  909. id = plus->n_plines + i + 1; /* points already registered */
  910. read_p_line(plus, id, &line_data, &(pg_info->cache));
  911. /* TODO: update category index */
  912. }
  913. PQclear(res);
  914. /* read PostGIS Topo standalone nodes (containing_face is not null)
  915. -> centroids
  916. */
  917. sprintf(stmt,
  918. "SELECT node_id,geom,containing_face FROM \"%s\".node WHERE containing_face "
  919. "IS NOT NULL AND node_id NOT IN "
  920. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  921. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  922. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  923. pg_info->toposchema_name, pg_info->toposchema_name,
  924. pg_info->toposchema_name);
  925. G_debug(2, "SQL: %s", stmt);
  926. res = PQexec(pg_info->conn, stmt);
  927. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  928. PQntuples(res) != plus->n_clines) {
  929. G_warning(_("Inconsistency in topology: number of "
  930. "centroids %d (should be %d)"),
  931. PQntuples(res), plus->n_clines);
  932. if (res)
  933. PQclear(res);
  934. return -1;
  935. }
  936. G_zero(&line_data, sizeof(struct edge_data));
  937. id = plus->n_plines + plus->n_llines + plus->n_blines + 1;
  938. for (i = 0; i < plus->n_clines; i++) {
  939. line_data.id = atoi(PQgetvalue(res, i, 0));
  940. line_data.wkb_geom = (char *)PQgetvalue(res, i, 1);
  941. line_data.left_face = atoi(PQgetvalue(res, i, 2)); /* face id */
  942. /* area id and face id can be different */
  943. read_p_line(plus, id + i, &line_data, &(pg_info->cache));
  944. }
  945. PQclear(res);
  946. /* build areas for boundaries
  947. reset values -> build from scratch */
  948. plus->n_areas = plus->n_isles = 0;
  949. for (line = 1; line <= plus->n_lines; line++) {
  950. Line = plus->Line[line]; /* centroids: Line is NULL */
  951. if (!Line || Line->type != GV_BOUNDARY)
  952. continue;
  953. for (i = 0; i < 2; i++) { /* for both sides build an area/isle */
  954. side = i == 0 ? GV_LEFT : GV_RIGHT;
  955. G_debug(3, "Build area for line = %d, side = %d",
  956. id, side);
  957. Vect_build_line_area(Map, line, side);
  958. }
  959. }
  960. plus->built = GV_BUILD_AREAS;
  961. /* TODO: attach isles */
  962. plus->built = GV_BUILD_ATTACH_ISLES;
  963. /* attach centroids */
  964. if (plus->n_areas > 0) {
  965. struct P_topo_c *topo;
  966. for (line = 1; line <= plus->n_lines; line++) {
  967. Line = plus->Line[line];
  968. if (Line->type != GV_CENTROID)
  969. continue;
  970. Vect_read_line(Map, Points, NULL, line);
  971. area = Vect_find_area(Map, Points->x[0], Points->y[0]);
  972. topo = (struct P_topo_c *)Line->topo;
  973. topo->area = area;
  974. Area = plus->Area[topo->area];
  975. Area->centroid = Line->offset;
  976. }
  977. }
  978. plus->built = GV_BUILD_CENTROIDS;
  979. /* done */
  980. plus->built = GV_BUILD_ALL;
  981. Vect_destroy_line_struct(Points);
  982. Vect_destroy_list(List);
  983. return 0;
  984. }
  985. /*
  986. \brief PostgreSQL notice processor
  987. Print out NOTICE message only on verbose level
  988. */
  989. void notice_processor(void *arg, const char *message)
  990. {
  991. if (G_verbose() > G_verbose_std()) {
  992. fprintf(stderr, "%s", message);
  993. }
  994. }
  995. #endif