1 /* cvm/cvm-pgsql.c - PgSQL CVM
2 * Copyright (C) 2010 Bruce Guenter <bruce@untroubled.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18 #include <libpq-fe.h>
19 #include <stdlib.h>
20 #include <bglibs/str.h>
21 #include "module.h"
22 #include "sql.h"
23
24 const char program[] = "cvm-pgsql";
25
26 const char sql_query_var[] = "CVM_PGSQL_QUERY";
27 const char sql_pwcmp_var[] = "CVM_PGSQL_PWCMP";
28 const char sql_postq_var[] = "CVM_PGSQL_POSTQ";
29
30 static PGconn* pg;
31
sql_auth_init(void)32 int sql_auth_init(void)
33 {
34 if ((pg = PQconnectdb("")) == 0) return CVME_IO;
35 if (PQstatus(pg) == CONNECTION_BAD) return CVME_IO;
36 return 0;
37 }
38
39 static PGresult* result;
40
sql_get_field(int field)41 const char* sql_get_field(int field)
42 {
43 return PQgetisnull(result, 0, field) ? 0 : PQgetvalue(result, 0, field);
44 }
45
pgsql_query(const str * query)46 static int pgsql_query(const str* query)
47 {
48 if (result) PQclear(result);
49 if ((result = PQexec(pg, query->s)) != 0) return 1;
50 if (PQstatus(pg) != CONNECTION_BAD) return 0;
51 PQreset(pg);
52 if ((result = PQexec(pg, query->s)) != 0) return 1;
53 return 0;
54 }
55
sql_post_query(const str * query)56 int sql_post_query(const str* query)
57 {
58 if (!pgsql_query(query)) return CVME_IO | CVME_FATAL;
59 switch (PQresultStatus(result)) {
60 case PGRES_TUPLES_OK:
61 case PGRES_COMMAND_OK:
62 return 0;
63 default: return CVME_IO;
64 }
65 }
66
sql_auth_query(const str * query)67 int sql_auth_query(const str* query)
68 {
69 if (!pgsql_query(query)) return -(CVME_IO | CVME_FATAL);
70 switch (PQresultStatus(result)) {
71 case PGRES_TUPLES_OK: return PQntuples(result);
72 case PGRES_COMMAND_OK: return -CVME_PERMFAIL;
73 default: return -CVME_IO;
74 }
75 }
76
sql_auth_stop(void)77 void sql_auth_stop(void)
78 {
79 PQfinish(pg);
80 }
81