select.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdlib.h>
  2. #include <grass/dbmi.h>
  3. #include <grass/gis.h>
  4. #include "globals.h"
  5. #include "proto.h"
  6. int db__driver_open_select_cursor(dbString * sel, dbCursor * dbc, int mode)
  7. {
  8. PGresult *res;
  9. cursor *c;
  10. dbTable *table;
  11. char *str;
  12. init_error();
  13. /* Set datetime style */
  14. res = PQexec(pg_conn, "SET DATESTYLE TO ISO");
  15. if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
  16. append_error("Cannot set DATESTYLE\n");
  17. report_error();
  18. PQclear(res);
  19. return DB_FAILED;
  20. }
  21. PQclear(res);
  22. /* allocate cursor */
  23. c = alloc_cursor();
  24. if (c == NULL)
  25. return DB_FAILED;
  26. db_set_cursor_mode(dbc, mode);
  27. db_set_cursor_type_readonly(dbc);
  28. /* \ must be escaped, see explanation in db_driver_execute_immediate() */
  29. str = G_str_replace(db_get_string(sel), "\\", "\\\\");
  30. G_debug(3, "Escaped SQL: %s", str);
  31. c->res = PQexec(pg_conn, str);
  32. if (!c->res || PQresultStatus(c->res) != PGRES_TUPLES_OK) {
  33. append_error("Cannot select: \n");
  34. append_error(db_get_string(sel));
  35. append_error("\n");
  36. append_error(PQerrorMessage(pg_conn));
  37. report_error();
  38. PQclear(c->res);
  39. if (str)
  40. G_free(str);
  41. return DB_FAILED;
  42. }
  43. if (str)
  44. G_free(str);
  45. if (describe_table(c->res, &table, c) == DB_FAILED) {
  46. append_error("Cannot describe table\n");
  47. report_error();
  48. PQclear(res);
  49. return DB_FAILED;
  50. }
  51. c->nrows = PQntuples(c->res);
  52. c->row = -1;
  53. /* record table with dbCursor */
  54. db_set_cursor_table(dbc, table);
  55. /* set dbCursor's token for my cursor */
  56. db_set_cursor_token(dbc, c->token);
  57. return DB_OK;
  58. }