select.c 1.9 KB

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