listdb.c 2.0 KB

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