1 /*$Id: opensql.c,v 1.4 1999/11/28 19:55:31 lindberg Exp $*/
2 /*$Name: ezmlm-idx-040 $*/
10 static stralloc myp
= {0};
11 static stralloc ers
= {0};
12 static stralloc fn
= {0};
13 static stralloc ourdb
= {0};
14 static char *ourtable
= (char *) 0;
16 char *opensql(dbname
,table
)
17 /* reads the file dbname/sql, and if the file exists, parses it into the */
18 /* components. The string should be host:port:user:pw:db:table. If */
19 /* the file does not exists, returns "". On success returns NULL. On error */
20 /* returns error string for temporary error. If table is NULL it is */
21 /* left alone. If *table is not null, it overrides the table in the sql */
22 /* file. If we already opended dbname the cached info is used, rather than */
23 /* rereading the file. Note that myp is static and all pointers point to it.*/
24 char *dbname
; /* database directory */
25 char **table
; /* table root_name */
28 char *host
= (char *) 0;
29 char *port
= (char *) 0;
30 char *db
= "ezmlm"; /* default */
31 char *user
= (char *) 0;
32 char *pw
= (char *) 0;
35 if (!stralloc_copys(&fn
,dbname
)) return ERR_NOMEM
;
36 if (fn
.len
== ourdb
.len
&& !str_diffn(ourdb
.s
,fn
.s
,fn
.len
)) {
38 if (*table
) ourtable
= *table
;
39 else *table
= ourtable
;
43 if (!stralloc_cats(&fn
,"/sql")) return ERR_NOMEM
;
44 if (!stralloc_0(&fn
)) return ERR_NOMEM
;
45 /* host:port:db:table:user:pw:name */
48 switch (slurp(fn
.s
,&myp
,128)) {
49 case -1: if (!stralloc_copys(&ers
,ERR_READ
)) return ERR_NOMEM
;
50 if (!stralloc_cat(&ers
,&fn
)) return ERR_NOMEM
;
51 if (!stralloc_0(&ers
)) return ERR_NOMEM
;
55 if (!stralloc_copy(&ourdb
,&fn
)) return ERR_NOMEM
;
56 if (!stralloc_append(&myp
,"\n")) return ERR_NOMEM
;
57 for (j
=0; j
< myp
.len
; ++j
) {
58 if (myp
.s
[j
] == '\n') { myp
.s
[j
] = '\0'; break; }
60 /* get connection parameters */
61 if (!stralloc_0(&myp
)) return ERR_NOMEM
;
63 if (myp
.s
[j
= str_chr(myp
.s
,':')]) {
66 if (myp
.s
[j
+= str_chr(myp
.s
+j
,':')]) {
69 if (myp
.s
[j
+= str_chr(myp
.s
+j
,':')]) {
72 if (myp
.s
[j
+= str_chr(myp
.s
+j
,':')]) {
75 if (myp
.s
[j
+= str_chr(myp
.s
+j
,':')]) {
76 ourtable
= myp
.s
+ j
++;
84 if (host
&& !*host
) host
= (char *) 0;
85 if (user
&& !*user
) user
= (char *) 0;
86 if (pw
&& !*pw
) pw
= (char *) 0;
87 if (db
&& !*db
) db
= (char *) 0;
88 if (ourtable
&& !*ourtable
) ourtable
= (char *) 0;
90 if (*table
) ourtable
= *table
;
91 else *table
= ourtable
;
92 if (!*table
) return ERR_NO_TABLE
;
95 /* Make connection to database */
96 psql
= PQsetdbLogin( host
, port
, NULL
, NULL
, db
, user
, pw
);
97 /* Check to see that the backend connection was successfully made */
98 if (PQstatus(psql
) == CONNECTION_BAD
)
99 return PQerrorMessage(psql
);
105 /* close connection to SQL server, if open */
107 if (psql
) PQfinish(psql
);
108 psql
= (void *) 0; /* Destroy pointer */