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