open_pg.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  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 *, const char *, const char *,
  33. struct Format_info_pg *);
  34. static struct P_line *read_p_line(struct Plus_head *, int,
  35. const struct edge_data *,
  36. struct Format_info_cache *);
  37. static struct P_area *read_p_area(struct Plus_head *, int,
  38. const char *, int, const char *);
  39. static struct P_isle *read_p_isle(struct Plus_head *, int,
  40. const char *, int);
  41. static int load_plus_head(struct Format_info_pg *, struct Plus_head *);
  42. static void notice_processor(void *, const char *);
  43. static char **scan_array(const char *);
  44. static int remap_node(const struct Format_info_offset *, int);
  45. static int remap_line(const struct Plus_head*, int);
  46. #endif
  47. /*!
  48. \brief Open vector map - PostGIS feature table on non-topological
  49. level
  50. \param[in,out] Map pointer to Map_info structure
  51. \param update TRUE for write mode, otherwise read-only
  52. \return 0 success
  53. \return -1 error
  54. */
  55. int V1_open_old_pg(struct Map_info *Map, int update)
  56. {
  57. #ifdef HAVE_POSTGRES
  58. int found;
  59. char stmt[DB_SQL_MAX];
  60. PGresult *res;
  61. struct Format_info_pg *pg_info;
  62. G_debug(2, "V1_open_old_pg(): update = %d", update);
  63. pg_info = &(Map->fInfo.pg);
  64. if (!pg_info->conninfo) {
  65. G_warning(_("Connection string not defined"));
  66. return -1;
  67. }
  68. if (!pg_info->table_name) {
  69. G_warning(_("PostGIS feature table not defined"));
  70. return -1;
  71. }
  72. G_debug(1, "V1_open_old_pg(): conninfo='%s' table='%s'",
  73. pg_info->conninfo, pg_info->table_name);
  74. /* connect database */
  75. if (!pg_info->conn)
  76. connect_db(pg_info);
  77. /* get DB name */
  78. pg_info->db_name = G_store(PQdb(pg_info->conn));
  79. if (!pg_info->db_name) {
  80. G_warning(_("Unable to get database name"));
  81. return -1;
  82. }
  83. /* get fid and geometry column */
  84. sprintf(stmt, "SELECT f_geometry_column, coord_dimension, srid, type "
  85. "FROM geometry_columns WHERE f_table_schema = '%s' AND "
  86. "f_table_name = '%s'", pg_info->schema_name, pg_info->table_name);
  87. G_debug(2, "SQL: %s", stmt);
  88. res = PQexec(pg_info->conn, stmt);
  89. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  90. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  91. PQresultErrorMessage(res));
  92. found = PQntuples(res) > 0 ? TRUE : FALSE;
  93. if (found) {
  94. /* geometry column */
  95. pg_info->geom_column = G_store(PQgetvalue(res, 0, 0));
  96. G_debug(3, "\t-> table = %s column = %s", pg_info->table_name,
  97. pg_info->geom_column);
  98. /* fid column */
  99. pg_info->fid_column = get_key_column(pg_info);
  100. /* coordinates dimension */
  101. pg_info->coor_dim = atoi(PQgetvalue(res, 0, 1));
  102. /* SRS ID */
  103. pg_info->srid = atoi(PQgetvalue(res, 0, 2));
  104. /* feature type */
  105. pg_info->feature_type = ftype_from_string(PQgetvalue(res, 0, 3));
  106. }
  107. PQclear(res);
  108. /* no feature in cache */
  109. pg_info->cache.fid = -1;
  110. if (!found) {
  111. G_warning(_("Feature table <%s> not found in 'geometry_columns'"),
  112. pg_info->table_name);
  113. return -1;
  114. }
  115. /* check for topo schema */
  116. check_topo(pg_info, &(Map->plus));
  117. return 0;
  118. #else
  119. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  120. return -1;
  121. #endif
  122. }
  123. /*!
  124. \brief Open vector map - PostGIS feature table on topological level
  125. Simple feature access:
  126. - open feature index file
  127. PostGIS Topology:
  128. - check if topological schema exists
  129. \param[in,out] Map pointer to Map_info structure
  130. \return 0 success
  131. \return -1 error
  132. */
  133. int V2_open_old_pg(struct Map_info *Map)
  134. {
  135. #ifdef HAVE_POSTGRES
  136. struct Format_info_pg *pg_info;
  137. PGresult *res;
  138. G_debug(3, "V2_open_old_pg(): name = %s mapset = %s", Map->name,
  139. Map->mapset);
  140. pg_info = &(Map->fInfo.pg);
  141. if (pg_info->toposchema_name) {
  142. char stmt[DB_SQL_MAX];
  143. /* get topo schema id */
  144. sprintf(stmt, "SELECT id FROM topology.topology WHERE name = '%s'",
  145. pg_info->toposchema_name);
  146. res = PQexec(pg_info->conn, stmt);
  147. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  148. G_warning("%s\n%s", _("Topology schema not found."),
  149. PQresultErrorMessage(res));
  150. if (res)
  151. PQclear(res);
  152. return -1;
  153. }
  154. pg_info->toposchema_id = atoi(PQgetvalue(res, 0, 0));
  155. PQclear(res);
  156. }
  157. else {
  158. /* fidx file needed only for simple features access */
  159. if (Vect_open_fidx(Map, &(pg_info->offset)) != 0) {
  160. G_warning(_("Unable to open feature index file for vector map <%s>"),
  161. Vect_get_full_name(Map));
  162. G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
  163. }
  164. }
  165. return 0;
  166. #else
  167. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  168. return -1;
  169. #endif
  170. }
  171. /*!
  172. \brief Prepare PostGIS database for creating new feature table
  173. (level 1)
  174. New PostGIS table is created when writing features by
  175. Vect_wrile_line().
  176. \param[out] Map pointer to Map_info structure
  177. \param name name of PostGIS feature table to create
  178. \param with_z WITH_Z for 3D vector data otherwise WITHOUT_Z
  179. \return 0 success
  180. \return -1 error
  181. */
  182. int V1_open_new_pg(struct Map_info *Map, const char *name, int with_z)
  183. {
  184. #ifdef HAVE_POSTGRES
  185. char stmt[DB_SQL_MAX];
  186. struct Format_info_pg *pg_info;
  187. PGresult *res;
  188. G_debug(2, "V1_open_new_pg(): name = %s with_z = %d", name, with_z);
  189. pg_info = &(Map->fInfo.pg);
  190. if (!pg_info->conninfo) {
  191. G_warning(_("Connection string not defined"));
  192. return -1;
  193. }
  194. if (!pg_info->table_name) {
  195. G_warning(_("PostGIS feature table not defined"));
  196. return -1;
  197. }
  198. G_debug(1, "V1_open_new_pg(): conninfo='%s' table='%s'",
  199. pg_info->conninfo, pg_info->table_name);
  200. /* connect database */
  201. connect_db(pg_info);
  202. /* get DB name */
  203. pg_info->db_name = G_store(PQdb(pg_info->conn));
  204. if (!pg_info->db_name) {
  205. G_warning(_("Unable to get database name"));
  206. return -1;
  207. }
  208. /* if schema not defined, use 'public' */
  209. if (!pg_info->schema_name)
  210. pg_info->schema_name = G_store("public");
  211. /* if fid_column not defined, use 'fid' */
  212. if (!pg_info->fid_column)
  213. pg_info->fid_column = G_store(GV_PG_FID_COLUMN);
  214. /* if geom_column not defined, use 'geom' */
  215. if (!pg_info->geom_column)
  216. pg_info->geom_column = G_store(GV_PG_GEOMETRY_COLUMN);
  217. /* check if feature table already exists */
  218. sprintf(stmt, "SELECT * FROM pg_tables "
  219. "WHERE schemaname = '%s' AND tablename = '%s'",
  220. pg_info->schema_name, pg_info->table_name);
  221. G_debug(2, "SQL: %s", stmt);
  222. res = PQexec(pg_info->conn, stmt);
  223. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  224. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  225. PQresultErrorMessage(res));
  226. if (PQntuples(res) > 0) {
  227. /* table found */
  228. if (G_get_overwrite()) {
  229. G_warning(_("PostGIS layer <%s.%s> already exists and will be overwritten"),
  230. pg_info->schema_name, pg_info->table_name);
  231. if (drop_table(pg_info) == -1) {
  232. G_warning(_("Unable to delete PostGIS layer <%s>"),
  233. pg_info->table_name);
  234. return -1;
  235. }
  236. }
  237. else {
  238. G_warning(_("PostGIS layer <%s.%s> already exists in database '%s'"),
  239. pg_info->schema_name, pg_info->table_name,
  240. pg_info->db_name);
  241. return -1;
  242. }
  243. }
  244. /* no feature in cache */
  245. pg_info->cache.fid = -1;
  246. /* unknown feature type */
  247. pg_info->feature_type = SF_UNKNOWN;
  248. PQclear(res);
  249. return 0;
  250. #else
  251. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  252. return -1;
  253. #endif
  254. }
  255. /*!
  256. \brief Read full-topology for PostGIS links
  257. Note: Only 2D topological primitives are currently supported
  258. \param[in,out] Map pointer to Map_info structure
  259. \param head_only TRUE to read only header
  260. \return 0 on success
  261. \return 1 topology layer does not exist
  262. \return -1 on error
  263. */
  264. int Vect_open_topo_pg(struct Map_info *Map, int head_only)
  265. {
  266. #ifdef HAVE_POSTGRES
  267. struct Plus_head *plus;
  268. struct Format_info_pg *pg_info;
  269. Map->open = VECT_OPEN_CODE; /* needed by load_plus */
  270. plus = &(Map->plus);
  271. pg_info = &(Map->fInfo.pg);
  272. /* check for topo schema */
  273. if (check_topo(pg_info, plus) != 0)
  274. return 1;
  275. /* free and init plus structure */
  276. dig_init_plus(plus);
  277. plus->Spidx_new = TRUE;
  278. return Vect__load_plus_pg(Map, head_only);
  279. #else
  280. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  281. return -1;
  282. #endif
  283. }
  284. #ifdef HAVE_POSTGRES
  285. /*!
  286. \brief Get key column for feature table
  287. \param pg_info pointer to Format_info_pg
  288. \return string buffer with key column name
  289. \return NULL on missing key column
  290. */
  291. char *get_key_column(struct Format_info_pg *pg_info)
  292. {
  293. char *key_column;
  294. char stmt[DB_SQL_MAX];
  295. PGresult *res;
  296. sprintf(stmt,
  297. "SELECT kcu.column_name "
  298. "FROM INFORMATION_SCHEMA.TABLES t "
  299. "LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc "
  300. "ON tc.table_catalog = t.table_catalog "
  301. "AND tc.table_schema = t.table_schema "
  302. "AND tc.table_name = t.table_name "
  303. "AND tc.constraint_type = 'PRIMARY KEY' "
  304. "LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu "
  305. "ON kcu.table_catalog = tc.table_catalog "
  306. "AND kcu.table_schema = tc.table_schema "
  307. "AND kcu.table_name = tc.table_name "
  308. "AND kcu.constraint_name = tc.constraint_name "
  309. "WHERE t.table_schema = '%s' AND t.table_name = '%s'",
  310. pg_info->schema_name, pg_info->table_name);
  311. G_debug(2, "SQL: %s", stmt);
  312. res = PQexec(pg_info->conn, stmt);
  313. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  314. PQntuples(res) != 1 || strlen(PQgetvalue(res, 0, 0)) < 1) {
  315. G_warning(_("No key column detected."));
  316. if (res)
  317. PQclear(res);
  318. return NULL;
  319. }
  320. key_column = G_store(PQgetvalue(res, 0, 0));
  321. PQclear(res);
  322. return key_column;
  323. }
  324. /*!
  325. \brief Get simple feature type from string
  326. \param type string
  327. \return SF type
  328. */
  329. SF_FeatureType ftype_from_string(const char *type)
  330. {
  331. SF_FeatureType sf_type;
  332. if (G_strcasecmp(type, "POINT") == 0)
  333. return SF_POINT;
  334. else if (G_strcasecmp(type, "LINESTRING") == 0)
  335. return SF_LINESTRING;
  336. else if (G_strcasecmp(type, "POLYGON") == 0)
  337. return SF_POLYGON;
  338. else if (G_strcasecmp(type, "MULTIPOINT") == 0)
  339. return SF_MULTIPOINT;
  340. else if (G_strcasecmp(type, "MULTILINESTRING") == 0)
  341. return SF_MULTILINESTRING;
  342. else if (G_strcasecmp(type, "MULTIPOLYGON") == 0)
  343. return SF_MULTIPOLYGON;
  344. else if (G_strcasecmp(type, "GEOMETRYCOLLECTION") == 0)
  345. return SF_GEOMETRYCOLLECTION;
  346. else
  347. return SF_UNKNOWN;
  348. G_debug(3, "ftype_from_string(): type='%s' -> %d", type, sf_type);
  349. return sf_type;
  350. }
  351. /*!
  352. \brief Drop feature table and topology schema if exists
  353. \param pg_info pointer to Format_info_pg
  354. \return -1 on error
  355. \return 0 on success
  356. */
  357. int drop_table(struct Format_info_pg *pg_info)
  358. {
  359. int i;
  360. char stmt[DB_SQL_MAX];
  361. char *topo_schema;
  362. PGresult *result, *result_drop;
  363. /* drop topology schema(s) related to the feature table */
  364. sprintf(stmt, "SELECT t.name FROM topology.layer AS l JOIN "
  365. "topology.topology AS t ON l.topology_id = t.id "
  366. "WHERE l.table_name = '%s'", pg_info->table_name);
  367. G_debug(2, "SQL: %s", stmt);
  368. result = PQexec(pg_info->conn, stmt);
  369. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  370. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  371. PQclear(result);
  372. return -1;
  373. }
  374. for (i = 0; i < PQntuples(result); i++) {
  375. topo_schema = PQgetvalue(result, i, 0);
  376. sprintf(stmt, "SELECT topology.DropTopology('%s')",
  377. topo_schema);
  378. G_debug(2, "SQL: %s", stmt);
  379. result_drop = PQexec(pg_info->conn, stmt);
  380. if (!result_drop || PQresultStatus(result_drop) != PGRES_TUPLES_OK)
  381. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  382. G_verbose_message(_("PostGIS topology schema <%s> dropped"),
  383. topo_schema);
  384. PQclear(result_drop);
  385. }
  386. PQclear(result);
  387. /* drop feature table */
  388. sprintf(stmt, "DROP TABLE \"%s\".\"%s\"",
  389. pg_info->schema_name, pg_info->table_name);
  390. G_debug(2, "SQL: %s", stmt);
  391. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  392. return -1;
  393. }
  394. return 0;
  395. }
  396. /*!
  397. \brief Establish PG connection (pg_info->conninfo)
  398. \param pg_info pointer to Format_info_pg
  399. */
  400. void connect_db(struct Format_info_pg *pg_info)
  401. {
  402. pg_info->conn = PQconnectdb(pg_info->conninfo);
  403. G_debug(2, " PQconnectdb(): %s", pg_info->conninfo);
  404. if (PQstatus(pg_info->conn) == CONNECTION_BAD)
  405. G_fatal_error("%s\n%s",
  406. _("Connection to PostgreSQL database failed."),
  407. PQerrorMessage(pg_info->conn));
  408. /* print notice messages only on verbose level */
  409. PQsetNoticeProcessor(pg_info->conn, notice_processor, NULL);
  410. }
  411. /*!
  412. \brief Check for topology schema (pg_info->toposchema_name)
  413. \param pg_info pointer to Format_info_pg
  414. \return 0 schema exists
  415. \return 1 schema doesn't exists
  416. */
  417. int check_topo(struct Format_info_pg *pg_info, struct Plus_head *plus)
  418. {
  419. char stmt[DB_SQL_MAX];
  420. PGresult *res;
  421. /* connect database */
  422. if (!pg_info->conn)
  423. connect_db(pg_info);
  424. if (pg_info->toposchema_name)
  425. return 0;
  426. /* check if topology layer/schema exists */
  427. sprintf(stmt,
  428. "SELECT t.id,t.name,t.hasz,l.feature_column FROM topology.layer "
  429. "AS l JOIN topology.topology AS t ON l.topology_id = t.id "
  430. "WHERE schema_name = '%s' AND table_name = '%s'",
  431. pg_info->schema_name, pg_info->table_name);
  432. G_debug(2, "SQL: %s", stmt);
  433. res = PQexec(pg_info->conn, stmt);
  434. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  435. PQntuples(res) != 1) {
  436. G_debug(1, "Topology layers for '%s.%s' not found (%s)",
  437. pg_info->schema_name, pg_info->table_name,
  438. PQerrorMessage(pg_info->conn));
  439. if (res)
  440. PQclear(res);
  441. return 1;
  442. }
  443. pg_info->toposchema_id = atoi(PQgetvalue(res, 0, 0));
  444. pg_info->toposchema_name = G_store(PQgetvalue(res, 0, 1));
  445. pg_info->topogeom_column = G_store(PQgetvalue(res, 0, 3));
  446. /* check extra GRASS tables */
  447. sprintf(stmt, "SELECT COUNT(*) FROM pg_tables WHERE schemaname = '%s' "
  448. "AND tablename LIKE '%%_grass'", pg_info->toposchema_name);
  449. if (Vect__execute_get_value_pg(pg_info->conn, stmt) != TOPO_TABLE_NUM)
  450. pg_info->topo_geo_only = TRUE;
  451. G_debug(1, "PostGIS topology detected: schema = %s column = %s topo_geo_only = %d",
  452. pg_info->toposchema_name, pg_info->topogeom_column, pg_info->topo_geo_only);
  453. /* check for 3D */
  454. if (strcmp(PQgetvalue(res, 0, 2), "t") == 0)
  455. plus->with_z = WITH_Z;
  456. PQclear(res);
  457. return 0;
  458. }
  459. /*!
  460. \brief Parse BBOX string
  461. \param value string buffer
  462. \param[out] bbox pointer to output bound_box struct
  463. \return 0 on success
  464. \return -1 on error
  465. */
  466. int parse_bbox(const char *value, struct bound_box *bbox)
  467. {
  468. unsigned int i;
  469. size_t length, prefix_length;
  470. char **tokens, **tokens_coord, *coord;
  471. if (strlen(value) < 1) {
  472. G_warning(_("Empty bounding box"));
  473. return -1;
  474. }
  475. prefix_length = strlen("box3d(");
  476. if (G_strncasecmp(value, "box3d(", prefix_length) != 0)
  477. return -1;
  478. /* strip off "bbox3d(...)" */
  479. length = strlen(value);
  480. coord = G_malloc(length - prefix_length);
  481. for (i = prefix_length; i < length; i++)
  482. coord[i-prefix_length] = value[i];
  483. coord[length-prefix_length-1] = '\0';
  484. tokens = G_tokenize(coord, ",");
  485. G_free(coord);
  486. if (G_number_of_tokens(tokens) != 2) {
  487. G_free_tokens(tokens);
  488. return -1;
  489. }
  490. /* parse bbox LL corner */
  491. tokens_coord = G_tokenize(tokens[0], " ");
  492. if (G_number_of_tokens(tokens_coord) != 3) {
  493. G_free_tokens(tokens);
  494. G_free_tokens(tokens_coord);
  495. }
  496. bbox->W = atof(tokens_coord[0]);
  497. bbox->S = atof(tokens_coord[1]);
  498. bbox->B = atof(tokens_coord[2]);
  499. G_free_tokens(tokens_coord);
  500. /* parse bbox UR corner */
  501. tokens_coord = G_tokenize(tokens[1], " ");
  502. if (G_number_of_tokens(tokens_coord) != 3) {
  503. G_free_tokens(tokens);
  504. G_free_tokens(tokens_coord);
  505. }
  506. bbox->E = atof(tokens_coord[0]);
  507. bbox->N = atof(tokens_coord[1]);
  508. bbox->T = atof(tokens_coord[2]);
  509. G_free_tokens(tokens_coord);
  510. G_free_tokens(tokens);
  511. return 0;
  512. }
  513. /*!
  514. \brief Read P_node structure
  515. See dig_Rd_P_node() for reference.
  516. \param plus pointer to Plus_head structure
  517. \param n index (starts at 1)
  518. \param id node id (table "node")
  519. \param wkb_data geometry data (wkb)
  520. \param lines_data lines array or NULL
  521. \param angles_data angles array or NULL
  522. \param pg_info pointer to Format_info_pg sttucture
  523. \return pointer to new P_node struct
  524. \return NULL on error
  525. */
  526. struct P_node *read_p_node(struct Plus_head *plus, int n,
  527. int id, const char *wkb_data, const char *lines_data,
  528. const char *angles_data, struct Format_info_pg *pg_info)
  529. {
  530. int i, cnt;
  531. char **lines, **angles;
  532. struct P_node *node;
  533. struct line_pnts *points;
  534. PGresult *res;
  535. /* get lines connected to the node */
  536. lines = angles = NULL;
  537. if (!lines_data && !angles_data) { /* pg_info->topo_geo_only == TRUE */
  538. char stmt[DB_SQL_MAX];
  539. sprintf(stmt,
  540. "SELECT edge_id,'s' as node,"
  541. "ST_Azimuth(ST_StartPoint(geom), ST_PointN(geom, 2)) AS angle"
  542. " FROM \"%s\".edge WHERE start_node = %d UNION ALL "
  543. "SELECT edge_id,'e' as node,"
  544. "ST_Azimuth(ST_EndPoint(geom), ST_PointN(geom, ST_NumPoints(geom) - 1)) AS angle"
  545. " FROM \"%s\".edge WHERE end_node = %d"
  546. " ORDER BY angle DESC",
  547. pg_info->toposchema_name, id,
  548. pg_info->toposchema_name, id);
  549. G_debug(2, "SQL: %s", stmt);
  550. res = PQexec(pg_info->conn, stmt);
  551. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  552. G_warning(_("Inconsistency in topology: unable to read node %d"), id);
  553. if (res)
  554. PQclear(res);
  555. return NULL;
  556. }
  557. cnt = PQntuples(res);
  558. }
  559. else { /* pg_info->topo_geo_only != TRUE */
  560. lines = scan_array(lines_data);
  561. angles = scan_array(angles_data);
  562. cnt = G_number_of_tokens(lines);
  563. if (cnt != G_number_of_tokens(angles))
  564. return NULL; /* 'lines' and 'angles' array must have the same size */
  565. }
  566. if (cnt == 0) { /* dead */
  567. plus->Node[n] = NULL;
  568. return NULL;
  569. }
  570. node = dig_alloc_node();
  571. node->n_lines = cnt;
  572. G_debug(4, "read_p_node(): id = %d, n_lines = %d", id, cnt);
  573. if (dig_node_alloc_line(node, node->n_lines) == -1)
  574. return NULL;
  575. /* lines / angles */
  576. if (lines) {
  577. for (i = 0; i < node->n_lines; i++) {
  578. node->lines[i] = atoi(lines[i]);
  579. node->angles[i] = atof(angles[i]);
  580. G_debug(5, "\tline = %d angle = %f", node->lines[i],
  581. node->angles[i]);
  582. }
  583. G_free_tokens(lines);
  584. G_free_tokens(angles);
  585. }
  586. else {
  587. for (i = 0; i < node->n_lines; i++) {
  588. node->lines[i] = atoi(PQgetvalue(res, i, 0));
  589. if (strcmp(PQgetvalue(res, i, 1), "s") != 0) {
  590. /* end node */
  591. node->lines[i] *= -1;
  592. }
  593. node->angles[i] = M_PI / 2 - atof(PQgetvalue(res, i, 2));
  594. /* angles range <-PI; PI> */
  595. if (node->angles[i] > M_PI)
  596. node->angles[i] = node->angles[i] - 2 * M_PI;
  597. if (node->angles[i] < -1.0 * M_PI)
  598. node->angles[i] = node->angles[i] + 2 * M_PI;
  599. G_debug(5, "\tline = %d angle = %f", node->lines[i],
  600. node->angles[i]);
  601. }
  602. PQclear(res);
  603. }
  604. /* get node coordinates */
  605. if (SF_POINT != Vect__cache_feature_pg(wkb_data, FALSE, FALSE,
  606. &(pg_info->cache), NULL))
  607. G_warning(_("Inconsistency in topology: node %d - unexpected feature type %d"),
  608. n, pg_info->cache.sf_type);
  609. points = pg_info->cache.lines[0];
  610. node->x = points->x[0];
  611. node->y = points->y[0];
  612. if (plus->with_z)
  613. node->z = points->z[0];
  614. else
  615. node->z = 0.0;
  616. /* update spatial index */
  617. dig_spidx_add_node(plus, n, node->x, node->y, node->z);
  618. if (plus->uplist.do_uplist)
  619. /* collect updated nodes if requested */
  620. dig_node_add_updated(plus, n);
  621. plus->Node[n] = node;
  622. return node;
  623. }
  624. /*!
  625. \brief Read P_line structure
  626. See dig_Rd_P_line() for reference.
  627. Supported feature types:
  628. - GV_POINT
  629. - GV_LINE
  630. - GV_BOUNDARY
  631. \param plus pointer to Plus_head structure
  632. \param n index (starts at 1)
  633. \param data edge data (id, start/end node, left/right face, ...)
  634. \param pg_info pointer to Format_info_pg sttucture
  635. \return pointer to P_line struct
  636. \return NULL on error
  637. */
  638. struct P_line *read_p_line(struct Plus_head *plus, int n,
  639. const struct edge_data *data,
  640. struct Format_info_cache *cache)
  641. {
  642. int tp, itype;
  643. struct P_line *line;
  644. struct line_pnts *points;
  645. struct bound_box box;
  646. if (data->start_node == 0 && data->end_node == 0) {
  647. if (data->left_face == 0)
  648. tp = GV_POINT;
  649. else
  650. tp = GV_CENTROID;
  651. }
  652. else if (data->left_face == 0 && data->right_face == 0) {
  653. tp = GV_LINE;
  654. }
  655. else {
  656. tp = GV_BOUNDARY;
  657. }
  658. if (tp == 0) { /* dead ??? */
  659. plus->Line[n] = NULL;
  660. return NULL;
  661. }
  662. line = dig_alloc_line();
  663. /* type & offset ( = id) */
  664. line->type = tp;
  665. line->offset = data->id;
  666. G_debug(4, "read_p_line(): id/offset = %d type = %d", data->id, line->type);
  667. /* topo */
  668. if (line->type == GV_POINT) {
  669. line->topo = NULL;
  670. }
  671. else {
  672. line->topo = dig_alloc_topo(line->type);
  673. if ((line->type & GV_LINES) & (data->start_node < 0 || data->end_node < 0))
  674. return NULL;
  675. /* lines */
  676. if (line->type == GV_LINE) {
  677. struct P_topo_l *topo = (struct P_topo_l *)line->topo;
  678. topo->N1 = data->start_node;
  679. topo->N2 = data->end_node;
  680. }
  681. /* boundaries */
  682. else if (line->type == GV_BOUNDARY) {
  683. struct P_topo_b *topo = (struct P_topo_b *)line->topo;
  684. topo->N1 = data->start_node;
  685. topo->N2 = data->end_node;
  686. /* skip left/right area - will be detected when building
  687. areas/isles */
  688. topo->left = topo->right = 0;
  689. }
  690. /* centroids */
  691. else if (line->type == GV_CENTROID) {
  692. struct P_topo_c *topo = (struct P_topo_c *)line->topo;
  693. topo->area = data->left_face;
  694. }
  695. }
  696. /* update spatial index */
  697. Vect__cache_feature_pg(data->wkb_geom, FALSE, FALSE, cache, NULL);
  698. itype = cache->lines_types[0];
  699. if ((line->type & GV_POINTS && itype != GV_POINT) ||
  700. (line->type & GV_LINES && itype != GV_LINE))
  701. G_warning(_("Inconsistency in topology: line %d - unexpected feature type"), n);
  702. points = cache->lines[0];
  703. dig_line_box(points, &box);
  704. dig_spidx_add_line(plus, n, &box);
  705. if (plus->uplist.do_uplist) {
  706. /* collect updated lines if requested */
  707. dig_line_add_updated(plus, n);
  708. plus->uplist.uplines_offset[plus->uplist.n_uplines - 1] = line->offset;
  709. }
  710. plus->Line[n] = line;
  711. return line;
  712. }
  713. /*!
  714. \brief Read P_area structure
  715. \param plus pointer to Plus_head structure
  716. \param n index (starts at 1)
  717. \param lines_data lines array (see P_area struct)
  718. \param centroid centroid id (see P_area struct)
  719. \param isles_data lines array (see P_area struct)
  720. \return pointer to P_area struct
  721. \return NULL on error
  722. */
  723. struct P_area *read_p_area(struct Plus_head *plus, int n,
  724. const char *lines_data, int centroid, const char *isles_data)
  725. {
  726. int i;
  727. int nlines, nisles;
  728. char **lines, **isles;
  729. struct P_area *area;
  730. lines = scan_array(lines_data);
  731. nlines = G_number_of_tokens(lines);
  732. isles = scan_array(isles_data);
  733. nisles = G_number_of_tokens(isles);
  734. if (nlines < 1) {
  735. G_warning(_("Area %d without boundary detected"), n);
  736. return NULL;
  737. }
  738. G_debug(3, "read_p_area(): n = %d nlines = %d nisles = %d", n, nlines, nisles);
  739. /* allocate area */
  740. area = dig_alloc_area();
  741. dig_area_alloc_line(area, nlines);
  742. dig_area_alloc_isle(area, nisles);
  743. /* set lines */
  744. area->n_lines = nlines;
  745. for (i = 0; i < nlines; i++) {
  746. area->lines[i] = atoi(lines[i]);
  747. }
  748. /* set isles */
  749. area->n_isles = nisles;
  750. for (i = 0; i < nisles; i++) {
  751. area->isles[i] = atoi(isles[i]);
  752. }
  753. /* set centroid */
  754. area->centroid = remap_line(plus, centroid);
  755. G_free_tokens(lines);
  756. G_free_tokens(isles);
  757. plus->Area[n] = area;
  758. return area;
  759. }
  760. /*!
  761. \brief Read P_isle structure
  762. \param plus pointer to Plus_head structure
  763. \param n index (starts at 1)
  764. \param lines_data lines array (see P_isle struct)
  765. \param area area id (see P_isle struct)
  766. \return pointer to P_isle struct
  767. \return NULL on error
  768. */
  769. struct P_isle *read_p_isle(struct Plus_head *plus, int n,
  770. const char *lines_data, int area)
  771. {
  772. int i;
  773. int nlines;
  774. char **lines;
  775. struct P_isle *isle;
  776. lines = scan_array(lines_data);
  777. nlines = G_number_of_tokens(lines);
  778. if (nlines < 1) {
  779. G_warning(_("Isle %d without boundary detected"), n);
  780. return NULL;
  781. }
  782. G_debug(3, "read_p_isle(): n = %d nlines = %d", n, nlines);
  783. /* allocate isle */
  784. isle = dig_alloc_isle();
  785. dig_isle_alloc_line(isle, nlines);
  786. /* set lines */
  787. isle->n_lines = nlines;
  788. for (i = 0; i < nlines; i++) {
  789. isle->lines[i] = atoi(lines[i]);
  790. }
  791. /* set area */
  792. isle->area = area;
  793. G_free_tokens(lines);
  794. plus->Isle[n] = isle;
  795. return isle;
  796. }
  797. /*!
  798. \brief Read topo from PostGIS topology schema -- header info only
  799. \param[in,out] plus pointer to Plus_head struct
  800. \return 0 on success
  801. \return -1 on error
  802. */
  803. int load_plus_head(struct Format_info_pg *pg_info, struct Plus_head *plus)
  804. {
  805. char stmt[DB_SQL_MAX];
  806. PGresult *res;
  807. plus->off_t_size = -1;
  808. /* get map bounding box
  809. fisrt try to get info from 'topology.grass' table */
  810. sprintf(stmt,
  811. "SELECT %s FROM \"%s\".\"%s\" WHERE %s = %d",
  812. TOPO_BBOX, TOPO_SCHEMA, TOPO_TABLE, TOPO_ID, pg_info->toposchema_id);
  813. G_debug(2, "SQL: %s", stmt);
  814. res = PQexec(pg_info->conn, stmt);
  815. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  816. PQntuples(res) != 1) {
  817. PQclear(res);
  818. /* otherwise try to calculate bbox from TopoGeometry elements */
  819. sprintf(stmt,
  820. "SELECT ST_3DExtent(%s) FROM \"%s\".\"%s\"",
  821. pg_info->topogeom_column, pg_info->schema_name, pg_info->table_name);
  822. G_debug(2, "SQL: %s", stmt);
  823. res = PQexec(pg_info->conn, stmt);
  824. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  825. PQntuples(res) != 1 || strlen(PQgetvalue(res, 0, 0)) < 1) {
  826. G_warning(_("Unable to get map bounding box from topology"));
  827. PQclear(res);
  828. return -1;
  829. }
  830. }
  831. if (parse_bbox(PQgetvalue(res, 0, 0), &(plus->box)) != 0) {
  832. G_warning(_("Unable to parse map bounding box:\n%s"),
  833. PQgetvalue(res, 0, 0));
  834. return -1;
  835. }
  836. PQclear(res);
  837. /* get number of topological elements */
  838. /* nodes
  839. note: isolated nodes are registered in GRASS Topology model */
  840. sprintf(stmt,
  841. "SELECT COUNT(DISTINCT node) FROM (SELECT start_node AS node "
  842. "FROM \"%s\".edge GROUP BY start_node UNION ALL SELECT end_node "
  843. "AS node FROM \"%s\".edge GROUP BY end_node) AS foo",
  844. pg_info->toposchema_name, pg_info->toposchema_name);
  845. plus->n_nodes = Vect__execute_get_value_pg(pg_info->conn, stmt);
  846. if (!pg_info->topo_geo_only) {
  847. int n_nodes;
  848. /* check nodes consistency */
  849. sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".%s",
  850. pg_info->toposchema_name, TOPO_TABLE_NODE);
  851. n_nodes = Vect__execute_get_value_pg(pg_info->conn, stmt);
  852. if (n_nodes != plus->n_nodes) {
  853. G_warning(_("Different number of nodes detected (%d, %d)"),
  854. plus->n_nodes, n_nodes);
  855. return -1;
  856. }
  857. }
  858. G_debug(3, "Vect_open_topo_pg(): n_nodes=%d", plus->n_nodes);
  859. /* lines (edges in PostGIS Topology model) */
  860. sprintf(stmt,
  861. "SELECT COUNT(*) FROM \"%s\".edge",
  862. pg_info->toposchema_name);
  863. /* + isolated nodes as points
  864. + centroids */
  865. plus->n_lines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  866. /* areas (faces with face_id > 0 in PostGIS Topology model) */
  867. sprintf(stmt,
  868. "SELECT COUNT(*) FROM \"%s\".face WHERE face_id > 0",
  869. pg_info->toposchema_name);
  870. plus->n_areas = Vect__execute_get_value_pg(pg_info->conn, stmt);
  871. if (!pg_info->topo_geo_only) {
  872. int n_areas;
  873. /* check areas consistency */
  874. sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".%s",
  875. pg_info->toposchema_name, TOPO_TABLE_AREA);
  876. n_areas = Vect__execute_get_value_pg(pg_info->conn, stmt);
  877. if (n_areas != plus->n_areas) {
  878. G_warning(_("Different number of areas detected (%d, %d)"),
  879. plus->n_areas, n_areas);
  880. return -1;
  881. }
  882. }
  883. G_debug(3, "Vect_open_topo_pg(): n_areas=%d", plus->n_areas);
  884. /* isles (faces with face_id <=0 in PostGIS Topology model)
  885. note: universal face is represented in GRASS Topology model as isle (area=0)
  886. */
  887. sprintf(stmt,
  888. "SELECT COUNT(*) FROM \"%s\".face WHERE face_id < 0",
  889. pg_info->toposchema_name);
  890. plus->n_isles = Vect__execute_get_value_pg(pg_info->conn, stmt);
  891. if (!pg_info->topo_geo_only) {
  892. int n_isles;
  893. /* check areas consistency */
  894. sprintf(stmt, "SELECT COUNT(*) FROM \"%s\".%s",
  895. pg_info->toposchema_name, TOPO_TABLE_ISLE);
  896. n_isles = Vect__execute_get_value_pg(pg_info->conn, stmt);
  897. if (n_isles != plus->n_isles) {
  898. G_warning(_("Different number of areas detected (%d, %d)"),
  899. plus->n_isles, n_isles);
  900. return -1;
  901. }
  902. }
  903. G_debug(3, "Vect_open_topo_pg(): n_isles=%d", plus->n_isles);
  904. /* number of features according the type */
  905. /* points */
  906. sprintf(stmt,
  907. "SELECT COUNT(*) FROM \"%s\".node WHERE containing_face "
  908. "IS NULL AND node_id NOT IN "
  909. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  910. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  911. "\"%s\".edge GROUP BY end_node) AS foo)",
  912. pg_info->toposchema_name, pg_info->toposchema_name,
  913. pg_info->toposchema_name);
  914. plus->n_plines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  915. G_debug(3, "Vect_open_topo_pg(): n_plines=%d", plus->n_plines);
  916. /* lines */
  917. sprintf(stmt,
  918. "SELECT COUNT(*) FROM \"%s\".edge WHERE "
  919. "left_face = 0 AND right_face = 0",
  920. pg_info->toposchema_name);
  921. plus->n_llines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  922. G_debug(3, "Vect_open_topo_pg(): n_llines=%d", plus->n_llines);
  923. /* boundaries */
  924. sprintf(stmt,
  925. "SELECT COUNT(*) FROM \"%s\".edge WHERE "
  926. "left_face != 0 OR right_face != 0",
  927. pg_info->toposchema_name);
  928. plus->n_blines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  929. G_debug(3, "Vect_open_topo_pg(): n_blines=%d", plus->n_blines);
  930. /* centroids */
  931. sprintf(stmt,
  932. "SELECT COUNT(*) FROM \"%s\".node WHERE containing_face "
  933. "IS NOT NULL AND node_id NOT IN "
  934. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  935. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  936. "\"%s\".edge GROUP BY end_node) AS foo)",
  937. pg_info->toposchema_name, pg_info->toposchema_name,
  938. pg_info->toposchema_name);
  939. plus->n_clines = Vect__execute_get_value_pg(pg_info->conn, stmt);
  940. G_debug(3, "Vect_open_topo_pg(): n_clines=%d", plus->n_clines);
  941. /* update number of lines - add points and centroids */
  942. plus->n_lines += plus->n_plines + plus->n_clines;
  943. G_debug(3, "Vect_open_topo_pg(): n_lines=%d", plus->n_lines);
  944. return 0;
  945. }
  946. /*!
  947. \brief Read topo info from PostGIS topology schema
  948. \param pg_info pointer to Format_info_pg
  949. \param[in,out] plus pointer to Plus_head struct
  950. \param head_only TRUE to read only header info
  951. \return 0 on success
  952. \return -1 on error
  953. */
  954. int Vect__load_plus_pg(struct Map_info *Map, int head_only)
  955. {
  956. int i, side, line, id, ntuples;
  957. char stmt[DB_SQL_MAX];
  958. struct edge_data line_data;
  959. struct Format_info_pg *pg_info;
  960. struct Format_info_offset *offset;
  961. struct Plus_head *plus;
  962. struct P_line *Line;
  963. struct line_pnts *Points;
  964. struct ilist *List;
  965. PGresult *res;
  966. pg_info = &(Map->fInfo.pg);
  967. plus = &(Map->plus);
  968. offset = &(pg_info->offset);
  969. if (load_plus_head(pg_info, plus) != 0)
  970. return -1;
  971. if (head_only)
  972. return 0;
  973. Points = Vect_new_line_struct();
  974. List = Vect_new_list();
  975. /* read nodes (GRASS Topo)
  976. note: standalone nodes (ie. points/centroids) are ignored
  977. */
  978. if (pg_info->topo_geo_only)
  979. sprintf(stmt,
  980. "SELECT node_id,geom FROM \"%s\".node WHERE node_id IN "
  981. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  982. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  983. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  984. pg_info->toposchema_name, pg_info->toposchema_name,
  985. pg_info->toposchema_name);
  986. else
  987. sprintf(stmt, "SELECT node.node_id,geom,lines,angles FROM \"%s\".node AS node "
  988. "join \"%s\".%s AS node_grass ON node.node_id = node_grass.node_id "
  989. "ORDER BY node_id", pg_info->toposchema_name, pg_info->toposchema_name,
  990. TOPO_TABLE_NODE);
  991. G_debug(2, "SQL: %s", stmt);
  992. res = PQexec(pg_info->conn, stmt);
  993. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  994. PQntuples(res) != plus->n_nodes) {
  995. G_warning(_("Inconsistency in topology: number of "
  996. "nodes %d (should be %d)"),
  997. PQntuples(res), plus->n_nodes);
  998. if (res)
  999. PQclear(res);
  1000. return -1;
  1001. }
  1002. G_debug(3, "load_plus(): n_nodes = %d", plus->n_nodes);
  1003. dig_alloc_nodes(plus, plus->n_nodes);
  1004. offset->array = (int *) G_malloc (sizeof(int) * plus->n_nodes);
  1005. offset->array_num = offset->array_alloc = plus->n_nodes;
  1006. for (i = 0; i < plus->n_nodes; i++) {
  1007. G_debug(5, "node: %d", i);
  1008. id = atoi(PQgetvalue(res, i, 0));
  1009. read_p_node(plus, i + 1, /* node index starts at 1 */
  1010. id, (const char *) PQgetvalue(res, i, 1),
  1011. !pg_info->topo_geo_only ? (const char *) PQgetvalue(res, i, 2) : NULL,
  1012. !pg_info->topo_geo_only ? (const char *) PQgetvalue(res, i, 3) : NULL,
  1013. pg_info);
  1014. /* update offset */
  1015. offset->array[i] = id;
  1016. }
  1017. PQclear(res);
  1018. /* read lines (GRASS Topo)
  1019. - standalone nodes -> points|centroids
  1020. - edges -> lines/boundaries
  1021. */
  1022. G_debug(3, "load_plus(): n_lines = %d", plus->n_lines);
  1023. dig_alloc_lines(plus, plus->n_lines);
  1024. G_zero(plus->Line, sizeof(struct P_line *) * (plus->n_lines + 1)); /* index starts at 1 */
  1025. /* read PostGIS Topo standalone nodes (containing_face is null)
  1026. -> points
  1027. */
  1028. if (pg_info->topo_geo_only)
  1029. sprintf(stmt,
  1030. "SELECT node_id,geom FROM \"%s\".node WHERE containing_face "
  1031. "IS NULL AND node_id NOT IN "
  1032. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  1033. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  1034. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  1035. pg_info->toposchema_name, pg_info->toposchema_name,
  1036. pg_info->toposchema_name);
  1037. else
  1038. sprintf(stmt,
  1039. "SELECT node.node_id,geom FROM \"%s\".node AS node WHERE node_id NOT IN "
  1040. "(SELECT node_id FROM \"%s\".%s) AND containing_face IS NULL ORDER BY node_id",
  1041. pg_info->toposchema_name, pg_info->toposchema_name, TOPO_TABLE_NODE);
  1042. G_debug(2, "SQL: %s", stmt);
  1043. res = PQexec(pg_info->conn, stmt);
  1044. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1045. PQntuples(res) > plus->n_plines) {
  1046. G_warning(_("Inconsistency in topology: number of "
  1047. "points %d (should be %d)"),
  1048. PQntuples(res), plus->n_plines);
  1049. if (res)
  1050. PQclear(res);
  1051. return -1;
  1052. }
  1053. ntuples = PQntuples(res); /* plus->n_plines */
  1054. G_zero(&line_data, sizeof(struct edge_data));
  1055. for (i = 0; i < ntuples; i++) {
  1056. /* process standalone nodes (PostGIS Topo) */
  1057. line_data.id = atoi(PQgetvalue(res, i, 0));
  1058. line_data.wkb_geom = (char *) PQgetvalue(res, i, 1);
  1059. read_p_line(plus, i + 1, &line_data, &(pg_info->cache));
  1060. }
  1061. PQclear(res);
  1062. /* read PostGIS Topo edges
  1063. -> lines
  1064. -> boundaries
  1065. */
  1066. sprintf(stmt,
  1067. "SELECT edge_id,start_node,end_node,left_face,right_face,geom "
  1068. "FROM \"%s\".edge ORDER BY edge_id",
  1069. pg_info->toposchema_name);
  1070. G_debug(2, "SQL: %s", stmt);
  1071. res = PQexec(pg_info->conn, stmt);
  1072. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1073. PQntuples(res) > plus->n_lines) {
  1074. G_warning(_("Inconsistency in topology: number of "
  1075. "lines %d (should be %d)"),
  1076. PQntuples(res), plus->n_lines);
  1077. if (res)
  1078. PQclear(res);
  1079. return -1;
  1080. }
  1081. /* process edges (PostGIS Topo) */
  1082. ntuples = PQntuples(res);
  1083. for (i = 0; i < ntuples; i++) {
  1084. line_data.id = atoi(PQgetvalue(res, i, 0));
  1085. line_data.start_node = remap_node(offset, atoi(PQgetvalue(res, i, 1)));
  1086. line_data.end_node = remap_node(offset, atoi(PQgetvalue(res, i, 2)));
  1087. line_data.left_face = atoi(PQgetvalue(res, i, 3));
  1088. line_data.right_face = atoi(PQgetvalue(res, i, 4));
  1089. line_data.wkb_geom = (char *) PQgetvalue(res, i, 5);
  1090. id = plus->n_plines + i + 1; /* points already registered */
  1091. read_p_line(plus, id, &line_data, &(pg_info->cache));
  1092. /* TODO: update category index */
  1093. }
  1094. PQclear(res);
  1095. /* read PostGIS Topo standalone nodes (containing_face is not null)
  1096. -> centroids
  1097. */
  1098. if (pg_info->topo_geo_only)
  1099. sprintf(stmt,
  1100. "SELECT node_id,geom,containing_face FROM \"%s\".node WHERE containing_face "
  1101. "IS NOT NULL AND node_id NOT IN "
  1102. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  1103. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  1104. "\"%s\".edge GROUP BY end_node) AS foo) ORDER BY node_id",
  1105. pg_info->toposchema_name, pg_info->toposchema_name,
  1106. pg_info->toposchema_name);
  1107. else
  1108. sprintf(stmt,
  1109. "SELECT node.node_id,geom,containing_face FROM \"%s\".node AS node WHERE "
  1110. "node_id NOT IN (SELECT node_id FROM \"%s\".%s) AND containing_face "
  1111. "IS NOT NULL ORDER BY node_id",
  1112. pg_info->toposchema_name, pg_info->toposchema_name, TOPO_TABLE_NODE);
  1113. G_debug(2, "SQL: %s", stmt);
  1114. res = PQexec(pg_info->conn, stmt);
  1115. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1116. PQntuples(res) != plus->n_clines) {
  1117. G_warning(_("Inconsistency in topology: number of "
  1118. "centroids %d (should be %d)"),
  1119. PQntuples(res), plus->n_clines);
  1120. if (res)
  1121. PQclear(res);
  1122. return -1;
  1123. }
  1124. G_zero(&line_data, sizeof(struct edge_data));
  1125. id = plus->n_plines + plus->n_llines + plus->n_blines + 1;
  1126. for (i = 0; i < plus->n_clines; i++) {
  1127. line_data.id = atoi(PQgetvalue(res, i, 0));
  1128. line_data.wkb_geom = (char *)PQgetvalue(res, i, 1);
  1129. line_data.left_face = atoi(PQgetvalue(res, i, 2)); /* face id */
  1130. /* area id and face id can be different */
  1131. read_p_line(plus, id + i, &line_data, &(pg_info->cache));
  1132. }
  1133. PQclear(res);
  1134. plus->built = GV_BUILD_BASE;
  1135. /* build areas */
  1136. if (pg_info->topo_geo_only) {
  1137. /* build areas for boundaries
  1138. reset values -> build from scratch */
  1139. plus->n_areas = plus->n_isles = 0;
  1140. for (line = 1; line <= plus->n_lines; line++) {
  1141. Line = plus->Line[line]; /* centroids: Line is NULL */
  1142. if (!Line || Line->type != GV_BOUNDARY)
  1143. continue;
  1144. for (i = 0; i < 2; i++) { /* for both sides build an area/isle */
  1145. side = i == 0 ? GV_LEFT : GV_RIGHT;
  1146. G_debug(3, "Build area for line = %d, side = %d",
  1147. id, side);
  1148. Vect_build_line_area(Map, line, side);
  1149. }
  1150. }
  1151. }
  1152. else {
  1153. /* read areas from 'area_grass' table */
  1154. sprintf(stmt,
  1155. "SELECT area_id,lines,centroid,isles FROM \"%s\".%s ORDER BY area_id",
  1156. pg_info->toposchema_name, TOPO_TABLE_AREA);
  1157. G_debug(2, "SQL: %s", stmt);
  1158. res = PQexec(pg_info->conn, stmt);
  1159. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1160. plus->n_areas != PQntuples(res)) {
  1161. if (res)
  1162. PQclear(res);
  1163. return -1;
  1164. }
  1165. dig_alloc_areas(plus, plus->n_areas);
  1166. G_zero(plus->Area, sizeof(struct P_area *) * (plus->n_areas + 1)); /* index starts at 1 */
  1167. G_debug(3, "Vect_open_topo_pg(): n_areas=%d", plus->n_areas);
  1168. for (i = 0; i < plus->n_areas; i++) {
  1169. read_p_area(plus, i + 1, (char *)PQgetvalue(res, i, 1),
  1170. atoi(PQgetvalue(res, i, 2)), (char *)PQgetvalue(res, i, 3));
  1171. }
  1172. PQclear(res);
  1173. }
  1174. plus->built = GV_BUILD_AREAS;
  1175. /* attach isles */
  1176. if (pg_info->topo_geo_only) {
  1177. plus->n_isles = 0; /* reset isles */
  1178. G_warning(_("To be implemented: isles not attached in Topo-Geo-only mode"));
  1179. }
  1180. else {
  1181. /* read isles from 'isle_grass' table */
  1182. sprintf(stmt,
  1183. "SELECT isle_id,lines,area FROM \"%s\".%s ORDER BY isle_id",
  1184. pg_info->toposchema_name, TOPO_TABLE_ISLE);
  1185. G_debug(2, "SQL: %s", stmt);
  1186. res = PQexec(pg_info->conn, stmt);
  1187. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1188. plus->n_isles != PQntuples(res)) {
  1189. if (res)
  1190. PQclear(res);
  1191. return -1;
  1192. }
  1193. dig_alloc_isles(plus, plus->n_isles);
  1194. G_zero(plus->Isle, sizeof(struct P_isle *) * (plus->n_isles + 1)); /* index starts at 1 */
  1195. G_debug(3, "Vect_open_topo_pg(): n_isles=%d", plus->n_isles);
  1196. for (i = 0; i < plus->n_isles; i++) {
  1197. read_p_isle(plus, i + 1, (char *)PQgetvalue(res, i, 1),
  1198. atoi(PQgetvalue(res, i, 2)));
  1199. }
  1200. PQclear(res);
  1201. }
  1202. plus->built = GV_BUILD_ATTACH_ISLES;
  1203. /* attach centroids */
  1204. if (pg_info->topo_geo_only && plus->n_areas > 0) {
  1205. int area;
  1206. struct P_area *Area;
  1207. struct P_topo_c *topo;
  1208. for (line = 1; line <= plus->n_lines; line++) {
  1209. Line = plus->Line[line];
  1210. if (Line->type != GV_CENTROID)
  1211. continue;
  1212. Vect_read_line(Map, Points, NULL, line);
  1213. area = Vect_find_area(Map, Points->x[0], Points->y[0]);
  1214. topo = (struct P_topo_c *)Line->topo;
  1215. topo->area = area;
  1216. Area = plus->Area[topo->area];
  1217. Area->centroid = Line->offset;
  1218. }
  1219. }
  1220. plus->built = GV_BUILD_CENTROIDS;
  1221. /* done */
  1222. plus->built = GV_BUILD_ALL;
  1223. Vect_destroy_line_struct(Points);
  1224. Vect_destroy_list(List);
  1225. return 0;
  1226. }
  1227. /*
  1228. \brief PostgreSQL notice processor
  1229. Print out NOTICE message only on verbose level
  1230. */
  1231. void notice_processor(void *arg, const char *message)
  1232. {
  1233. if (G_verbose() > G_verbose_std()) {
  1234. fprintf(stderr, "%s", message);
  1235. }
  1236. }
  1237. /*!
  1238. \brief Scan string array
  1239. Creates tokens based on string array, eg. '{1, 2, 3}' become
  1240. [1,2,3].
  1241. Allocated tokes should be freed by G_free_tokens().
  1242. \param sArray string array
  1243. \return tokens
  1244. */
  1245. char **scan_array(const char *sarray)
  1246. {
  1247. char *buf, **tokens;
  1248. int i, len;
  1249. /* remove '{}' */
  1250. len = strlen(sarray) - 1; /* skip '}' */
  1251. buf = (char *)G_malloc(len);
  1252. for (i = 1; i < len; i++)
  1253. buf[i-1] = sarray[i];
  1254. buf[len-1] = '\0';
  1255. tokens = G_tokenize(buf, ",");
  1256. G_free(buf);
  1257. return tokens;
  1258. }
  1259. /*!
  1260. \brief Get node id from offset
  1261. \todo speed up
  1262. \param offset pointer to Format_info_offset struct
  1263. \param node node to find
  1264. \return node id
  1265. \return -1 not found
  1266. */
  1267. int remap_node(const struct Format_info_offset *offset, int node)
  1268. {
  1269. int i;
  1270. for (i = 0; i < offset->array_num; i++) {
  1271. if (offset->array[i] == node)
  1272. return i + 1; /* node id starts at 1 */
  1273. }
  1274. return -1;
  1275. }
  1276. /*!
  1277. \brief Get line id from offset
  1278. \todo speed up
  1279. \param plus pointer to Plus_head struct
  1280. \param line line to find
  1281. \return line id
  1282. \return -1 not found
  1283. */
  1284. int remap_line(const struct Plus_head* plus, int line)
  1285. {
  1286. int i;
  1287. struct P_line *Line;
  1288. for (i = 1; i <= plus->n_lines; i++) {
  1289. Line = plus->Line[i];
  1290. if (!Line)
  1291. continue;
  1292. if ((int) Line->offset == line)
  1293. return i;
  1294. }
  1295. return -1;
  1296. }
  1297. #endif