open_pg.c 54 KB

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