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