open_pg.c 52 KB

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