-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.c
49 lines (36 loc) · 912 Bytes
/
db.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <libpq-fe.h>
#include "config.h"
void db_ensureconnected(PGconn *db) {
while(PQstatus(db) != CONNECTION_OK) {
fprintf(stderr, "ERROR: DATABASE COULD NOT BE CONTACTED, BUT WILL RETRY; ERROR WAS %s", PQerrorMessage(db));
PQreset(db);
sleep(5);
}
}
char *db_query_scalar(PGconn *db, char *query) {
PGresult *q = NULL;
char *r = NULL;
db_ensureconnected(db);
q = PQexec(db, query);
if(PQntuples(q) <= 0) {
PQclear(q);
return NULL;
}
if(PQresultStatus(q) == PGRES_TUPLES_OK)
r = (char *)strdup(PQgetvalue(q, 0, 0));
else
fprintf(stderr,"ERROR: DB REPORTED: %s; %s\n", PQresStatus(PQresultStatus(q)), PQresultErrorMessage(q));
PQclear(q);
return r;
}
PGconn *db_connect() {
PGconn *db = PQconnectdb(DB_CONNECTION_STRING);
db_ensureconnected(db);
return db;
}
void db_close(PGconn *db) {
PQfinish(db);
}