1 /*
2 +----------------------------------------------------------------------+
3 | Copyright (c) The PHP Group |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.01 of the PHP license, |
6 | that is bundled with this package in the file LICENSE, and is |
7 | available through the world-wide-web at the following url: |
8 | https://www.php.net/license/3_01.txt |
9 | If you did not receive a copy of the PHP license and are unable to |
10 | obtain it through the world-wide-web, please send a note to |
11 | license@php.net so we can mail you a copy immediately. |
12 +----------------------------------------------------------------------+
13 | Authors: Edin Kadribasic <edink@emini.dk> |
14 | Ilia Alshanestsky <ilia@prohost.org> |
15 | Wez Furlong <wez@php.net> |
16 +----------------------------------------------------------------------+
17 */
18
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
22
23 #include "php.h"
24 #include "php_ini.h"
25 #include "ext/standard/php_string.h" /* For php_addcslashes_str() in _pdo_pgsql_escape_credentials() */
26 #include "main/php_network.h"
27 #include "ext/pdo/php_pdo.h"
28 #include "ext/pdo/php_pdo_driver.h"
29 #include "ext/pdo/php_pdo_error.h"
30 #include "ext/standard/file.h"
31 #include "php_pdo_pgsql.h"
32 #include "php_pdo_pgsql_int.h"
33 #include "zend_exceptions.h"
34 #include "zend_smart_str.h"
35 #include "pgsql_driver_arginfo.h"
36
37 static bool pgsql_handle_in_transaction(pdo_dbh_t *dbh);
38
_pdo_pgsql_trim_message(const char * message,int persistent)39 static char * _pdo_pgsql_trim_message(const char *message, int persistent)
40 {
41 size_t i = strlen(message)-1;
42 char *tmp;
43
44 if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
45 --i;
46 }
47 while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
48 --i;
49 }
50 ++i;
51 tmp = pemalloc(i + 1, persistent);
52 memcpy(tmp, message, i);
53 tmp[i] = '\0';
54
55 return tmp;
56 }
57
_pdo_pgsql_escape_credentials(char * str)58 static zend_string* _pdo_pgsql_escape_credentials(char *str)
59 {
60 if (str) {
61 return php_addcslashes_str(str, strlen(str), "\\'", sizeof("\\'"));
62 }
63
64 return NULL;
65 }
66
_pdo_pgsql_error(pdo_dbh_t * dbh,pdo_stmt_t * stmt,int errcode,const char * sqlstate,const char * msg,const char * file,int line)67 int _pdo_pgsql_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, int errcode, const char *sqlstate, const char *msg, const char *file, int line) /* {{{ */
68 {
69 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
70 pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
71 pdo_pgsql_error_info *einfo = &H->einfo;
72 char *errmsg = PQerrorMessage(H->server);
73
74 einfo->errcode = errcode;
75 einfo->file = file;
76 einfo->line = line;
77
78 if (einfo->errmsg) {
79 pefree(einfo->errmsg, dbh->is_persistent);
80 einfo->errmsg = NULL;
81 }
82
83 if (sqlstate == NULL || strlen(sqlstate) >= sizeof(pdo_error_type)) {
84 strcpy(*pdo_err, "HY000");
85 }
86 else {
87 strcpy(*pdo_err, sqlstate);
88 }
89
90 if (msg) {
91 einfo->errmsg = pestrdup(msg, dbh->is_persistent);
92 }
93 else if (errmsg) {
94 einfo->errmsg = _pdo_pgsql_trim_message(errmsg, dbh->is_persistent);
95 }
96
97 if (!dbh->methods) {
98 pdo_throw_exception(einfo->errcode, einfo->errmsg, pdo_err);
99 }
100
101 return errcode;
102 }
103 /* }}} */
104
_pdo_pgsql_notice(void * context,const char * message)105 static void _pdo_pgsql_notice(void *context, const char *message) /* {{{ */
106 {
107 pdo_dbh_t * dbh = (pdo_dbh_t *)context;
108 zend_fcall_info_cache *fc = ((pdo_pgsql_db_handle *)dbh->driver_data)->notice_callback;
109 if (fc) {
110 zval zarg;
111 ZVAL_STRING(&zarg, message);
112 zend_call_known_fcc(fc, NULL, 1, &zarg, NULL);
113 zval_ptr_dtor_str(&zarg);
114 }
115 }
116 /* }}} */
117
pdo_pgsql_fetch_error_func(pdo_dbh_t * dbh,pdo_stmt_t * stmt,zval * info)118 static void pdo_pgsql_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info) /* {{{ */
119 {
120 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
121 pdo_pgsql_error_info *einfo = &H->einfo;
122
123 if (einfo->errcode) {
124 add_next_index_long(info, einfo->errcode);
125 } else {
126 /* Add null to respect expected info array structure */
127 add_next_index_null(info);
128 }
129 if (einfo->errmsg) {
130 add_next_index_string(info, einfo->errmsg);
131 }
132 }
133 /* }}} */
134
pdo_pgsql_cleanup_notice_callback(pdo_pgsql_db_handle * H)135 void pdo_pgsql_cleanup_notice_callback(pdo_pgsql_db_handle *H) /* {{{ */
136 {
137 if (H->notice_callback) {
138 zend_fcc_dtor(H->notice_callback);
139 efree(H->notice_callback);
140 H->notice_callback = NULL;
141 }
142 }
143 /* }}} */
144
145 /* {{{ pdo_pgsql_create_lob_stream */
pgsql_lob_write(php_stream * stream,const char * buf,size_t count)146 static ssize_t pgsql_lob_write(php_stream *stream, const char *buf, size_t count)
147 {
148 struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
149 return lo_write(self->conn, self->lfd, (char*)buf, count);
150 }
151
pgsql_lob_read(php_stream * stream,char * buf,size_t count)152 static ssize_t pgsql_lob_read(php_stream *stream, char *buf, size_t count)
153 {
154 struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
155 return lo_read(self->conn, self->lfd, buf, count);
156 }
157
pgsql_lob_close(php_stream * stream,int close_handle)158 static int pgsql_lob_close(php_stream *stream, int close_handle)
159 {
160 struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
161 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)(Z_PDO_DBH_P(&self->dbh))->driver_data;
162
163 if (close_handle) {
164 lo_close(self->conn, self->lfd);
165 }
166 zend_hash_index_del(H->lob_streams, php_stream_get_resource_id(stream));
167 zval_ptr_dtor(&self->dbh);
168 efree(self);
169 return 0;
170 }
171
pgsql_lob_flush(php_stream * stream)172 static int pgsql_lob_flush(php_stream *stream)
173 {
174 return 0;
175 }
176
pgsql_lob_seek(php_stream * stream,zend_off_t offset,int whence,zend_off_t * newoffset)177 static int pgsql_lob_seek(php_stream *stream, zend_off_t offset, int whence,
178 zend_off_t *newoffset)
179 {
180 struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
181 #ifdef ZEND_ENABLE_ZVAL_LONG64
182 zend_off_t pos = lo_lseek64(self->conn, self->lfd, offset, whence);
183 #else
184 zend_off_t pos = lo_lseek(self->conn, self->lfd, offset, whence);
185 #endif
186 *newoffset = pos;
187 return pos >= 0 ? 0 : -1;
188 }
189
190 const php_stream_ops pdo_pgsql_lob_stream_ops = {
191 pgsql_lob_write,
192 pgsql_lob_read,
193 pgsql_lob_close,
194 pgsql_lob_flush,
195 "pdo_pgsql lob stream",
196 pgsql_lob_seek,
197 NULL,
198 NULL,
199 NULL
200 };
201
pdo_pgsql_create_lob_stream(zval * dbh,int lfd,Oid oid)202 php_stream *pdo_pgsql_create_lob_stream(zval *dbh, int lfd, Oid oid)
203 {
204 php_stream *stm;
205 struct pdo_pgsql_lob_self *self = ecalloc(1, sizeof(*self));
206 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)(Z_PDO_DBH_P(dbh))->driver_data;
207
208 ZVAL_COPY_VALUE(&self->dbh, dbh);
209 self->lfd = lfd;
210 self->oid = oid;
211 self->conn = H->server;
212
213 stm = php_stream_alloc(&pdo_pgsql_lob_stream_ops, self, 0, "r+b");
214
215 if (stm) {
216 Z_ADDREF_P(dbh);
217 zend_hash_index_add_ptr(H->lob_streams, php_stream_get_resource_id(stm), stm->res);
218 return stm;
219 }
220
221 efree(self);
222 return NULL;
223 }
224 /* }}} */
225
pdo_pgsql_close_lob_streams(pdo_dbh_t * dbh)226 void pdo_pgsql_close_lob_streams(pdo_dbh_t *dbh)
227 {
228 zend_resource *res;
229 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
230 if (H->lob_streams) {
231 ZEND_HASH_REVERSE_FOREACH_PTR(H->lob_streams, res) {
232 if (res->type >= 0) {
233 zend_list_close(res);
234 }
235 } ZEND_HASH_FOREACH_END();
236 }
237 }
238
pgsql_handle_closer(pdo_dbh_t * dbh)239 static void pgsql_handle_closer(pdo_dbh_t *dbh) /* {{{ */
240 {
241 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
242 if (H) {
243 if (H->lob_streams) {
244 pdo_pgsql_close_lob_streams(dbh);
245 zend_hash_destroy(H->lob_streams);
246 pefree(H->lob_streams, dbh->is_persistent);
247 H->lob_streams = NULL;
248 }
249 pdo_pgsql_cleanup_notice_callback(H);
250 if (H->server) {
251 PQfinish(H->server);
252 H->server = NULL;
253 }
254 if (H->einfo.errmsg) {
255 pefree(H->einfo.errmsg, dbh->is_persistent);
256 H->einfo.errmsg = NULL;
257 }
258 pefree(H, dbh->is_persistent);
259 dbh->driver_data = NULL;
260 }
261 }
262 /* }}} */
263
pgsql_handle_preparer(pdo_dbh_t * dbh,zend_string * sql,pdo_stmt_t * stmt,zval * driver_options)264 static bool pgsql_handle_preparer(pdo_dbh_t *dbh, zend_string *sql, pdo_stmt_t *stmt, zval *driver_options)
265 {
266 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
267 pdo_pgsql_stmt *S = ecalloc(1, sizeof(pdo_pgsql_stmt));
268 int scrollable;
269 int ret;
270 zend_string *nsql = NULL;
271 int emulate = 0;
272 int execute_only = 0;
273
274 S->H = H;
275 stmt->driver_data = S;
276 stmt->methods = &pgsql_stmt_methods;
277
278 scrollable = pdo_attr_lval(driver_options, PDO_ATTR_CURSOR,
279 PDO_CURSOR_FWDONLY) == PDO_CURSOR_SCROLL;
280
281 if (scrollable) {
282 if (S->cursor_name) {
283 efree(S->cursor_name);
284 }
285 spprintf(&S->cursor_name, 0, "pdo_crsr_%08x", ++H->stmt_counter);
286 emulate = 1;
287 } else if (driver_options) {
288 if (pdo_attr_lval(driver_options, PDO_ATTR_EMULATE_PREPARES, H->emulate_prepares) == 1) {
289 emulate = 1;
290 }
291 if (pdo_attr_lval(driver_options, PDO_PGSQL_ATTR_DISABLE_PREPARES, H->disable_prepares) == 1) {
292 execute_only = 1;
293 }
294 } else {
295 emulate = H->disable_native_prepares || H->emulate_prepares;
296 execute_only = H->disable_prepares;
297 }
298
299 if (emulate) {
300 stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
301 } else {
302 stmt->supports_placeholders = PDO_PLACEHOLDER_NAMED;
303 stmt->named_rewrite_template = "$%d";
304 }
305
306 ret = pdo_parse_params(stmt, sql, &nsql);
307
308 if (ret == -1) {
309 /* couldn't grok it */
310 strcpy(dbh->error_code, stmt->error_code);
311 return false;
312 } else if (ret == 1) {
313 /* query was re-written */
314 S->query = nsql;
315 } else {
316 S->query = zend_string_copy(sql);
317 }
318
319 if (!emulate && !execute_only) {
320 /* prepared query: set the query name and defer the
321 actual prepare until the first execute call */
322 spprintf(&S->stmt_name, 0, "pdo_stmt_%08x", ++H->stmt_counter);
323 }
324
325 return true;
326 }
327
pgsql_handle_doer(pdo_dbh_t * dbh,const zend_string * sql)328 static zend_long pgsql_handle_doer(pdo_dbh_t *dbh, const zend_string *sql)
329 {
330 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
331 PGresult *res;
332 zend_long ret = 1;
333 ExecStatusType qs;
334
335 bool in_trans = pgsql_handle_in_transaction(dbh);
336
337 if (!(res = PQexec(H->server, ZSTR_VAL(sql)))) {
338 /* fatal error */
339 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
340 return -1;
341 }
342 qs = PQresultStatus(res);
343 if (qs != PGRES_COMMAND_OK && qs != PGRES_TUPLES_OK) {
344 pdo_pgsql_error(dbh, qs, pdo_pgsql_sqlstate(res));
345 PQclear(res);
346 return -1;
347 }
348 H->pgoid = PQoidValue(res);
349 if (qs == PGRES_COMMAND_OK) {
350 ret = ZEND_ATOL(PQcmdTuples(res));
351 } else {
352 ret = Z_L(0);
353 }
354 PQclear(res);
355 if (in_trans && !pgsql_handle_in_transaction(dbh)) {
356 pdo_pgsql_close_lob_streams(dbh);
357 }
358
359 return ret;
360 }
361
pgsql_handle_quoter(pdo_dbh_t * dbh,const zend_string * unquoted,enum pdo_param_type paramtype)362 static zend_string* pgsql_handle_quoter(pdo_dbh_t *dbh, const zend_string *unquoted, enum pdo_param_type paramtype)
363 {
364 unsigned char *escaped;
365 char *quoted;
366 size_t quotedlen;
367 zend_string *quoted_str;
368 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
369 size_t tmp_len;
370
371 switch (paramtype) {
372 case PDO_PARAM_LOB:
373 /* escapedlen returned by PQescapeBytea() accounts for trailing 0 */
374 escaped = PQescapeByteaConn(H->server, (unsigned char *)ZSTR_VAL(unquoted), ZSTR_LEN(unquoted), &tmp_len);
375 quotedlen = tmp_len + 1;
376 quoted = emalloc(quotedlen + 1);
377 memcpy(quoted+1, escaped, quotedlen-2);
378 quoted[0] = '\'';
379 quoted[quotedlen-1] = '\'';
380 quoted[quotedlen] = '\0';
381 PQfreemem(escaped);
382 break;
383 default:
384 quoted = safe_emalloc(2, ZSTR_LEN(unquoted), 3);
385 quoted[0] = '\'';
386 quotedlen = PQescapeStringConn(H->server, quoted + 1, ZSTR_VAL(unquoted), ZSTR_LEN(unquoted), NULL);
387 quoted[quotedlen + 1] = '\'';
388 quoted[quotedlen + 2] = '\0';
389 quotedlen += 2;
390 }
391
392 quoted_str = zend_string_init(quoted, quotedlen, 0);
393 efree(quoted);
394 return quoted_str;
395 }
396
pdo_pgsql_last_insert_id(pdo_dbh_t * dbh,const zend_string * name)397 static zend_string *pdo_pgsql_last_insert_id(pdo_dbh_t *dbh, const zend_string *name)
398 {
399 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
400 zend_string *id = NULL;
401 PGresult *res;
402 ExecStatusType status;
403
404 if (name == NULL) {
405 res = PQexec(H->server, "SELECT LASTVAL()");
406 } else {
407 const char *q[1];
408 q[0] = ZSTR_VAL(name);
409
410 res = PQexecParams(H->server, "SELECT CURRVAL($1)", 1, NULL, q, NULL, NULL, 0);
411 }
412 status = PQresultStatus(res);
413
414 if (res && (status == PGRES_TUPLES_OK)) {
415 id = zend_string_init((char *)PQgetvalue(res, 0, 0), PQgetlength(res, 0, 0), 0);
416 } else {
417 pdo_pgsql_error(dbh, status, pdo_pgsql_sqlstate(res));
418 }
419
420 if (res) {
421 PQclear(res);
422 }
423
424 return id;
425 }
426
pdo_libpq_version(char * buf,size_t len)427 void pdo_libpq_version(char *buf, size_t len)
428 {
429 int version = PQlibVersion();
430 int major = version / 10000;
431 if (major >= 10) {
432 int minor = version % 10000;
433 snprintf(buf, len, "%d.%d", major, minor);
434 } else {
435 int minor = version / 100 % 100;
436 int revision = version % 100;
437 snprintf(buf, len, "%d.%d.%d", major, minor, revision);
438 }
439 }
440
pdo_pgsql_get_attribute(pdo_dbh_t * dbh,zend_long attr,zval * return_value)441 static int pdo_pgsql_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value)
442 {
443 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
444
445 switch (attr) {
446 case PDO_ATTR_EMULATE_PREPARES:
447 ZVAL_BOOL(return_value, H->emulate_prepares);
448 break;
449
450 case PDO_PGSQL_ATTR_DISABLE_PREPARES:
451 ZVAL_BOOL(return_value, H->disable_prepares);
452 break;
453
454 case PDO_ATTR_CLIENT_VERSION: {
455 char buf[16];
456 pdo_libpq_version(buf, sizeof(buf));
457 ZVAL_STRING(return_value, buf);
458 break;
459 }
460
461 case PDO_ATTR_SERVER_VERSION:
462 ZVAL_STRING(return_value, (char*)PQparameterStatus(H->server, "server_version"));
463 break;
464
465 case PDO_ATTR_CONNECTION_STATUS:
466 switch (PQstatus(H->server)) {
467 case CONNECTION_STARTED:
468 ZVAL_STRINGL(return_value, "Waiting for connection to be made.", strlen("Waiting for connection to be made."));
469 break;
470
471 case CONNECTION_MADE:
472 case CONNECTION_OK:
473 ZVAL_STRINGL(return_value, "Connection OK; waiting to send.", strlen("Connection OK; waiting to send."));
474 break;
475
476 case CONNECTION_AWAITING_RESPONSE:
477 ZVAL_STRINGL(return_value, "Waiting for a response from the server.", strlen("Waiting for a response from the server."));
478 break;
479
480 case CONNECTION_AUTH_OK:
481 ZVAL_STRINGL(return_value, "Received authentication; waiting for backend start-up to finish.", strlen("Received authentication; waiting for backend start-up to finish."));
482 break;
483 #ifdef CONNECTION_SSL_STARTUP
484 case CONNECTION_SSL_STARTUP:
485 ZVAL_STRINGL(return_value, "Negotiating SSL encryption.", strlen("Negotiating SSL encryption."));
486 break;
487 #endif
488 case CONNECTION_SETENV:
489 ZVAL_STRINGL(return_value, "Negotiating environment-driven parameter settings.", strlen("Negotiating environment-driven parameter settings."));
490 break;
491
492 #ifdef CONNECTION_CONSUME
493 case CONNECTION_CONSUME:
494 ZVAL_STRINGL(return_value, "Flushing send queue/consuming extra data.", strlen("Flushing send queue/consuming extra data."));
495 break;
496 #endif
497 #ifdef CONNECTION_GSS_STARTUP
498 case CONNECTION_SSL_STARTUP:
499 ZVAL_STRINGL(return_value, "Negotiating GSSAPI.", strlen("Negotiating GSSAPI."));
500 break;
501 #endif
502 #ifdef CONNECTION_CHECK_TARGET
503 case CONNECTION_CHECK_TARGET:
504 ZVAL_STRINGL(return_value, "Connection OK; checking target server properties.", strlen("Connection OK; checking target server properties."));
505 break;
506 #endif
507 #ifdef CONNECTION_CHECK_STANDBY
508 case CONNECTION_CHECK_STANDBY:
509 ZVAL_STRINGL(return_value, "Connection OK; checking if server in standby.", strlen("Connection OK; checking if server in standby."));
510 break;
511 #endif
512 case CONNECTION_BAD:
513 default:
514 ZVAL_STRINGL(return_value, "Bad connection.", strlen("Bad connection."));
515 break;
516 }
517 break;
518
519 case PDO_ATTR_SERVER_INFO: {
520 int spid = PQbackendPID(H->server);
521
522
523 zend_string *str_info =
524 strpprintf(0,
525 "PID: %d; Client Encoding: %s; Is Superuser: %s; Session Authorization: %s; Date Style: %s",
526 spid,
527 (char*)PQparameterStatus(H->server, "client_encoding"),
528 (char*)PQparameterStatus(H->server, "is_superuser"),
529 (char*)PQparameterStatus(H->server, "session_authorization"),
530 (char*)PQparameterStatus(H->server, "DateStyle"));
531
532 ZVAL_STR(return_value, str_info);
533 break;
534 }
535
536 default:
537 return 0;
538 }
539
540 return 1;
541 }
542
543 /* {{{ */
pdo_pgsql_check_liveness(pdo_dbh_t * dbh)544 static zend_result pdo_pgsql_check_liveness(pdo_dbh_t *dbh)
545 {
546 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
547 if (!PQconsumeInput(H->server) || PQstatus(H->server) == CONNECTION_BAD) {
548 PQreset(H->server);
549 }
550 return (PQstatus(H->server) == CONNECTION_OK) ? SUCCESS : FAILURE;
551 }
552 /* }}} */
553
pgsql_handle_in_transaction(pdo_dbh_t * dbh)554 static bool pgsql_handle_in_transaction(pdo_dbh_t *dbh)
555 {
556 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
557
558 return PQtransactionStatus(H->server) > PQTRANS_IDLE;
559 }
560
pdo_pgsql_transaction_cmd(const char * cmd,pdo_dbh_t * dbh)561 static bool pdo_pgsql_transaction_cmd(const char *cmd, pdo_dbh_t *dbh)
562 {
563 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
564 PGresult *res;
565 bool ret = true;
566
567 res = PQexec(H->server, cmd);
568
569 if (PQresultStatus(res) != PGRES_COMMAND_OK) {
570 pdo_pgsql_error(dbh, PQresultStatus(res), pdo_pgsql_sqlstate(res));
571 ret = false;
572 }
573
574 PQclear(res);
575 return ret;
576 }
577
pgsql_handle_begin(pdo_dbh_t * dbh)578 static bool pgsql_handle_begin(pdo_dbh_t *dbh)
579 {
580 return pdo_pgsql_transaction_cmd("BEGIN", dbh);
581 }
582
pgsql_handle_commit(pdo_dbh_t * dbh)583 static bool pgsql_handle_commit(pdo_dbh_t *dbh)
584 {
585 bool ret = pdo_pgsql_transaction_cmd("COMMIT", dbh);
586
587 /* When deferred constraints are used the commit could
588 fail, and a ROLLBACK implicitly ran. See bug #67462 */
589 if (ret) {
590 pdo_pgsql_close_lob_streams(dbh);
591 } else {
592 dbh->in_txn = pgsql_handle_in_transaction(dbh);
593 }
594
595 return ret;
596 }
597
pgsql_handle_rollback(pdo_dbh_t * dbh)598 static bool pgsql_handle_rollback(pdo_dbh_t *dbh)
599 {
600 int ret = pdo_pgsql_transaction_cmd("ROLLBACK", dbh);
601
602 if (ret) {
603 pdo_pgsql_close_lob_streams(dbh);
604 }
605
606 return ret;
607 }
608
pgsqlCopyFromArray_internal(INTERNAL_FUNCTION_PARAMETERS)609 void pgsqlCopyFromArray_internal(INTERNAL_FUNCTION_PARAMETERS)
610 {
611 pdo_dbh_t *dbh;
612 pdo_pgsql_db_handle *H;
613
614 zval *pg_rows;
615
616 char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
617 size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
618 char *query;
619
620 PGresult *pgsql_result;
621 ExecStatusType status;
622
623 if (zend_parse_parameters(ZEND_NUM_ARGS(), "sa|sss!",
624 &table_name, &table_name_len, &pg_rows,
625 &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
626 RETURN_THROWS();
627 }
628
629 if (!zend_hash_num_elements(Z_ARRVAL_P(pg_rows))) {
630 zend_argument_must_not_be_empty_error(2);
631 RETURN_THROWS();
632 }
633
634 dbh = Z_PDO_DBH_P(ZEND_THIS);
635 PDO_CONSTRUCT_CHECK;
636 PDO_DBH_CLEAR_ERR();
637
638 /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
639 if (pg_fields) {
640 spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
641 } else {
642 spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
643 }
644
645 /* Obtain db Handle */
646 H = (pdo_pgsql_db_handle *)dbh->driver_data;
647
648 while ((pgsql_result = PQgetResult(H->server))) {
649 PQclear(pgsql_result);
650 }
651 pgsql_result = PQexec(H->server, query);
652
653 efree(query);
654 query = NULL;
655
656 if (pgsql_result) {
657 status = PQresultStatus(pgsql_result);
658 } else {
659 status = (ExecStatusType) PQstatus(H->server);
660 }
661
662 if (status == PGRES_COPY_IN && pgsql_result) {
663 int command_failed = 0;
664 size_t buffer_len = 0;
665 zval *tmp;
666
667 PQclear(pgsql_result);
668 ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) {
669 size_t query_len;
670 if (!try_convert_to_string(tmp)) {
671 efree(query);
672 RETURN_THROWS();
673 }
674
675 if (buffer_len < Z_STRLEN_P(tmp)) {
676 buffer_len = Z_STRLEN_P(tmp);
677 query = erealloc(query, buffer_len + 2); /* room for \n\0 */
678 }
679 query_len = Z_STRLEN_P(tmp);
680 memcpy(query, Z_STRVAL_P(tmp), query_len);
681 if (query[query_len - 1] != '\n') {
682 query[query_len++] = '\n';
683 }
684 query[query_len] = '\0';
685 if (PQputCopyData(H->server, query, query_len) != 1) {
686 efree(query);
687 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
688 PDO_HANDLE_DBH_ERR();
689 RETURN_FALSE;
690 }
691 } ZEND_HASH_FOREACH_END();
692 if (query) {
693 efree(query);
694 }
695
696 if (PQputCopyEnd(H->server, NULL) != 1) {
697 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
698 PDO_HANDLE_DBH_ERR();
699 RETURN_FALSE;
700 }
701
702 while ((pgsql_result = PQgetResult(H->server))) {
703 if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
704 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
705 command_failed = 1;
706 }
707 PQclear(pgsql_result);
708 }
709
710 PDO_HANDLE_DBH_ERR();
711 RETURN_BOOL(!command_failed);
712 } else {
713 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
714 PQclear(pgsql_result);
715 PDO_HANDLE_DBH_ERR();
716 RETURN_FALSE;
717 }
718 }
719
720 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyFromArray)721 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyFromArray)
722 {
723 pgsqlCopyFromArray_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
724 }
725 /* }}} */
726
pgsqlCopyFromFile_internal(INTERNAL_FUNCTION_PARAMETERS)727 void pgsqlCopyFromFile_internal(INTERNAL_FUNCTION_PARAMETERS)
728 {
729 pdo_dbh_t *dbh;
730 pdo_pgsql_db_handle *H;
731
732 char *table_name, *filename, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
733 size_t table_name_len, filename_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
734 char *query;
735 PGresult *pgsql_result;
736 ExecStatusType status;
737 php_stream *stream;
738
739 if (zend_parse_parameters(ZEND_NUM_ARGS(), "sp|sss!",
740 &table_name, &table_name_len, &filename, &filename_len,
741 &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
742 RETURN_THROWS();
743 }
744
745 /* Obtain db Handler */
746 dbh = Z_PDO_DBH_P(ZEND_THIS);
747 PDO_CONSTRUCT_CHECK;
748 PDO_DBH_CLEAR_ERR();
749
750 stream = php_stream_open_wrapper_ex(filename, "rb", 0, NULL, FG(default_context));
751 if (!stream) {
752 pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file");
753 PDO_HANDLE_DBH_ERR();
754 RETURN_FALSE;
755 }
756
757 /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
758 if (pg_fields) {
759 spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
760 } else {
761 spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
762 }
763
764 H = (pdo_pgsql_db_handle *)dbh->driver_data;
765
766 while ((pgsql_result = PQgetResult(H->server))) {
767 PQclear(pgsql_result);
768 }
769 pgsql_result = PQexec(H->server, query);
770
771 efree(query);
772
773 if (pgsql_result) {
774 status = PQresultStatus(pgsql_result);
775 } else {
776 status = (ExecStatusType) PQstatus(H->server);
777 }
778
779 if (status == PGRES_COPY_IN && pgsql_result) {
780 char *buf;
781 int command_failed = 0;
782 size_t line_len = 0;
783
784 PQclear(pgsql_result);
785 while ((buf = php_stream_get_line(stream, NULL, 0, &line_len)) != NULL) {
786 if (PQputCopyData(H->server, buf, line_len) != 1) {
787 efree(buf);
788 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
789 php_stream_close(stream);
790 PDO_HANDLE_DBH_ERR();
791 RETURN_FALSE;
792 }
793 efree(buf);
794 }
795 php_stream_close(stream);
796
797 if (PQputCopyEnd(H->server, NULL) != 1) {
798 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
799 PDO_HANDLE_DBH_ERR();
800 RETURN_FALSE;
801 }
802
803 while ((pgsql_result = PQgetResult(H->server))) {
804 if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
805 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
806 command_failed = 1;
807 }
808 PQclear(pgsql_result);
809 }
810
811 PDO_HANDLE_DBH_ERR();
812 RETURN_BOOL(!command_failed);
813 } else {
814 php_stream_close(stream);
815 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
816 PQclear(pgsql_result);
817 PDO_HANDLE_DBH_ERR();
818 RETURN_FALSE;
819 }
820 }
821
822 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyFromFile)823 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyFromFile)
824 {
825 pgsqlCopyFromFile_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
826 }
827 /* }}} */
828
pgsqlCopyToFile_internal(INTERNAL_FUNCTION_PARAMETERS)829 void pgsqlCopyToFile_internal(INTERNAL_FUNCTION_PARAMETERS)
830 {
831 pdo_dbh_t *dbh;
832 pdo_pgsql_db_handle *H;
833
834 char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL, *filename = NULL;
835 size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len, filename_len;
836 char *query;
837
838 PGresult *pgsql_result;
839 ExecStatusType status;
840
841 php_stream *stream;
842
843 if (zend_parse_parameters(ZEND_NUM_ARGS(), "sp|sss!",
844 &table_name, &table_name_len, &filename, &filename_len,
845 &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
846 RETURN_THROWS();
847 }
848
849 dbh = Z_PDO_DBH_P(ZEND_THIS);
850 PDO_CONSTRUCT_CHECK;
851 PDO_DBH_CLEAR_ERR();
852
853 H = (pdo_pgsql_db_handle *)dbh->driver_data;
854
855 stream = php_stream_open_wrapper_ex(filename, "wb", 0, NULL, FG(default_context));
856 if (!stream) {
857 pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file for writing");
858 PDO_HANDLE_DBH_ERR();
859 RETURN_FALSE;
860 }
861
862 while ((pgsql_result = PQgetResult(H->server))) {
863 PQclear(pgsql_result);
864 }
865
866 /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
867 if (pg_fields) {
868 spprintf(&query, 0, "COPY %s (%s) TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
869 } else {
870 spprintf(&query, 0, "COPY %s TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
871 }
872 pgsql_result = PQexec(H->server, query);
873 efree(query);
874
875 if (pgsql_result) {
876 status = PQresultStatus(pgsql_result);
877 } else {
878 status = (ExecStatusType) PQstatus(H->server);
879 }
880
881 if (status == PGRES_COPY_OUT && pgsql_result) {
882 PQclear(pgsql_result);
883 while (1) {
884 char *csv = NULL;
885 int ret = PQgetCopyData(H->server, &csv, 0);
886
887 if (ret == -1) {
888 break; /* done */
889 } else if (ret > 0) {
890 if (php_stream_write(stream, csv, ret) != (size_t)ret) {
891 pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to write to file");
892 PQfreemem(csv);
893 php_stream_close(stream);
894 PDO_HANDLE_DBH_ERR();
895 RETURN_FALSE;
896 } else {
897 PQfreemem(csv);
898 }
899 } else {
900 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
901 php_stream_close(stream);
902 PDO_HANDLE_DBH_ERR();
903 RETURN_FALSE;
904 }
905 }
906 php_stream_close(stream);
907
908 while ((pgsql_result = PQgetResult(H->server))) {
909 PQclear(pgsql_result);
910 }
911 RETURN_TRUE;
912 } else {
913 php_stream_close(stream);
914 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
915 PQclear(pgsql_result);
916 PDO_HANDLE_DBH_ERR();
917 RETURN_FALSE;
918 }
919 }
920
921 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyToFile)922 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyToFile)
923 {
924 pgsqlCopyToFile_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
925
926 }
927 /* }}} */
928
pgsqlCopyToArray_internal(INTERNAL_FUNCTION_PARAMETERS)929 void pgsqlCopyToArray_internal(INTERNAL_FUNCTION_PARAMETERS)
930 {
931 pdo_dbh_t *dbh;
932 pdo_pgsql_db_handle *H;
933
934 char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
935 size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
936 char *query;
937
938 PGresult *pgsql_result;
939 ExecStatusType status;
940
941 if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sss!",
942 &table_name, &table_name_len,
943 &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
944 RETURN_THROWS();
945 }
946
947 dbh = Z_PDO_DBH_P(ZEND_THIS);
948 PDO_CONSTRUCT_CHECK;
949 PDO_DBH_CLEAR_ERR();
950
951 H = (pdo_pgsql_db_handle *)dbh->driver_data;
952
953 while ((pgsql_result = PQgetResult(H->server))) {
954 PQclear(pgsql_result);
955 }
956
957 /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
958 if (pg_fields) {
959 spprintf(&query, 0, "COPY %s (%s) TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
960 } else {
961 spprintf(&query, 0, "COPY %s TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
962 }
963 pgsql_result = PQexec(H->server, query);
964 efree(query);
965
966 if (pgsql_result) {
967 status = PQresultStatus(pgsql_result);
968 } else {
969 status = (ExecStatusType) PQstatus(H->server);
970 }
971
972 if (status == PGRES_COPY_OUT && pgsql_result) {
973 PQclear(pgsql_result);
974 array_init(return_value);
975
976 while (1) {
977 char *csv = NULL;
978 int ret = PQgetCopyData(H->server, &csv, 0);
979 if (ret == -1) {
980 break; /* copy done */
981 } else if (ret > 0) {
982 add_next_index_stringl(return_value, csv, ret);
983 PQfreemem(csv);
984 } else {
985 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
986 PDO_HANDLE_DBH_ERR();
987 RETURN_FALSE;
988 }
989 }
990
991 while ((pgsql_result = PQgetResult(H->server))) {
992 PQclear(pgsql_result);
993 }
994 } else {
995 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
996 PQclear(pgsql_result);
997 PDO_HANDLE_DBH_ERR();
998 RETURN_FALSE;
999 }
1000 }
1001
1002 /* {{{ Returns true if the copy worked fine or false if error */
PHP_METHOD(PDO_PGSql_Ext,pgsqlCopyToArray)1003 PHP_METHOD(PDO_PGSql_Ext, pgsqlCopyToArray)
1004 {
1005 pgsqlCopyToArray_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
1006 }
1007 /* }}} */
1008
pgsqlLOBCreate_internal(INTERNAL_FUNCTION_PARAMETERS)1009 void pgsqlLOBCreate_internal(INTERNAL_FUNCTION_PARAMETERS)
1010 {
1011 pdo_dbh_t *dbh;
1012 pdo_pgsql_db_handle *H;
1013 Oid lfd;
1014
1015 ZEND_PARSE_PARAMETERS_NONE();
1016
1017 dbh = Z_PDO_DBH_P(ZEND_THIS);
1018 PDO_CONSTRUCT_CHECK;
1019 PDO_DBH_CLEAR_ERR();
1020
1021 H = (pdo_pgsql_db_handle *)dbh->driver_data;
1022 lfd = lo_creat(H->server, INV_READ|INV_WRITE);
1023
1024 if (lfd != InvalidOid) {
1025 zend_string *buf = strpprintf(0, ZEND_ULONG_FMT, (zend_long) lfd);
1026
1027 RETURN_STR(buf);
1028 }
1029
1030 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1031 PDO_HANDLE_DBH_ERR();
1032 RETURN_FALSE;
1033 }
1034
1035 /* {{{ Creates a new large object, returning its identifier. Must be called inside a transaction. */
PHP_METHOD(PDO_PGSql_Ext,pgsqlLOBCreate)1036 PHP_METHOD(PDO_PGSql_Ext, pgsqlLOBCreate)
1037 {
1038 pgsqlLOBCreate_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
1039 }
1040 /* }}} */
1041
pgsqlLOBOpen_internal(INTERNAL_FUNCTION_PARAMETERS)1042 void pgsqlLOBOpen_internal(INTERNAL_FUNCTION_PARAMETERS)
1043 {
1044 pdo_dbh_t *dbh;
1045 pdo_pgsql_db_handle *H;
1046 Oid oid;
1047 int lfd;
1048 char *oidstr;
1049 size_t oidstrlen;
1050 char *modestr = "rb";
1051 size_t modestrlen;
1052 int mode = INV_READ;
1053 char *end_ptr;
1054
1055 if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s|s",
1056 &oidstr, &oidstrlen, &modestr, &modestrlen)) {
1057 RETURN_THROWS();
1058 }
1059
1060 oid = (Oid)strtoul(oidstr, &end_ptr, 10);
1061 if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
1062 RETURN_FALSE;
1063 }
1064
1065 if (strpbrk(modestr, "+w")) {
1066 mode = INV_READ|INV_WRITE;
1067 }
1068
1069 dbh = Z_PDO_DBH_P(ZEND_THIS);
1070 PDO_CONSTRUCT_CHECK;
1071 PDO_DBH_CLEAR_ERR();
1072
1073 H = (pdo_pgsql_db_handle *)dbh->driver_data;
1074
1075 lfd = lo_open(H->server, oid, mode);
1076
1077 if (lfd >= 0) {
1078 php_stream *stream = pdo_pgsql_create_lob_stream(ZEND_THIS, lfd, oid);
1079 if (stream) {
1080 php_stream_to_zval(stream, return_value);
1081 return;
1082 }
1083 } else {
1084 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1085 }
1086
1087 PDO_HANDLE_DBH_ERR();
1088 RETURN_FALSE;
1089 }
1090
1091 /* {{{ Opens an existing large object stream. Must be called inside a transaction. */
PHP_METHOD(PDO_PGSql_Ext,pgsqlLOBOpen)1092 PHP_METHOD(PDO_PGSql_Ext, pgsqlLOBOpen)
1093 {
1094 pgsqlLOBOpen_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
1095 }
1096 /* }}} */
1097
pgsqlLOBUnlink_internal(INTERNAL_FUNCTION_PARAMETERS)1098 void pgsqlLOBUnlink_internal(INTERNAL_FUNCTION_PARAMETERS)
1099 {
1100 pdo_dbh_t *dbh;
1101 pdo_pgsql_db_handle *H;
1102 Oid oid;
1103 char *oidstr, *end_ptr;
1104 size_t oidlen;
1105
1106 if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s",
1107 &oidstr, &oidlen)) {
1108 RETURN_THROWS();
1109 }
1110
1111 oid = (Oid)strtoul(oidstr, &end_ptr, 10);
1112 if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
1113 RETURN_FALSE;
1114 }
1115
1116 dbh = Z_PDO_DBH_P(ZEND_THIS);
1117 PDO_CONSTRUCT_CHECK;
1118 PDO_DBH_CLEAR_ERR();
1119
1120 H = (pdo_pgsql_db_handle *)dbh->driver_data;
1121
1122 if (1 == lo_unlink(H->server, oid)) {
1123 RETURN_TRUE;
1124 }
1125
1126 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1127 PDO_HANDLE_DBH_ERR();
1128 RETURN_FALSE;
1129 }
1130
1131 /* {{{ Deletes the large object identified by oid. Must be called inside a transaction. */
PHP_METHOD(PDO_PGSql_Ext,pgsqlLOBUnlink)1132 PHP_METHOD(PDO_PGSql_Ext, pgsqlLOBUnlink)
1133 {
1134 pgsqlLOBUnlink_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
1135 }
1136 /* }}} */
1137
pgsqlGetNotify_internal(INTERNAL_FUNCTION_PARAMETERS)1138 void pgsqlGetNotify_internal(INTERNAL_FUNCTION_PARAMETERS)
1139 {
1140 pdo_dbh_t *dbh;
1141 pdo_pgsql_db_handle *H;
1142 zend_long result_type = PDO_FETCH_USE_DEFAULT;
1143 zend_long ms_timeout = 0;
1144 PGnotify *pgsql_notify;
1145
1146 if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "|ll",
1147 &result_type, &ms_timeout)) {
1148 RETURN_THROWS();
1149 }
1150
1151 dbh = Z_PDO_DBH_P(ZEND_THIS);
1152 PDO_CONSTRUCT_CHECK;
1153
1154 if (result_type == PDO_FETCH_USE_DEFAULT) {
1155 result_type = dbh->default_fetch_type;
1156 }
1157
1158 if (result_type != PDO_FETCH_BOTH && result_type != PDO_FETCH_ASSOC && result_type != PDO_FETCH_NUM) {
1159 zend_argument_value_error(1, "must be one of PDO::FETCH_BOTH, PDO::FETCH_ASSOC, or PDO::FETCH_NUM");
1160 RETURN_THROWS();
1161 }
1162
1163 if (ms_timeout < 0) {
1164 zend_argument_value_error(2, "must be greater than or equal to 0");
1165 RETURN_THROWS();
1166 #ifdef ZEND_ENABLE_ZVAL_LONG64
1167 } else if (ms_timeout > INT_MAX) {
1168 php_error_docref(NULL, E_WARNING, "Timeout was shrunk to %d", INT_MAX);
1169 ms_timeout = INT_MAX;
1170 #endif
1171 }
1172
1173 H = (pdo_pgsql_db_handle *)dbh->driver_data;
1174
1175 if (!PQconsumeInput(H->server)) {
1176 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1177 PDO_HANDLE_DBH_ERR();
1178 RETURN_FALSE;
1179 }
1180 pgsql_notify = PQnotifies(H->server);
1181
1182 if (ms_timeout && !pgsql_notify) {
1183 php_pollfd_for_ms(PQsocket(H->server), PHP_POLLREADABLE, (int)ms_timeout);
1184
1185 if (!PQconsumeInput(H->server)) {
1186 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1187 PDO_HANDLE_DBH_ERR();
1188 RETURN_FALSE;
1189 }
1190 pgsql_notify = PQnotifies(H->server);
1191 }
1192
1193 if (!pgsql_notify) {
1194 RETURN_FALSE;
1195 }
1196
1197 array_init(return_value);
1198 if (result_type == PDO_FETCH_NUM || result_type == PDO_FETCH_BOTH) {
1199 add_index_string(return_value, 0, pgsql_notify->relname);
1200 add_index_long(return_value, 1, pgsql_notify->be_pid);
1201 if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1202 add_index_string(return_value, 2, pgsql_notify->extra);
1203 }
1204 }
1205 if (result_type == PDO_FETCH_ASSOC || result_type == PDO_FETCH_BOTH) {
1206 add_assoc_string(return_value, "message", pgsql_notify->relname);
1207 add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
1208 if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1209 add_assoc_string(return_value, "payload", pgsql_notify->extra);
1210 }
1211 }
1212
1213 PQfreemem(pgsql_notify);
1214 }
1215
1216 /* {{{ Get asynchronous notification */
PHP_METHOD(PDO_PGSql_Ext,pgsqlGetNotify)1217 PHP_METHOD(PDO_PGSql_Ext, pgsqlGetNotify)
1218 {
1219 pgsqlGetNotify_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
1220 }
1221 /* }}} */
1222
pgsqlGetPid_internal(INTERNAL_FUNCTION_PARAMETERS)1223 void pgsqlGetPid_internal(INTERNAL_FUNCTION_PARAMETERS)
1224 {
1225 pdo_dbh_t *dbh;
1226 pdo_pgsql_db_handle *H;
1227
1228 ZEND_PARSE_PARAMETERS_NONE();
1229
1230 dbh = Z_PDO_DBH_P(ZEND_THIS);
1231 PDO_CONSTRUCT_CHECK;
1232
1233 H = (pdo_pgsql_db_handle *)dbh->driver_data;
1234
1235 RETURN_LONG(PQbackendPID(H->server));
1236 }
1237
1238 /* {{{ Get backend(server) pid */
PHP_METHOD(PDO_PGSql_Ext,pgsqlGetPid)1239 PHP_METHOD(PDO_PGSql_Ext, pgsqlGetPid)
1240 {
1241 pgsqlGetPid_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU);
1242 }
1243 /* }}} */
1244
1245 /* {{{ Sets a callback to receive DB notices (after client_min_messages has been set) */
PHP_METHOD(PDO_PGSql_Ext,pgsqlSetNoticeCallback)1246 PHP_METHOD(PDO_PGSql_Ext, pgsqlSetNoticeCallback)
1247 {
1248 zend_fcall_info fci = empty_fcall_info;
1249 zend_fcall_info_cache fcc = empty_fcall_info_cache;
1250 if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "F!", &fci, &fcc)) {
1251 RETURN_THROWS();
1252 }
1253
1254 pdo_dbh_t *dbh = Z_PDO_DBH_P(ZEND_THIS);
1255 PDO_CONSTRUCT_CHECK_WITH_CLEANUP(cleanup);
1256
1257 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
1258
1259 pdo_pgsql_cleanup_notice_callback(H);
1260
1261 if (ZEND_FCC_INITIALIZED(fcc)) {
1262 H->notice_callback = emalloc(sizeof(zend_fcall_info_cache));
1263 zend_fcc_dup(H->notice_callback, &fcc);
1264 }
1265
1266 return;
1267
1268 cleanup:
1269 if (ZEND_FCC_INITIALIZED(fcc)) {
1270 zend_fcc_dtor(&fcc);
1271 }
1272 RETURN_THROWS();
1273 }
1274 /* }}} */
1275
pdo_pgsql_get_driver_methods(pdo_dbh_t * dbh,int kind)1276 static const zend_function_entry *pdo_pgsql_get_driver_methods(pdo_dbh_t *dbh, int kind)
1277 {
1278 switch (kind) {
1279 case PDO_DBH_DRIVER_METHOD_KIND_DBH:
1280 return class_PDO_PGSql_Ext_methods;
1281 default:
1282 return NULL;
1283 }
1284 }
1285
pdo_pgsql_set_attr(pdo_dbh_t * dbh,zend_long attr,zval * val)1286 static bool pdo_pgsql_set_attr(pdo_dbh_t *dbh, zend_long attr, zval *val)
1287 {
1288 bool bval;
1289 pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
1290
1291 switch (attr) {
1292 case PDO_ATTR_EMULATE_PREPARES:
1293 if (!pdo_get_bool_param(&bval, val)) {
1294 return false;
1295 }
1296 H->emulate_prepares = bval;
1297 return true;
1298 case PDO_PGSQL_ATTR_DISABLE_PREPARES:
1299 if (!pdo_get_bool_param(&bval, val)) {
1300 return false;
1301 }
1302 H->disable_prepares = bval;
1303 return true;
1304 default:
1305 return false;
1306 }
1307 }
1308
1309 static const struct pdo_dbh_methods pgsql_methods = {
1310 pgsql_handle_closer,
1311 pgsql_handle_preparer,
1312 pgsql_handle_doer,
1313 pgsql_handle_quoter,
1314 pgsql_handle_begin,
1315 pgsql_handle_commit,
1316 pgsql_handle_rollback,
1317 pdo_pgsql_set_attr,
1318 pdo_pgsql_last_insert_id,
1319 pdo_pgsql_fetch_error_func,
1320 pdo_pgsql_get_attribute,
1321 pdo_pgsql_check_liveness, /* check_liveness */
1322 pdo_pgsql_get_driver_methods, /* get_driver_methods */
1323 NULL,
1324 pgsql_handle_in_transaction,
1325 NULL, /* get_gc */
1326 pdo_pgsql_scanner
1327 };
1328
pdo_pgsql_handle_factory(pdo_dbh_t * dbh,zval * driver_options)1329 static int pdo_pgsql_handle_factory(pdo_dbh_t *dbh, zval *driver_options) /* {{{ */
1330 {
1331 pdo_pgsql_db_handle *H;
1332 int ret = 0;
1333 char *p, *e;
1334 zend_string *tmp_user, *tmp_pass;
1335 smart_str conn_str = {0};
1336 zend_long connect_timeout = 30;
1337
1338 H = pecalloc(1, sizeof(pdo_pgsql_db_handle), dbh->is_persistent);
1339 dbh->driver_data = H;
1340
1341 dbh->skip_param_evt =
1342 1 << PDO_PARAM_EVT_EXEC_POST |
1343 1 << PDO_PARAM_EVT_FETCH_PRE |
1344 1 << PDO_PARAM_EVT_FETCH_POST;
1345
1346 H->einfo.errcode = 0;
1347 H->einfo.errmsg = NULL;
1348
1349 /* PostgreSQL wants params in the connect string to be separated by spaces,
1350 * if the PDO standard semicolons are used, we convert them to spaces
1351 */
1352 e = (char *) dbh->data_source + strlen(dbh->data_source);
1353 p = (char *) dbh->data_source;
1354 while ((p = memchr(p, ';', (e - p)))) {
1355 *p = ' ';
1356 }
1357
1358 if (driver_options) {
1359 connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30);
1360 }
1361
1362 /* escape username and password, if provided */
1363 tmp_user = !strstr((char *) dbh->data_source, "user=") ? _pdo_pgsql_escape_credentials(dbh->username) : NULL;
1364 tmp_pass = !strstr((char *) dbh->data_source, "password=") ? _pdo_pgsql_escape_credentials(dbh->password) : NULL;
1365
1366 smart_str_appends(&conn_str, dbh->data_source);
1367 smart_str_append_printf(&conn_str, " connect_timeout=" ZEND_LONG_FMT, connect_timeout);
1368
1369 /* support both full connection string & connection string + login and/or password */
1370 if (tmp_user) {
1371 smart_str_append_printf(&conn_str, " user='%s'", ZSTR_VAL(tmp_user));
1372 }
1373
1374 if (tmp_pass) {
1375 smart_str_append_printf(&conn_str, " password='%s'", ZSTR_VAL(tmp_pass));
1376 }
1377 smart_str_0(&conn_str);
1378
1379 H->server = PQconnectdb(ZSTR_VAL(conn_str.s));
1380 H->lob_streams = (HashTable *) pemalloc(sizeof(HashTable), dbh->is_persistent);
1381 zend_hash_init(H->lob_streams, 0, NULL, NULL, 1);
1382
1383 if (tmp_user) {
1384 zend_string_release_ex(tmp_user, 0);
1385 }
1386 if (tmp_pass) {
1387 zend_string_release_ex(tmp_pass, 0);
1388 }
1389
1390 smart_str_free(&conn_str);
1391
1392 if (PQstatus(H->server) != CONNECTION_OK) {
1393 pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, PHP_PDO_PGSQL_CONNECTION_FAILURE_SQLSTATE);
1394 goto cleanup;
1395 }
1396
1397 PQsetNoticeProcessor(H->server, _pdo_pgsql_notice, (void *)dbh);
1398
1399 H->attached = 1;
1400 H->pgoid = -1;
1401
1402 dbh->methods = &pgsql_methods;
1403 dbh->alloc_own_columns = 1;
1404 dbh->max_escaped_char_length = 2;
1405
1406 ret = 1;
1407
1408 cleanup:
1409 dbh->methods = &pgsql_methods;
1410 if (!ret) {
1411 pgsql_handle_closer(dbh);
1412 }
1413
1414 return ret;
1415 }
1416 /* }}} */
1417
1418 const pdo_driver_t pdo_pgsql_driver = {
1419 PDO_DRIVER_HEADER(pgsql),
1420 pdo_pgsql_handle_factory
1421 };
1422