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