dsn.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. dsn = G_store(opt_dsn);
  9. return dsn;
  10. /* input OGR dsn and GRASS db connections are independent of each other */
  11. /* TODO: remove below code */
  12. if (G_strncasecmp(opt_dsn, "PG:", 3) == 0) {
  13. /* PostgreSQL/PostGIS */
  14. size_t i;
  15. char connect_str[DB_SQL_MAX], database[GNAME_MAX];
  16. char *p, *pp;
  17. const char *user, *passwd, *host, *port;
  18. /* dbname is mandatory */
  19. p = G_strcasestr(opt_dsn, "dbname");
  20. if (!p)
  21. G_fatal_error(_("Invalid connection string (dbname missing)"));
  22. /* get dbname */
  23. p += strlen("dbname=");
  24. for (i = 0, pp = p; *pp != ' ' && *pp != '\0'; pp++, i++)
  25. database[i] = *pp;
  26. database[i] = '\0';
  27. /* build connection string */
  28. sprintf(connect_str, "dbname=%s", database);
  29. /* add db.login settings (user, password, host, port) */
  30. if (DB_OK == db_get_login2("pg", database, &user, &passwd, &host, &port)) {
  31. if (user) {
  32. if (!G_strcasestr(opt_dsn, "user=")) {
  33. strcat(connect_str, " user=");
  34. strcat(connect_str, user);
  35. }
  36. G_free((char *)user);
  37. }
  38. if (passwd) {
  39. if (!G_strcasestr(opt_dsn, "password=")) {
  40. strcat(connect_str, " password=");
  41. strcat(connect_str, passwd);
  42. }
  43. G_free((char *)passwd);
  44. }
  45. if (host) {
  46. if (!G_strcasestr(opt_dsn, "host=")) {
  47. strcat(connect_str, " host=");
  48. strcat(connect_str, host);
  49. }
  50. G_free((char *)host);
  51. }
  52. if (port) {
  53. if (!G_strcasestr(opt_dsn, "port=")) {
  54. strcat(connect_str, " port=");
  55. strcat(connect_str, port);
  56. }
  57. G_free((char *)port);
  58. }
  59. }
  60. if (!use_ogr)
  61. /* be friendly, ignored 'PG:' prefix for PostGIS links */
  62. dsn = G_store(connect_str);
  63. else
  64. G_asprintf(&dsn, "PG:%s", connect_str);
  65. }
  66. else {
  67. /* other datasources */
  68. dsn = G_store(opt_dsn);
  69. }
  70. G_debug(1, "dsn: %s", dsn);
  71. return dsn;
  72. }