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