forked from PocketRent/hhvm-pgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdo_pgsql_connection.cpp
435 lines (359 loc) · 13.8 KB
/
pdo_pgsql_connection.cpp
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
#include "pdo_pgsql_connection.h"
#include "pdo_pgsql_statement.h"
#include "pdo_pgsql_resource.h"
#include "pdo_pgsql.h"
#include "hphp/runtime/ext/stream/ext_stream.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#undef PACKAGE_VERSION // pg_config defines it
#include "pg_config.h" // needed for PG_VERSION
#define HANDLE_ERROR(stmt, res) handleError(stmt, sqlstate(res), res.errorMessage())
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
/* For the convenience of drivers, this function will parse a data source
* string, of the form "name=value; name2=value2" and populate variables
* according to the data you pass in and array of pdo_data_src_parser structures */
struct pdo_data_src_parser {
const char *optname;
char *optval;
int freeme;
};
static int php_pdo_parse_data_source(const char *data_source,
int data_source_len,
struct pdo_data_src_parser *parsed,
int nparams) {
int i, j;
int valstart = -1;
int delim = -1;
int optstart = 0;
int nlen;
int n_matches = 0;
i = 0;
while (i < data_source_len) {
/* looking for NAME= */
if (data_source[i] == '\0') {
break;
}
if (data_source[i] != '=') {
++i;
continue;
}
valstart = ++i;
/* now we're looking for VALUE; or just VALUE<NUL> */
delim = -1;
while (i < data_source_len) {
if (data_source[i] == '\0' ||
data_source[i] == ' ' ||
data_source[i] == ';') {
delim = i++;
break;
}
++i;
}
if (delim == -1) {
delim = i;
}
/* find the entry in the array */
nlen = valstart - optstart - 1;
for (j = 0; j < nparams; j++) {
if (0 == strncmp(data_source + optstart, parsed[j].optname, nlen) &&
parsed[j].optname[nlen] == '\0') {
/* got a match */
if (parsed[j].freeme) {
free(parsed[j].optval);
}
parsed[j].optval = strndup(data_source + valstart, delim - valstart);
parsed[j].freeme = 1;
++n_matches;
break;
}
}
while (i < data_source_len && isspace(data_source[i])) {
i++;
}
optstart = i;
}
return n_matches;
}
namespace HPHP {
PDOPgSqlConnection::PDOPgSqlConnection() : m_server(nullptr), pgoid(InvalidOid) {
}
PDOPgSqlConnection::~PDOPgSqlConnection(){
if(m_server){
delete m_server;
}
}
bool PDOPgSqlConnection::create(const Array &options){
long connect_timeout = pdo_attr_lval(options, PDO_ATTR_TIMEOUT, 30);
struct pdo_data_src_parser vars[] = {
{ "host", "localhost", 0 },
{ "port", "5432", 0 },
{ "dbname", "", 0 },
{ "user", nullptr, 0 },
{ "password", nullptr, 0 }
};
php_pdo_parse_data_source(data_source.data(), data_source.size(), vars, 5);
std::stringstream conninfo;
conninfo << "host='";
std::string host(vars[0].optval);
ReplaceStringInPlace(host, "\\", "\\\\");
ReplaceStringInPlace(host, "'", "\\'");
conninfo << host << "' port='";
std::string port(vars[1].optval);
ReplaceStringInPlace(port, "\\", "\\\\");
ReplaceStringInPlace(port, "'", "\\'");
conninfo << port << "' dbname='";
std::string dbname(vars[2].optval);
ReplaceStringInPlace(dbname, "\\", "\\\\");
ReplaceStringInPlace(dbname, "'", "\\'");
conninfo << dbname << "' password='";
std::string password(vars[4].optval ? vars[4].optval : this->password);
ReplaceStringInPlace(password, "\\", "\\\\");
ReplaceStringInPlace(password, "'", "\\'");
conninfo << password << "' user='";
std::string username(vars[3].optval ? vars[3].optval : this->username);
ReplaceStringInPlace(username, "\\", "\\\\");
ReplaceStringInPlace(username, "'", "\\'");
conninfo << username << "'";
conninfo << " connect_timeout=" << connect_timeout;
m_server = new PQ::Connection(conninfo.str());
if(m_server->status() == CONNECTION_OK){
return true;
} else {
handleError(nullptr, PHP_PDO_PGSQL_CONNECTION_FAILURE_SQLSTATE, m_server->errorMessage());
return false;
}
}
bool PDOPgSqlConnection::closer(){
if(m_server){
delete m_server;
m_server = nullptr;
}
return false;
}
int64_t PDOPgSqlConnection::doer(const String& sql){
testConnection();
const char* query = sql.data();
PQ::Result res = m_server->exec(query);
if(!res){
// I think this error should be handled in a different way perhaps?
handleError(nullptr, "XX000", "Invalid result data");
return -1;
}
ExecStatusType status = m_lastExec = res.status();
int64_t ret;
if(status == PGRES_COMMAND_OK){
ret = (int64_t)res.cmdTuples();
} else if(status == PGRES_TUPLES_OK) {
ret = 0L;
} else {
HANDLE_ERROR(nullptr, res);
return -1L;
}
this->pgoid = res.oidValue();
return ret;
}
bool PDOPgSqlConnection::transactionCommand(const char* command){
testConnection();
PQ::Result res = m_server->exec(command);
if(!res){
// I think this error should be handled in a different way perhaps?
handleError(nullptr, "XX000", "Invalid result data");
return -1;
}
ExecStatusType status = m_lastExec = res.status();
if(status == PGRES_COMMAND_OK){
return true;
}
HANDLE_ERROR(nullptr, res);
return false;
}
bool PDOPgSqlConnection::begin(){
return transactionCommand("BEGIN");
}
bool PDOPgSqlConnection::rollback(){
return transactionCommand("ROLLBACK");
}
bool PDOPgSqlConnection::commit(){
return transactionCommand("COMMIT");
}
void PDOPgSqlConnection::testConnection(){
if(!m_server){
handleError(nullptr, "08003", nullptr);
}
}
bool PDOPgSqlConnection::checkLiveness(){
if(!m_server){
return false;
}
return m_server->status() == CONNECTION_OK;
}
const char* PDOPgSqlConnection::sqlstate(PQ::Result& result){
const char* sqlstate = result.errorField(PG_DIAG_SQLSTATE);
// Handle case where libpq doesn't return an SQLSTATE (eg. server connection lost)
if(sqlstate == nullptr){
sqlstate = "XX000";
}
return sqlstate;
}
bool PDOPgSqlConnection::quoter(const String& input, String "ed, PDOParamType paramtype){
switch(paramtype){
case PDO_PARAM_LOB:
quoted = m_server->escapeByteA(input.data(), input.length());
return true;
break;
default:
// http://www.postgresql.org/message-id/[email protected] + space for the two surrounding quotes
std::unique_ptr<char[]> buffer(new char[input.length()*2+3]);
buffer[0] = '\'';
int error;
size_t written = m_server->escapeString(buffer.get()+1, input.c_str(), input.length()*2+1, &error);
if(error){
return false;
}
buffer.get()[1+written] = '\'';
buffer.get()[2+written] = '\0';
quoted = String(buffer.get(), CopyString);
break;
}
return true;
}
String PDOPgSqlConnection::lastId(const char *name){
if (name == nullptr || strlen(name) == 0){
// This branch of code doesn't seem to ever do anything useful
// however it does pretty much the same as the zend implementation
// and that doesn't seem to provide anything useful either
if(this->pgoid == InvalidOid){
return empty_string();
}
return String((long)this->pgoid);
} else {
const char *values[1];
values[0] = name;
PQ::Result res = m_server->exec("SELECT CURRVAL($1)", 1, values);
ExecStatusType status = res.status();
if(res && (status == PGRES_TUPLES_OK)){
return String(res.getValue(0, 0), CopyString);
} else {
HANDLE_ERROR(nullptr, res);
return empty_string();
}
}
}
int PDOPgSqlConnection::getAttribute(int64_t attr, Variant &value){
switch(attr){
case PDO_ATTR_CLIENT_VERSION:
value = String(PG_VERSION);
break;
case PDO_ATTR_SERVER_VERSION:
if(m_server->protocolVersion() >= 3){ // Postgres 7.4 or later
value = String(m_server->parameterStatus("server_version"), CopyString);
} else {
PQ::Result res = m_server->exec("SELECT VERSION()");
if(res && res.status() == PGRES_TUPLES_OK){
value = String((char *)res.getValue(0, 0), CopyString);
}
}
break;
case PDO_ATTR_CONNECTION_STATUS:
switch(m_server->status()){
case CONNECTION_STARTED:
value = String("Waiting for connection to be made.", CopyString);
break;
case CONNECTION_MADE:
case CONNECTION_OK:
value = String("Connection OK; waiting to send.", CopyString);
break;
case CONNECTION_AWAITING_RESPONSE:
value = String("Waiting for a response from the server.", CopyString);
break;
case CONNECTION_AUTH_OK:
value = String("Received authentication; waiting for backend start-up to finish.", CopyString);
break;
#ifdef CONNECTION_SSL_STARTUP
case CONNECTION_SSL_STARTUP:
value = String("Negotiating SSL encryption.", CopyString);
break;
#endif
case CONNECTION_SETENV:
value = String("Negotiating environment-driven parameter settings.", CopyString);
break;
case CONNECTION_BAD:
default:
value = String("Bad connection.", CopyString);
break;
}
break;
case PDO_ATTR_SERVER_INFO: {
int spid = m_server->backendPID();
std::stringstream result;
result << "PID: " << spid << "; Client Encoding: " << m_server->parameterStatus("client_encoding");
result << "; Is Superusser: " << m_server->parameterStatus("is_superuser") << "; Session Authorization: ";
result << m_server->parameterStatus("session_authorization") << "; Date Style: " << m_server->parameterStatus("DateStyle");
value = String(result.str());
}
break;
default:
return 0;
}
return 1;
}
bool PDOPgSqlConnection::fetchErr(PDOStatement* stmt, Array &info){
if(stmt == nullptr){
info.append(m_lastExec == InvalidOid ? Variant(Variant::NullInit()) : Variant(m_lastExec));
info.append(err_msg.empty() ? Variant(Variant::NullInit()) : Variant(err_msg));
return true;
} else {
PDOPgSqlStatement* s = static_cast<PDOPgSqlStatement*>(stmt);
auto status = s->m_result.status();
auto emsg = s->err_msg;
info.append(status == InvalidOid ? Variant(Variant::NullInit()) : Variant(status));
info.append(emsg.empty() ? Variant(Variant::NullInit()) : Variant(emsg));
return true;
}
}
bool PDOPgSqlConnection::setAttribute(int64_t attr, const Variant &value){
switch(attr){
case PDO_ATTR_EMULATE_PREPARES:
m_emulate_prepare = value.toBoolean();
return true;
default:
return false;
}
}
bool PDOPgSqlConnection::support(SupportedMethod method){
return true;
}
bool PDOPgSqlConnection::preparer(const String& sql, sp_PDOStatement *stmt, const Variant& options) {
auto rsrc = newres<PDOPgSqlResource>(
std::dynamic_pointer_cast<PDOPgSqlConnection>(shared_from_this()));
auto s = newres<PDOPgSqlStatement>(rsrc, m_server);
*stmt = s;
if(s->create(sql, options.toArray())){
alloc_own_columns = 1;
return true;
}
stmt->reset();
strcpy(error_code, s->error_code);
return false;
}
void PDOPgSqlConnection::handleError(PDOPgSqlStatement* stmt, const char* sqlState, const char* msg){
PDOErrorType* err = &error_code;
std::string* emsg = &err_msg;
if(stmt != nullptr){
err = &stmt->error_code;
emsg = &stmt->err_msg;
}
strncpy(*err, sqlState, 6);
(*err)[5] = '\0';
*emsg = std::string(msg);
}
String PDOPgSqlConnection::pgsqlLOBCreate(){
return String("ROFL LOB");
}
}