open_pg.c 54 KB

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