open_pg.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  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 int num_of_records(const struct Format_info_pg *, const char *);
  36. static struct P_node *read_p_node(struct Plus_head *, int, int,
  37. const char *, struct Format_info_pg *);
  38. static struct P_line *read_p_line(struct Plus_head *, int,
  39. const struct edge_data *,
  40. struct Format_info_cache *);
  41. static int load_plus_head(struct Format_info_pg *, struct Plus_head *);
  42. static void notice_processor(void *, const char *);
  43. static char *get_sftype(SF_FeatureType);
  44. #endif
  45. /*!
  46. \brief Open vector map - PostGIS feature table (level 1 - without topology)
  47. \todo Check database instead of geometry_columns
  48. \param[in,out] Map pointer to Map_info structure
  49. \param update TRUE for write mode, otherwise read-only
  50. \return 0 success
  51. \return -1 error
  52. */
  53. int V1_open_old_pg(struct Map_info *Map, int update)
  54. {
  55. #ifdef HAVE_POSTGRES
  56. int found;
  57. char stmt[DB_SQL_MAX];
  58. PGresult *res;
  59. struct Format_info_pg *pg_info;
  60. G_debug(2, "V1_open_old_pg(): update = %d", update);
  61. pg_info = &(Map->fInfo.pg);
  62. if (!pg_info->conninfo) {
  63. G_warning(_("Connection string not defined"));
  64. return -1;
  65. }
  66. if (!pg_info->table_name) {
  67. G_warning(_("PostGIS feature table not defined"));
  68. return -1;
  69. }
  70. G_debug(1, "V1_open_old_pg(): conninfo='%s' table='%s'",
  71. pg_info->conninfo, pg_info->table_name);
  72. /* connect database */
  73. if (!pg_info->conn)
  74. connect_db(pg_info);
  75. /* get DB name */
  76. pg_info->db_name = G_store(PQdb(pg_info->conn));
  77. if (!pg_info->db_name) {
  78. G_warning(_("Unable to get database name"));
  79. return -1;
  80. }
  81. /* get fid and geometry column */
  82. sprintf(stmt, "SELECT f_geometry_column, coord_dimension, srid, type "
  83. "FROM geometry_columns WHERE f_table_schema = '%s' AND "
  84. "f_table_name = '%s'", pg_info->schema_name, pg_info->table_name);
  85. G_debug(2, "SQL: %s", stmt);
  86. res = PQexec(pg_info->conn, stmt);
  87. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  88. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  89. PQresultErrorMessage(res));
  90. found = PQntuples(res) > 0 ? TRUE : FALSE;
  91. if (found) {
  92. /* geometry column */
  93. pg_info->geom_column = G_store(PQgetvalue(res, 0, 0));
  94. G_debug(3, "\t-> table = %s column = %s", pg_info->table_name,
  95. pg_info->geom_column);
  96. /* fid column */
  97. pg_info->fid_column = get_key_column(pg_info);
  98. /* coordinates dimension */
  99. pg_info->coor_dim = atoi(PQgetvalue(res, 0, 1));
  100. /* SRS ID */
  101. pg_info->srid = atoi(PQgetvalue(res, 0, 2));
  102. /* feature type */
  103. pg_info->feature_type = ftype_from_string(PQgetvalue(res, 0, 3));
  104. }
  105. PQclear(res);
  106. /* no feature in cache */
  107. pg_info->cache.fid = -1;
  108. if (!found) {
  109. G_warning(_("Feature table <%s> not found in 'geometry_columns'"),
  110. pg_info->table_name);
  111. return -1;
  112. }
  113. /* check for topo schema */
  114. check_topo(pg_info, &(Map->plus));
  115. return 0;
  116. #else
  117. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  118. return -1;
  119. #endif
  120. }
  121. /*!
  122. \brief Open vector map - PostGIS feature table (level 2 - feature index)
  123. \param[in,out] Map pointer to Map_info structure
  124. \return 0 success
  125. \return -1 error
  126. */
  127. int V2_open_old_pg(struct Map_info *Map)
  128. {
  129. #ifdef HAVE_POSTGRES
  130. struct Format_info_pg *pg_info;
  131. PGresult *res;
  132. G_debug(3, "V2_open_old_pg(): name = %s mapset = %s", Map->name,
  133. Map->mapset);
  134. pg_info = &(Map->fInfo.pg);
  135. if (pg_info->toposchema_name) {
  136. char stmt[DB_SQL_MAX];
  137. /* get topo schema id */
  138. sprintf(stmt, "SELECT id FROM topology.topology WHERE name = '%s'",
  139. pg_info->toposchema_name);
  140. res = PQexec(pg_info->conn, stmt);
  141. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  142. G_warning("%s\n%s", _("Topology schema not found."),
  143. PQresultErrorMessage(res));
  144. if (res)
  145. PQclear(res);
  146. return -1;
  147. }
  148. pg_info->toposchema_id = atoi(PQgetvalue(res, 0, 0));
  149. PQclear(res);
  150. }
  151. else {
  152. /* fidx file needed only for simple features access */
  153. if (Vect_open_fidx(Map, &(pg_info->offset)) != 0) {
  154. G_warning(_("Unable to open feature index file for vector map <%s>"),
  155. Vect_get_full_name(Map));
  156. G_zero(&(pg_info->offset), sizeof(struct Format_info_offset));
  157. }
  158. }
  159. return 0;
  160. #else
  161. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  162. return -1;
  163. #endif
  164. }
  165. /*!
  166. \brief Prepare PostGIS database for creating new feature table
  167. (level 1)
  168. \todo To implement
  169. \param[out] Map pointer to Map_info structure
  170. \param name name of PostGIS feature table to create
  171. \param with_z WITH_Z for 3D vector data otherwise WITHOUT_Z
  172. \return 0 success
  173. \return -1 error
  174. */
  175. int V1_open_new_pg(struct Map_info *Map, const char *name, int with_z)
  176. {
  177. #ifdef HAVE_POSTGRES
  178. char stmt[DB_SQL_MAX];
  179. struct Format_info_pg *pg_info;
  180. PGresult *res;
  181. G_debug(2, "V1_open_new_pg(): name = %s with_z = %d", name, with_z);
  182. pg_info = &(Map->fInfo.pg);
  183. if (!pg_info->conninfo) {
  184. G_warning(_("Connection string not defined"));
  185. return -1;
  186. }
  187. if (!pg_info->table_name) {
  188. G_warning(_("PostGIS feature table not defined"));
  189. return -1;
  190. }
  191. G_debug(1, "V1_open_new_pg(): conninfo='%s' table='%s'",
  192. pg_info->conninfo, pg_info->table_name);
  193. /* connect database */
  194. connect_db(pg_info);
  195. /* get DB name */
  196. pg_info->db_name = G_store(PQdb(pg_info->conn));
  197. if (!pg_info->db_name) {
  198. G_warning(_("Unable to get database name"));
  199. return -1;
  200. }
  201. /* if schema not defined, use 'public' */
  202. if (!pg_info->schema_name)
  203. pg_info->schema_name = G_store("public");
  204. /* if fid_column not defined, use 'fid' */
  205. if (!pg_info->fid_column)
  206. pg_info->fid_column = G_store(FID_COLUMN);
  207. /* if geom_column not defined, use 'geom' */
  208. if (!pg_info->geom_column)
  209. pg_info->geom_column = G_store(GEOMETRY_COLUMN);
  210. /* check if feature table already exists */
  211. sprintf(stmt, "SELECT * FROM pg_tables "
  212. "WHERE schemaname = '%s' AND tablename = '%s'",
  213. pg_info->schema_name, pg_info->table_name);
  214. G_debug(2, "SQL: %s", stmt);
  215. res = PQexec(pg_info->conn, stmt);
  216. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  217. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  218. PQresultErrorMessage(res));
  219. if (PQntuples(res) > 0) {
  220. /* table found */
  221. if (G_get_overwrite()) {
  222. G_warning(_("PostGIS layer <%s.%s> already exists and will be overwritten"),
  223. pg_info->schema_name, pg_info->table_name);
  224. if (drop_table(pg_info) == -1) {
  225. G_warning(_("Unable to delete PostGIS layer <%s>"),
  226. pg_info->table_name);
  227. return -1;
  228. }
  229. }
  230. else {
  231. G_warning(_("PostGIS layer <%s.%s> already exists in database '%s'"),
  232. pg_info->schema_name, pg_info->table_name,
  233. pg_info->db_name);
  234. return -1;
  235. }
  236. }
  237. /* no feature in cache */
  238. pg_info->cache.fid = -1;
  239. /* unknown feature type */
  240. pg_info->feature_type = SF_UNKNOWN;
  241. PQclear(res);
  242. return 0;
  243. #else
  244. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  245. return -1;
  246. #endif
  247. }
  248. /*!
  249. \brief Create new PostGIS layer in given database (level 2)
  250. V1_open_new_pg() is required to be called before this function.
  251. List of currently supported types:
  252. - GV_POINT (SF_POINT)
  253. - GV_LINE (SF_LINESTRING)
  254. - GV_BOUNDARY (SF_POLYGON)
  255. \param[in,out] Map pointer to Map_info structure
  256. \param type feature type (GV_POINT, GV_LINE, ...)
  257. \return 0 success
  258. \return -1 error
  259. */
  260. int V2_open_new_pg(struct Map_info *Map, int type)
  261. {
  262. #ifdef HAVE_POSTGRES
  263. int ndblinks;
  264. struct Format_info_pg *pg_info;
  265. struct field_info *Fi;
  266. struct Key_Value *projinfo, *projunits;
  267. Fi = NULL;
  268. pg_info = &(Map->fInfo.pg);
  269. if (!pg_info->conninfo) {
  270. G_warning(_("Connection string not defined"));
  271. return -1;
  272. }
  273. if (!pg_info->table_name) {
  274. G_warning(_("PostGIS feature table not defined"));
  275. return -1;
  276. }
  277. G_debug(1, "V2_open_new_pg(): conninfo='%s' table='%s' -> type = %d",
  278. pg_info->conninfo, pg_info->table_name, type);
  279. /* get spatial reference */
  280. projinfo = G_get_projinfo();
  281. projunits = G_get_projunits();
  282. pg_info->srid = 0; /* TODO */
  283. // Ogr_spatial_ref = GPJ_grass_to_osr(projinfo, projunits);
  284. G_free_key_value(projinfo);
  285. G_free_key_value(projunits);
  286. /* determine geometry type */
  287. switch (type) {
  288. case GV_POINT:
  289. pg_info->feature_type = SF_POINT;
  290. break;
  291. case GV_LINE:
  292. pg_info->feature_type = SF_LINESTRING;
  293. break;
  294. case GV_BOUNDARY:
  295. pg_info->feature_type = SF_POLYGON;
  296. break;
  297. default:
  298. G_warning(_("Unsupported geometry type (%d)"), type);
  299. return -1;
  300. }
  301. /* coordinate dimension */
  302. pg_info->coor_dim = Vect_is_3d(Map) ? 3 : 2;
  303. /* create new PostGIS table */
  304. ndblinks = Vect_get_num_dblinks(Map);
  305. if (ndblinks > 0) {
  306. Fi = Vect_get_dblink(Map, 0);
  307. if (Fi) {
  308. if (ndblinks > 1)
  309. G_warning(_("More layers defined, using driver <%s> and "
  310. "database <%s>"), Fi->driver, Fi->database);
  311. }
  312. else {
  313. G_warning(_("Database connection not defined. "
  314. "Unable to write attributes."));
  315. }
  316. }
  317. /* create new feature table */
  318. if (create_table(pg_info, Fi) == -1) {
  319. G_warning(_("Unable to create new PostGIS feature table"));
  320. return -1;
  321. }
  322. /* create new topology schema (if PostGIS topology support is enabled) */
  323. if(pg_info->toposchema_name) {
  324. if (create_topo_schema(pg_info, Vect_is_3d(Map)) == -1) {
  325. G_warning(_("Unable to create new PostGIS topology schema"));
  326. return -1;
  327. }
  328. }
  329. if (Fi)
  330. G_free(Fi);
  331. return 0;
  332. #else
  333. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  334. return -1;
  335. #endif
  336. }
  337. /*!
  338. \brief Read full-topology for PostGIS links
  339. Note: Only 2D topological primitives are currently supported
  340. \param[in,out] Map pointer to Map_info structure
  341. \param head_only TRUE to read only header
  342. \return 0 on success
  343. \return 1 topology layer does not exist
  344. \return -1 on error
  345. */
  346. int Vect_open_topo_pg(struct Map_info *Map, int head_only)
  347. {
  348. #ifdef HAVE_POSTGRES
  349. struct Plus_head *plus;
  350. struct Format_info_pg *pg_info;
  351. Map->open = VECT_OPEN_CODE; /* needed by load_plus */
  352. plus = &(Map->plus);
  353. pg_info = &(Map->fInfo.pg);
  354. /* check for topo schema */
  355. if (check_topo(pg_info, plus) != 0)
  356. return 1;
  357. /* free and init plus structure */
  358. dig_init_plus(plus);
  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 Get number of records for given SQL statement
  902. \param stmt string buffer with SQL statement
  903. \return number of returned records
  904. \return -1 on error
  905. */
  906. int num_of_records(const struct Format_info_pg *pg_info,
  907. const char *stmt)
  908. {
  909. int result;
  910. PGresult *res;
  911. G_debug(2, "SQL: %s", stmt);
  912. res = PQexec(pg_info->conn, stmt);
  913. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  914. PQntuples(res) != 1) {
  915. G_warning(_("Unable to get number of records for:\n%s"), stmt);
  916. if (res)
  917. PQclear(res);
  918. return -1;
  919. }
  920. result = atoi(PQgetvalue(res, 0, 0));
  921. PQclear(res);
  922. return result;
  923. }
  924. /*!
  925. \brief Read P_node structure
  926. See dig_Rd_P_node() for reference.
  927. \param plus pointer to Plus_head structure
  928. \param n index (starts at 1)
  929. \param id node id (table "node")
  930. \param wkb_data geometry data (wkb)
  931. \param pg_info pointer to Format_info_pg sttucture
  932. \return pointer to new P_node struct
  933. \return NULL on error
  934. */
  935. struct P_node *read_p_node(struct Plus_head *plus, int n,
  936. int id, const char *wkb_data,
  937. struct Format_info_pg *pg_info)
  938. {
  939. int i, cnt;
  940. char stmt[DB_SQL_MAX];
  941. struct P_node *node;
  942. struct line_pnts *points;
  943. PGresult *res;
  944. /* get lines connected to the node */
  945. sprintf(stmt,
  946. "SELECT edge_id,'s' as node,"
  947. "ST_Azimuth(ST_StartPoint(geom), ST_PointN(geom, 2)) AS angle"
  948. " FROM \"%s\".edge WHERE start_node = %d UNION ALL "
  949. "SELECT edge_id,'e' as node,"
  950. "ST_Azimuth(ST_EndPoint(geom), ST_PointN(geom, ST_NumPoints(geom) - 1)) AS angle"
  951. " FROM \"%s\".edge WHERE end_node = %d"
  952. " ORDER BY angle DESC",
  953. pg_info->toposchema_name, id,
  954. pg_info->toposchema_name, id);
  955. G_debug(2, "SQL: %s", stmt);
  956. res = PQexec(pg_info->conn, stmt);
  957. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  958. G_warning(_("Unable to read node %d"), id);
  959. if (res)
  960. PQclear(res);
  961. return NULL;
  962. }
  963. cnt = PQntuples(res);
  964. if (cnt == 0) { /* dead ??? */
  965. plus->Node[n] = NULL;
  966. return NULL;
  967. }
  968. node = dig_alloc_node();
  969. node->n_lines = cnt;
  970. G_debug(4, "read_p_node(): id = %d, n_lines = %d", id, cnt);
  971. if (dig_node_alloc_line(node, node->n_lines) == -1)
  972. return NULL;
  973. /* lines / angles */
  974. for (i = 0; i < node->n_lines; i++) {
  975. node->lines[i] = atoi(PQgetvalue(res, i, 0));
  976. if (strcmp(PQgetvalue(res, i, 1), "s") != 0) {
  977. /* end node */
  978. node->lines[i] *= -1;
  979. }
  980. node->angles[i] = M_PI / 2 - atof(PQgetvalue(res, i, 2));
  981. /* angles range <-PI; PI> */
  982. if (node->angles[i] > M_PI)
  983. node->angles[i] = node->angles[i] - 2 * M_PI;
  984. if (node->angles[i] < -1.0 * M_PI)
  985. node->angles[i] = node->angles[i] + 2 * M_PI;
  986. G_debug(5, "\tline = %d angle = %f", node->lines[i],
  987. node->angles[i]);
  988. }
  989. PQclear(res);
  990. /* get node coordinates */
  991. if (SF_POINT != Vect__cache_feature_pg(wkb_data, FALSE, FALSE,
  992. &(pg_info->cache), NULL))
  993. G_warning(_("Node %d: unexpected feature type %d"),
  994. n, pg_info->cache.sf_type);
  995. points = pg_info->cache.lines[0];
  996. node->x = points->x[0];
  997. node->y = points->y[0];
  998. if (plus->with_z)
  999. node->z = points->z[0];
  1000. else
  1001. node->z = 0.0;
  1002. /* update spatial index */
  1003. dig_spidx_add_node(plus, n, node->x, node->y, node->z);
  1004. plus->Node[n] = node;
  1005. return node;
  1006. }
  1007. /*!
  1008. \brief Read P_line structure
  1009. See dig_Rd_P_line() for reference.
  1010. Supported feature types:
  1011. - GV_POINT
  1012. - GV_LINE
  1013. - GV_BOUNDARY
  1014. \param plus pointer to Plus_head structure
  1015. \param n index (starts at 1)
  1016. \param data edge data (id, start/end node, left/right face, ...)
  1017. \param pg_info pointer to Format_info_pg sttucture
  1018. \return pointer to P_line struct
  1019. \return NULL on error
  1020. */
  1021. struct P_line *read_p_line(struct Plus_head *plus, int n,
  1022. const struct edge_data *data,
  1023. struct Format_info_cache *cache)
  1024. {
  1025. int tp, itype;
  1026. struct P_line *line;
  1027. struct line_pnts *points;
  1028. struct bound_box box;
  1029. if (data->start_node == 0 && data->end_node == 0) {
  1030. if (data->left_face == 0)
  1031. tp = GV_POINT;
  1032. else
  1033. tp = GV_CENTROID;
  1034. }
  1035. else if (data->left_face == 0 && data->right_face == 0) {
  1036. tp = GV_LINE;
  1037. }
  1038. else {
  1039. tp = GV_BOUNDARY;
  1040. }
  1041. if (tp == 0) { /* dead ??? */
  1042. plus->Line[n] = NULL;
  1043. return NULL;
  1044. }
  1045. line = dig_alloc_line();
  1046. /* type & offset ( = id) */
  1047. line->type = tp;
  1048. line->offset = data->id;
  1049. G_debug(4, "read_p_line(): id/offset = %d type = %d", data->id, line->type);
  1050. /* topo */
  1051. if (line->type == GV_POINT) {
  1052. line->topo = NULL;
  1053. }
  1054. else {
  1055. line->topo = dig_alloc_topo(line->type);
  1056. /* lines */
  1057. if (line->type == GV_LINE) {
  1058. struct P_topo_l *topo = (struct P_topo_l *)line->topo;
  1059. topo->N1 = data->start_node;
  1060. topo->N2 = data->end_node;
  1061. }
  1062. /* boundaries */
  1063. else if (line->type == GV_BOUNDARY) {
  1064. struct P_topo_b *topo = (struct P_topo_b *)line->topo;
  1065. topo->N1 = data->start_node;
  1066. topo->N2 = data->end_node;
  1067. /* skip left/right area - will be detected when building
  1068. areas/isles */
  1069. topo->left = topo->right = 0;
  1070. }
  1071. /* centroids */
  1072. else if (line->type == GV_CENTROID) {
  1073. struct P_topo_c *topo = (struct P_topo_c *)line->topo;
  1074. topo->area = data->left_face;
  1075. }
  1076. /* TODO: faces | kernels */
  1077. }
  1078. /* update spatial index */
  1079. Vect__cache_feature_pg(data->wkb_geom, FALSE, FALSE, cache, NULL);
  1080. itype = cache->lines_types[0];
  1081. if ((line->type & GV_POINTS && itype != GV_POINT) ||
  1082. (line->type & GV_LINES && itype != GV_LINE))
  1083. G_warning(_("Line %d: unexpected feature type"), n);
  1084. points = cache->lines[0];
  1085. dig_line_box(points, &box);
  1086. dig_spidx_add_line(plus, n, &box);
  1087. plus->Line[n] = line;
  1088. return line;
  1089. }
  1090. /*!
  1091. \brief Read topo (from PostGIS topology schema) header info only
  1092. \param[in,out] plus pointer to Plus_head struct
  1093. \return 0 on success
  1094. \return -1 on error
  1095. */
  1096. int load_plus_head(struct Format_info_pg *pg_info, struct Plus_head *plus)
  1097. {
  1098. char stmt[DB_SQL_MAX];
  1099. PGresult *res;
  1100. plus->off_t_size = -1;
  1101. /* get map bounding box */
  1102. sprintf(stmt,
  1103. "SELECT ST_3DExtent(%s) FROM \"%s\".\"%s\"",
  1104. pg_info->topogeom_column, pg_info->schema_name, pg_info->table_name);
  1105. G_debug(2, "SQL: %s", stmt);
  1106. res = PQexec(pg_info->conn, stmt);
  1107. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1108. PQntuples(res) != 1) {
  1109. G_warning(_("Unable to get map bounding box from topology"));
  1110. if (res)
  1111. PQclear(res);
  1112. return -1;
  1113. }
  1114. if (parse_bbox(PQgetvalue(res, 0, 0), &(plus->box)) != 0) {
  1115. G_warning(_("Unable to parse map bounding box:\n%s"),
  1116. PQgetvalue(res, 0, 0));
  1117. return -1;
  1118. }
  1119. PQclear(res);
  1120. /* number of topological primitives */
  1121. /* nodes
  1122. note: isolated nodes are registered in GRASS Topology model */
  1123. sprintf(stmt,
  1124. "SELECT COUNT(DISTINCT node) FROM (SELECT start_node AS node "
  1125. "FROM \"%s\".edge GROUP BY start_node UNION ALL SELECT end_node "
  1126. "AS node FROM \"%s\".edge GROUP BY end_node) AS foo",
  1127. pg_info->toposchema_name, pg_info->toposchema_name);
  1128. plus->n_nodes = num_of_records(pg_info, stmt);
  1129. G_debug(3, "Vect_open_topo_pg(): n_nodes=%d", plus->n_nodes);
  1130. /* lines (edges in PostGIS Topology model) */
  1131. sprintf(stmt,
  1132. "SELECT COUNT(*) FROM \"%s\".edge",
  1133. pg_info->toposchema_name);
  1134. /* + isolated nodes as points
  1135. + centroids */
  1136. plus->n_lines = num_of_records(pg_info, stmt);
  1137. /* areas (faces in PostGIS Topology model)
  1138. sprintf(stmt,
  1139. "SELECT COUNT(*) FROM \"%s\".face WHERE mbr IS NOT NULL",
  1140. pg_info->toposchema_name);
  1141. plus->n_areas = num_of_records(pg_info, stmt);
  1142. G_debug(3, "Vect_open_topo_pg(): n_areas=%d", plus->n_areas);
  1143. */
  1144. /* TODO: n_isles | n_volumes | n_holes */
  1145. /* number of features group by type */
  1146. /* points */
  1147. sprintf(stmt,
  1148. "SELECT COUNT(*) FROM \"%s\".node WHERE 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 = num_of_records(pg_info, 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 = num_of_records(pg_info, 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 = num_of_records(pg_info, 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\".face WHERE mbr IS NOT NULL",
  1173. pg_info->toposchema_name);
  1174. plus->n_clines = num_of_records(pg_info, stmt);
  1175. G_debug(3, "Vect_open_topo_pg(): n_clines=%d", plus->n_clines);
  1176. /* TODO: nflines | n_klines */
  1177. /* lines - register isolated nodes as points and centroids */
  1178. plus->n_lines += plus->n_plines + plus->n_clines;
  1179. G_debug(3, "Vect_open_topo_pg(): n_lines=%d", plus->n_lines);
  1180. return 0;
  1181. }
  1182. /*!
  1183. \brief Read topo info (from PostGIS topology schema)
  1184. \param pg_info pointer to Format_info_pg
  1185. \param[in,out] plus pointer to Plus_head struct
  1186. \param head_only TRUE to read only header info
  1187. \return 0 on success
  1188. \return -1 on error
  1189. */
  1190. int Vect__load_plus_pg(struct Map_info *Map, int head_only)
  1191. {
  1192. int i, id, ntuples;
  1193. char stmt[DB_SQL_MAX];
  1194. struct edge_data line_data;
  1195. struct Format_info_pg *pg_info;
  1196. struct Plus_head *plus;
  1197. struct P_line *line;
  1198. struct P_area *area;
  1199. PGresult *res;
  1200. pg_info = &(Map->fInfo.pg);
  1201. plus = &(Map->plus);
  1202. if (load_plus_head(pg_info, plus) != 0)
  1203. return -1;
  1204. if (head_only)
  1205. return 0;
  1206. /* read nodes (GRASS Topo)
  1207. note: standalone nodes 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)",
  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(_("Unable to read nodes"));
  1221. if (res)
  1222. PQclear(res);
  1223. return -1;
  1224. }
  1225. G_debug(3, "load_plus(): n_nodes = %d", plus->n_nodes);
  1226. dig_alloc_nodes(plus, plus->n_nodes);
  1227. for (i = 0; i < plus->n_nodes; i++) {
  1228. id = atoi(PQgetvalue(res, i, 0));
  1229. read_p_node(plus, i + 1, /* node index starts at 1 */
  1230. id, (const char *) PQgetvalue(res, i, 1), pg_info);
  1231. }
  1232. PQclear(res);
  1233. /* read lines (GRASS Topo)
  1234. - standalone nodes -> points
  1235. - edges -> lines/boundaries
  1236. */
  1237. G_debug(3, "load_plus(): n_lines = %d", plus->n_lines);
  1238. dig_alloc_lines(plus, plus->n_lines);
  1239. /* read PostGIS Topo standalone nodes
  1240. -> points
  1241. */
  1242. sprintf(stmt,
  1243. "SELECT node_id,geom FROM \"%s\".node WHERE node_id NOT IN "
  1244. "(SELECT node FROM (SELECT start_node AS node FROM \"%s\".edge "
  1245. "GROUP BY start_node UNION ALL SELECT end_node AS node FROM "
  1246. "\"%s\".edge GROUP BY end_node) AS foo)",
  1247. pg_info->toposchema_name, pg_info->toposchema_name,
  1248. pg_info->toposchema_name);
  1249. G_debug(2, "SQL: %s", stmt);
  1250. res = PQexec(pg_info->conn, stmt);
  1251. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1252. PQntuples(res) > plus->n_plines) {
  1253. G_warning(_("Unable to read lines"));
  1254. if (res)
  1255. PQclear(res);
  1256. return -1;
  1257. }
  1258. ntuples = PQntuples(res); /* plus->n_plines */
  1259. G_zero(&line_data, sizeof(struct edge_data));
  1260. for (i = 0; i < ntuples; i++) {
  1261. /* process standalone nodes (PostGIS Topo) */
  1262. line_data.id = atoi(PQgetvalue(res, i, 0));
  1263. line_data.wkb_geom = (char *) PQgetvalue(res, i, 1);
  1264. read_p_line(plus, i + 1, &line_data, &(pg_info->cache));
  1265. }
  1266. PQclear(res);
  1267. /* read PostGIS Topo edges
  1268. -> lines
  1269. -> boundaries
  1270. */
  1271. sprintf(stmt,
  1272. "SELECT edge_id,start_node,end_node,left_face,right_face,geom "
  1273. "FROM \"%s\".edge",
  1274. pg_info->toposchema_name);
  1275. G_debug(2, "SQL: %s", stmt);
  1276. res = PQexec(pg_info->conn, stmt);
  1277. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1278. PQntuples(res) > plus->n_lines) {
  1279. G_warning(_("Unable to read lines"));
  1280. if (res)
  1281. PQclear(res);
  1282. return -1;
  1283. }
  1284. ntuples = PQntuples(res);
  1285. for (i = 0; i < ntuples; i++) {
  1286. /* process edges (PostGIS Topo) */
  1287. line_data.id = atoi(PQgetvalue(res, i, 0));
  1288. line_data.start_node = atoi(PQgetvalue(res, i, 1));
  1289. line_data.end_node = atoi(PQgetvalue(res, i, 2));
  1290. line_data.left_face = atoi(PQgetvalue(res, i, 3));
  1291. line_data.right_face = atoi(PQgetvalue(res, i, 4));
  1292. line_data.wkb_geom = (char *) PQgetvalue(res, i, 5);
  1293. id = plus->n_plines + i + 1; /* points already registered */
  1294. line = read_p_line(plus, id, &line_data, &(pg_info->cache));
  1295. if (line_data.left_face != 0 || line_data.right_face != 0) {
  1296. /* boundary detected -> build area/isle on left and right*/
  1297. int s, side;
  1298. for (s = 0; s < 2; s++) {
  1299. if (s == 0)
  1300. side = GV_LEFT;
  1301. else
  1302. side = GV_RIGHT;
  1303. G_debug(3, "Build area for line = %d, side = %d",
  1304. id, side);
  1305. Vect_build_line_area(Map, id, side);
  1306. }
  1307. }
  1308. if (line->type == GV_BOUNDARY) {
  1309. struct P_topo_b *topo;
  1310. if (line_data.left_face == 0)
  1311. line_data.left_face = -1;
  1312. if (line_data.right_face == 0)
  1313. line_data.right_face = -1;
  1314. /* check topo - left / right areas */
  1315. topo = (struct P_topo_b *)line->topo;
  1316. if (topo->left != line_data.left_face)
  1317. G_warning(_("Left area detected as %d (should be %d"),
  1318. topo->left, line_data.left_face);
  1319. if (topo->right != line_data.right_face)
  1320. G_warning(_("Right area detected as %d (should be %d"),
  1321. topo->right, line_data.right_face);
  1322. }
  1323. }
  1324. PQclear(res);
  1325. /* attach centroids */
  1326. if (plus->n_areas > 0) {
  1327. sprintf(stmt,
  1328. "SELECT ST_PointOnSurface(geom) AS geom FROM "
  1329. "ST_GetFaceGeometry('%s',"
  1330. "(SELECT face_id FROM \"%s\".face WHERE face_id > 0)) "
  1331. "AS geom",
  1332. pg_info->toposchema_name, pg_info->toposchema_name);
  1333. G_debug(2, "SQL: %s", stmt);
  1334. res = PQexec(pg_info->conn, stmt);
  1335. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  1336. PQntuples(res) > plus->n_areas) {
  1337. G_warning(_("Unable to attach centroids"));
  1338. if (res)
  1339. PQclear(res);
  1340. return -1;
  1341. }
  1342. G_zero(&line_data, sizeof(struct edge_data));
  1343. for (i = 1; i <= plus->n_areas; i++) {
  1344. area = plus->Area[i];
  1345. id = plus->n_lines - plus->n_clines + i;
  1346. line_data.id = line_data.left_face = i;
  1347. line_data.wkb_geom = (char *)PQgetvalue(res, 0, 0);
  1348. read_p_line(plus, id, &line_data, &(pg_info->cache));
  1349. area->centroid = line_data.id;
  1350. }
  1351. }
  1352. return 0;
  1353. }
  1354. /*
  1355. \brief PostgreSQL notice processor
  1356. Print out NOTICE message only on verbose level
  1357. */
  1358. void notice_processor(void *arg, const char *message)
  1359. {
  1360. if (G_verbose() > G_verbose_std()) {
  1361. fprintf(stderr, "%s", message);
  1362. }
  1363. }
  1364. /*!
  1365. \brief Get simple feature type as a string
  1366. Used for AddTopoGeometryColumn().
  1367. Valid types:
  1368. - SF_POINT
  1369. - SF_LINESTRING
  1370. - SF_POLYGON
  1371. \return string with feature type
  1372. \return empty string
  1373. */
  1374. char *get_sftype(SF_FeatureType sftype)
  1375. {
  1376. if (sftype == SF_POINT)
  1377. return "POINT";
  1378. else if (sftype == SF_LINESTRING)
  1379. return "LINE";
  1380. else if (sftype == SF_POLYGON)
  1381. return "POLYGON";
  1382. else
  1383. G_warning(_("Unsupported feature type %d"), sftype);
  1384. return "";
  1385. }
  1386. #endif