listdb.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. \author Updated for GRASS 7 by Martin Landa <landa.martin gmail.com>
  8. */
  9. #include <grass/dbmi.h>
  10. #include <grass/glocale.h>
  11. #include "globals.h"
  12. #include "proto.h"
  13. int db__driver_list_databases(dbString * dbpath, int npaths,
  14. dbHandle ** dblist, int *dbcount)
  15. {
  16. int i;
  17. PGCONN pgconn;
  18. PGresult *res;
  19. int rec_num = 0;
  20. dbHandle *list;
  21. *dblist = NULL;
  22. *dbcount = 0;
  23. /* TODO: the solution below is not good as user usually does not have permissions for "template1" */
  24. /* db_d_append_error(_("db_driver_list_databases() is not implemented"));
  25. db_d_report_error();
  26. return DB_FAILED;
  27. */
  28. if (npaths < 1) {
  29. db_d_append_error(_("No path given"));
  30. db_d_report_error();
  31. return DB_FAILED;
  32. }
  33. if (parse_conn(db_get_string(dbpath), &pgconn) == DB_FAILED) {
  34. db_d_report_error();
  35. return DB_FAILED;
  36. }
  37. G_debug(3, "host = %s, port = %s, options = %s, tty = %s",
  38. pgconn.host, pgconn.port, pgconn.options, pgconn.tty);
  39. pg_conn =
  40. PQsetdb(pgconn.host, pgconn.port, pgconn.options, pgconn.tty,
  41. "template1");
  42. if (PQstatus(pg_conn) == CONNECTION_BAD) {
  43. db_d_append_error("%s\n%s",
  44. _("Unable to connect to Postgres:"),
  45. PQerrorMessage(pg_conn));
  46. db_d_report_error();
  47. PQfinish(pg_conn);
  48. return DB_FAILED;
  49. }
  50. res = PQexec(pg_conn, "select datname from pg_database");
  51. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  52. db_d_append_error("%s\n%s",
  53. _("Unable to select from Postgres:"),
  54. PQerrorMessage(pg_conn));
  55. db_d_report_error();
  56. PQclear(res);
  57. PQfinish(pg_conn);
  58. return DB_FAILED;
  59. }
  60. rec_num = PQntuples(res);
  61. list = db_alloc_handle_array(rec_num);
  62. if (list == NULL) {
  63. db_d_append_error(_("Out of memory"));
  64. db_d_report_error();
  65. return DB_FAILED;
  66. }
  67. for (i = 0; i < rec_num; i++) {
  68. db_init_handle(&list[i]);
  69. if (db_set_handle(&list[i], PQgetvalue(res, i, 0), NULL) != DB_OK) {
  70. db_d_append_error(_("Unable to set handle"));
  71. db_d_report_error();
  72. db_free_handle_array(list, rec_num);
  73. return DB_FAILED;
  74. }
  75. }
  76. PQclear(res);
  77. PQfinish(pg_conn);
  78. *dblist = list;
  79. *dbcount = rec_num;
  80. return DB_OK;
  81. }