open_pg.c 51 KB

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