xref: /PHP-7.4/ext/pdo_pgsql/pgsql_statement.c (revision b8e49fe8)
1 /*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 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 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24 
25 #include "php.h"
26 #include "php_ini.h"
27 #include "ext/standard/info.h"
28 #include "pdo/php_pdo.h"
29 #include "pdo/php_pdo_driver.h"
30 #include "php_pdo_pgsql.h"
31 #include "php_pdo_pgsql_int.h"
32 #if HAVE_NETINET_IN_H
33 #include <netinet/in.h>
34 #endif
35 
36 /* from postgresql/src/include/catalog/pg_type.h */
37 #define BOOLLABEL   "bool"
38 #define BOOLOID     16
39 #define BYTEALABEL  "bytea"
40 #define BYTEAOID    17
41 #define DATELABEL   "date"
42 #define DATEOID     1082
43 #define INT2LABEL   "int2"
44 #define INT2OID     21
45 #define INT4LABEL   "int4"
46 #define INT4OID     23
47 #define INT8LABEL   "int8"
48 #define INT8OID     20
49 #define OIDOID      26
50 #define TEXTLABEL   "text"
51 #define TEXTOID     25
52 #define TIMESTAMPLABEL "timestamp"
53 #define TIMESTAMPOID   1114
54 #define VARCHARLABEL "varchar"
55 #define VARCHAROID   1043
56 
57 
58 
pgsql_stmt_dtor(pdo_stmt_t * stmt)59 static int pgsql_stmt_dtor(pdo_stmt_t *stmt)
60 {
61 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
62 	zend_bool server_obj_usable = !Z_ISUNDEF(stmt->database_object_handle)
63 		&& IS_OBJ_VALID(EG(objects_store).object_buckets[Z_OBJ_HANDLE(stmt->database_object_handle)])
64 		&& !(OBJ_FLAGS(Z_OBJ(stmt->database_object_handle)) & IS_OBJ_FREE_CALLED);
65 
66 	if (S->result) {
67 		/* free the resource */
68 		PQclear(S->result);
69 		S->result = NULL;
70 	}
71 
72 	if (S->stmt_name) {
73 		if (S->is_prepared && server_obj_usable) {
74 			pdo_pgsql_db_handle *H = S->H;
75 			char *q = NULL;
76 			PGresult *res;
77 
78 			spprintf(&q, 0, "DEALLOCATE %s", S->stmt_name);
79 			res = PQexec(H->server, q);
80 			efree(q);
81 			if (res) {
82 				PQclear(res);
83 			}
84 		}
85 		efree(S->stmt_name);
86 		S->stmt_name = NULL;
87 	}
88 	if (S->param_lengths) {
89 		efree(S->param_lengths);
90 		S->param_lengths = NULL;
91 	}
92 	if (S->param_values) {
93 		efree(S->param_values);
94 		S->param_values = NULL;
95 	}
96 	if (S->param_formats) {
97 		efree(S->param_formats);
98 		S->param_formats = NULL;
99 	}
100 	if (S->param_types) {
101 		efree(S->param_types);
102 		S->param_types = NULL;
103 	}
104 	if (S->query) {
105 		efree(S->query);
106 		S->query = NULL;
107 	}
108 
109 	if (S->cursor_name) {
110 		if (server_obj_usable) {
111 			pdo_pgsql_db_handle *H = S->H;
112 			char *q = NULL;
113 			PGresult *res;
114 
115 			spprintf(&q, 0, "CLOSE %s", S->cursor_name);
116 			res = PQexec(H->server, q);
117 			efree(q);
118 			if (res) PQclear(res);
119 		}
120 		efree(S->cursor_name);
121 		S->cursor_name = NULL;
122 	}
123 
124 	if(S->cols) {
125 		efree(S->cols);
126 		S->cols = NULL;
127 	}
128 	efree(S);
129 	stmt->driver_data = NULL;
130 	return 1;
131 }
132 
pgsql_stmt_execute(pdo_stmt_t * stmt)133 static int pgsql_stmt_execute(pdo_stmt_t *stmt)
134 {
135 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
136 	pdo_pgsql_db_handle *H = S->H;
137 	ExecStatusType status;
138 
139 	/* ensure that we free any previous unfetched results */
140 	if(S->result) {
141 		PQclear(S->result);
142 		S->result = NULL;
143 	}
144 
145 	S->current_row = 0;
146 
147 	if (S->cursor_name) {
148 		char *q = NULL;
149 
150 		if (S->is_prepared) {
151 			spprintf(&q, 0, "CLOSE %s", S->cursor_name);
152 			PQclear(PQexec(H->server, q));
153 			efree(q);
154 		}
155 
156 		spprintf(&q, 0, "DECLARE %s SCROLL CURSOR WITH HOLD FOR %s", S->cursor_name, stmt->active_query_string);
157 		S->result = PQexec(H->server, q);
158 		efree(q);
159 
160 		/* check if declare failed */
161 		status = PQresultStatus(S->result);
162 		if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
163 			pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
164 			return 0;
165 		}
166 		PQclear(S->result);
167 
168 		/* the cursor was declared correctly */
169 		S->is_prepared = 1;
170 
171 		/* fetch to be able to get the number of tuples later, but don't advance the cursor pointer */
172 		spprintf(&q, 0, "FETCH FORWARD 0 FROM %s", S->cursor_name);
173 		S->result = PQexec(H->server, q);
174 		efree(q);
175 	} else if (S->stmt_name) {
176 		/* using a prepared statement */
177 
178 		if (!S->is_prepared) {
179 stmt_retry:
180 			/* we deferred the prepare until now, because we didn't
181 			 * know anything about the parameter types; now we do */
182 			S->result = PQprepare(H->server, S->stmt_name, S->query,
183 						stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
184 						S->param_types);
185 			status = PQresultStatus(S->result);
186 			switch (status) {
187 				case PGRES_COMMAND_OK:
188 				case PGRES_TUPLES_OK:
189 					/* it worked */
190 					S->is_prepared = 1;
191 					PQclear(S->result);
192 					break;
193 				default: {
194 					char *sqlstate = pdo_pgsql_sqlstate(S->result);
195 					/* 42P05 means that the prepared statement already existed. this can happen if you use
196 					 * a connection pooling software line pgpool which doesn't close the db-connection once
197 					 * php disconnects. if php dies (no chance to run RSHUTDOWN) during execution it has no
198 					 * chance to DEALLOCATE the prepared statements it has created. so, if we hit a 42P05 we
199 					 * deallocate it and retry ONCE (thies 2005.12.15)
200 					 */
201 					if (sqlstate && !strcmp(sqlstate, "42P05")) {
202 						char buf[100]; /* stmt_name == "pdo_crsr_%08x" */
203 						PGresult *res;
204 						snprintf(buf, sizeof(buf), "DEALLOCATE %s", S->stmt_name);
205 						res = PQexec(H->server, buf);
206 						if (res) {
207 							PQclear(res);
208 						}
209 						goto stmt_retry;
210 					} else {
211 						pdo_pgsql_error_stmt(stmt, status, sqlstate);
212 						return 0;
213 					}
214 				}
215 			}
216 		}
217 		S->result = PQexecPrepared(H->server, S->stmt_name,
218 				stmt->bound_params ?
219 					zend_hash_num_elements(stmt->bound_params) :
220 					0,
221 				(const char**)S->param_values,
222 				S->param_lengths,
223 				S->param_formats,
224 				0);
225 	} else if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED) {
226 		/* execute query with parameters */
227 		S->result = PQexecParams(H->server, S->query,
228 				stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
229 				S->param_types,
230 				(const char**)S->param_values,
231 				S->param_lengths,
232 				S->param_formats,
233 				0);
234 	} else {
235 		/* execute plain query (with embedded parameters) */
236 		S->result = PQexec(H->server, stmt->active_query_string);
237 	}
238 	status = PQresultStatus(S->result);
239 
240 	if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
241 		pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
242 		return 0;
243 	}
244 
245 	if (!stmt->executed && (!stmt->column_count || S->cols == NULL)) {
246 		stmt->column_count = (int) PQnfields(S->result);
247 		S->cols = ecalloc(stmt->column_count, sizeof(pdo_pgsql_column));
248 	}
249 
250 	if (status == PGRES_COMMAND_OK) {
251 		ZEND_ATOL(stmt->row_count, PQcmdTuples(S->result));
252 		H->pgoid = PQoidValue(S->result);
253 	} else {
254 		stmt->row_count = (zend_long)PQntuples(S->result);
255 	}
256 
257 	return 1;
258 }
259 
pgsql_stmt_param_hook(pdo_stmt_t * stmt,struct pdo_bound_param_data * param,enum pdo_param_event event_type)260 static int pgsql_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
261 		enum pdo_param_event event_type)
262 {
263 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
264 
265 	if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED && param->is_param) {
266 		switch (event_type) {
267 			case PDO_PARAM_EVT_FREE:
268 				if (param->driver_data) {
269 					efree(param->driver_data);
270 				}
271 				break;
272 
273 			case PDO_PARAM_EVT_NORMALIZE:
274 				/* decode name from $1, $2 into 0, 1 etc. */
275 				if (param->name) {
276 					if (ZSTR_VAL(param->name)[0] == '$') {
277 						ZEND_ATOL(param->paramno, ZSTR_VAL(param->name) + 1);
278 					} else {
279 						/* resolve parameter name to rewritten name */
280 						char *namevar;
281 
282 						if (stmt->bound_param_map && (namevar = zend_hash_find_ptr(stmt->bound_param_map,
283 								param->name)) != NULL) {
284 							ZEND_ATOL(param->paramno, namevar + 1);
285 							param->paramno--;
286 						} else {
287 							pdo_raise_impl_error(stmt->dbh, stmt, "HY093", ZSTR_VAL(param->name));
288 							return 0;
289 						}
290 					}
291 				}
292 				break;
293 
294 			case PDO_PARAM_EVT_ALLOC:
295 				if (!stmt->bound_param_map) {
296 					return 1;
297 				}
298 				if (!zend_hash_index_exists(stmt->bound_param_map, param->paramno)) {
299 					pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined");
300 					return 0;
301 				}
302 			case PDO_PARAM_EVT_EXEC_POST:
303 			case PDO_PARAM_EVT_FETCH_PRE:
304 			case PDO_PARAM_EVT_FETCH_POST:
305 				/* work is handled by EVT_NORMALIZE */
306 				return 1;
307 
308 			case PDO_PARAM_EVT_EXEC_PRE:
309 				if (!stmt->bound_param_map) {
310 					return 1;
311 				}
312 				if (!S->param_values) {
313 					S->param_values = ecalloc(
314 							zend_hash_num_elements(stmt->bound_param_map),
315 							sizeof(char*));
316 					S->param_lengths = ecalloc(
317 							zend_hash_num_elements(stmt->bound_param_map),
318 							sizeof(int));
319 					S->param_formats = ecalloc(
320 							zend_hash_num_elements(stmt->bound_param_map),
321 							sizeof(int));
322 					S->param_types = ecalloc(
323 							zend_hash_num_elements(stmt->bound_param_map),
324 							sizeof(Oid));
325 				}
326 				if (param->paramno >= 0) {
327 					zval *parameter;
328 
329 					/*
330 					if (param->paramno >= zend_hash_num_elements(stmt->bound_params)) {
331 						pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined");
332 						return 0;
333 					}
334 					*/
335 
336 					if (Z_ISREF(param->parameter)) {
337 						parameter = Z_REFVAL(param->parameter);
338 					} else {
339 						parameter = &param->parameter;
340 					}
341 
342 					if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB &&
343 							Z_TYPE_P(parameter) == IS_RESOURCE) {
344 						php_stream *stm;
345 						php_stream_from_zval_no_verify(stm, parameter);
346 						if (stm) {
347 							if (php_stream_is(stm, &pdo_pgsql_lob_stream_ops)) {
348 								struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stm->abstract;
349 								pdo_pgsql_bound_param *P = param->driver_data;
350 
351 								if (P == NULL) {
352 									P = ecalloc(1, sizeof(*P));
353 									param->driver_data = P;
354 								}
355 								P->oid = htonl(self->oid);
356 								S->param_values[param->paramno] = (char*)&P->oid;
357 								S->param_lengths[param->paramno] = sizeof(P->oid);
358 								S->param_formats[param->paramno] = 1;
359 								S->param_types[param->paramno] = OIDOID;
360 								return 1;
361 							} else {
362 								zend_string *str = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0);
363 								if (str != NULL) {
364 									//??SEPARATE_ZVAL_IF_NOT_REF(&param->parameter);
365 									ZVAL_STR(parameter, str);
366 								} else {
367 									ZVAL_EMPTY_STRING(parameter);
368 								}
369 							}
370 						} else {
371 							/* expected a stream resource */
372 							pdo_pgsql_error_stmt(stmt, PGRES_FATAL_ERROR, "HY105");
373 							return 0;
374 						}
375 					}
376 
377 					if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_NULL ||
378 							Z_TYPE_P(parameter) == IS_NULL) {
379 						S->param_values[param->paramno] = NULL;
380 						S->param_lengths[param->paramno] = 0;
381 					} else if (Z_TYPE_P(parameter) == IS_FALSE || Z_TYPE_P(parameter) == IS_TRUE) {
382 						S->param_values[param->paramno] = Z_TYPE_P(parameter) == IS_TRUE ? "t" : "f";
383 						S->param_lengths[param->paramno] = 1;
384 						S->param_formats[param->paramno] = 0;
385 					} else {
386 						//SEPARATE_ZVAL_IF_NOT_REF(&param->parameter);
387 						convert_to_string_ex(parameter);
388 						S->param_values[param->paramno] = Z_STRVAL_P(parameter);
389 						S->param_lengths[param->paramno] = Z_STRLEN_P(parameter);
390 						S->param_formats[param->paramno] = 0;
391 					}
392 
393 					if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
394 						S->param_types[param->paramno] = 0;
395 						S->param_formats[param->paramno] = 1;
396 					} else {
397 						S->param_types[param->paramno] = 0;
398 					}
399 				}
400 				break;
401 		}
402 	} else if (param->is_param && event_type == PDO_PARAM_EVT_NORMALIZE) {
403 		/* We need to manually convert to a pg native boolean value */
404 		if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL &&
405 			((param->param_type & PDO_PARAM_INPUT_OUTPUT) != PDO_PARAM_INPUT_OUTPUT)) {
406 			const char *s = zend_is_true(&param->parameter) ? "t" : "f";
407 			param->param_type = PDO_PARAM_STR;
408 			zval_ptr_dtor(&param->parameter);
409 			ZVAL_STRINGL(&param->parameter, s, 1);
410 		}
411 	}
412 	return 1;
413 }
414 
pgsql_stmt_fetch(pdo_stmt_t * stmt,enum pdo_fetch_orientation ori,zend_long offset)415 static int pgsql_stmt_fetch(pdo_stmt_t *stmt,
416 	enum pdo_fetch_orientation ori, zend_long offset)
417 {
418 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
419 
420 	if (S->cursor_name) {
421 		char *ori_str = NULL;
422 		char *q = NULL;
423 		ExecStatusType status;
424 
425 		switch (ori) {
426 			case PDO_FETCH_ORI_NEXT: 	spprintf(&ori_str, 0, "NEXT"); break;
427 			case PDO_FETCH_ORI_PRIOR:	spprintf(&ori_str, 0, "BACKWARD"); break;
428 			case PDO_FETCH_ORI_FIRST:	spprintf(&ori_str, 0, "FIRST"); break;
429 			case PDO_FETCH_ORI_LAST:	spprintf(&ori_str, 0, "LAST"); break;
430 			case PDO_FETCH_ORI_ABS:		spprintf(&ori_str, 0, "ABSOLUTE " ZEND_LONG_FMT, offset); break;
431 			case PDO_FETCH_ORI_REL:		spprintf(&ori_str, 0, "RELATIVE " ZEND_LONG_FMT, offset); break;
432 			default:
433 				return 0;
434 		}
435 
436 		if(S->result) {
437 			PQclear(S->result);
438 			S->result = NULL;
439 		}
440 
441 		spprintf(&q, 0, "FETCH %s FROM %s", ori_str, S->cursor_name);
442 		efree(ori_str);
443 		S->result = PQexec(S->H->server, q);
444 		efree(q);
445 		status = PQresultStatus(S->result);
446 
447 		if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
448 			pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
449 			return 0;
450 		}
451 
452 		if (PQntuples(S->result)) {
453 			S->current_row = 1;
454 			return 1;
455 		} else {
456 			return 0;
457 		}
458 	} else {
459 		if (S->current_row < stmt->row_count) {
460 			S->current_row++;
461 			return 1;
462 		} else {
463 			return 0;
464 		}
465 	}
466 }
467 
pgsql_stmt_describe(pdo_stmt_t * stmt,int colno)468 static int pgsql_stmt_describe(pdo_stmt_t *stmt, int colno)
469 {
470 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
471 	struct pdo_column_data *cols = stmt->columns;
472 	struct pdo_bound_param_data *param;
473 	char *str;
474 
475 	if (!S->result) {
476 		return 0;
477 	}
478 
479 	str = PQfname(S->result, colno);
480 	cols[colno].name = zend_string_init(str, strlen(str), 0);
481 	cols[colno].maxlen = PQfsize(S->result, colno);
482 	cols[colno].precision = PQfmod(S->result, colno);
483 	S->cols[colno].pgsql_type = PQftype(S->result, colno);
484 
485 	switch (S->cols[colno].pgsql_type) {
486 
487 		case BOOLOID:
488 			cols[colno].param_type = PDO_PARAM_BOOL;
489 			break;
490 
491 		case OIDOID:
492 			/* did the user bind the column as a LOB ? */
493 			if (stmt->bound_columns && (
494 					(param = zend_hash_index_find_ptr(stmt->bound_columns, colno)) != NULL ||
495 					(param = zend_hash_find_ptr(stmt->bound_columns, cols[colno].name)) != NULL)) {
496 
497 				if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
498 					cols[colno].param_type = PDO_PARAM_LOB;
499 					break;
500 				}
501 			}
502 			cols[colno].param_type = PDO_PARAM_INT;
503 			break;
504 
505 		case INT2OID:
506 		case INT4OID:
507 			cols[colno].param_type = PDO_PARAM_INT;
508 			break;
509 
510 		case INT8OID:
511 			if (sizeof(zend_long)>=8) {
512 				cols[colno].param_type = PDO_PARAM_INT;
513 			} else {
514 				cols[colno].param_type = PDO_PARAM_STR;
515 			}
516 			break;
517 
518 		case BYTEAOID:
519 			cols[colno].param_type = PDO_PARAM_LOB;
520 			break;
521 
522 		default:
523 			cols[colno].param_type = PDO_PARAM_STR;
524 	}
525 
526 	return 1;
527 }
528 
pgsql_stmt_get_col(pdo_stmt_t * stmt,int colno,char ** ptr,size_t * len,int * caller_frees)529 static int pgsql_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, size_t *len, int *caller_frees )
530 {
531 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
532 	struct pdo_column_data *cols = stmt->columns;
533 	size_t tmp_len;
534 
535 	if (!S->result) {
536 		return 0;
537 	}
538 
539 	/* We have already increased count by 1 in pgsql_stmt_fetch() */
540 	if (PQgetisnull(S->result, S->current_row - 1, colno)) { /* Check if we got NULL */
541 		*ptr = NULL;
542 		*len = 0;
543 	} else {
544 		*ptr = PQgetvalue(S->result, S->current_row - 1, colno);
545 		*len = PQgetlength(S->result, S->current_row - 1, colno);
546 
547 		switch (cols[colno].param_type) {
548 
549 			case PDO_PARAM_INT:
550 				ZEND_ATOL(S->cols[colno].intval, *ptr);
551 				*ptr = (char *) &(S->cols[colno].intval);
552 				*len = sizeof(zend_long);
553 				break;
554 
555 			case PDO_PARAM_BOOL:
556 				S->cols[colno].boolval = **ptr == 't';
557 				*ptr = (char *) &(S->cols[colno].boolval);
558 				*len = sizeof(zend_bool);
559 				break;
560 
561 			case PDO_PARAM_LOB:
562 				if (S->cols[colno].pgsql_type == OIDOID) {
563 					/* ooo, a real large object */
564 					char *end_ptr;
565 					Oid oid = (Oid)strtoul(*ptr, &end_ptr, 10);
566 					int loid = lo_open(S->H->server, oid, INV_READ);
567 					if (loid >= 0) {
568 						*ptr = (char*)pdo_pgsql_create_lob_stream(&stmt->database_object_handle, loid, oid);
569 						*len = 0;
570 						return *ptr ? 1 : 0;
571 					}
572 					*ptr = NULL;
573 					*len = 0;
574 					return 0;
575 				} else {
576 					char *tmp_ptr = (char *)PQunescapeBytea((unsigned char *)*ptr, &tmp_len);
577 					if (!tmp_ptr) {
578 						/* PQunescapeBytea returned an error */
579 						*len = 0;
580 						return 0;
581 					}
582 					if (!tmp_len) {
583 						/* Empty string, return as empty stream */
584 						*ptr = (char *)php_stream_memory_open(TEMP_STREAM_READONLY, "", 0);
585 						PQfreemem(tmp_ptr);
586 						*len = 0;
587 					} else {
588 						*ptr = estrndup(tmp_ptr, tmp_len);
589 						PQfreemem(tmp_ptr);
590 						*len = tmp_len;
591 						*caller_frees = 1;
592 					}
593 				}
594 				break;
595 			case PDO_PARAM_NULL:
596 			case PDO_PARAM_STR:
597 			case PDO_PARAM_STMT:
598 			case PDO_PARAM_INPUT_OUTPUT:
599 			case PDO_PARAM_ZVAL:
600 			default:
601 				break;
602 		}
603 	}
604 
605 	return 1;
606 }
607 
pdo_pgsql_translate_oid_to_table(Oid oid,PGconn * conn)608 static zend_always_inline char * pdo_pgsql_translate_oid_to_table(Oid oid, PGconn *conn)
609 {
610 	char *table_name = NULL;
611 	PGresult *tmp_res;
612 	char *querystr = NULL;
613 
614 	spprintf(&querystr, 0, "SELECT RELNAME FROM PG_CLASS WHERE OID=%d", oid);
615 
616 	if ((tmp_res = PQexec(conn, querystr)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
617 		if (tmp_res) {
618 			PQclear(tmp_res);
619 		}
620 		efree(querystr);
621 		return 0;
622 	}
623 	efree(querystr);
624 
625 	if (1 == PQgetisnull(tmp_res, 0, 0) || (table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
626 		PQclear(tmp_res);
627 		return 0;
628 	}
629 
630 	table_name = estrdup(table_name);
631 
632 	PQclear(tmp_res);
633 	return table_name;
634 }
635 
pgsql_stmt_get_column_meta(pdo_stmt_t * stmt,zend_long colno,zval * return_value)636 static int pgsql_stmt_get_column_meta(pdo_stmt_t *stmt, zend_long colno, zval *return_value)
637 {
638 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
639 	PGresult *res;
640 	char *q=NULL;
641 	ExecStatusType status;
642 	Oid table_oid;
643 	char *table_name=NULL;
644 
645 	if (!S->result) {
646 		return FAILURE;
647 	}
648 
649 	if (colno >= stmt->column_count) {
650 		return FAILURE;
651 	}
652 
653 	array_init(return_value);
654 	add_assoc_long(return_value, "pgsql:oid", S->cols[colno].pgsql_type);
655 
656 	table_oid = PQftable(S->result, colno);
657 	add_assoc_long(return_value, "pgsql:table_oid", table_oid);
658 	table_name = pdo_pgsql_translate_oid_to_table(table_oid, S->H->server);
659 	if (table_name) {
660 		add_assoc_string(return_value, "table", table_name);
661 		efree(table_name);
662 	}
663 
664 	switch (S->cols[colno].pgsql_type) {
665 		case BOOLOID:
666 			add_assoc_string(return_value, "native_type", BOOLLABEL);
667 			break;
668 		case BYTEAOID:
669 			add_assoc_string(return_value, "native_type", BYTEALABEL);
670 			break;
671 		case INT8OID:
672 			add_assoc_string(return_value, "native_type", INT8LABEL);
673 			break;
674 		case INT2OID:
675 			add_assoc_string(return_value, "native_type", INT2LABEL);
676 			break;
677 		case INT4OID:
678 			add_assoc_string(return_value, "native_type", INT4LABEL);
679 			break;
680 		case TEXTOID:
681 			add_assoc_string(return_value, "native_type", TEXTLABEL);
682 			break;
683 		case VARCHAROID:
684 			add_assoc_string(return_value, "native_type", VARCHARLABEL);
685 			break;
686 		case DATEOID:
687 			add_assoc_string(return_value, "native_type", DATELABEL);
688 			break;
689 		case TIMESTAMPOID:
690 			add_assoc_string(return_value, "native_type", TIMESTAMPLABEL);
691 			break;
692 		default:
693 			/* Fetch metadata from Postgres system catalogue */
694 			spprintf(&q, 0, "SELECT TYPNAME FROM PG_TYPE WHERE OID=%u", S->cols[colno].pgsql_type);
695 			res = PQexec(S->H->server, q);
696 			efree(q);
697 			status = PQresultStatus(res);
698 			if (status == PGRES_TUPLES_OK && 1 == PQntuples(res)) {
699 				add_assoc_string(return_value, "native_type", PQgetvalue(res, 0, 0));
700 			}
701 			PQclear(res);
702 	}
703 	return 1;
704 }
705 
pdo_pgsql_stmt_cursor_closer(pdo_stmt_t * stmt)706 static int pdo_pgsql_stmt_cursor_closer(pdo_stmt_t *stmt)
707 {
708 	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
709 
710 	if (S->cols != NULL){
711 		efree(S->cols);
712 		S->cols = NULL;
713 	}
714 	return 1;
715 }
716 
717 const struct pdo_stmt_methods pgsql_stmt_methods = {
718 	pgsql_stmt_dtor,
719 	pgsql_stmt_execute,
720 	pgsql_stmt_fetch,
721 	pgsql_stmt_describe,
722 	pgsql_stmt_get_col,
723 	pgsql_stmt_param_hook,
724 	NULL, /* set_attr */
725 	NULL, /* get_attr */
726 	pgsql_stmt_get_column_meta,
727 	NULL,  /* next_rowset */
728 	pdo_pgsql_stmt_cursor_closer
729 };
730