open_pg.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. G_debug(5, "node: %d", i);
  839. id = atoi(PQgetvalue(res, i, 0));
  840. read_p_node(plus, i + 1, /* node index starts at 1 */
  841. id, (const char *) PQgetvalue(res, i, 1), pg_info);
  842. }
  843. PQclear(res);
  844. /* read lines (GRASS Topo)
  845. - standalone nodes -> points|centroids
  846. - edges -> lines/boundaries
  847. */
  848. G_debug(3, "load_plus(): n_lines = %d", plus->n_lines);
  849. dig_alloc_lines(plus, plus->n_lines);
  850. G_zero(plus->Line, sizeof(struct P_line *) * (plus->n_lines + 1)); /* index starts at 1 */
  851. /* read PostGIS Topo standalone nodes (containing_face is null)
  852. -> points
  853. */
  854. sprintf(stmt,
  855. "SELECT node_id,geom FROM \"%s\".node WHERE containing_face "
  856. "IS NULL AND node_id NOT IN "
  857. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  858. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  859. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  860. pg_info->toposchema_name, pg_info->toposchema_name,
  861. pg_info->toposchema_name);
  862. G_debug(2, "SQL: %s", stmt);
  863. res = PQexec(pg_info->conn, stmt);
  864. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  865. PQntuples(res) > plus->n_plines) {
  866. G_warning(_("Inconsistency in topology: number of "
  867. "points %d (should be %d)"),
  868. PQntuples(res), plus->n_plines);
  869. if (res)
  870. PQclear(res);
  871. return -1;
  872. }
  873. ntuples = PQntuples(res); /* plus->n_plines */
  874. G_zero(&line_data, sizeof(struct edge_data));
  875. for (i = 0; i < ntuples; i++) {
  876. /* process standalone nodes (PostGIS Topo) */
  877. line_data.id = atoi(PQgetvalue(res, i, 0));
  878. line_data.wkb_geom = (char *) PQgetvalue(res, i, 1);
  879. read_p_line(plus, i + 1, &line_data, &(pg_info->cache));
  880. }
  881. PQclear(res);
  882. /* read PostGIS Topo edges
  883. -> lines
  884. -> boundaries
  885. */
  886. sprintf(stmt,
  887. "SELECT edge_id,start_node,end_node,left_face,right_face,geom "
  888. "FROM \"%s\".edge ORDER BY edge_id",
  889. pg_info->toposchema_name);
  890. G_debug(2, "SQL: %s", stmt);
  891. res = PQexec(pg_info->conn, stmt);
  892. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  893. PQntuples(res) > plus->n_lines) {
  894. G_warning(_("Inconsistency in topology: number of "
  895. "lines %d (should be %d)"),
  896. PQntuples(res), plus->n_lines);
  897. if (res)
  898. PQclear(res);
  899. return -1;
  900. }
  901. /* process edges (PostGIS Topo) */
  902. ntuples = PQntuples(res);
  903. for (i = 0; i < ntuples; i++) {
  904. line_data.id = atoi(PQgetvalue(res, i, 0));
  905. line_data.start_node = atoi(PQgetvalue(res, i, 1));
  906. line_data.end_node = atoi(PQgetvalue(res, i, 2));
  907. line_data.left_face = atoi(PQgetvalue(res, i, 3));
  908. line_data.right_face = atoi(PQgetvalue(res, i, 4));
  909. line_data.wkb_geom = (char *) PQgetvalue(res, i, 5);
  910. id = plus->n_plines + i + 1; /* points already registered */
  911. read_p_line(plus, id, &line_data, &(pg_info->cache));
  912. /* TODO: update category index */
  913. }
  914. PQclear(res);
  915. /* read PostGIS Topo standalone nodes (containing_face is not null)
  916. -> centroids
  917. */
  918. sprintf(stmt,
  919. "SELECT node_id,geom,containing_face FROM \"%s\".node WHERE containing_face "
  920. "IS NOT NULL AND node_id NOT IN "
  921. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  922. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  923. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  924. pg_info->toposchema_name, pg_info->toposchema_name,
  925. pg_info->toposchema_name);
  926. G_debug(2, "SQL: %s", stmt);
  927. res = PQexec(pg_info->conn, stmt);
  928. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  929. PQntuples(res) != plus->n_clines) {
  930. G_warning(_("Inconsistency in topology: number of "
  931. "centroids %d (should be %d)"),
  932. PQntuples(res), plus->n_clines);
  933. if (res)
  934. PQclear(res);
  935. return -1;
  936. }
  937. G_zero(&line_data, sizeof(struct edge_data));
  938. id = plus->n_plines + plus->n_llines + plus->n_blines + 1;
  939. for (i = 0; i < plus->n_clines; i++) {
  940. line_data.id = atoi(PQgetvalue(res, i, 0));
  941. line_data.wkb_geom = (char *)PQgetvalue(res, i, 1);
  942. line_data.left_face = atoi(PQgetvalue(res, i, 2)); /* face id */
  943. /* area id and face id can be different */
  944. read_p_line(plus, id + i, &line_data, &(pg_info->cache));
  945. }
  946. PQclear(res);
  947. /* build areas for boundaries
  948. reset values -> build from scratch */
  949. plus->n_areas = plus->n_isles = 0;
  950. for (line = 1; line <= plus->n_lines; line++) {
  951. Line = plus->Line[line]; /* centroids: Line is NULL */
  952. if (!Line || Line->type != GV_BOUNDARY)
  953. continue;
  954. for (i = 0; i < 2; i++) { /* for both sides build an area/isle */
  955. side = i == 0 ? GV_LEFT : GV_RIGHT;
  956. G_debug(3, "Build area for line = %d, side = %d",
  957. id, side);
  958. Vect_build_line_area(Map, line, side);
  959. }
  960. }
  961. plus->built = GV_BUILD_AREAS;
  962. /* TODO: attach isles */
  963. plus->built = GV_BUILD_ATTACH_ISLES;
  964. /* attach centroids */
  965. if (plus->n_areas > 0) {
  966. struct P_topo_c *topo;
  967. for (line = 1; line <= plus->n_lines; line++) {
  968. Line = plus->Line[line];
  969. if (Line->type != GV_CENTROID)
  970. continue;
  971. Vect_read_line(Map, Points, NULL, line);
  972. area = Vect_find_area(Map, Points->x[0], Points->y[0]);
  973. topo = (struct P_topo_c *)Line->topo;
  974. topo->area = area;
  975. Area = plus->Area[topo->area];
  976. Area->centroid = Line->offset;
  977. }
  978. }
  979. plus->built = GV_BUILD_CENTROIDS;
  980. /* done */
  981. plus->built = GV_BUILD_ALL;
  982. Vect_destroy_line_struct(Points);
  983. Vect_destroy_list(List);
  984. return 0;
  985. }
  986. /*
  987. \brief PostgreSQL notice processor
  988. Print out NOTICE message only on verbose level
  989. */
  990. void notice_processor(void *arg, const char *message)
  991. {
  992. if (G_verbose() > G_verbose_std()) {
  993. fprintf(stderr, "%s", message);
  994. }
  995. }
  996. #endif