dsn.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <string.h>
  2. #include <grass/gis.h>
  3. #include <grass/dbmi.h>
  4. #include <grass/glocale.h>
  5. char *get_datasource_name(const char *opt_dsn, int use_ogr)
  6. {
  7. char *dsn;
  8. if (G_strncasecmp(opt_dsn, "PG:", 3) == 0) {
  9. /* PostgreSQL/PostGIS */
  10. size_t i;
  11. char connect_str[DB_SQL_MAX], database[GNAME_MAX];
  12. char *p, *pp;
  13. const char *user, *passwd, *host, *port;
  14. /* dbname is mandatory */
  15. p = G_strcasestr(opt_dsn, "dbname");
  16. if (!p)
  17. G_fatal_error(_("Invalid connection string (dbname missing)"));
  18. /* get dbname */
  19. p += strlen("dbname=");
  20. for (i = 0, pp = p; *pp != ' ' && *pp != '\0'; pp++, i++)
  21. database[i] = *pp;
  22. database[i] = '\0';
  23. /* build connection string */
  24. sprintf(connect_str, "%s", opt_dsn);
  25. /* add db.login settings (user, password, host, port) */
  26. if (DB_OK == db_get_login2("pg", database, &user, &passwd, &host, &port)) {
  27. if (user) {
  28. if (!G_strcasestr(opt_dsn, "user=")) {
  29. strcat(connect_str, " user=");
  30. strcat(connect_str, user);
  31. }
  32. G_free((char *)user);
  33. }
  34. if (passwd) {
  35. if (!G_strcasestr(opt_dsn, "password=")) {
  36. strcat(connect_str, " password=");
  37. strcat(connect_str, passwd);
  38. }
  39. G_free((char *)passwd);
  40. }
  41. if (host) {
  42. if (!G_strcasestr(opt_dsn, "host=")) {
  43. strcat(connect_str, " host=");
  44. strcat(connect_str, host);
  45. }
  46. G_free((char *)host);
  47. }
  48. if (port) {
  49. if (!G_strcasestr(opt_dsn, "port=")) {
  50. strcat(connect_str, " port=");
  51. strcat(connect_str, port);
  52. }
  53. G_free((char *)port);
  54. }
  55. }
  56. if (use_ogr) {
  57. dsn = G_store(connect_str);
  58. }
  59. else {
  60. /* strip PG: prefix */
  61. p = (char *)connect_str;
  62. p += strlen("PG:");
  63. dsn = G_store(p);
  64. }
  65. }
  66. else {
  67. /* other datasources */
  68. dsn = G_store(opt_dsn);
  69. }
  70. G_debug(1, "dsn: %s", dsn);
  71. return dsn;
  72. }