open_pg.c 41 KB

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