open_pg.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. static char *get_key_column(struct Format_info_pg *);
  18. static SF_FeatureType ftype_from_string(const char *);
  19. static int drop_table(struct Format_info_pg *);
  20. static int create_table(struct Format_info_pg *, const struct field_info *);
  21. #endif
  22. /*!
  23. \brief Open existing PostGIS feature table (level 1 - without topology)
  24. \todo Check database instead of geometry_columns
  25. \param[in,out] Map pointer to Map_info structure
  26. \param update TRUE for write mode, otherwise read-only
  27. \return 0 success
  28. \return -1 error
  29. */
  30. int V1_open_old_pg(struct Map_info *Map, int update)
  31. {
  32. #ifdef HAVE_POSTGRES
  33. int found;
  34. char stmt[DB_SQL_MAX];
  35. PGresult *res;
  36. struct Format_info_pg *pg_info;
  37. pg_info = &(Map->fInfo.pg);
  38. if (!pg_info->conninfo) {
  39. G_warning(_("Connection string not defined"));
  40. return -1;
  41. }
  42. if (!pg_info->table_name) {
  43. G_warning(_("PostGIS feature table not defined"));
  44. return -1;
  45. }
  46. G_debug(1, "V1_open_old_pg(): conninfo='%s' table='%s'", pg_info->conninfo,
  47. pg_info->table_name);
  48. /* connect database */
  49. pg_info->conn = PQconnectdb(pg_info->conninfo);
  50. G_debug(2, " PQconnectdb(): %s", pg_info->conninfo);
  51. if (PQstatus(pg_info->conn) == CONNECTION_BAD)
  52. G_fatal_error("%s\n%s", _("Connection ton PostgreSQL database failed."),
  53. PQerrorMessage(pg_info->conn));
  54. /* get DB name */
  55. pg_info->db_name = G_store(PQdb(pg_info->conn));
  56. if (!pg_info->db_name) {
  57. G_warning(_("Unable to get database name"));
  58. return -1;
  59. }
  60. /* if schema not defined, use 'public' */
  61. if (!pg_info->schema_name) {
  62. pg_info->schema_name = G_store("public");
  63. }
  64. /* get fid and geometry column */
  65. sprintf(stmt, "SELECT f_geometry_column, coord_dimension, srid, type "
  66. "FROM geometry_columns WHERE f_table_schema = '%s' AND "
  67. "f_table_name = '%s'",
  68. pg_info->schema_name, pg_info->table_name);
  69. G_debug(2, "SQL: %s", stmt);
  70. res = PQexec(pg_info->conn, stmt);
  71. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  72. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  73. PQresultErrorMessage(res));
  74. found = PQntuples(res) > 0 ? TRUE : FALSE;
  75. if (found) {
  76. /* geometry column */
  77. pg_info->geom_column = G_store(PQgetvalue(res, 0, 0));
  78. G_debug(3, "\t-> table = %s column = %s", pg_info->table_name,
  79. pg_info->geom_column);
  80. /* fid column */
  81. pg_info->fid_column = get_key_column(pg_info);
  82. /* coordinates dimension */
  83. pg_info->coor_dim = atoi(PQgetvalue(res, 0, 1));
  84. /* SRS ID */
  85. pg_info->srid = atoi(PQgetvalue(res, 0, 2));
  86. /* feature type */
  87. pg_info->feature_type = ftype_from_string(PQgetvalue(res, 0, 3));
  88. }
  89. /* no feature in cache */
  90. pg_info->cache.fid = -1;
  91. PQclear(res);
  92. if (!found) {
  93. G_warning(_("Feature table <%s> not found in 'geometry_columns'"),
  94. pg_info->table_name);
  95. return -1;
  96. }
  97. return 0;
  98. #else
  99. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  100. return -1;
  101. #endif
  102. }
  103. /*!
  104. \brief Open existing PostGIS layer (level 2 - feature index)
  105. \param[in,out] Map pointer to Map_info structure
  106. \return 0 success
  107. \return -1 error
  108. */
  109. int V2_open_old_pg(struct Map_info *Map)
  110. {
  111. #ifdef HAVE_POSTGRES
  112. G_debug(3, "V2_open_old_pg(): name = %s mapset = %s", Map->name,
  113. Map->mapset);
  114. if (Vect_open_fidx(Map, &(Map->fInfo.pg.offset)) != 0) {
  115. G_warning(_("Unable to open feature index file for vector map <%s>"),
  116. Vect_get_full_name(Map));
  117. G_zero(&(Map->fInfo.pg.offset), sizeof(struct Format_info_offset));
  118. }
  119. return 0;
  120. #else
  121. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  122. return -1;
  123. #endif
  124. }
  125. /*!
  126. \brief Prepare PostGIS database for creating new feature table
  127. (level 1)
  128. \todo To implement
  129. \param[out] Map pointer to Map_info structure
  130. \param name name of PostGIS feature table to create
  131. \param with_z WITH_Z for 3D vector data otherwise WITHOUT_Z
  132. \return 0 success
  133. \return -1 error
  134. */
  135. int V1_open_new_pg(struct Map_info *Map, const char *name, int with_z)
  136. {
  137. #ifdef HAVE_POSTGRES
  138. char stmt[DB_SQL_MAX];
  139. struct Format_info_pg *pg_info;
  140. PGresult *res;
  141. pg_info = &(Map->fInfo.pg);
  142. if (!pg_info->conninfo) {
  143. G_warning(_("Connection string not defined"));
  144. return -1;
  145. }
  146. if (!pg_info->table_name) {
  147. G_warning(_("PostGIS feature table not defined"));
  148. return -1;
  149. }
  150. G_debug(1, "V1_open_new_pg(): conninfo='%s' table='%s'", pg_info->conninfo,
  151. pg_info->table_name);
  152. /* connect database */
  153. pg_info->conn = PQconnectdb(pg_info->conninfo);
  154. G_debug(2, " PQconnectdb(): %s", pg_info->conninfo);
  155. if (PQstatus(pg_info->conn) == CONNECTION_BAD)
  156. G_fatal_error("%s\n%s", _("Connection ton PostgreSQL database failed."),
  157. PQerrorMessage(pg_info->conn));
  158. /* get DB name */
  159. pg_info->db_name = G_store(PQdb(pg_info->conn));
  160. if (!pg_info->db_name) {
  161. G_warning(_("Unable to get database name"));
  162. return -1;
  163. }
  164. /* if schema not defined, use 'public' */
  165. if (!pg_info->schema_name) {
  166. pg_info->schema_name = G_store("public");
  167. }
  168. /* if fid_column not defined, use 'ogc_fid' */
  169. if (!pg_info->fid_column) {
  170. pg_info->fid_column = G_store("ogc_fid");
  171. }
  172. /* if geom_column not defined, use 'wkb_geometry' */
  173. if (!pg_info->geom_column) {
  174. pg_info->geom_column = G_store("wkb_geometry");
  175. }
  176. /* check if feature table already exists */
  177. sprintf(stmt, "SELECT * FROM pg_tables "
  178. "WHERE schemaname = '%s' AND tablename = '%s'",
  179. pg_info->schema_name, pg_info->table_name);
  180. G_debug(2, "SQL: %s", stmt);
  181. res = PQexec(pg_info->conn, stmt);
  182. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
  183. G_fatal_error("%s\n%s", _("No feature tables found in database."),
  184. PQresultErrorMessage(res));
  185. if (PQntuples(res) > 0) {
  186. /* table found */
  187. if (G_get_overwrite()) {
  188. G_warning(_("PostGIS layer <%s.%s> already exists and will be overwritten"),
  189. pg_info->schema_name, pg_info->table_name);
  190. if (drop_table(pg_info) == -1) {
  191. G_warning(_("Unable to delete PostGIS layer <%s>"),
  192. pg_info->table_name);
  193. return -1;
  194. }
  195. }
  196. else {
  197. G_fatal_error(_("PostGIS layer <%s.%s> already exists in database '%s'"),
  198. pg_info->schema_name, pg_info->table_name,
  199. pg_info->db_name);
  200. return -1;
  201. }
  202. }
  203. /* no feature in cache */
  204. pg_info->cache.fid = -1;
  205. /* unknown feature type */
  206. pg_info->feature_type = SF_UNKNOWN;
  207. PQclear(res);
  208. return 0;
  209. #else
  210. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  211. return -1;
  212. #endif
  213. }
  214. /*!
  215. \brief Create new PostGIS layer in given database (level 2)
  216. V1_open_new_pg() is required to be called before this function.
  217. List of currently supported types:
  218. - GV_POINT (SF_POINT)
  219. - GV_LINE (SF_LINESTRING)
  220. - GV_BOUNDARY (SF_POLYGON)
  221. \param[in,out] Map pointer to Map_info structure
  222. \param type feature type (GV_POINT, GV_LINE, ...)
  223. \return 0 success
  224. \return -1 error
  225. */
  226. int V2_open_new_pg(struct Map_info *Map, int type)
  227. {
  228. #ifdef HAVE_POSTGRES
  229. int ndblinks;
  230. struct Format_info_pg *pg_info;
  231. struct field_info *Fi;
  232. struct Key_Value *projinfo, *projunits;
  233. Fi = NULL;
  234. pg_info = &(Map->fInfo.pg);
  235. if (!pg_info->conninfo) {
  236. G_warning(_("Connection string not defined"));
  237. return -1;
  238. }
  239. if (!pg_info->table_name) {
  240. G_warning(_("PostGIS feature table not defined"));
  241. return -1;
  242. }
  243. G_debug(1, "V2_open_new_pg(): conninfo='%s' table='%s' -> type = %d",
  244. pg_info->conninfo, pg_info->table_name, type);
  245. /* get spatial reference */
  246. projinfo = G_get_projinfo();
  247. projunits = G_get_projunits();
  248. pg_info->srid = 0; /* TODO */
  249. // Ogr_spatial_ref = GPJ_grass_to_osr(projinfo, projunits);
  250. G_free_key_value(projinfo);
  251. G_free_key_value(projunits);
  252. /* determine geometry type */
  253. switch(type) {
  254. case GV_POINT:
  255. pg_info->feature_type = SF_POINT;
  256. break;
  257. case GV_LINE:
  258. pg_info->feature_type = SF_LINESTRING;
  259. break;
  260. case GV_BOUNDARY:
  261. pg_info->feature_type = SF_POLYGON;
  262. break;
  263. default:
  264. G_warning(_("Unsupported geometry type (%d)"), type);
  265. return -1;
  266. }
  267. /* coordinate dimension */
  268. pg_info->coor_dim = Vect_is_3d(Map) ? 3 : 2;
  269. /* create new PostGIS table */
  270. ndblinks = Vect_get_num_dblinks(Map);
  271. if (ndblinks > 0) {
  272. Fi = Vect_get_dblink(Map, 0);
  273. if (Fi) {
  274. if (ndblinks > 1)
  275. G_warning(_("More layers defined, using driver <%s> and "
  276. "database <%s>"), Fi->driver, Fi->database);
  277. }
  278. else {
  279. G_warning(_("Database connection not defined. "
  280. "Unable to write attributes."));
  281. }
  282. }
  283. if (create_table(pg_info, Fi) == -1) {
  284. G_warning(_("Unable to create new PostGIS table"));
  285. return -1;
  286. }
  287. if (Fi)
  288. G_free(Fi);
  289. return 0;
  290. #else
  291. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  292. return -1;
  293. #endif
  294. }
  295. #ifdef HAVE_POSTGRES
  296. char *get_key_column(struct Format_info_pg *pg_info)
  297. {
  298. char *key_column;
  299. char stmt[DB_SQL_MAX];
  300. PGresult *res;
  301. sprintf(stmt,
  302. "SELECT kcu.column_name "
  303. "FROM INFORMATION_SCHEMA.TABLES t "
  304. "LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc "
  305. "ON tc.table_catalog = t.table_catalog "
  306. "AND tc.table_schema = t.table_schema "
  307. "AND tc.table_name = t.table_name "
  308. "AND tc.constraint_type = 'PRIMARY KEY' "
  309. "LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu "
  310. "ON kcu.table_catalog = tc.table_catalog "
  311. "AND kcu.table_schema = tc.table_schema "
  312. "AND kcu.table_name = tc.table_name "
  313. "AND kcu.constraint_name = tc.constraint_name "
  314. "WHERE t.table_schema = '%s' AND t.table_name = '%s'",
  315. pg_info->schema_name, pg_info->table_name);
  316. G_debug(2, "SQL: %s", stmt);
  317. res = PQexec(pg_info->conn, stmt);
  318. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK ||
  319. PQntuples(res) != 1 || strlen(PQgetvalue(res, 0, 0)) < 1) {
  320. G_warning(_("No key column detected."));
  321. if (res)
  322. PQclear(res);
  323. return NULL;
  324. }
  325. key_column = G_store(PQgetvalue(res, 0, 0));
  326. PQclear(res);
  327. return key_column;
  328. }
  329. SF_FeatureType ftype_from_string(const char *type)
  330. {
  331. SF_FeatureType sf_type;
  332. if (G_strcasecmp(type, "POINT") == 0)
  333. return SF_POINT;
  334. else if (G_strcasecmp(type, "LINESTRING") == 0)
  335. return SF_LINESTRING;
  336. else if (G_strcasecmp(type, "POLYGON") == 0)
  337. return SF_POLYGON;
  338. else if (G_strcasecmp(type, "MULTIPOINT") == 0)
  339. return SF_MULTIPOINT;
  340. else if (G_strcasecmp(type, "MULTILINESTRING") == 0)
  341. return SF_MULTILINESTRING;
  342. else if (G_strcasecmp(type, "MULTIPOLYGON") == 0)
  343. return SF_MULTIPOLYGON;
  344. else if (G_strcasecmp(type, "GEOMETRYCOLLECTION") == 0)
  345. return SF_GEOMETRYCOLLECTION;
  346. return SF_UNKNOWN;
  347. G_debug(3, "ftype_from_string(): type='%s' -> %d", type, sf_type);
  348. return sf_type;
  349. }
  350. int drop_table(struct Format_info_pg *pg_info)
  351. {
  352. char stmt[DB_SQL_MAX];
  353. sprintf(stmt, "DROP TABLE \"%s\".\"%s\"",
  354. pg_info->schema_name, pg_info->table_name);
  355. G_debug(2, "SQL: %s", stmt);
  356. if (execute(pg_info->conn, stmt) == -1) {
  357. return -1;
  358. }
  359. return 0;
  360. }
  361. int create_table(struct Format_info_pg *pg_info, const struct field_info *Fi)
  362. {
  363. int spatial_index, primary_key;
  364. char stmt[DB_SQL_MAX], *geom_type;
  365. PGresult *result;
  366. /* by default create spatial index & add primary key */
  367. spatial_index = primary_key = TRUE;
  368. if (G_find_file2("", "PG", G_mapset())) {
  369. FILE *fp;
  370. const char *p;
  371. struct Key_Value *key_val;
  372. fp = G_fopen_old("", "PG", G_mapset());
  373. if (!fp) {
  374. G_fatal_error(_("Unable to open PG file"));
  375. }
  376. key_val = G_fread_key_value(fp);
  377. fclose(fp);
  378. /* spatial index */
  379. p = G_find_key_value("spatial_index", key_val);
  380. if (p && G_strcasecmp(p, "off") == 0)
  381. spatial_index = FALSE;
  382. /* primary key */
  383. p = G_find_key_value("primary_key", key_val);
  384. if (p && G_strcasecmp(p, "off") == 0)
  385. primary_key = FALSE;
  386. }
  387. /* begin transaction */
  388. if (execute(pg_info->conn, "BEGIN") == -1) {
  389. return -1;
  390. }
  391. /* create table */
  392. sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s SERIAL)",
  393. pg_info->schema_name, pg_info->table_name,
  394. pg_info->fid_column);
  395. G_debug(2, "SQL: %s", stmt);
  396. if (execute(pg_info->conn, stmt) == -1) {
  397. execute(pg_info->conn, "ROLLBACK");
  398. return -1;
  399. }
  400. /* add primary key ? */
  401. if (primary_key) {
  402. sprintf(stmt, "ALTER TABLE \"%s\".\"%s\" ADD PRIMARY KEY (%s)",
  403. pg_info->schema_name, pg_info->table_name,
  404. pg_info->fid_column);
  405. G_debug(2, "SQL: %s", stmt);
  406. if (execute(pg_info->conn, stmt) == -1) {
  407. execute(pg_info->conn, "ROLLBACK");
  408. return -1;
  409. }
  410. }
  411. /* determine geometry type (string) */
  412. switch(pg_info->feature_type) {
  413. case (SF_POINT):
  414. geom_type = "POINT";
  415. break;
  416. case (SF_LINESTRING):
  417. geom_type = "LINESTRING";
  418. break;
  419. case (SF_POLYGON):
  420. geom_type = "POLYGON";
  421. break;
  422. default:
  423. G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
  424. execute(pg_info->conn, "ROLLBACK");
  425. return -1;
  426. }
  427. /* add geometry column */
  428. sprintf(stmt, "SELECT AddGeometryColumn('%s', '%s', "
  429. "'%s', %d, '%s', %d)",
  430. pg_info->schema_name, pg_info->table_name,
  431. pg_info->geom_column, pg_info->srid,
  432. geom_type, pg_info->coor_dim);
  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. /* create index ? */
  441. if (spatial_index) {
  442. sprintf(stmt, "CREATE INDEX %s_%s_idx ON %s USING GIST (%s)",
  443. pg_info->table_name, pg_info->geom_column, pg_info->table_name,
  444. pg_info->geom_column);
  445. G_debug(2, "SQL: %s", stmt);
  446. if (execute(pg_info->conn, stmt) == -1) {
  447. execute(pg_info->conn, "ROLLBACK");
  448. return -1;
  449. }
  450. }
  451. /* close transaction */
  452. if (execute(pg_info->conn, "COMMIT") == -1) {
  453. return -1;
  454. }
  455. return 0;
  456. }
  457. #endif