-
Notifications
You must be signed in to change notification settings - Fork 22
/
gksql_pgsql.cxx
444 lines (379 loc) · 12 KB
/
gksql_pgsql.cxx
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
* gksql_pgsql.cxx
*
* PostgreSQL driver module for GnuGk
*
* Copyright (c) 2004, Michal Zygmuntowicz
* Copyright (c) 2006-2014, Jan Willamowius
*
* This work is published under the GNU Public License version 2 (GPLv2)
* see file COPYING for details.
* We also explicitly grant the right to link this code
* with the OpenH323/H323Plus and OpenSSL library.
*
*/
#include "config.h"
#if HAS_PGSQL
#include <ptlib.h>
#include <libpq-fe.h>
#include "gksql.h"
static PDynaLink g_sharedLibrary;
static void (*g_PQclear)(PGresult *res) = NULL;
static char * (*g_PQcmdTuples)(PGresult *res) = NULL;
static char * (*g_PQerrorMessage)(const PGconn *conn) = NULL;
static size_t (*g_PQescapeStringConn)(PGconn *conn, char *to, const char *from, size_t length, int *error) = NULL;
static PGresult * (*g_PQexec)(PGconn *conn, const char *query) = NULL;
static void (*g_PQfinish)(PGconn *conn) = NULL;
static char * (*g_PQfname)(const PGresult *res, int field_num) = NULL;
static int (*g_PQgetlength)(const PGresult *res, int tup_num, int field_num) = NULL;
static char * (*g_PQgetvalue)(const PGresult *res, int tup_num, int field_num) = NULL;
static int (*g_PQnfields)(const PGresult *res) = NULL;
static int (*g_PQntuples)(const PGresult *res) = NULL;
static char * (*g_PQresultErrorMessage)(const PGresult *res) = NULL;
static ExecStatusType (*g_PQresultStatus)(const PGresult *res) = NULL;
static PGconn * (*g_PQsetdbLogin)(const char *pghost, const char *pgport,
const char *pgoptions, const char *pgtty,
const char *dbName,
const char *login, const char *pwd) = NULL;
static ConnStatusType (*g_PQstatus)(const PGconn *conn) = NULL;
/** Class that encapsulates SQL query result for PostgreSQL backend.
It does not provide any multithread safety, so should be accessed
from a single thread at time.
*/
class GkPgSQLResult : public GkSQLResult
{
public:
/// Build the result from SELECT type query
GkPgSQLResult(
/// SELECT type query result
PGresult* selectResult
);
/// Build the result from INSERT, DELETE or UPDATE query
GkPgSQLResult(
/// number of rows affected by the query
long numRowsAffected
);
/// Build the empty result and store query execution error information
GkPgSQLResult(
/// PostgreSQL specific error code
unsigned int errorCode,
/// PostgreSQL specific error message text
const char* errorMsg
);
virtual ~GkPgSQLResult();
/** @return
Backend specific error message, if the query failed.
*/
virtual PString GetErrorMessage();
/** @return
Backend specific error code, if the query failed.
*/
virtual long GetErrorCode();
/** Fetch a single row from the result set. After each row is fetched,
cursor position is moved to a next row.
@return
True if the row has been fetched, false if no more rows are available.
*/
virtual bool FetchRow(
/// array to be filled with string representations of the row fields
PStringArray& result
);
virtual bool FetchRow(
/// array to be filled with string representations of the row fields
ResultRow& result
);
private:
GkPgSQLResult();
GkPgSQLResult(const GkPgSQLResult&);
GkPgSQLResult& operator=(const GkPgSQLResult&);
protected:
/// query result for SELECT type queries, NULL otherwise
PGresult* m_sqlResult;
/// the most recent row returned by fetch operation
int m_sqlRow;
/// PgSQL specific error code (if the query failed)
unsigned int m_errorCode;
/// PgSQL specific error message text (if the query failed)
PString m_errorMessage;
};
/// PostgreSQL backend connection implementation.
class GkPgSQLConnection : public GkSQLConnection
{
public:
/// Build a new PgSQL connection object
GkPgSQLConnection(
/// name to use in the log
const char* name = "PostgreSQL"
);
virtual ~GkPgSQLConnection();
protected:
class PgSQLConnWrapper : public GkSQLConnection::SQLConnWrapper
{
public:
PgSQLConnWrapper(
/// unique identifier for this connection
int id,
/// host:port this connection is made to
const PString& host,
/// PostgreSQL connection object
PGconn* conn
) : SQLConnWrapper(id, host), m_conn(conn) {}
virtual ~PgSQLConnWrapper();
private:
PgSQLConnWrapper();
PgSQLConnWrapper(const PgSQLConnWrapper&);
PgSQLConnWrapper& operator=(const PgSQLConnWrapper&);
public:
PGconn* m_conn;
};
/** Create a new SQL connection using parameters stored in this object.
When the connection is to be closed, the object is simply deleted
using delete operator.
@return
NULL if database connection could not be established
or an object of PgSQLConnWrapper class.
*/
virtual SQLConnPtr CreateNewConnection(
/// unique identifier for this connection
int id
);
/** Execute the query using specified SQL connection.
@return
Query execution result.
*/
virtual GkSQLResult* ExecuteQuery(
/// SQL connection to use for query execution
SQLConnPtr conn,
/// query string
const char* queryStr,
/// maximum time (ms) for the query execution, -1 means infinite
long timeout = -1
);
/** Escape any special characters in the string, so it can be used in a SQL query.
@return
Escaped string.
*/
virtual PString EscapeString(
/// SQL connection to get escaping parameters from
SQLConnPtr conn,
/// string to be escaped
const char* str
);
private:
GkPgSQLConnection(const GkPgSQLConnection&);
GkPgSQLConnection& operator=(const GkPgSQLConnection&);
};
GkPgSQLResult::GkPgSQLResult(
/// SELECT type query result
PGresult* selectResult
)
: GkSQLResult(false), m_sqlResult(selectResult), m_sqlRow(-1),
m_errorCode(0)
{
if (m_sqlResult) {
m_numRows = (*g_PQntuples)(m_sqlResult);
m_numFields = (*g_PQnfields)(m_sqlResult);
} else
m_queryError = true;
}
GkPgSQLResult::GkPgSQLResult(
/// number of rows affected by the query
long numRowsAffected
)
: GkSQLResult(false), m_sqlResult(NULL), m_sqlRow(-1),
m_errorCode(0)
{
m_numRows = numRowsAffected;
}
GkPgSQLResult::GkPgSQLResult(
/// PostgreSQL specific error code
unsigned int errorCode,
/// PostgreSQL specific error message text
const char* errorMsg
)
: GkSQLResult(true), m_sqlResult(NULL), m_sqlRow(-1),
m_errorCode(errorCode), m_errorMessage(errorMsg)
{
}
GkPgSQLResult::~GkPgSQLResult()
{
if (m_sqlResult)
(*g_PQclear)(m_sqlResult);
}
PString GkPgSQLResult::GetErrorMessage()
{
return m_errorMessage;
}
long GkPgSQLResult::GetErrorCode()
{
return m_errorCode;
}
bool GkPgSQLResult::FetchRow(
/// array to be filled with string representations of the row fields
PStringArray & result
)
{
if (m_sqlResult == NULL || m_numRows <= 0)
return false;
if (m_sqlRow < 0)
m_sqlRow = 0;
if (m_sqlRow >= m_numRows)
return false;
result.SetSize(m_numFields);
for (PINDEX i = 0; i < m_numFields; i++)
result[i] = PString(
(*g_PQgetvalue)(m_sqlResult, m_sqlRow, i),
(*g_PQgetlength)(m_sqlResult, m_sqlRow, i)
);
m_sqlRow++;
return true;
}
bool GkPgSQLResult::FetchRow(
/// array to be filled with string representations of the row fields
ResultRow & result
)
{
if (m_sqlResult == NULL || m_numRows <= 0)
return false;
if (m_sqlRow < 0)
m_sqlRow = 0;
if (m_sqlRow >= m_numRows)
return false;
result.resize(m_numFields);
for (PINDEX i = 0; i < m_numFields; i++) {
result[i].first = PString(
(*g_PQgetvalue)(m_sqlResult, m_sqlRow, i),
(*g_PQgetlength)(m_sqlResult, m_sqlRow, i)
);
result[i].second = (*g_PQfname)(m_sqlResult, i);
}
m_sqlRow++;
return true;
}
GkPgSQLConnection::GkPgSQLConnection(
/// name to use in the log
const char* name
) : GkSQLConnection(name)
{
}
GkPgSQLConnection::~GkPgSQLConnection()
{
}
GkPgSQLConnection::PgSQLConnWrapper::~PgSQLConnWrapper()
{
(*g_PQfinish)(m_conn);
}
GkSQLConnection::SQLConnPtr GkPgSQLConnection::CreateNewConnection(
/// unique identifier for this connection
int id
)
{
if (!g_sharedLibrary.IsLoaded()) {
if (m_library.IsEmpty()) {
m_library = "libpq" + g_sharedLibrary.GetExtension();
}
if (!g_sharedLibrary.Open(m_library)) {
PTRACE (1, GetName() << "\tCan't load library " << m_library);
return NULL;
}
if (!g_sharedLibrary.GetFunction("PQclear", (PDynaLink::Function &)g_PQclear)
|| !g_sharedLibrary.GetFunction("PQcmdTuples", (PDynaLink::Function &)g_PQcmdTuples)
|| !g_sharedLibrary.GetFunction("PQerrorMessage", (PDynaLink::Function &)g_PQerrorMessage)
|| !g_sharedLibrary.GetFunction("PQescapeStringConn", (PDynaLink::Function &)g_PQescapeStringConn)
|| !g_sharedLibrary.GetFunction("PQexec", (PDynaLink::Function &)g_PQexec)
|| !g_sharedLibrary.GetFunction("PQfinish", (PDynaLink::Function &)g_PQfinish)
|| !g_sharedLibrary.GetFunction("PQfname", (PDynaLink::Function &)g_PQfname)
|| !g_sharedLibrary.GetFunction("PQgetlength", (PDynaLink::Function &)g_PQgetlength)
|| !g_sharedLibrary.GetFunction("PQgetvalue", (PDynaLink::Function &)g_PQgetvalue)
|| !g_sharedLibrary.GetFunction("PQnfields", (PDynaLink::Function &)g_PQnfields)
|| !g_sharedLibrary.GetFunction("PQntuples", (PDynaLink::Function &)g_PQntuples)
|| !g_sharedLibrary.GetFunction("PQresultErrorMessage", (PDynaLink::Function &)g_PQresultErrorMessage)
|| !g_sharedLibrary.GetFunction("PQresultStatus", (PDynaLink::Function &)g_PQresultStatus)
|| !g_sharedLibrary.GetFunction("PQsetdbLogin", (PDynaLink::Function &)g_PQsetdbLogin)
|| !g_sharedLibrary.GetFunction("PQstatus", (PDynaLink::Function &)g_PQstatus)
) {
#ifdef hasDynaLinkGetLastError
PTRACE (1, GetName() << "\tFailed to load shared database library: " << g_sharedLibrary.GetLastError());
#else
PTRACE (1, GetName() << "\tFailed to load shared database library: unknown error");
#endif
g_sharedLibrary.Close();
SNMP_TRAP(5, SNMPError, Database, GetName() + " DLL load error");
return NULL;
}
}
PGconn* conn;
const PString portStr(m_port);
// const PString optionsStr("connect_timeout=10000"); // TODO: use m_connectTimeout
if ((conn = (*g_PQsetdbLogin)(m_host,
m_port ? (const char*)portStr : (const char*)NULL,
NULL /*(const char*)optionsStr*/, NULL,
m_database, m_username,
m_password.IsEmpty() ? (const char*)NULL : (const char*)m_password
)) && (*g_PQstatus)(conn) == CONNECTION_OK) {
PTRACE(5, GetName() << "\tPgSQL connection to " << m_username << '@' << m_host
<< '[' << m_database << "] established successfully");
return new PgSQLConnWrapper(id, m_host, conn);
} else {
PTRACE(2, GetName() << "\tPgSQL connection to " << m_username << '@' << m_host
<< '[' << m_database << "] failed (PQsetdbLogin failed): "
<< (conn ? (*g_PQerrorMessage)(conn) : ""));
SNMP_TRAP(5, SNMPError, Database, GetName() + " connection failed")
if (conn)
(*g_PQfinish)(conn);
}
return NULL;
}
GkSQLResult* GkPgSQLConnection::ExecuteQuery(
/// SQL connection to use for query execution
GkSQLConnection::SQLConnPtr conn,
/// query string
const char* queryStr,
/// maximum time (ms) for the query execution, -1 means infinite
long /*timeout*/
)
{
PGconn * pgsqlconn = ((PgSQLConnWrapper*)conn)->m_conn;
PGresult* result = (*g_PQexec)(pgsqlconn, queryStr);
if (result == NULL) {
GkSQLResult * sqlResult = new GkPgSQLResult(PGRES_FATAL_ERROR, (*g_PQerrorMessage)(pgsqlconn));
Disconnect();
return sqlResult;
}
ExecStatusType resultInfo = (*g_PQresultStatus)(result);
switch (resultInfo)
{
case PGRES_COMMAND_OK:
return new GkPgSQLResult(
(*g_PQcmdTuples)(result) ? atoi((*g_PQcmdTuples)(result)) : 0
);
case PGRES_TUPLES_OK:
return new GkPgSQLResult(result);
default:
GkSQLResult * sqlResult = new GkPgSQLResult(resultInfo, (*g_PQresultErrorMessage)(result));
Disconnect();
return sqlResult;
}
}
PString GkPgSQLConnection::EscapeString(
/// SQL connection to get escaping parameters from
SQLConnPtr conn,
/// string to be escaped
const char* str
)
{
PString escapedStr;
const size_t numChars = str ? strlen(str) : 0;
int err = 0;
if (numChars) {
char * buf = (char *)malloc(numChars * 2 + 1);
(*g_PQescapeStringConn) (((PgSQLConnWrapper*)conn)->m_conn, buf, str, numChars, &err);
escapedStr = buf;
free(buf);
}
return escapedStr;
}
namespace {
GkSQLCreator<GkPgSQLConnection> PgSQLCreator("PostgreSQL");
}
#endif /* HAS_PGSQL */