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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
|
/*
Copyright (C) 1999-2004 IC & S dbmail@ic-s.nl
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/**
* dbpgsql.c
* PostgreSQL driver file
* Handles connection and queries to PostgreSQL backend
*/
#include "libpq-fe.h" /* PostgreSQL header */
#include "dbmail.h"
#define THIS_MODULE "sql"
#define BYTEAOID 17
const char * db_get_sql(sql_fragment_t frag)
{
switch(frag) {
case SQL_TO_CHAR:
return "TO_CHAR(%s, 'YYYY-MM-DD HH24:MI:SS' )";
break;
case SQL_TO_DATE:
return "TO_DATE(%s::text,'YYYY-MM-DD')";
break;
case SQL_TO_DATETIME:
return "TO_TIMESTAMP(%s::text, 'YYYY-MM-DD HH24:MI:SS')";
break;
case SQL_CURRENT_TIMESTAMP:
return "CURRENT_TIMESTAMP";
break;
case SQL_EXPIRE:
return "NOW() - INTERVAL '%d DAY'";
break;
case SQL_BINARY:
return "";
break;
case SQL_REGEXP:
return "~";
break;
case SQL_SENSITIVE_LIKE:
return "LIKE";
break;
case SQL_INSENSITIVE_LIKE:
return "ILIKE";
break;
case SQL_ENCODE_ESCAPE:
return "ENCODE(%s::bytea,'escape')";
break;
case SQL_STRCASE:
return "LOWER(%s)";
break;
case SQL_PARTIAL:
return "SUBSTRING(%s,0,255)";
break;
}
return NULL;
}
static PGconn *conn = NULL;
static PGresult *res = NULL;
static void _create_binary_table(void);
static void _free_binary_table(void);
static void _set_binary_table(unsigned row, unsigned field);
static char*** bintbl = NULL;
extern db_param_t _db_params;
int db_connect()
{
GString *cs = g_string_new("");
/* Warn if both the host= and sqlsocket= parameters are defined.
* Prefer just the socket if given. */
if (strlen(_db_params.sock) && strlen(_db_params.host)
&& strncmp(_db_params.host, "localhost", FIELDSIZE != 0)) {
TRACE(TRACE_WARNING, "PostgreSQL socket and a hostname other "
"than localhost have both been defined. The socket "
"will be used and the hostname will be ignored.");
g_string_append_printf(cs, "host='%s'", _db_params.sock);
} else if (strlen(_db_params.sock)) {
g_string_append_printf(cs, "host='%s'", _db_params.sock);
} else {
g_string_append_printf(cs, "host='%s'", _db_params.host);
}
/* Add the username and password. */
g_string_append_printf(cs,
" user='%s' password='%s' dbname='%s'",
_db_params.user, _db_params.pass, _db_params.db);
/* Finally the port, if given. */
if (_db_params.port != 0)
g_string_append_printf(cs, " port='%d'", _db_params.port);
conn = PQconnectdb(cs->str);
g_string_free(cs, TRUE);
if (PQstatus(conn) == CONNECTION_BAD) {
TRACE(TRACE_ERROR, "PQconnectdb failed: %s", PQerrorMessage(conn));
return -1;
}
return 0;
}
int db_check_connection() {
if (!conn) {
/* There seem to be some circumstances which cause
* db_check_connection to be called before db_connect. */
TRACE(TRACE_ERROR, "connection with database invalid, retrying");
return db_connect();
}
if (PQstatus(conn) == CONNECTION_BAD) {
PQreset(conn);
if (PQstatus(conn) == CONNECTION_BAD) {
TRACE(TRACE_ERROR, "connection with database gone bad");
return -1;
}
}
return 0;
}
int db_disconnect()
{
if (res)
db_free_result();
PQfinish(conn);
conn = NULL;
return 0;
}
unsigned db_num_rows()
{
int num_rows;
if (!res)
return 0;
num_rows = PQntuples(res);
if (num_rows < 0)
return 0;
else
return (unsigned) num_rows;
}
unsigned db_num_fields()
{
int num_fields;
if (!res)
return 0;
num_fields = PQnfields(res);
if (num_fields < 0)
return 0;
else
return (unsigned) num_fields;
}
void db_free_result()
{
_free_binary_table();
if (res != NULL)
PQclear(res);
res = NULL;
}
static void _create_binary_table(void){
unsigned rows, fields, i;
rows = db_num_rows(); fields = db_num_fields();
if(!bintbl){
bintbl = (char***)g_malloc(sizeof(char**) * rows);
memset(bintbl, 0, sizeof(char**) * rows);
for(i = 0; i < rows; i++){
*(bintbl + i) = (char**)g_malloc(sizeof(char*) * fields);
memset(*(bintbl + i), 0, sizeof(char*) * fields);
}
}
}
static void _free_binary_table(void){
unsigned rows, fields, i, j;
rows = db_num_rows(); fields = db_num_fields();
if(bintbl){
for(i = 0; i < rows; i++){
for(j = 0; j < fields; j++)
if(bintbl[i][j])
g_free(bintbl[i][j]);
g_free(bintbl[i]);
}
g_free(bintbl);
bintbl = NULL;
}
}
static void _set_binary_table(unsigned row, unsigned field){
unsigned char* tmp;
size_t result_size;
if(!bintbl[row][field]){
tmp = PQunescapeBytea((const unsigned char *)PQgetvalue(res, row, field), &result_size);
bintbl[row][field] = (char*)g_malloc(result_size + 1);
memcpy(bintbl[row][field], tmp, result_size);
PQfreemem(tmp); tmp = NULL;
bintbl[row][field][result_size] = '\0';
}
}
const char *db_get_result(unsigned row, unsigned field)
{
if (!res) {
TRACE(TRACE_WARNING, "result set is NULL");
return NULL;
}
if ((row > db_num_rows()) || (field > db_num_fields())) {
TRACE(TRACE_WARNING, "row = %u or field = %u out of range", row, field);
return NULL;
}
if(PQftype(res, field) == BYTEAOID){
_create_binary_table();
_set_binary_table(row, field);
return bintbl[row][field];
}
return PQgetvalue(res, row, field);
}
/* get the result of the RETURNING clause added
* by way of db_returning() */
u64_t db_insert_result(const char *sequence_identifier)
{
u64_t insert_result;
if (db_num_rows() == 0) {
db_free_result();
return 0;
}
insert_result = strtoull(db_get_result(0, 0), NULL, 10);
db_free_result();
return insert_result;
}
int db_query(const char *q)
{
int PQresultStatusVar;
db_free_result();
g_return_val_if_fail(q != NULL,DM_EQUERY);
if (db_check_connection())
return DM_EQUERY;
TRACE(TRACE_DEBUG, "[%s]", q);
if (! (res = PQexec(conn, q)))
return DM_EQUERY;
PQresultStatusVar = PQresultStatus(res);
if (PQresultStatusVar != PGRES_COMMAND_OK && PQresultStatusVar != PGRES_TUPLES_OK) {
TRACE(TRACE_ERROR, "query failed [%s] : [%s]\n", q, PQresultErrorMessage(res));
db_free_result();
return DM_EQUERY;
}
return 0;
}
unsigned long db_escape_string(char *to,
const char *from, unsigned long length)
{
assert(from);
return PQescapeString(to, from, length);
}
unsigned long db_escape_binary(char *to,
const char *from, unsigned long length)
{
size_t to_length;
unsigned char *esc_to;
esc_to = PQescapeBytea((const unsigned char *)from, length, &to_length);
strncpy(to, (const char *)esc_to, to_length);
PQfreemem(esc_to);
return (unsigned long)(to_length - 1);
}
int db_do_cleanup(const char **tables, int num_tables)
{
int result = 0;
int i;
char the_query[DEF_QUERYSIZE];
for (i = 0; i < num_tables; i++) {
snprintf(the_query, DEF_QUERYSIZE, "VACUUM %s%s", _db_params.pfx,tables[i]);
if (db_query(the_query) == -1) {
TRACE(TRACE_ERROR, "error vacuuming table [%s%s]",
_db_params.pfx,tables[i]);
result = -1;
}
}
return result;
}
u64_t db_get_length(unsigned row, unsigned field)
{
if (!res) {
TRACE(TRACE_WARNING, "result set is NULL");
return -1;
}
if ((row >= db_num_rows()) || (field >= db_num_fields())) {
TRACE(TRACE_ERROR, "row = %u or field = %u out of range", row, field);
return -1;
}
if(PQftype(res, field) == BYTEAOID){
_create_binary_table();
_set_binary_table(row, field);
return strlen(bintbl[row][field]);
}
return PQgetlength(res, row, field);
}
u64_t db_get_affected_rows()
{
char *s;
if (! res) return 0;
if ((s = PQcmdTuples(res)) != NULL)
return strtoull(s, NULL, 10);
return 0;
}
void *db_get_result_set()
{
return (void *) res;
}
void db_set_result_set(void *the_result_set)
{
res = (PGresult *) the_result_set;
}
char *db_returning(char *query)
{
unsigned bufferlen = 10 + strlen(query) + 1;
char *buffer = g_new0(char, bufferlen);
snprintf(buffer, bufferlen,
"RETURNING %s", query);
return buffer;
}
|