open_pg.c 56 KB

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