open_pg.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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-2012 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. #ifdef HAVE_POSTGRES
  16. #include "pg_local_proto.h"
  17. struct edge_data {
  18. int id;
  19. int start_node;
  20. int end_node;
  21. int left_face;
  22. int right_face;
  23. };
  24. static char *get_key_column(struct Format_info_pg *);
  25. static SF_FeatureType ftype_from_string(const char *);
  26. static int drop_table(struct Format_info_pg *);
  27. static int check_schema(const struct Format_info_pg *);
  28. static int create_table(struct Format_info_pg *, const struct field_info *);
  29. static void connect_db(struct Format_info_pg *);
  30. static int check_topo(struct Format_info_pg *, struct Plus_head *);
  31. static int parse_bbox(const char *, struct bound_box *);
  32. static int num_of_records(const struct Format_info_pg *, const char *);
  33. static int read_p_node(struct Plus_head *, int, int, struct Format_info_pg *);
  34. static int read_p_line(struct Plus_head *, int, const struct edge_data *);
  35. static int read_p_area(struct Plus_head *, int, int, struct Format_info_pg *);
  36. static int load_plus_head(struct Format_info_pg *, struct Plus_head *);
  37. static void notice_processor(void *, const char *);
  38. #endif
  39. /*!
  40. \brief Open vector map - PostGIS feature table (level 1 - without topology)
  41. \todo Check database instead of geometry_columns
  42. \param[in,out] Map pointer to Map_info structure
  43. \param update TRUE for write mode, otherwise read-only
  44. \return 0 success
  45. \return -1 error
  46. */
  47. int V1_open_old_pg(struct Map_info *Map, int update)
  48. {
  49. #ifdef HAVE_POSTGRES
  50. int found;
  51. char stmt[DB_SQL_MAX];
  52. PGresult *res;
  53. struct Format_info_pg *pg_info;
  54. G_debug(2, "V1_open_old_pg(): update = %d", update);
  55. pg_info = &(Map->fInfo.pg);
  56. if (!pg_info->conninfo) {
  57. G_warning(_("Connection string not defined"));
  58. return -1;
  59. }
  60. if (!pg_info->table_name) {
  61. G_warning(_("PostGIS feature table not defined"));
  62. return -1;
  63. }
  64. G_debug(1, "V1_open_old_pg(): conninfo='%s' table='%s'",
  65. pg_info->conninfo, pg_info->table_name);
  66. /* connect database */
  67. if (!pg_info->conn)
  68. connect_db(pg_info);
  69. /* get DB name */
  70. pg_info->db_name = G_store(PQdb(pg_info->conn));
  71. if (!pg_info->db_name) {
  72. G_warning(_("Unable to get database name"));
  73. return -1;
  74. }
  75. /* get fid and geometry column */
  76. sprintf(stmt, "SELECT f_geometry_column, coord_dimension, srid, type "
  77. "FROM geometry_columns WHERE f_table_schema = '%s' AND "
  78. "f_table_name = '%s'", pg_info->schema_name, pg_info->table_name);
  79. G_debug(2, "SQL: %s", stmt);
  80. res = PQexec(pg_info->conn, stmt);
  81. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  82. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  83. PQresultErrorMessage(res));
  84. found = PQntuples(res) > 0 ? TRUE : FALSE;
  85. if (found) {
  86. /* geometry column */
  87. pg_info->geom_column = G_store(PQgetvalue(res, 0, 0));
  88. G_debug(3, "\t-> table = %s column = %s", pg_info->table_name,
  89. pg_info->geom_column);
  90. /* fid column */
  91. pg_info->fid_column = get_key_column(pg_info);
  92. /* coordinates dimension */
  93. pg_info->coor_dim = atoi(PQgetvalue(res, 0, 1));
  94. /* SRS ID */
  95. pg_info->srid = atoi(PQgetvalue(res, 0, 2));
  96. /* feature type */
  97. pg_info->feature_type = ftype_from_string(PQgetvalue(res, 0, 3));
  98. }
  99. PQclear(res);
  100. /* no feature in cache */
  101. pg_info->cache.fid = -1;
  102. if (!found) {
  103. G_warning(_("Feature table <%s> not found in 'geometry_columns'"),
  104. pg_info->table_name);
  105. return -1;
  106. }
  107. /* check for topo schema */
  108. check_topo(pg_info, &(Map->plus));
  109. return 0;
  110. #else
  111. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  112. return -1;
  113. #endif
  114. }
  115. /*!
  116. \brief Open vector map - PostGIS feature table (level 2 - feature index)
  117. \param[in,out] Map pointer to Map_info structure
  118. \return 0 success
  119. \return -1 error
  120. */
  121. int V2_open_old_pg(struct Map_info *Map)
  122. {
  123. #ifdef HAVE_POSTGRES
  124. struct Format_info_pg *pg_info;
  125. G_debug(3, "V2_open_old_pg(): name = %s mapset = %s", Map->name,
  126. Map->mapset);
  127. pg_info = &(Map->fInfo.pg);
  128. if (pg_info->toposchema_name)
  129. /* no fidx file needed for PostGIS topology access */
  130. return 0;
  131. if (Vect_open_fidx(Map, &(pg_info->offset)) != 0) {
  132. G_warning(_("Unable to open feature index file for vector map <%s>"),
  133. Vect_get_full_name(Map));
  134. G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
  135. }
  136. return 0;
  137. #else
  138. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  139. return -1;
  140. #endif
  141. }
  142. /*!
  143. \brief Prepare PostGIS database for creating new feature table
  144. (level 1)
  145. \todo To implement
  146. \param[out] Map pointer to Map_info structure
  147. \param name name of PostGIS feature table to create
  148. \param with_z WITH_Z for 3D vector data otherwise WITHOUT_Z
  149. \return 0 success
  150. \return -1 error
  151. */
  152. int V1_open_new_pg(struct Map_info *Map, const char *name, int with_z)
  153. {
  154. #ifdef HAVE_POSTGRES
  155. char stmt[DB_SQL_MAX];
  156. struct Format_info_pg *pg_info;
  157. PGresult *res;
  158. G_debug(2, "V1_open_new_pg(): name = %s with_z = %d", name, with_z);
  159. pg_info = &(Map->fInfo.pg);
  160. if (!pg_info->conninfo) {
  161. G_warning(_("Connection string not defined"));
  162. return -1;
  163. }
  164. if (!pg_info->table_name) {
  165. G_warning(_("PostGIS feature table not defined"));
  166. return -1;
  167. }
  168. G_debug(1, "V1_open_new_pg(): conninfo='%s' table='%s'",
  169. pg_info->conninfo, pg_info->table_name);
  170. /* connect database */
  171. connect_db(pg_info);
  172. /* get DB name */
  173. pg_info->db_name = G_store(PQdb(pg_info->conn));
  174. if (!pg_info->db_name) {
  175. G_warning(_("Unable to get database name"));
  176. return -1;
  177. }
  178. /* if schema not defined, use 'public' */
  179. if (!pg_info->schema_name) {
  180. pg_info->schema_name = G_store("public");
  181. }
  182. /* if fid_column not defined, use 'ogc_fid' */
  183. if (!pg_info->fid_column) {
  184. pg_info->fid_column = G_store("ogc_fid");
  185. }
  186. /* if geom_column not defined, use 'wkb_geometry' */
  187. if (!pg_info->geom_column) {
  188. pg_info->geom_column = G_store("wkb_geometry");
  189. }
  190. /* check if feature table already exists */
  191. sprintf(stmt, "SELECT * FROM pg_tables "
  192. "WHERE schemaname = '%s' AND tablename = '%s'",
  193. pg_info->schema_name, pg_info->table_name);
  194. G_debug(2, "SQL: %s", stmt);
  195. res = PQexec(pg_info->conn, stmt);
  196. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  197. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  198. PQresultErrorMessage(res));
  199. if (PQntuples(res) > 0) {
  200. /* table found */
  201. if (G_get_overwrite()) {
  202. G_warning(_("PostGIS layer <%s.%s> already exists and will be overwritten"),
  203. pg_info->schema_name, pg_info->table_name);
  204. if (drop_table(pg_info) == -1) {
  205. G_warning(_("Unable to delete PostGIS layer <%s>"),
  206. pg_info->table_name);
  207. return -1;
  208. }
  209. }
  210. else {
  211. G_fatal_error(_("PostGIS layer <%s.%s> already exists in database '%s'"),
  212. pg_info->schema_name, pg_info->table_name,
  213. pg_info->db_name);
  214. return -1;
  215. }
  216. }
  217. /* no feature in cache */
  218. pg_info->cache.fid = -1;
  219. /* unknown feature type */
  220. pg_info->feature_type = SF_UNKNOWN;
  221. PQclear(res);
  222. return 0;
  223. #else
  224. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  225. return -1;
  226. #endif
  227. }
  228. /*!
  229. \brief Create new PostGIS layer in given database (level 2)
  230. V1_open_new_pg() is required to be called before this function.
  231. List of currently supported types:
  232. - GV_POINT (SF_POINT)
  233. - GV_LINE (SF_LINESTRING)
  234. - GV_BOUNDARY (SF_POLYGON)
  235. \param[in,out] Map pointer to Map_info structure
  236. \param type feature type (GV_POINT, GV_LINE, ...)
  237. \return 0 success
  238. \return -1 error
  239. */
  240. int V2_open_new_pg(struct Map_info *Map, int type)
  241. {
  242. #ifdef HAVE_POSTGRES
  243. int ndblinks;
  244. struct Format_info_pg *pg_info;
  245. struct field_info *Fi;
  246. struct Key_Value *projinfo, *projunits;
  247. Fi = NULL;
  248. pg_info = &(Map->fInfo.pg);
  249. if (!pg_info->conninfo) {
  250. G_warning(_("Connection string not defined"));
  251. return -1;
  252. }
  253. if (!pg_info->table_name) {
  254. G_warning(_("PostGIS feature table not defined"));
  255. return -1;
  256. }
  257. G_debug(1, "V2_open_new_pg(): conninfo='%s' table='%s' -> type = %d",
  258. pg_info->conninfo, pg_info->table_name, type);
  259. /* get spatial reference */
  260. projinfo = G_get_projinfo();
  261. projunits = G_get_projunits();
  262. pg_info->srid = 0; /* TODO */
  263. // Ogr_spatial_ref = GPJ_grass_to_osr(projinfo, projunits);
  264. G_free_key_value(projinfo);
  265. G_free_key_value(projunits);
  266. /* determine geometry type */
  267. switch (type) {
  268. case GV_POINT:
  269. pg_info->feature_type = SF_POINT;
  270. break;
  271. case GV_LINE:
  272. pg_info->feature_type = SF_LINESTRING;
  273. break;
  274. case GV_BOUNDARY:
  275. pg_info->feature_type = SF_POLYGON;
  276. break;
  277. default:
  278. G_warning(_("Unsupported geometry type (%d)"), type);
  279. return -1;
  280. }
  281. /* coordinate dimension */
  282. pg_info->coor_dim = Vect_is_3d(Map) ? 3 : 2;
  283. /* create new PostGIS table */
  284. ndblinks = Vect_get_num_dblinks(Map);
  285. if (ndblinks > 0) {
  286. Fi = Vect_get_dblink(Map, 0);
  287. if (Fi) {
  288. if (ndblinks > 1)
  289. G_warning(_("More layers defined, using driver <%s> and "
  290. "database <%s>"), Fi->driver, Fi->database);
  291. }
  292. else {
  293. G_warning(_("Database connection not defined. "
  294. "Unable to write attributes."));
  295. }
  296. }
  297. if (create_table(pg_info, Fi) == -1) {
  298. G_warning(_("Unable to create new PostGIS table"));
  299. return -1;
  300. }
  301. if (Fi)
  302. G_free(Fi);
  303. return 0;
  304. #else
  305. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  306. return -1;
  307. #endif
  308. }
  309. /*!
  310. \brief Read full-topology for PostGIS links
  311. Note: Only 2D topological primitives are currently supported
  312. \param[in,out] Map pointer to Map_info structure
  313. \param head_only TRUE to read only header
  314. \return 0 on success
  315. \return 1 topology layer does not exist
  316. \return -1 on error
  317. */
  318. int Vect_open_topo_pg(struct Map_info *Map, int head_only)
  319. {
  320. #ifdef HAVE_POSTGRES
  321. struct Plus_head *plus;
  322. struct Format_info_pg *pg_info;
  323. plus = &(Map->plus);
  324. pg_info = &(Map->fInfo.pg);
  325. /* check for topo schema */
  326. if (check_topo(pg_info, plus) != 0)
  327. return 1;
  328. /* free and init plus structure */
  329. dig_init_plus(plus);
  330. return load_plus(pg_info, plus, head_only);
  331. #else
  332. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  333. return -1;
  334. #endif
  335. }
  336. #ifdef HAVE_POSTGRES
  337. /*!
  338. \brief Get key column for feature table
  339. \param pg_info pointer to Format_info_pg
  340. \return string buffer with key column name
  341. \return NULL on missing key column
  342. */
  343. char *get_key_column(struct Format_info_pg *pg_info)
  344. {
  345. char *key_column;
  346. char stmt[DB_SQL_MAX];
  347. PGresult *res;
  348. sprintf(stmt,
  349. "SELECT kcu.column_name "
  350. "FROM INFORMATION_SCHEMA.TABLES t "
  351. "LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc "
  352. "ON tc.table_catalog = t.table_catalog "
  353. "AND tc.table_schema = t.table_schema "
  354. "AND tc.table_name = t.table_name "
  355. "AND tc.constraint_type = 'PRIMARY KEY' "
  356. "LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu "
  357. "ON kcu.table_catalog = tc.table_catalog "
  358. "AND kcu.table_schema = tc.table_schema "
  359. "AND kcu.table_name = tc.table_name "
  360. "AND kcu.constraint_name = tc.constraint_name "
  361. "WHERE t.table_schema = '%s' AND t.table_name = '%s'",
  362. pg_info->schema_name, pg_info->table_name);
  363. G_debug(2, "SQL: %s", stmt);
  364. res = PQexec(pg_info->conn, stmt);
  365. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  366. PQntuples(res) != 1 || strlen(PQgetvalue(res, 0, 0)) < 1) {
  367. G_warning(_("No key column detected."));
  368. if (res)
  369. PQclear(res);
  370. return NULL;
  371. }
  372. key_column = G_store(PQgetvalue(res, 0, 0));
  373. PQclear(res);
  374. return key_column;
  375. }
  376. /*!
  377. \brief Get simple feature type from string
  378. \param type string
  379. \return SF type
  380. */
  381. SF_FeatureType ftype_from_string(const char *type)
  382. {
  383. SF_FeatureType sf_type;
  384. if (G_strcasecmp(type, "POINT") == 0)
  385. return SF_POINT;
  386. else if (G_strcasecmp(type, "LINESTRING") == 0)
  387. return SF_LINESTRING;
  388. else if (G_strcasecmp(type, "POLYGON") == 0)
  389. return SF_POLYGON;
  390. else if (G_strcasecmp(type, "MULTIPOINT") == 0)
  391. return SF_MULTIPOINT;
  392. else if (G_strcasecmp(type, "MULTILINESTRING") == 0)
  393. return SF_MULTILINESTRING;
  394. else if (G_strcasecmp(type, "MULTIPOLYGON") == 0)
  395. return SF_MULTIPOLYGON;
  396. else if (G_strcasecmp(type, "GEOMETRYCOLLECTION") == 0)
  397. return SF_GEOMETRYCOLLECTION;
  398. else
  399. return SF_UNKNOWN;
  400. G_debug(3, "ftype_from_string(): type='%s' -> %d", type, sf_type);
  401. return sf_type;
  402. }
  403. /*!
  404. \brief Drop feature table
  405. \param pg_info pointer to Format_info_pg
  406. \return -1 on error
  407. \return 0 on success
  408. */
  409. int drop_table(struct Format_info_pg *pg_info)
  410. {
  411. char stmt[DB_SQL_MAX];
  412. sprintf(stmt, "DROP TABLE \"%s\".\"%s\"",
  413. pg_info->schema_name, pg_info->table_name);
  414. G_debug(2, "SQL: %s", stmt);
  415. if (execute(pg_info->conn, stmt) == -1) {
  416. return -1;
  417. }
  418. return 0;
  419. }
  420. /*!
  421. \brief Creates new schema for feature table if not exists
  422. \param pg_info pointer to Format_info_pg
  423. \return -1 on error
  424. \return 0 on success
  425. */
  426. int check_schema(const struct Format_info_pg *pg_info)
  427. {
  428. int i, found, nschema;
  429. char stmt[DB_SQL_MAX];
  430. PGresult *result;
  431. /* add geometry column */
  432. sprintf(stmt, "SELECT nspname FROM pg_namespace");
  433. G_debug(2, "SQL: %s", stmt);
  434. result = PQexec(pg_info->conn, stmt);
  435. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  436. PQclear(result);
  437. execute(pg_info->conn, "ROLLBACK");
  438. return -1;
  439. }
  440. found = FALSE;
  441. nschema = PQntuples(result);
  442. for (i = 0; i < nschema && !found; i++) {
  443. if (strcmp(pg_info->schema_name, PQgetvalue(result, i, 0)) == 0)
  444. found = TRUE;
  445. }
  446. PQclear(result);
  447. if (!found) {
  448. sprintf(stmt, "CREATE SCHEMA %s", pg_info->schema_name);
  449. if (execute(pg_info->conn, stmt) == -1) {
  450. execute(pg_info->conn, "ROLLBACK");
  451. return -1;
  452. }
  453. G_warning(_("Schema <%s> doesn't exist, created"),
  454. pg_info->schema_name);
  455. }
  456. return 0;
  457. }
  458. /*!
  459. \brief Create new feature table
  460. \param pg_info pointer to Format_info_pg
  461. \param Fi pointer to field_info
  462. \return -1 on error
  463. \return 0 on success
  464. */
  465. int create_table(struct Format_info_pg *pg_info, const struct field_info *Fi)
  466. {
  467. int spatial_index, primary_key;
  468. char stmt[DB_SQL_MAX], *geom_type;
  469. PGresult *result;
  470. /* by default create spatial index & add primary key */
  471. spatial_index = primary_key = TRUE;
  472. if (G_find_file2("", "PG", G_mapset())) {
  473. FILE *fp;
  474. const char *p;
  475. struct Key_Value *key_val;
  476. fp = G_fopen_old("", "PG", G_mapset());
  477. if (!fp) {
  478. G_fatal_error(_("Unable to open PG file"));
  479. }
  480. key_val = G_fread_key_value(fp);
  481. fclose(fp);
  482. /* disable spatial index ? */
  483. p = G_find_key_value("spatial_index", key_val);
  484. if (p && G_strcasecmp(p, "off") == 0)
  485. spatial_index = FALSE;
  486. /* disable primary key ? */
  487. p = G_find_key_value("primary_key", key_val);
  488. if (p && G_strcasecmp(p, "off") == 0)
  489. primary_key = FALSE;
  490. }
  491. /* create schema if not exists */
  492. if (G_strcasecmp(pg_info->schema_name, "public") != 0) {
  493. if (check_schema(pg_info) != 0)
  494. return -1;
  495. }
  496. /* prepare CREATE TABLE statement */
  497. sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s SERIAL",
  498. pg_info->schema_name, pg_info->table_name, pg_info->fid_column);
  499. if (Fi) {
  500. /* append attributes */
  501. int col, ncols, sqltype, length, ctype;
  502. char stmt_col[DB_SQL_MAX];
  503. const char *colname;
  504. dbString dbstmt;
  505. dbHandle handle;
  506. dbDriver *driver;
  507. dbCursor cursor;
  508. dbTable *table;
  509. dbColumn *column;
  510. db_init_string(&dbstmt);
  511. db_init_handle(&handle);
  512. pg_info->dbdriver = driver = db_start_driver(Fi->driver);
  513. if (!driver) {
  514. G_warning(_("Unable to start driver <%s>"), Fi->driver);
  515. return -1;
  516. }
  517. db_set_handle(&handle, Fi->database, NULL);
  518. if (db_open_database(driver, &handle) != DB_OK) {
  519. G_warning(_("Unable to open database <%s> by driver <%s>"),
  520. Fi->database, Fi->driver);
  521. db_close_database_shutdown_driver(driver);
  522. pg_info->dbdriver = NULL;
  523. return -1;
  524. }
  525. /* describe table */
  526. db_set_string(&dbstmt, "select * from ");
  527. db_append_string(&dbstmt, Fi->table);
  528. db_append_string(&dbstmt, " where 0 = 1");
  529. if (db_open_select_cursor(driver, &dbstmt,
  530. &cursor, DB_SEQUENTIAL) != DB_OK) {
  531. G_warning(_("Unable to open select cursor: '%s'"),
  532. db_get_string(&dbstmt));
  533. db_close_database_shutdown_driver(driver);
  534. pg_info->dbdriver = NULL;
  535. return -1;
  536. }
  537. table = db_get_cursor_table(&cursor);
  538. ncols = db_get_table_number_of_columns(table);
  539. G_debug(3,
  540. "copying attributes: driver = %s database = %s table = %s cols = %d",
  541. Fi->driver, Fi->database, Fi->table, ncols);
  542. for (col = 0; col < ncols; col++) {
  543. column = db_get_table_column(table, col);
  544. colname = db_get_column_name(column);
  545. sqltype = db_get_column_sqltype(column);
  546. ctype = db_sqltype_to_Ctype(sqltype);
  547. length = db_get_column_length(column);
  548. G_debug(3, "\tcolumn = %d name = %s type = %d length = %d",
  549. col, colname, sqltype, length);
  550. if (strcmp(pg_info->fid_column, colname) == 0) {
  551. /* skip fid column if exists */
  552. G_debug(3, "\t%s skipped", pg_info->fid_column);
  553. continue;
  554. }
  555. /* append column */
  556. sprintf(stmt_col, ",%s %s", colname, db_sqltype_name(sqltype));
  557. strcat(stmt, stmt_col);
  558. if (ctype == DB_C_TYPE_STRING) {
  559. /* length only for string columns */
  560. sprintf(stmt_col, "(%d)", length);
  561. strcat(stmt, stmt_col);
  562. }
  563. }
  564. db_free_string(&dbstmt);
  565. }
  566. strcat(stmt, ")"); /* close CREATE TABLE statement */
  567. /* begin transaction (create table) */
  568. if (execute(pg_info->conn, "BEGIN") == -1) {
  569. return -1;
  570. }
  571. /* create table */
  572. G_debug(2, "SQL: %s", stmt);
  573. if (execute(pg_info->conn, stmt) == -1) {
  574. execute(pg_info->conn, "ROLLBACK");
  575. return -1;
  576. }
  577. /* add primary key ? */
  578. if (primary_key) {
  579. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD PRIMARY KEY (%s)",
  580. pg_info->schema_name, pg_info->table_name,
  581. pg_info->fid_column);
  582. G_debug(2, "SQL: %s", stmt);
  583. if (execute(pg_info->conn, stmt) == -1) {
  584. execute(pg_info->conn, "ROLLBACK");
  585. return -1;
  586. }
  587. }
  588. /* determine geometry type (string) */
  589. switch (pg_info->feature_type) {
  590. case (SF_POINT):
  591. geom_type = "POINT";
  592. break;
  593. case (SF_LINESTRING):
  594. geom_type = "LINESTRING";
  595. break;
  596. case (SF_POLYGON):
  597. geom_type = "POLYGON";
  598. break;
  599. default:
  600. G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
  601. execute(pg_info->conn, "ROLLBACK");
  602. return -1;
  603. }
  604. /* add geometry column */
  605. sprintf(stmt, "SELECT AddGeometryColumn('%s', '%s', "
  606. "'%s', %d, '%s', %d)",
  607. pg_info->schema_name, pg_info->table_name,
  608. pg_info->geom_column, pg_info->srid,
  609. geom_type, pg_info->coor_dim);
  610. G_debug(2, "SQL: %s", stmt);
  611. result = PQexec(pg_info->conn, stmt);
  612. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  613. PQclear(result);
  614. execute(pg_info->conn, "ROLLBACK");
  615. return -1;
  616. }
  617. /* create index ? */
  618. if (spatial_index) {
  619. G_verbose_message(_("Building spatial index on <%s>..."),
  620. pg_info->geom_column);
  621. sprintf(stmt,
  622. "CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" USING GIST (%s)",
  623. pg_info->table_name, pg_info->geom_column,
  624. pg_info->schema_name, pg_info->table_name,
  625. pg_info->geom_column);
  626. G_debug(2, "SQL: %s", stmt);
  627. if (execute(pg_info->conn, stmt) == -1) {
  628. execute(pg_info->conn, "ROLLBACK");
  629. return -1;
  630. }
  631. }
  632. /* close transaction (create table) */
  633. if (execute(pg_info->conn, "COMMIT") == -1) {
  634. return -1;
  635. }
  636. return 0;
  637. }
  638. /*!
  639. \brief Establish PG connection (pg_info->conninfo)
  640. \param pg_info pointer to Format_info_pg
  641. */
  642. void connect_db(struct Format_info_pg *pg_info)
  643. {
  644. pg_info->conn = PQconnectdb(pg_info->conninfo);
  645. G_debug(2, " PQconnectdb(): %s", pg_info->conninfo);
  646. if (PQstatus(pg_info->conn) == CONNECTION_BAD)
  647. G_fatal_error("%s\n%s",
  648. _("Connection ton PostgreSQL database failed."),
  649. PQerrorMessage(pg_info->conn));
  650. /* print notice messages only on verbose level */
  651. PQsetNoticeProcessor(pg_info->conn, notice_processor, NULL);
  652. }
  653. /*!
  654. \brief Check for topology schema (pg_info->toposchema_name)
  655. \param pg_info pointer to Format_info_pg
  656. \return 0 schema exists
  657. \return 1 schema doesn't exists
  658. */
  659. int check_topo(struct Format_info_pg *pg_info, struct Plus_head *plus)
  660. {
  661. char stmt[DB_SQL_MAX];
  662. PGresult *res;
  663. /* connect database */
  664. if (!pg_info->conn)
  665. connect_db(pg_info);
  666. if (pg_info->toposchema_name)
  667. return 0;
  668. /* check if topology layer/schema exists */
  669. sprintf(stmt,
  670. "SELECT t.name,t.hasz,l.feature_column FROM topology.layer "
  671. "AS l JOIN topology.topology AS t ON l.topology_id = t.id "
  672. "WHERE schema_name = '%s' AND table_name = '%s'",
  673. pg_info->schema_name, pg_info->table_name);
  674. G_debug(2, "SQL: %s", stmt);
  675. res = PQexec(pg_info->conn, stmt);
  676. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  677. PQntuples(res) != 1) {
  678. G_debug(1, "Topology layers for '%s.%s' not found (%s)",
  679. pg_info->schema_name, pg_info->table_name,
  680. PQerrorMessage(pg_info->conn));
  681. if (res)
  682. PQclear(res);
  683. return 1;
  684. }
  685. pg_info->toposchema_name = G_store(PQgetvalue(res, 0, 0));
  686. pg_info->topogeom_column = G_store(PQgetvalue(res, 0, 2));
  687. G_debug(1, "PostGIS topology detected: schema = %s column = %s",
  688. pg_info->toposchema_name, pg_info->topogeom_column);
  689. /* check for 3D */
  690. if (strcmp(PQgetvalue(res, 0, 1), "t") == 0)
  691. plus->with_z = WITH_Z;
  692. PQclear(res);
  693. return 0;
  694. }
  695. /*!
  696. \brief Parse BBOX string
  697. \param value string buffer
  698. \param[out] bbox pointer to output bound_box struct
  699. \return 0 on success
  700. \return -1 on error
  701. */
  702. int parse_bbox(const char *value, struct bound_box *bbox)
  703. {
  704. unsigned int i;
  705. size_t length, prefix_length;
  706. char **tokens, **tokens_coord, *coord;
  707. prefix_length = strlen("box3d(");
  708. if (G_strncasecmp(value, "box3d(", prefix_length) != 0)
  709. return -1;
  710. /* strip off "bbox3d(...)" */
  711. length = strlen(value);
  712. coord = G_malloc(length - prefix_length);
  713. for (i = prefix_length; i < length; i++)
  714. coord[i-prefix_length] = value[i];
  715. coord[length-prefix_length-1] = '\0';
  716. tokens = G_tokenize(coord, ",");
  717. G_free(coord);
  718. if (G_number_of_tokens(tokens) != 2) {
  719. G_free_tokens(tokens);
  720. return -1;
  721. }
  722. /* parse bbox LL corner */
  723. tokens_coord = G_tokenize(tokens[0], " ");
  724. if (G_number_of_tokens(tokens_coord) != 3) {
  725. G_free_tokens(tokens);
  726. G_free_tokens(tokens_coord);
  727. }
  728. bbox->W = atof(tokens_coord[0]);
  729. bbox->S = atof(tokens_coord[1]);
  730. bbox->B = atof(tokens_coord[2]);
  731. G_free_tokens(tokens_coord);
  732. /* parse bbox UR corner */
  733. tokens_coord = G_tokenize(tokens[1], " ");
  734. if (G_number_of_tokens(tokens_coord) != 3) {
  735. G_free_tokens(tokens);
  736. G_free_tokens(tokens_coord);
  737. }
  738. bbox->E = atof(tokens_coord[0]);
  739. bbox->N = atof(tokens_coord[1]);
  740. bbox->T = atof(tokens_coord[2]);
  741. G_free_tokens(tokens_coord);
  742. G_free_tokens(tokens);
  743. return 0;
  744. }
  745. /*!
  746. \brief Get number of records for given SQL statement
  747. \param stmt string buffer with SQL statement
  748. \return number of returned records
  749. \return -1 on error
  750. */
  751. int num_of_records(const struct Format_info_pg *pg_info,
  752. const char *stmt)
  753. {
  754. int result;
  755. PGresult *res;
  756. G_debug(2, "SQL: %s", stmt);
  757. res = PQexec(pg_info->conn, stmt);
  758. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  759. PQntuples(res) != 1) {
  760. G_warning(_("Unable to get number of records for:\n%s"), stmt);
  761. if (res)
  762. PQclear(res);
  763. return -1;
  764. }
  765. result = atoi(PQgetvalue(res, 0, 0));
  766. PQclear(res);
  767. return result;
  768. }
  769. /*!
  770. \brief Read P_node structure
  771. See dig_Rd_P_node() for reference.
  772. \param plus pointer to Plus_head structure
  773. \param n index (starts at 1)
  774. \param id node id (table "node")
  775. \param pg_info pointer to Format_info_pg sttucture
  776. \return 0 on success
  777. \return -1 on failure
  778. */
  779. int read_p_node(struct Plus_head *plus, int n, int id,
  780. struct Format_info_pg *pg_info)
  781. {
  782. int i, cnt;
  783. char stmt[DB_SQL_MAX];
  784. struct P_node *node;
  785. PGresult *res;
  786. /* get lines connected to the node */
  787. sprintf(stmt,
  788. "SELECT edge_id,'s' as node,"
  789. "ST_Azimuth(ST_StartPoint(geom), ST_PointN(geom, 2)) AS angle"
  790. " FROM \"%s\".edge WHERE start_node = %d UNION ALL "
  791. "SELECT edge_id,'e' as node,"
  792. "ST_Azimuth(ST_EndPoint(geom), ST_PointN(geom, ST_NumPoints(geom) - 1)) AS angle"
  793. " FROM \"%s\".edge WHERE end_node = %d"
  794. " ORDER BY angle DESC",
  795. pg_info->toposchema_name, id,
  796. pg_info->toposchema_name, id);
  797. G_debug(2, "SQL: %s", stmt);
  798. res = PQexec(pg_info->conn, stmt);
  799. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  800. G_warning(_("Unable to read node %d"), id);
  801. if (res)
  802. PQclear(res);
  803. return -1;
  804. }
  805. cnt = PQntuples(res);
  806. if (cnt == 0) { /* dead ??? */
  807. plus->Node[n] = NULL;
  808. return 0;
  809. }
  810. node = dig_alloc_node();
  811. node->n_lines = cnt;
  812. G_debug(4, "read_p_node(): id = %d, n_lines = %d", id, cnt);
  813. if (dig_node_alloc_line(node, node->n_lines) == -1)
  814. return -1;
  815. /* lines / angles */
  816. for (i = 0; i < node->n_lines; i++) {
  817. node->lines[i] = atoi(PQgetvalue(res, i, 0));
  818. if (strcmp(PQgetvalue(res, i, 1), "s") != 0) {
  819. /* end node */
  820. node->lines[i] *= -1;
  821. }
  822. node->angles[i] = M_PI / 2 - atof(PQgetvalue(res, i, 2));
  823. /* angles range <-PI; PI> */
  824. if (node->angles[i] > M_PI)
  825. node->angles[i] = node->angles[i] - 2 * M_PI;
  826. if (node->angles[i] < -1.0 * M_PI)
  827. node->angles[i] = node->angles[i] + 2 * M_PI;
  828. G_debug(5, "\tline = %d angle = %f", node->lines[i],
  829. node->angles[i]);
  830. }
  831. PQclear(res);
  832. /* ???
  833. if (plus->with_z)
  834. if (0 >= dig__fread_port_P(&n_edges, 1, fp))
  835. */
  836. /* get node coordinates */
  837. sprintf(stmt,
  838. "SELECT ST_X(geom),ST_Y(geom),ST_Z(geom) FROM \"%s\".node "
  839. "WHERE node_id = %d",
  840. pg_info->toposchema_name, id);
  841. G_debug(2, "SQL: %s", stmt);
  842. res = PQexec(pg_info->conn, stmt);
  843. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  844. PQntuples(res) != 1) {
  845. G_warning(_("Unable to read node %d"), id);
  846. if (res)
  847. PQclear(res);
  848. return -1;
  849. }
  850. node->x = atof(PQgetvalue(res, 0, 0));
  851. node->y = atof(PQgetvalue(res, 0, 1));
  852. if (plus->with_z)
  853. node->z = atof(PQgetvalue(res, 0, 2));
  854. else
  855. node->z = 0;
  856. PQclear(res);
  857. plus->Node[n] = node;
  858. return 0;
  859. }
  860. /*!
  861. \brief Read P_line structure
  862. See dig_Rd_P_line() for reference.
  863. Supported feature types:
  864. - GV_POINT
  865. - GV_LINE
  866. - GV_BOUNDARY
  867. \param plus pointer to Plus_head structure
  868. \param n index (starts at 1)
  869. \param data edge data (id, start/end node, left/right face, ...)
  870. \param pg_info pointer to Format_info_pg sttucture
  871. \return 0 on success
  872. \return -1 on failure
  873. */
  874. int read_p_line(struct Plus_head *plus, int n,
  875. const struct edge_data *data)
  876. {
  877. int tp;
  878. struct P_line *line;
  879. if (data->start_node == 0 && data->end_node == 0) {
  880. if (data->left_face == 0)
  881. tp = GV_POINT;
  882. else
  883. tp = GV_CENTROID;
  884. }
  885. else if (data->left_face == 0 && data->right_face == 0) {
  886. tp = GV_LINE;
  887. }
  888. else {
  889. tp = GV_BOUNDARY;
  890. }
  891. if (tp == 0) { /* dead ??? */
  892. plus->Line[n] = NULL;
  893. return 0;
  894. }
  895. line = dig_alloc_line();
  896. /* type & offset ( = id) */
  897. line->type = tp;
  898. line->offset = data->id;
  899. G_debug(4, "read_p_line(): id/offset = %d type = %d", data->id, line->type);
  900. /* topo */
  901. if (line->type == GV_POINT) {
  902. line->topo = NULL;
  903. }
  904. else {
  905. line->topo = dig_alloc_topo(line->type);
  906. /* lines */
  907. if (line->type == GV_LINE) {
  908. struct P_topo_l *topo = (struct P_topo_l *)line->topo;
  909. topo->N1 = data->start_node;
  910. topo->N2 = data->end_node;
  911. }
  912. /* boundaries */
  913. else if (line->type == GV_BOUNDARY) {
  914. struct P_topo_b *topo = (struct P_topo_b *)line->topo;
  915. topo->N1 = data->start_node;
  916. topo->N2 = data->end_node;
  917. topo->left = data->left_face == 0 ? -1 : data->left_face;
  918. topo->right = data->right_face == 0 ? -1 : data->right_face;
  919. }
  920. /* centroids */
  921. else if (line->type == GV_CENTROID) {
  922. struct P_topo_c *topo = (struct P_topo_c *)line->topo;
  923. topo->area = data->left_face;
  924. }
  925. /* TODO: faces | kernels */
  926. }
  927. plus->Line[n] = line;
  928. return 0;
  929. }
  930. /*!
  931. \brief Read P_area structure
  932. See dig_Rd_P_area() for reference.
  933. \param plus pointer to Plus_head structure
  934. \param n index (starts at 1)
  935. \param face_id face id (see 'face' table)
  936. \param pg_info pointer to Format_info_pg sttucture
  937. \return 0 on success
  938. \return -1 on failure
  939. */
  940. int read_p_area(struct Plus_head *plus, int n, int face_id, struct Format_info_pg *pg_info)
  941. {
  942. int i, cnt;
  943. char stmt[DB_SQL_MAX];
  944. PGresult *res;
  945. struct P_area *area;
  946. sprintf(stmt,
  947. "SELECT edge from ST_GetFaceEdges('%s', %d)",
  948. pg_info->toposchema_name, face_id);
  949. G_debug(2, "SQL: %s", stmt);
  950. res = PQexec(pg_info->conn, stmt);
  951. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  952. G_warning(_("Unable to read face %d"), face_id);
  953. if (res)
  954. PQclear(res);
  955. return -1;
  956. }
  957. cnt = PQntuples(res);
  958. if (cnt == 0) { /* dead */
  959. plus->Area[n] = NULL;
  960. return 0;
  961. }
  962. area = dig_alloc_area();
  963. /* boundaries */
  964. area->n_lines = cnt;
  965. if (dig_area_alloc_line(area, area->n_lines) == -1)
  966. return -1;
  967. area->lines = (plus_t *)G_realloc(area->lines, sizeof(plus_t) * area->n_lines);
  968. for (i = 0; i < area->n_lines; i++) {
  969. /* GRASS Topo model: lines in clockwise order
  970. PosTGIS Topo model: lines in counter clockwise order */
  971. area->lines[i] = -1 * atoi(PQgetvalue(res, i, 0));
  972. }
  973. /* isles */
  974. /* TODO */
  975. /* centroid */
  976. area->centroid = plus->n_lines - plus->n_clines + i;
  977. plus->Area[n] = area;
  978. PQclear(res);
  979. return 0;
  980. }
  981. /*!
  982. \brief Read topo (from PostGIS topology schema) header info only
  983. \param[in,out] plus pointer to Plus_head struct
  984. \return 0 on success
  985. \return -1 on error
  986. */
  987. int load_plus_head(struct Format_info_pg *pg_info, struct Plus_head *plus)
  988. {
  989. char stmt[DB_SQL_MAX];
  990. PGresult *res;
  991. plus->off_t_size = -1;
  992. /* get map bounding box */
  993. sprintf(stmt,
  994. "SELECT ST_3DExtent(%s) FROM \"%s\".\"%s\"",
  995. pg_info->topogeom_column, pg_info->schema_name, pg_info->table_name);
  996. G_debug(2, "SQL: %s", stmt);
  997. res = PQexec(pg_info->conn, stmt);
  998. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  999. PQntuples(res) != 1) {
  1000. G_warning(_("Unable to get map bounding box from topology"));
  1001. if (res)
  1002. PQclear(res);
  1003. return -1;
  1004. }
  1005. if (parse_bbox(PQgetvalue(res, 0, 0), &(plus->box)) != 0) {
  1006. G_warning(_("Unable to parse map bounding box:\n%s"),
  1007. PQgetvalue(res, 0, 0));
  1008. return -1;
  1009. }
  1010. PQclear(res);
  1011. /* number of topological primitives */
  1012. /* nodes
  1013. note: isolated nodes are registered in GRASS Topology model */
  1014. sprintf(stmt,
  1015. "SELECT COUNT(DISTINCT node) FROM (SELECT start_node AS node "
  1016. "FROM \"%s\".edge GROUP BY start_node UNION ALL SELECT end_node "
  1017. "AS node FROM \"%s\".edge GROUP BY end_node) AS foo",
  1018. pg_info->toposchema_name, pg_info->toposchema_name);
  1019. plus->n_nodes = num_of_records(pg_info, stmt);
  1020. G_debug(3, "Vect_open_topo_pg(): n_nodes=%d", plus->n_nodes);
  1021. /* lines (edges in PostGIS Topology model) */
  1022. sprintf(stmt,
  1023. "SELECT COUNT(*) FROM \"%s\".edge",
  1024. pg_info->toposchema_name);
  1025. /* + isolated nodes as points
  1026. + centroids */
  1027. plus->n_lines = num_of_records(pg_info, stmt);
  1028. /* areas (faces in PostGIS Topology model) */
  1029. sprintf(stmt,
  1030. "SELECT COUNT(*) FROM \"%s\".face WHERE mbr IS NOT NULL",
  1031. pg_info->toposchema_name);
  1032. plus->n_areas = num_of_records(pg_info, stmt);
  1033. G_debug(3, "Vect_open_topo_pg(): n_areas=%d", plus->n_areas);
  1034. /* TODO: n_isles | n_volumes | n_holes */
  1035. /* number of features group by type */
  1036. /* points */
  1037. sprintf(stmt,
  1038. "SELECT COUNT(*) FROM \"%s\".node WHERE node_id NOT IN "
  1039. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  1040. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  1041. "\"%s\".edge GROUP BY end_node) AS foo)",
  1042. pg_info->toposchema_name, pg_info->toposchema_name,
  1043. pg_info->toposchema_name);
  1044. plus->n_plines = num_of_records(pg_info, stmt);
  1045. G_debug(3, "Vect_open_topo_pg(): n_plines=%d", plus->n_plines);
  1046. /* lines */
  1047. sprintf(stmt,
  1048. "SELECT COUNT(*) FROM \"%s\".edge WHERE "
  1049. "left_face = 0 AND right_face = 0",
  1050. pg_info->toposchema_name);
  1051. plus->n_llines = num_of_records(pg_info, stmt);
  1052. G_debug(3, "Vect_open_topo_pg(): n_llines=%d", plus->n_llines);
  1053. /* boundaries */
  1054. sprintf(stmt,
  1055. "SELECT COUNT(*) FROM \"%s\".edge WHERE "
  1056. "left_face != 0 OR right_face != 0",
  1057. pg_info->toposchema_name);
  1058. plus->n_blines = num_of_records(pg_info, stmt);
  1059. G_debug(3, "Vect_open_topo_pg(): n_blines=%d", plus->n_blines);
  1060. /* centroids */
  1061. sprintf(stmt,
  1062. "SELECT COUNT(*) FROM \"%s\".face WHERE mbr IS NOT NULL",
  1063. pg_info->toposchema_name);
  1064. plus->n_clines = num_of_records(pg_info, stmt);
  1065. G_debug(3, "Vect_open_topo_pg(): n_clines=%d", plus->n_clines);
  1066. /* TODO: nflines | n_klines */
  1067. /* lines - register isolated nodes as points and centroids */
  1068. plus->n_lines += plus->n_plines + plus->n_clines;
  1069. G_debug(3, "Vect_open_topo_pg(): n_lines=%d", plus->n_lines);
  1070. return 0;
  1071. }
  1072. /*!
  1073. \brief Read topo info (from PostGIS topology schema)
  1074. \param pg_info pointer to Format_info_pg
  1075. \param[in,out] plus pointer to Plus_head struct
  1076. \param head_only TRUE to read only header info
  1077. \return 0 on success
  1078. \return -1 on error
  1079. */
  1080. int load_plus(struct Format_info_pg *pg_info, struct Plus_head *plus,
  1081. int head_only)
  1082. {
  1083. int i, id, ntuples;
  1084. char stmt[DB_SQL_MAX];
  1085. struct edge_data line_data;
  1086. PGresult *res;
  1087. if (load_plus_head(pg_info, plus) != 0)
  1088. return -1;
  1089. if (head_only)
  1090. return 0;
  1091. /* read nodes (GRASS Topo)
  1092. note: standalone nodes are ignored
  1093. */
  1094. sprintf(stmt,
  1095. "SELECT node_id FROM \"%s\".node WHERE node_id IN "
  1096. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  1097. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  1098. "\"%s\".edge GROUP BY end_node) AS foo)",
  1099. pg_info->toposchema_name, pg_info->toposchema_name,
  1100. pg_info->toposchema_name);
  1101. G_debug(2, "SQL: %s", stmt);
  1102. res = PQexec(pg_info->conn, stmt);
  1103. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1104. PQntuples(res) != plus->n_nodes) {
  1105. G_warning(_("Unable to read nodes"));
  1106. if (res)
  1107. PQclear(res);
  1108. return -1;
  1109. }
  1110. G_debug(3, "load_plus(): n_nodes = %d", plus->n_nodes);
  1111. dig_alloc_nodes(plus, plus->n_nodes);
  1112. for (i = 1; i <= plus->n_nodes; i++) {
  1113. id = atoi(PQgetvalue(res, i - 1, 0));
  1114. read_p_node(plus, i, id, pg_info);
  1115. }
  1116. PQclear(res);
  1117. /* read lines (GRASS Topo)
  1118. - standalone nodes -> points
  1119. - edges -> lines/boundaries
  1120. */
  1121. G_debug(3, "load_plus(): n_lines = %d", plus->n_lines);
  1122. dig_alloc_lines(plus, plus->n_lines);
  1123. /* read PostGIS Topo standalone nodes */
  1124. sprintf(stmt,
  1125. "SELECT node_id FROM \"%s\".node WHERE node_id NOT IN "
  1126. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  1127. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  1128. "\"%s\".edge GROUP BY end_node) AS foo)",
  1129. pg_info->toposchema_name, pg_info->toposchema_name,
  1130. pg_info->toposchema_name);
  1131. G_debug(2, "SQL: %s", stmt);
  1132. res = PQexec(pg_info->conn, stmt);
  1133. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1134. PQntuples(res) > plus->n_plines) {
  1135. G_warning(_("Unable to read lines"));
  1136. if (res)
  1137. PQclear(res);
  1138. return -1;
  1139. }
  1140. ntuples = PQntuples(res); /* plus->n_plines */
  1141. G_zero(&line_data, sizeof(struct edge_data));
  1142. for (i = 0; i < ntuples; i++) {
  1143. /* process standalone nodes (PostGIS Topo) */
  1144. line_data.id = atoi(PQgetvalue(res, i, 0));
  1145. read_p_line(plus, i + 1, &line_data);
  1146. }
  1147. PQclear(res);
  1148. /* read PostGIS Topo edges */
  1149. sprintf(stmt,
  1150. "SELECT edge_id,start_node,end_node,left_face,right_face "
  1151. "FROM \"%s\".edge",
  1152. pg_info->toposchema_name);
  1153. G_debug(2, "SQL: %s", stmt);
  1154. res = PQexec(pg_info->conn, stmt);
  1155. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1156. PQntuples(res) > plus->n_lines) {
  1157. G_warning(_("Unable to read lines"));
  1158. if (res)
  1159. PQclear(res);
  1160. return -1;
  1161. }
  1162. ntuples = PQntuples(res);
  1163. for (i = 0; i < ntuples; i++) {
  1164. /* process edges (PostGIS Topo) */
  1165. line_data.id = atoi(PQgetvalue(res, i, 0));
  1166. line_data.start_node = atoi(PQgetvalue(res, i, 1));
  1167. line_data.end_node = atoi(PQgetvalue(res, i, 2));
  1168. line_data.left_face = atoi(PQgetvalue(res, i, 3));
  1169. line_data.right_face = atoi(PQgetvalue(res, i, 4));
  1170. read_p_line(plus, plus->n_plines + i + 1, &line_data);
  1171. }
  1172. PQclear(res);
  1173. /* read areas (GRASS Topo) */
  1174. sprintf(stmt,
  1175. "SELECT face_id from \"%s\".face WHERE mbr IS NOT NULL",
  1176. pg_info->toposchema_name);
  1177. G_debug(2, "SQL: %s", stmt);
  1178. res = PQexec(pg_info->conn, stmt);
  1179. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1180. PQntuples(res) != plus->n_areas) {
  1181. G_warning(_("Unable to read areas"));
  1182. if (res)
  1183. PQclear(res);
  1184. return -1;
  1185. }
  1186. G_debug(3, "load_plus(): n_areas = %d", plus->n_areas);
  1187. dig_alloc_areas(plus, plus->n_areas);
  1188. G_zero(&line_data, sizeof(struct edge_data));
  1189. for (i = 1; i <= plus->n_areas; i++) {
  1190. line_data.id = line_data.left_face = atoi(PQgetvalue(res, i - 1, 0));
  1191. read_p_area(plus, i, line_data.id, pg_info);
  1192. /* add centroids */
  1193. read_p_line(plus, plus->n_lines - plus->n_clines + i, &line_data);
  1194. }
  1195. PQclear(res);
  1196. /* read isle (GRASS Topo) */
  1197. return 0;
  1198. }
  1199. /*
  1200. \brief PostgreSQL notice processor
  1201. Print out NOTICE message only on verbose level
  1202. */
  1203. void notice_processor(void *arg, const char *message)
  1204. {
  1205. if (G_verbose() > G_verbose_std()) {
  1206. fprintf(stderr, "%s", message);
  1207. }
  1208. }
  1209. #endif