xref: /php-src/ext/pdo_pgsql/pgsql_statement.c (revision 68537fd9)
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/pdo/php_pdo.h"
27 #include "ext/pdo/php_pdo_driver.h"
28 #include "php_pdo_pgsql.h"
29 #include "php_pdo_pgsql_int.h"
30 #ifdef HAVE_NETINET_IN_H
31 #include <netinet/in.h>
32 #endif
33 
34 /* from postgresql/src/include/catalog/pg_type.h */
35 #define BOOLLABEL   "bool"
36 #define BOOLOID     16
37 #define BYTEALABEL  "bytea"
38 #define BYTEAOID    17
39 #define DATELABEL   "date"
40 #define DATEOID     1082
41 #define INT2LABEL   "int2"
42 #define INT2OID     21
43 #define INT4LABEL   "int4"
44 #define INT4OID     23
45 #define INT8LABEL   "int8"
46 #define INT8OID     20
47 #define OIDOID      26
48 #define TEXTLABEL   "text"
49 #define TEXTOID     25
50 #define TIMESTAMPLABEL "timestamp"
51 #define TIMESTAMPOID   1114
52 #define VARCHARLABEL "varchar"
53 #define VARCHAROID   1043
54 #define FLOAT4LABEL "float4"
55 #define FLOAT4OID 700
56 #define FLOAT8LABEL "float8"
57 #define FLOAT8OID 701
58 
59 #define FIN_DISCARD 0x1
60 #define FIN_CLOSE   0x2
61 #define FIN_ABORT   0x4
62 
63 
64 
pgsql_stmt_finish(pdo_pgsql_stmt * S,int fin_mode)65 static void pgsql_stmt_finish(pdo_pgsql_stmt *S, int fin_mode)
66 {
67 	pdo_pgsql_db_handle *H = S->H;
68 
69 	if (S->is_running_unbuffered && S->result && (fin_mode & FIN_ABORT)) {
70 		PGcancel *cancel = PQgetCancel(H->server);
71 		char errbuf[256];
72 		PQcancel(cancel, errbuf, 256);
73 		PQfreeCancel(cancel);
74 		S->is_running_unbuffered = false;
75 	}
76 
77 	if (S->result) {
78 		/* free the resource */
79 		PQclear(S->result);
80 		S->result = NULL;
81 	}
82 
83 	if (S->is_running_unbuffered) {
84 		/* https://postgresql.org/docs/current/libpq-async.html:
85 		 * "PQsendQuery cannot be called again until PQgetResult has returned NULL"
86 		 * And as all single-row functions are connection-wise instead of statement-wise,
87 		 * any new single-row query has to make sure no preceding one is still running.
88 		 */
89 		// @todo Implement !(fin_mode & FIN_DISCARD)
90 		//       instead of discarding results we could store them to their statement
91 		//       so that their fetch() will get them (albeit not in lazy mode anymore).
92 		while ((S->result = PQgetResult(H->server))) {
93 			PQclear(S->result);
94 			S->result = NULL;
95 		}
96 		S->is_running_unbuffered = false;
97 	}
98 
99 	if (S->stmt_name && S->is_prepared && (fin_mode & FIN_CLOSE)) {
100 		PGresult *res;
101 #ifndef HAVE_PQCLOSEPREPARED
102 		// TODO (??) libpq does not support close statement protocol < postgres 17
103 		// check if we can circumvent this.
104 		char *q = NULL;
105 		spprintf(&q, 0, "DEALLOCATE %s", S->stmt_name);
106 		res = PQexec(H->server, q);
107 		efree(q);
108 #else
109 		res = PQclosePrepared(H->server, S->stmt_name);
110 #endif
111 		if (res) {
112 			PQclear(res);
113 		}
114 
115 		S->is_prepared = false;
116 		if (H->running_stmt == S) {
117 			H->running_stmt = NULL;
118 		}
119 	}
120 }
121 
pgsql_stmt_dtor(pdo_stmt_t * stmt)122 static int pgsql_stmt_dtor(pdo_stmt_t *stmt)
123 {
124 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
125 	bool server_obj_usable = !Z_ISUNDEF(stmt->database_object_handle)
126 		&& IS_OBJ_VALID(EG(objects_store).object_buckets[Z_OBJ_HANDLE(stmt->database_object_handle)])
127 		&& !(OBJ_FLAGS(Z_OBJ(stmt->database_object_handle)) & IS_OBJ_FREE_CALLED);
128 
129 	pgsql_stmt_finish(S, FIN_DISCARD|(server_obj_usable ? FIN_CLOSE|FIN_ABORT : 0));
130 
131 	if (S->stmt_name) {
132 		efree(S->stmt_name);
133 		S->stmt_name = NULL;
134 	}
135 	if (S->param_lengths) {
136 		efree(S->param_lengths);
137 		S->param_lengths = NULL;
138 	}
139 	if (S->param_values) {
140 		efree(S->param_values);
141 		S->param_values = NULL;
142 	}
143 	if (S->param_formats) {
144 		efree(S->param_formats);
145 		S->param_formats = NULL;
146 	}
147 	if (S->param_types) {
148 		efree(S->param_types);
149 		S->param_types = NULL;
150 	}
151 	if (S->query) {
152 		zend_string_release(S->query);
153 		S->query = NULL;
154 	}
155 
156 	if (S->cursor_name) {
157 		if (server_obj_usable) {
158 			pdo_pgsql_db_handle *H = S->H;
159 			char *q = NULL;
160 			PGresult *res;
161 
162 			spprintf(&q, 0, "CLOSE %s", S->cursor_name);
163 			res = PQexec(H->server, q);
164 			efree(q);
165 			if (res) PQclear(res);
166 		}
167 		efree(S->cursor_name);
168 		S->cursor_name = NULL;
169 	}
170 
171 	if(S->cols) {
172 		efree(S->cols);
173 		S->cols = NULL;
174 	}
175 	efree(S);
176 	stmt->driver_data = NULL;
177 	return 1;
178 }
179 
pgsql_stmt_execute(pdo_stmt_t * stmt)180 static int pgsql_stmt_execute(pdo_stmt_t *stmt)
181 {
182 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
183 	pdo_pgsql_db_handle *H = S->H;
184 	ExecStatusType status;
185 	int dispatch_result = 1;
186 
187 	bool in_trans = stmt->dbh->methods->in_transaction(stmt->dbh);
188 
189 	/* in unbuffered mode, finish any running statement: libpq explicitely prohibits this
190 	 * and returns a PGRES_FATAL_ERROR when PQgetResult gets called for stmt 2 if DEALLOCATE
191 	 * was called for stmt 1 inbetween
192 	 * (maybe it will change with pipeline mode in libpq 14?) */
193 	if (S->is_unbuffered && H->running_stmt) {
194 		pgsql_stmt_finish(H->running_stmt, FIN_CLOSE);
195 		H->running_stmt = NULL;
196 	}
197 	/* ensure that we free any previous unfetched results */
198 	pgsql_stmt_finish(S, 0);
199 
200 	S->current_row = 0;
201 
202 	if (S->cursor_name) {
203 		char *q = NULL;
204 
205 		if (S->is_prepared) {
206 			spprintf(&q, 0, "CLOSE %s", S->cursor_name);
207 			PQclear(PQexec(H->server, q));
208 			efree(q);
209 		}
210 
211 		spprintf(&q, 0, "DECLARE %s SCROLL CURSOR WITH HOLD FOR %s", S->cursor_name, ZSTR_VAL(stmt->active_query_string));
212 		S->result = PQexec(H->server, q);
213 		efree(q);
214 
215 		/* check if declare failed */
216 		status = PQresultStatus(S->result);
217 		if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
218 			pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
219 			return 0;
220 		}
221 		PQclear(S->result);
222 
223 		/* the cursor was declared correctly */
224 		S->is_prepared = 1;
225 
226 		/* fetch to be able to get the number of tuples later, but don't advance the cursor pointer */
227 		spprintf(&q, 0, "FETCH FORWARD 0 FROM %s", S->cursor_name);
228 		S->result = PQexec(H->server, q);
229 		efree(q);
230 	} else if (S->stmt_name) {
231 		/* using a prepared statement */
232 
233 		if (!S->is_prepared) {
234 stmt_retry:
235 			/* we deferred the prepare until now, because we didn't
236 			 * know anything about the parameter types; now we do */
237 			S->result = PQprepare(H->server, S->stmt_name, ZSTR_VAL(S->query),
238 						stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
239 						S->param_types);
240 			status = PQresultStatus(S->result);
241 			switch (status) {
242 				case PGRES_COMMAND_OK:
243 				case PGRES_TUPLES_OK:
244 					/* it worked */
245 					S->is_prepared = 1;
246 					PQclear(S->result);
247 					S->result = NULL;
248 					break;
249 				default: {
250 					char *sqlstate = pdo_pgsql_sqlstate(S->result);
251 					/* 42P05 means that the prepared statement already existed. this can happen if you use
252 					 * a connection pooling software line pgpool which doesn't close the db-connection once
253 					 * php disconnects. if php dies (no chance to run RSHUTDOWN) during execution it has no
254 					 * chance to DEALLOCATE the prepared statements it has created. so, if we hit a 42P05 we
255 					 * deallocate it and retry ONCE (thies 2005.12.15)
256 					 */
257 					if (sqlstate && !strcmp(sqlstate, "42P05")) {
258 						PGresult *res;
259 #ifndef HAVE_PQCLOSEPREPARED
260 						char buf[100]; /* stmt_name == "pdo_crsr_%08x" */
261 						snprintf(buf, sizeof(buf), "DEALLOCATE %s", S->stmt_name);
262 						res = PQexec(H->server, buf);
263 #else
264 						res = PQclosePrepared(H->server, S->stmt_name);
265 #endif
266 						if (res) {
267 							PQclear(res);
268 						}
269 						goto stmt_retry;
270 					} else {
271 						pdo_pgsql_error_stmt(stmt, status, sqlstate);
272 						return 0;
273 					}
274 				}
275 			}
276 		}
277 		if (S->is_unbuffered) {
278 			dispatch_result = PQsendQueryPrepared(H->server, S->stmt_name,
279 					stmt->bound_params ?
280 						zend_hash_num_elements(stmt->bound_params) :
281 						0,
282 					(const char**)S->param_values,
283 					S->param_lengths,
284 					S->param_formats,
285 					0);
286 		} else {
287 			S->result = PQexecPrepared(H->server, S->stmt_name,
288 				stmt->bound_params ?
289 					zend_hash_num_elements(stmt->bound_params) :
290 					0,
291 				(const char**)S->param_values,
292 				S->param_lengths,
293 				S->param_formats,
294 				0);
295 		}
296 	} else if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED) {
297 		/* execute query with parameters */
298 		if (S->is_unbuffered) {
299 			dispatch_result = PQsendQueryParams(H->server, ZSTR_VAL(S->query),
300 					stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
301 					S->param_types,
302 					(const char**)S->param_values,
303 					S->param_lengths,
304 					S->param_formats,
305 					0);
306 		} else {
307 			S->result = PQexecParams(H->server, ZSTR_VAL(S->query),
308 				stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
309 				S->param_types,
310 				(const char**)S->param_values,
311 				S->param_lengths,
312 				S->param_formats,
313 				0);
314 		}
315 	} else {
316 		/* execute plain query (with embedded parameters) */
317 		if (S->is_unbuffered) {
318 			dispatch_result = PQsendQuery(H->server, ZSTR_VAL(stmt->active_query_string));
319 		} else {
320 			S->result = PQexec(H->server, ZSTR_VAL(stmt->active_query_string));
321 		}
322 	}
323 
324 	H->running_stmt = S;
325 
326 	if (S->is_unbuffered) {
327 		if (!dispatch_result) {
328 			pdo_pgsql_error_stmt(stmt, 0, NULL);
329 			H->running_stmt = NULL;
330 			return 0;
331 		}
332 		S->is_running_unbuffered = true;
333 		(void)PQsetSingleRowMode(H->server);
334 		/* no matter if it returns 0: PQ then transparently fallbacks to full result fetching */
335 
336 		/* try a first fetch to at least have column names and so on */
337 		S->result = PQgetResult(S->H->server);
338 	}
339 
340 	status = PQresultStatus(S->result);
341 
342 	if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_SINGLE_TUPLE) {
343 		pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
344 		return 0;
345 	}
346 
347 	stmt->column_count = (int) PQnfields(S->result);
348 	if (S->cols == NULL) {
349 		S->cols = ecalloc(stmt->column_count, sizeof(pdo_pgsql_column));
350 	}
351 
352 	if (status == PGRES_COMMAND_OK) {
353 		stmt->row_count = ZEND_ATOL(PQcmdTuples(S->result));
354 		H->pgoid = PQoidValue(S->result);
355 	} else {
356 		stmt->row_count = (zend_long)PQntuples(S->result);
357 	}
358 
359 	if (in_trans && !stmt->dbh->methods->in_transaction(stmt->dbh)) {
360 		pdo_pgsql_close_lob_streams(stmt->dbh);
361 	}
362 
363 	return 1;
364 }
365 
pgsql_stmt_param_hook(pdo_stmt_t * stmt,struct pdo_bound_param_data * param,enum pdo_param_event event_type)366 static int pgsql_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
367 		enum pdo_param_event event_type)
368 {
369 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
370 
371 	if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED && param->is_param) {
372 		switch (event_type) {
373 			case PDO_PARAM_EVT_FREE:
374 				if (param->driver_data) {
375 					efree(param->driver_data);
376 				}
377 				break;
378 
379 			case PDO_PARAM_EVT_NORMALIZE:
380 				/* decode name from $1, $2 into 0, 1 etc. */
381 				if (param->name) {
382 					if (ZSTR_VAL(param->name)[0] == '$') {
383 						param->paramno = ZEND_ATOL(ZSTR_VAL(param->name) + 1);
384 					} else {
385 						/* resolve parameter name to rewritten name */
386 						zend_string *namevar;
387 
388 						if (stmt->bound_param_map && (namevar = zend_hash_find_ptr(stmt->bound_param_map,
389 								param->name)) != NULL) {
390 							param->paramno = ZEND_ATOL(ZSTR_VAL(namevar) + 1);
391 							param->paramno--;
392 						} else {
393 							pdo_pgsql_error_stmt_msg(stmt, 0, "HY093", ZSTR_VAL(param->name));
394 							return 0;
395 						}
396 					}
397 				}
398 				break;
399 
400 			case PDO_PARAM_EVT_ALLOC:
401 				if (!stmt->bound_param_map) {
402 					return 1;
403 				}
404 				if (!zend_hash_index_exists(stmt->bound_param_map, param->paramno)) {
405 					pdo_pgsql_error_stmt_msg(stmt, 0, "HY093", "parameter was not defined");
406 					return 0;
407 				}
408 				ZEND_FALLTHROUGH;
409 			case PDO_PARAM_EVT_EXEC_POST:
410 			case PDO_PARAM_EVT_FETCH_PRE:
411 			case PDO_PARAM_EVT_FETCH_POST:
412 				/* work is handled by EVT_NORMALIZE */
413 				return 1;
414 
415 			case PDO_PARAM_EVT_EXEC_PRE:
416 				if (!stmt->bound_param_map) {
417 					return 1;
418 				}
419 				if (!S->param_values) {
420 					S->param_values = ecalloc(
421 							zend_hash_num_elements(stmt->bound_param_map),
422 							sizeof(char*));
423 					S->param_lengths = ecalloc(
424 							zend_hash_num_elements(stmt->bound_param_map),
425 							sizeof(int));
426 					S->param_formats = ecalloc(
427 							zend_hash_num_elements(stmt->bound_param_map),
428 							sizeof(int));
429 					S->param_types = ecalloc(
430 							zend_hash_num_elements(stmt->bound_param_map),
431 							sizeof(Oid));
432 				}
433 				if (param->paramno >= 0) {
434 					zval *parameter;
435 
436 					/*
437 					if (param->paramno >= zend_hash_num_elements(stmt->bound_params)) {
438 						pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined");
439 						return 0;
440 					}
441 					*/
442 
443 					if (Z_ISREF(param->parameter)) {
444 						parameter = Z_REFVAL(param->parameter);
445 					} else {
446 						parameter = &param->parameter;
447 					}
448 
449 					if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB &&
450 							Z_TYPE_P(parameter) == IS_RESOURCE) {
451 						php_stream *stm;
452 						php_stream_from_zval_no_verify(stm, parameter);
453 						if (stm) {
454 							if (php_stream_is(stm, &pdo_pgsql_lob_stream_ops)) {
455 								struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stm->abstract;
456 								pdo_pgsql_bound_param *P = param->driver_data;
457 
458 								if (P == NULL) {
459 									P = ecalloc(1, sizeof(*P));
460 									param->driver_data = P;
461 								}
462 								P->oid = htonl(self->oid);
463 								S->param_values[param->paramno] = (char*)&P->oid;
464 								S->param_lengths[param->paramno] = sizeof(P->oid);
465 								S->param_formats[param->paramno] = 1;
466 								S->param_types[param->paramno] = OIDOID;
467 								return 1;
468 							} else {
469 								zend_string *str = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0);
470 								if (str != NULL) {
471 									ZVAL_STR(parameter, str);
472 								} else {
473 									ZVAL_EMPTY_STRING(parameter);
474 								}
475 							}
476 						} else {
477 							/* expected a stream resource */
478 							pdo_pgsql_error_stmt(stmt, PGRES_FATAL_ERROR, "HY105");
479 							return 0;
480 						}
481 					}
482 
483 					if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_NULL ||
484 							Z_TYPE_P(parameter) == IS_NULL) {
485 						S->param_values[param->paramno] = NULL;
486 						S->param_lengths[param->paramno] = 0;
487 					} else if (Z_TYPE_P(parameter) == IS_FALSE || Z_TYPE_P(parameter) == IS_TRUE) {
488 						S->param_values[param->paramno] = Z_TYPE_P(parameter) == IS_TRUE ? "t" : "f";
489 						S->param_lengths[param->paramno] = 1;
490 						S->param_formats[param->paramno] = 0;
491 					} else {
492 						convert_to_string(parameter);
493 						S->param_values[param->paramno] = Z_STRVAL_P(parameter);
494 						S->param_lengths[param->paramno] = Z_STRLEN_P(parameter);
495 						S->param_formats[param->paramno] = 0;
496 					}
497 
498 					if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
499 						S->param_types[param->paramno] = 0;
500 						S->param_formats[param->paramno] = 1;
501 					} else {
502 						S->param_types[param->paramno] = 0;
503 					}
504 				}
505 				break;
506 		}
507 	} else if (param->is_param && event_type == PDO_PARAM_EVT_NORMALIZE) {
508 		/* We need to manually convert to a pg native boolean value */
509 		if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL &&
510 			((param->param_type & PDO_PARAM_INPUT_OUTPUT) != PDO_PARAM_INPUT_OUTPUT)) {
511 			const char *s = zend_is_true(&param->parameter) ? "t" : "f";
512 			param->param_type = PDO_PARAM_STR;
513 			zval_ptr_dtor(&param->parameter);
514 			ZVAL_STRINGL(&param->parameter, s, 1);
515 		}
516 	}
517 	return 1;
518 }
519 
pgsql_stmt_fetch(pdo_stmt_t * stmt,enum pdo_fetch_orientation ori,zend_long offset)520 static int pgsql_stmt_fetch(pdo_stmt_t *stmt,
521 	enum pdo_fetch_orientation ori, zend_long offset)
522 {
523 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
524 
525 	if (S->cursor_name) {
526 		char *ori_str = NULL;
527 		char *q = NULL;
528 		ExecStatusType status;
529 
530 		switch (ori) {
531 			case PDO_FETCH_ORI_NEXT: 	spprintf(&ori_str, 0, "NEXT"); break;
532 			case PDO_FETCH_ORI_PRIOR:	spprintf(&ori_str, 0, "BACKWARD"); break;
533 			case PDO_FETCH_ORI_FIRST:	spprintf(&ori_str, 0, "FIRST"); break;
534 			case PDO_FETCH_ORI_LAST:	spprintf(&ori_str, 0, "LAST"); break;
535 			case PDO_FETCH_ORI_ABS:		spprintf(&ori_str, 0, "ABSOLUTE " ZEND_LONG_FMT, offset); break;
536 			case PDO_FETCH_ORI_REL:		spprintf(&ori_str, 0, "RELATIVE " ZEND_LONG_FMT, offset); break;
537 			default:
538 				return 0;
539 		}
540 
541 		if(S->result) {
542 			PQclear(S->result);
543 			S->result = NULL;
544 		}
545 
546 		spprintf(&q, 0, "FETCH %s FROM %s", ori_str, S->cursor_name);
547 		efree(ori_str);
548 		S->result = PQexec(S->H->server, q);
549 		efree(q);
550 		status = PQresultStatus(S->result);
551 
552 		if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
553 			pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
554 			return 0;
555 		}
556 
557 		if (PQntuples(S->result)) {
558 			S->current_row = 1;
559 			return 1;
560 		} else {
561 			return 0;
562 		}
563 	} else {
564 		if (S->is_running_unbuffered && S->current_row >= stmt->row_count) {
565 			ExecStatusType status;
566 
567 			/* @todo in unbuffered mode, PQ allows multiple queries to be passed:
568 			 *       column_count should be recomputed on each iteration */
569 
570 			if(S->result) {
571 				PQclear(S->result);
572 				S->result = NULL;
573 			}
574 
575 			S->result = PQgetResult(S->H->server);
576 			status = PQresultStatus(S->result);
577 
578 			if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_SINGLE_TUPLE) {
579 				pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
580 				return 0;
581 			}
582 
583 			stmt->row_count = (zend_long)PQntuples(S->result);
584 			S->current_row = 0;
585 
586 			if (!stmt->row_count) {
587 				S->is_running_unbuffered = false;
588 				/* libpq requires looping until getResult returns null */
589 				pgsql_stmt_finish(S, 0);
590 			}
591 		}
592 		if (S->current_row < stmt->row_count) {
593 			S->current_row++;
594 			return 1;
595 		} else {
596 			return 0;
597 		}
598 	}
599 }
600 
pgsql_stmt_describe(pdo_stmt_t * stmt,int colno)601 static int pgsql_stmt_describe(pdo_stmt_t *stmt, int colno)
602 {
603 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
604 	struct pdo_column_data *cols = stmt->columns;
605 	char *str;
606 
607 	if (!S->result) {
608 		return 0;
609 	}
610 
611 	str = PQfname(S->result, colno);
612 	cols[colno].name = zend_string_init(str, strlen(str), 0);
613 	cols[colno].maxlen = PQfsize(S->result, colno);
614 	cols[colno].precision = PQfmod(S->result, colno);
615 	S->cols[colno].pgsql_type = PQftype(S->result, colno);
616 
617 	return 1;
618 }
619 
pgsql_stmt_get_col(pdo_stmt_t * stmt,int colno,zval * result,enum pdo_param_type * type)620 static int pgsql_stmt_get_col(pdo_stmt_t *stmt, int colno, zval *result, enum pdo_param_type *type)
621 {
622 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
623 	if (!S->result) {
624 		return 0;
625 	}
626 
627 	/* We have already increased count by 1 in pgsql_stmt_fetch() */
628 	if (PQgetisnull(S->result, S->current_row - 1, colno)) { /* Check if we got NULL */
629 		ZVAL_NULL(result);
630 	} else {
631 		char *ptr = PQgetvalue(S->result, S->current_row - 1, colno);
632 		size_t len = PQgetlength(S->result, S->current_row - 1, colno);
633 
634 		switch (S->cols[colno].pgsql_type) {
635 			case BOOLOID:
636 				ZVAL_BOOL(result, *ptr == 't');
637 				break;
638 
639 			case INT2OID:
640 			case INT4OID:
641 #if SIZEOF_ZEND_LONG >= 8
642 			case INT8OID:
643 #endif
644 				ZVAL_LONG(result, ZEND_ATOL(ptr));
645 				break;
646 			case FLOAT4OID:
647 			case FLOAT8OID:
648                 if (strncmp(ptr, "Infinity", len) == 0) {
649                     ZVAL_DOUBLE(result, ZEND_INFINITY);
650                 } else if (strncmp(ptr, "-Infinity", len) == 0) {
651                     ZVAL_DOUBLE(result, -ZEND_INFINITY);
652                 } else if (strncmp(ptr, "NaN", len) == 0) {
653                     ZVAL_DOUBLE(result, ZEND_NAN);
654                 } else {
655                     ZVAL_DOUBLE(result, zend_strtod(ptr, NULL));
656                 }
657 				break;
658 
659 			case OIDOID: {
660 				char *end_ptr;
661 				Oid oid = (Oid)strtoul(ptr, &end_ptr, 10);
662 				if (type && *type == PDO_PARAM_LOB) {
663 					/* If column was bound as LOB, return a stream. */
664 					int loid = lo_open(S->H->server, oid, INV_READ);
665 					if (loid >= 0) {
666 						php_stream *stream = pdo_pgsql_create_lob_stream(&stmt->database_object_handle, loid, oid);
667 						if (stream) {
668 							php_stream_to_zval(stream, result);
669 							return 1;
670 						}
671 					}
672 					return 0;
673 				} else {
674 					/* Otherwise return OID as integer. */
675 					ZVAL_LONG(result, oid);
676 				}
677 				break;
678 			}
679 
680 			case BYTEAOID: {
681 				size_t tmp_len;
682 				char *tmp_ptr = (char *)PQunescapeBytea((unsigned char *) ptr, &tmp_len);
683 				if (!tmp_ptr) {
684 					/* PQunescapeBytea returned an error */
685 					return 0;
686 				}
687 
688 				zend_string *str = zend_string_init(tmp_ptr, tmp_len, 0);
689 				php_stream *stream = php_stream_memory_open(TEMP_STREAM_READONLY, str);
690 				php_stream_to_zval(stream, result);
691 				zend_string_release(str);
692 				PQfreemem(tmp_ptr);
693 				break;
694 			}
695 
696 			default:
697 				ZVAL_STRINGL_FAST(result, ptr, len);
698 				break;
699 		}
700 	}
701 
702 	return 1;
703 }
704 
pdo_pgsql_translate_oid_to_table(Oid oid,PGconn * conn)705 static zend_always_inline char * pdo_pgsql_translate_oid_to_table(Oid oid, PGconn *conn)
706 {
707 	char *table_name = NULL;
708 	PGresult *tmp_res;
709 	char *querystr = NULL;
710 
711 	spprintf(&querystr, 0, "SELECT RELNAME FROM PG_CLASS WHERE OID=%d", oid);
712 
713 	if ((tmp_res = PQexec(conn, querystr)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
714 		if (tmp_res) {
715 			PQclear(tmp_res);
716 		}
717 		efree(querystr);
718 		return 0;
719 	}
720 	efree(querystr);
721 
722 	if (1 == PQgetisnull(tmp_res, 0, 0) || (table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
723 		PQclear(tmp_res);
724 		return 0;
725 	}
726 
727 	table_name = estrdup(table_name);
728 
729 	PQclear(tmp_res);
730 	return table_name;
731 }
732 
pgsql_stmt_get_column_meta(pdo_stmt_t * stmt,zend_long colno,zval * return_value)733 static int pgsql_stmt_get_column_meta(pdo_stmt_t *stmt, zend_long colno, zval *return_value)
734 {
735 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
736 	PGresult *res;
737 	char *q=NULL;
738 	ExecStatusType status;
739 	Oid table_oid;
740 	char *table_name=NULL;
741 
742 	if (!S->result) {
743 		return FAILURE;
744 	}
745 
746 	if (colno >= stmt->column_count) {
747 		return FAILURE;
748 	}
749 
750 	array_init(return_value);
751 	add_assoc_long(return_value, "pgsql:oid", S->cols[colno].pgsql_type);
752 
753 	table_oid = PQftable(S->result, colno);
754 	add_assoc_long(return_value, "pgsql:table_oid", table_oid);
755 	table_name = pdo_pgsql_translate_oid_to_table(table_oid, S->H->server);
756 	if (table_name) {
757 		add_assoc_string(return_value, "table", table_name);
758 		efree(table_name);
759 	}
760 
761 	switch (S->cols[colno].pgsql_type) {
762 		case BOOLOID:
763 			add_assoc_string(return_value, "native_type", BOOLLABEL);
764 			break;
765 		case BYTEAOID:
766 			add_assoc_string(return_value, "native_type", BYTEALABEL);
767 			break;
768 		case INT8OID:
769 			add_assoc_string(return_value, "native_type", INT8LABEL);
770 			break;
771 		case INT2OID:
772 			add_assoc_string(return_value, "native_type", INT2LABEL);
773 			break;
774 		case INT4OID:
775 			add_assoc_string(return_value, "native_type", INT4LABEL);
776 			break;
777 		case FLOAT4OID:
778 			add_assoc_string(return_value, "native_type", FLOAT4LABEL);
779 			break;
780 		case FLOAT8OID:
781 			add_assoc_string(return_value, "native_type", FLOAT8LABEL);
782 			break;
783 		case TEXTOID:
784 			add_assoc_string(return_value, "native_type", TEXTLABEL);
785 			break;
786 		case VARCHAROID:
787 			add_assoc_string(return_value, "native_type", VARCHARLABEL);
788 			break;
789 		case DATEOID:
790 			add_assoc_string(return_value, "native_type", DATELABEL);
791 			break;
792 		case TIMESTAMPOID:
793 			add_assoc_string(return_value, "native_type", TIMESTAMPLABEL);
794 			break;
795 		default:
796 			/* Fetch metadata from Postgres system catalogue */
797 			spprintf(&q, 0, "SELECT TYPNAME FROM PG_TYPE WHERE OID=%u", S->cols[colno].pgsql_type);
798 			res = PQexec(S->H->server, q);
799 			efree(q);
800 			status = PQresultStatus(res);
801 			if (status == PGRES_TUPLES_OK && 1 == PQntuples(res)) {
802 				add_assoc_string(return_value, "native_type", PQgetvalue(res, 0, 0));
803 			}
804 			PQclear(res);
805 	}
806 
807 	enum pdo_param_type param_type;
808 	switch (S->cols[colno].pgsql_type) {
809 		case BOOLOID:
810 			param_type = PDO_PARAM_BOOL;
811 			break;
812 		case INT2OID:
813 		case INT4OID:
814 		case INT8OID:
815 			param_type = PDO_PARAM_INT;
816 			break;
817 		case OIDOID:
818 		case BYTEAOID:
819 			param_type = PDO_PARAM_LOB;
820 			break;
821 		default:
822 			param_type = PDO_PARAM_STR;
823 	}
824 	add_assoc_long(return_value, "pdo_type", param_type);
825 
826 	return 1;
827 }
828 
pdo_pgsql_stmt_cursor_closer(pdo_stmt_t * stmt)829 static int pdo_pgsql_stmt_cursor_closer(pdo_stmt_t *stmt)
830 {
831 	return 1;
832 }
833 
pgsql_stmt_get_attr(pdo_stmt_t * stmt,zend_long attr,zval * val)834 static int pgsql_stmt_get_attr(pdo_stmt_t *stmt, zend_long attr, zval *val)
835 {
836 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
837 
838 	switch (attr) {
839 #ifdef HAVE_PG_RESULT_MEMORY_SIZE
840 		case PDO_PGSQL_ATTR_RESULT_MEMORY_SIZE:
841 			if(stmt->executed) {
842 				ZVAL_LONG(val, PQresultMemorySize(S->result));
843 			} else {
844 				char *tmp;
845 				spprintf(&tmp, 0, "statement '%s' has not been executed yet", S->stmt_name);
846 
847 				pdo_pgsql_error_stmt_msg(stmt, 0, "HY000", tmp);
848 				efree(tmp);
849 
850 				ZVAL_NULL(val);
851 			}
852 			return 1;
853 #endif
854 
855 		default:
856 			(void)S;
857 			return 0;
858 	}
859 }
860 
861 const struct pdo_stmt_methods pgsql_stmt_methods = {
862 	pgsql_stmt_dtor,
863 	pgsql_stmt_execute,
864 	pgsql_stmt_fetch,
865 	pgsql_stmt_describe,
866 	pgsql_stmt_get_col,
867 	pgsql_stmt_param_hook,
868 	NULL, /* set_attr */
869 	pgsql_stmt_get_attr,
870 	pgsql_stmt_get_column_meta,
871 	NULL,  /* next_rowset */
872 	pdo_pgsql_stmt_cursor_closer
873 };
874