open_pg.c 54 KB

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