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. *dblist = NULL;
  21. *dbcount = 0;
  22. /* TODO: the solution below is not good as user usually does not have permissions for "template1" */
  23. db_d_append_error(_("db_driver_list_databases() is not implemented"));
  24. db_d_report_error();
  25. return DB_FAILED;
  26. if (npaths > 0) {
  27. G_debug(3, "location: %s", db_get_string(dbpath));
  28. if (parse_conn(db_get_string(dbpath), &pgconn) == DB_FAILED) {
  29. db_d_report_error();
  30. return DB_FAILED;
  31. }
  32. }
  33. G_debug(3, "host = %s, port = %s, options = %s, tty = %s",
  34. pgconn.host, pgconn.port, pgconn.options, pgconn.tty);
  35. pg_conn =
  36. PQsetdb(pgconn.host, pgconn.port, pgconn.options, pgconn.tty,
  37. "template1");
  38. if (PQstatus(pg_conn) == CONNECTION_BAD) {
  39. db_d_append_error("%s\n%s",
  40. _("Unable to connect to Postgres:"),
  41. PQerrorMessage(pg_conn));
  42. db_d_report_error();
  43. PQfinish(pg_conn);
  44. return DB_FAILED;
  45. }
  46. res = PQexec(pg_conn, "select datname from pg_database");
  47. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  48. db_d_append_error("%s\n%s",
  49. _("Unable to select from Postgres:"),
  50. PQerrorMessage(pg_conn));
  51. db_d_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. db_d_append_error(_("Out of memory"));
  60. db_d_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. db_d_append_error(_("Unable to set handle"));
  67. db_d_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. }