open_pg.c 51 KB

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