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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "db.h"
#include "util.h"
#define DB_CACHE_BYTES (256u * 1024)
static PGconn *pg;
static redisContext *rc;
static int recycle_pg;
PGconn *
db_get(const struct conf *cf)
{
if (pg != NULL && PQstatus(pg) == CONNECTION_OK)
return pg;
if (pg != NULL)
PQfinish(pg);
recycle_pg = 0;
pg = PQconnectdb(conf_get(cf, "db.conninfo", "dbname=signet"));
if (PQstatus(pg) != CONNECTION_OK) {
log_err("database connection failed");
PQfinish(pg);
pg = NULL;
}
return pg;
}
/* libpq retains large I/O buffers even after PQclear(). Do not carry them
* across API requests; never close an in-flight query or worker transaction. */
void
db_request_done(void)
{
if (recycle_pg && pg != NULL) {
PQfinish(pg);
pg = NULL;
}
recycle_pg = 0;
}
redisContext *
redis_get(const struct conf *cf)
{
redisReply *r;
if (rc != NULL && !rc->err) {
if ((r = redisCommand(rc, "PING")) != NULL) {
freeReplyObject(r);
return rc;
}
}
redis_drop();
rc = redisConnect(conf_get(cf, "redis.host", "127.0.0.1"),
atoi(conf_get(cf, "redis.port", "6379")));
if (rc == NULL || rc->err) {
log_err("Redis connection unavailable");
redis_drop();
}
return rc;
}
void
redis_drop(void)
{
if (rc != NULL)
redisFree(rc);
rc = NULL;
}
PGresult *
db_q(PGconn *c, const char *sql, int n, const char *const *params)
{
PGresult *res;
ExecStatusType st;
size_t bytes = 0, len;
int i;
if (c == pg) {
for (i = 0; i < n; i++) {
if (params[i] == NULL)
continue;
len = strlen(params[i]);
if (len >= DB_CACHE_BYTES - bytes) {
recycle_pg = 1;
break;
}
bytes += len;
}
}
res = PQexecParams(c, sql, n, NULL, params, NULL, NULL, 0);
st = PQresultStatus(res);
if (c == pg && res != NULL && PQresultMemorySize(res) >= DB_CACHE_BYTES)
recycle_pg = 1;
if (st != PGRES_TUPLES_OK && st != PGRES_COMMAND_OK) {
/* DETAIL/CONTEXT and server messages can repeat private parameters. */
log_err("database query failed (SQLSTATE %.5s)",
res != NULL && PQresultErrorField(res, PG_DIAG_SQLSTATE) != NULL ?
PQresultErrorField(res, PG_DIAG_SQLSTATE) : "?????");
PQclear(res);
return NULL;
}
return res;
}
int
db_do(PGconn *c, const char *sql, int n, const char *const *params)
{
PGresult *res = db_q(c, sql, n, params);
if (res == NULL)
return -1;
PQclear(res);
return 0;
}