listdb.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*!
  2. \file db/driver/postgres/listdb.c
  3. \brief DBMI - Low Level PostgreSQL database driver - list databases
  4. This program is free software under the GNU General Public License
  5. (>=v2). Read the file COPYING that comes with GRASS for details.
  6. \author Radim Blazek
  7. */
  8. #include <grass/dbmi.h>
  9. #include <grass/glocale.h>
  10. #include "globals.h"
  11. #include "proto.h"
  12. int db__driver_list_databases(dbString * dbpath, int npaths,
  13. dbHandle ** dblist, int *dbcount)
  14. {
  15. int i;
  16. PGCONN pgconn;
  17. PGresult *res;
  18. int rec_num = 0;
  19. dbHandle *list;
  20. init_error();
  21. *dblist = NULL;
  22. *dbcount = 0;
  23. /* TODO: the solution below is not good as user usually does not have permissions for "template1" */
  24. append_error
  25. (_("db_driver_list_databases() is not implemented in pg driver"));
  26. report_error();
  27. return DB_FAILED;
  28. if (npaths > 0) {
  29. G_debug(3, "location: %s", db_get_string(dbpath));
  30. if (parse_conn(db_get_string(dbpath), &pgconn) == DB_FAILED) {
  31. report_error();
  32. return DB_FAILED;
  33. }
  34. }
  35. G_debug(3, "host = %s, port = %s, options = %s, tty = %s",
  36. pgconn.host, pgconn.port, pgconn.options, pgconn.tty);
  37. pg_conn =
  38. PQsetdb(pgconn.host, pgconn.port, pgconn.options, pgconn.tty,
  39. "template1");
  40. if (PQstatus(pg_conn) == CONNECTION_BAD) {
  41. append_error(_("Unable to connect to Postgres:\n"));
  42. append_error(PQerrorMessage(pg_conn));
  43. report_error();
  44. PQfinish(pg_conn);
  45. return DB_FAILED;
  46. }
  47. res = PQexec(pg_conn, "select datname from pg_database");
  48. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  49. append_error(_("Unable to select from Postgres:\n"));
  50. append_error(PQerrorMessage(pg_conn));
  51. report_error();
  52. PQclear(res);
  53. PQfinish(pg_conn);
  54. return DB_FAILED;
  55. }
  56. rec_num = PQntuples(res);
  57. list = db_alloc_handle_array(rec_num);
  58. if (list == NULL) {
  59. append_error(_("Out of memory"));
  60. report_error();
  61. return DB_FAILED;
  62. }
  63. for (i = 0; i < rec_num; i++) {
  64. db_init_handle(&list[i]);
  65. if (db_set_handle(&list[i], PQgetvalue(res, i, 0), NULL) != DB_OK) {
  66. append_error("db_set_handle()");
  67. report_error();
  68. db_free_handle_array(list, rec_num);
  69. return DB_FAILED;
  70. }
  71. }
  72. PQclear(res);
  73. PQfinish(pg_conn);
  74. *dblist = list;
  75. *dbcount = rec_num;
  76. return DB_OK;
  77. }