listdb.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <grass/dbmi.h>
  2. #include "globals.h"
  3. #include "proto.h"
  4. int db__driver_list_databases(dbString * dbpath, int npaths,
  5. dbHandle ** dblist, int *dbcount)
  6. {
  7. int i;
  8. PGCONN pgconn;
  9. PGresult *res;
  10. int rec_num = 0;
  11. dbHandle *list;
  12. init_error();
  13. *dblist = NULL;
  14. *dbcount = 0;
  15. /* TODO: the solution below is not good as user usually does not have permissions for "template1" */
  16. append_error
  17. ("db_driver_list_databases() is not implemented in pg driver");
  18. report_error();
  19. return DB_FAILED;
  20. if (npaths > 0) {
  21. G_debug(3, "location: %s", db_get_string(dbpath));
  22. if (parse_conn(db_get_string(dbpath), &pgconn) == DB_FAILED) {
  23. report_error();
  24. return DB_FAILED;
  25. }
  26. }
  27. G_debug(3, "host = %s, port = %s, options = %s, tty = %s",
  28. pgconn.host, pgconn.port, pgconn.options, pgconn.tty);
  29. pg_conn =
  30. PQsetdb(pgconn.host, pgconn.port, pgconn.options, pgconn.tty,
  31. "template1");
  32. if (PQstatus(pg_conn) == CONNECTION_BAD) {
  33. append_error("Cannot connect to Postgres:\n");
  34. append_error(PQerrorMessage(pg_conn));
  35. report_error();
  36. PQfinish(pg_conn);
  37. return DB_FAILED;
  38. }
  39. res = PQexec(pg_conn, "select datname from pg_database");
  40. if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
  41. append_error("Cannot select from Postgres:\n");
  42. append_error(PQerrorMessage(pg_conn));
  43. report_error();
  44. PQclear(res);
  45. PQfinish(pg_conn);
  46. return DB_FAILED;
  47. }
  48. rec_num = PQntuples(res);
  49. list = db_alloc_handle_array(rec_num);
  50. if (list == NULL) {
  51. append_error("Cannot db_alloc_handle_array()");
  52. report_error();
  53. return DB_FAILED;
  54. }
  55. for (i = 0; i < rec_num; i++) {
  56. db_init_handle(&list[i]);
  57. if (db_set_handle(&list[i], PQgetvalue(res, i, 0), NULL) != DB_OK) {
  58. append_error("db_set_handle()");
  59. report_error();
  60. db_free_handle_array(list, rec_num);
  61. return DB_FAILED;
  62. }
  63. }
  64. PQclear(res);
  65. PQfinish(pg_conn);
  66. *dblist = list;
  67. *dbcount = rec_num;
  68. return DB_OK;
  69. }