1 #include <string.h>
2 
3 #include <grass/gis.h>
4 #include <grass/dbmi.h>
5 #include <grass/glocale.h>
6 
get_datasource_name(const char * opt_dsn,int use_ogr)7 char *get_datasource_name(const char *opt_dsn, int use_ogr)
8 {
9     char *dsn;
10 
11     dsn = G_store(opt_dsn);
12 
13     return dsn;
14 
15     /* input OGR dsn and GRASS db connections are independent of each other */
16 
17     /* TODO: remove below code, or use it in e.g. a new v.in.pg */
18     if (G_strncasecmp(opt_dsn, "PG:", 3) == 0) {
19         /* PostgreSQL/PostGIS */
20         size_t i;
21         char connect_str[DB_SQL_MAX], database[GNAME_MAX];
22         char *p, *pp;
23         const char *user, *passwd, *host, *port;
24 
25         /* dbname is mandatory */
26         p = G_strcasestr(opt_dsn, "dbname");
27         if (!p)
28             G_fatal_error(_("Invalid connection string (dbname missing)"));
29 
30         /* get dbname */
31         p += strlen("dbname=");
32         for (i = 0, pp = p; *pp != ' ' && *pp != '\0'; pp++, i++)
33             database[i] = *pp;
34         database[i] = '\0';
35 
36         /* build connection string */
37         sprintf(connect_str, "dbname=%s", database);
38 
39         /* add db.login settings (user, password, host, port) */
40         if (DB_OK == db_get_login2("pg", database, &user, &passwd, &host, &port)) {
41             if (user) {
42                 if (!G_strcasestr(opt_dsn, "user=")) {
43                     strcat(connect_str, " user=");
44                     strcat(connect_str, user);
45                 }
46                 G_free((char *)user);
47             }
48             if (passwd) {
49                 if (!G_strcasestr(opt_dsn, "password=")) {
50                     strcat(connect_str, " password=");
51                     strcat(connect_str, passwd);
52                 }
53                 G_free((char *)passwd);
54             }
55             if (host) {
56                 if (!G_strcasestr(opt_dsn, "host=")) {
57                     strcat(connect_str, " host=");
58                     strcat(connect_str, host);
59                 }
60                 G_free((char *)host);
61             }
62             if (port) {
63                 if (!G_strcasestr(opt_dsn, "port=")) {
64                     strcat(connect_str, " port=");
65                     strcat(connect_str, port);
66                 }
67                 G_free((char *)port);
68             }
69         }
70 
71         if (!use_ogr)
72             /* be friendly, ignored 'PG:' prefix for PostGIS links */
73             dsn = G_store(connect_str);
74         else
75             G_asprintf(&dsn, "PG:%s", connect_str);
76     }
77     else {
78         /* other datasources */
79         dsn = G_store(opt_dsn);
80     }
81 
82     G_debug(1, "dsn: %s", dsn);
83 
84     return dsn;
85 }
86