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