open_pg.c 55 KB

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