PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LCOV - code coverage report
Current view: top level - ext/pgsql - pgsql.c (source / functions) Hit Total Coverage
Test: PHP Code Coverage Lines: 1803 2916 61.8 %
Date: 2014-07-21 Functions: 126 138 91.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :    +----------------------------------------------------------------------+
       3             :    | PHP Version 5                                                        |
       4             :    +----------------------------------------------------------------------+
       5             :    | Copyright (c) 1997-2014 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: Zeev Suraski <zeev@zend.com>                                |
      16             :    |          Jouni Ahto <jouni.ahto@exdec.fi>                            |
      17             :    |          Yasuo Ohgaki <yohgaki@php.net>                              |
      18             :    |          Youichi Iwakiri <yiwakiri@st.rim.or.jp> (pg_copy_*)         |
      19             :    |          Chris Kings-Lynne <chriskl@php.net> (v3 protocol)           |
      20             :    +----------------------------------------------------------------------+
      21             :  */
      22             : 
      23             : /* $Id$ */
      24             : 
      25             : #include <stdlib.h>
      26             : 
      27             : #define PHP_PGSQL_PRIVATE 1
      28             : 
      29             : #ifdef HAVE_CONFIG_H
      30             : #include "config.h"
      31             : #endif
      32             : 
      33             : #define SMART_STR_PREALLOC 512
      34             : 
      35             : #include "php.h"
      36             : #include "php_ini.h"
      37             : #include "ext/standard/php_standard.h"
      38             : #include "ext/standard/php_smart_str.h"
      39             : #include "ext/ereg/php_regex.h"
      40             : #ifdef PHP_WIN32
      41             : # include "win32/time.h"
      42             : #endif
      43             : 
      44             : #undef PACKAGE_BUGREPORT
      45             : #undef PACKAGE_NAME
      46             : #undef PACKAGE_STRING
      47             : #undef PACKAGE_TARNAME
      48             : #undef PACKAGE_VERSION
      49             : #include "php_pgsql.h"
      50             : #include "php_globals.h"
      51             : #include "zend_exceptions.h"
      52             : 
      53             : #if HAVE_PGSQL
      54             : 
      55             : #ifndef InvalidOid
      56             : #define InvalidOid ((Oid) 0)
      57             : #endif
      58             : 
      59             : #define PGSQL_ASSOC             1<<0
      60             : #define PGSQL_NUM               1<<1
      61             : #define PGSQL_BOTH              (PGSQL_ASSOC|PGSQL_NUM)
      62             : 
      63             : #define PGSQL_STATUS_LONG     1
      64             : #define PGSQL_STATUS_STRING   2
      65             : 
      66             : #define PGSQL_MAX_LENGTH_OF_LONG   30
      67             : #define PGSQL_MAX_LENGTH_OF_DOUBLE 60
      68             : 
      69             : #if LONG_MAX < UINT_MAX
      70             : #define PGSQL_RETURN_OID(oid) do { \
      71             :         if (oid > LONG_MAX) { \
      72             :                 smart_str s = {0}; \
      73             :                 smart_str_append_unsigned(&s, oid); \
      74             :                 smart_str_0(&s); \
      75             :                 RETURN_STRINGL(s.c, s.len, 0); \
      76             :         } \
      77             :         RETURN_LONG((long)oid); \
      78             : } while(0)
      79             : #else
      80             : #define PGSQL_RETURN_OID(oid) (RETURN_LONG((long)oid))
      81             : #endif
      82             : 
      83             : #if HAVE_PQSETNONBLOCKING
      84             : #define PQ_SETNONBLOCKING(pg_link, flag) PQsetnonblocking(pg_link, flag)
      85             : #else
      86             : #define PQ_SETNONBLOCKING(pg_link, flag) 0
      87             : #endif
      88             : 
      89             : #define CHECK_DEFAULT_LINK(x) if ((x) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No PostgreSQL link opened yet"); }
      90             : 
      91             : #ifndef HAVE_PQFREEMEM
      92             : #define PQfreemem free
      93             : #endif
      94             : 
      95             : ZEND_DECLARE_MODULE_GLOBALS(pgsql)
      96             : static PHP_GINIT_FUNCTION(pgsql);
      97             : 
      98             : /* {{{ arginfo */
      99             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connect, 0, 0, 1)
     100             :         ZEND_ARG_INFO(0, connection_string)
     101             :         ZEND_ARG_INFO(0, connect_type)
     102             :         ZEND_ARG_INFO(0, host)
     103             :         ZEND_ARG_INFO(0, port)
     104             :         ZEND_ARG_INFO(0, options)
     105             :         ZEND_ARG_INFO(0, tty)
     106             :         ZEND_ARG_INFO(0, database)
     107             : ZEND_END_ARG_INFO()
     108             : 
     109             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_pconnect, 0, 0, 1)
     110             :         ZEND_ARG_INFO(0, connection_string)
     111             :         ZEND_ARG_INFO(0, host)
     112             :         ZEND_ARG_INFO(0, port)
     113             :         ZEND_ARG_INFO(0, options)
     114             :         ZEND_ARG_INFO(0, tty)
     115             :         ZEND_ARG_INFO(0, database)
     116             : ZEND_END_ARG_INFO()
     117             : 
     118             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connect_poll, 0, 0, 0)
     119             :         ZEND_ARG_INFO(0, connection)
     120             : ZEND_END_ARG_INFO()
     121             : 
     122             : #if HAVE_PQPARAMETERSTATUS
     123             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_parameter_status, 0, 0, 1)
     124             :         ZEND_ARG_INFO(0, connection)
     125             :         ZEND_ARG_INFO(0, param_name)
     126             : ZEND_END_ARG_INFO()
     127             : #endif
     128             : 
     129             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_close, 0, 0, 0)
     130             :         ZEND_ARG_INFO(0, connection)
     131             : ZEND_END_ARG_INFO()
     132             : 
     133             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_dbname, 0, 0, 0)
     134             :         ZEND_ARG_INFO(0, connection)
     135             : ZEND_END_ARG_INFO()
     136             : 
     137             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_last_error, 0, 0, 0)
     138             :         ZEND_ARG_INFO(0, connection)
     139             : ZEND_END_ARG_INFO()
     140             : 
     141             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_options, 0, 0, 0)
     142             :         ZEND_ARG_INFO(0, connection)
     143             : ZEND_END_ARG_INFO()
     144             : 
     145             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_port, 0, 0, 0)
     146             :         ZEND_ARG_INFO(0, connection)
     147             : ZEND_END_ARG_INFO()
     148             : 
     149             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_tty, 0, 0, 0)
     150             :         ZEND_ARG_INFO(0, connection)
     151             : ZEND_END_ARG_INFO()
     152             : 
     153             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_host, 0, 0, 0)
     154             :         ZEND_ARG_INFO(0, connection)
     155             : ZEND_END_ARG_INFO()
     156             : 
     157             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_version, 0, 0, 0)
     158             :         ZEND_ARG_INFO(0, connection)
     159             : ZEND_END_ARG_INFO()
     160             : 
     161             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_ping, 0, 0, 0)
     162             :         ZEND_ARG_INFO(0, connection)
     163             : ZEND_END_ARG_INFO()
     164             : 
     165             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_query, 0, 0, 0)
     166             :         ZEND_ARG_INFO(0, connection)
     167             :         ZEND_ARG_INFO(0, query)
     168             : ZEND_END_ARG_INFO()
     169             : 
     170             : #if HAVE_PQEXECPARAMS
     171             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_query_params, 0, 0, 0)
     172             :         ZEND_ARG_INFO(0, connection)
     173             :         ZEND_ARG_INFO(0, query)
     174             :         ZEND_ARG_INFO(0, params)
     175             : ZEND_END_ARG_INFO()
     176             : #endif
     177             : 
     178             : #if HAVE_PQPREPARE
     179             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_prepare, 0, 0, 0)
     180             :         ZEND_ARG_INFO(0, connection)
     181             :         ZEND_ARG_INFO(0, stmtname)
     182             :         ZEND_ARG_INFO(0, query)
     183             : ZEND_END_ARG_INFO()
     184             : #endif
     185             : 
     186             : #if HAVE_PQEXECPREPARED
     187             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_execute, 0, 0, 0)
     188             :         ZEND_ARG_INFO(0, connection)
     189             :         ZEND_ARG_INFO(0, stmtname)
     190             :         ZEND_ARG_INFO(0, params)
     191             : ZEND_END_ARG_INFO()
     192             : #endif
     193             : 
     194             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_num_rows, 0, 0, 1)
     195             :         ZEND_ARG_INFO(0, result)
     196             : ZEND_END_ARG_INFO()
     197             : 
     198             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_num_fields, 0, 0, 1)
     199             :         ZEND_ARG_INFO(0, result)
     200             : ZEND_END_ARG_INFO()
     201             : 
     202             : #if HAVE_PQCMDTUPLES
     203             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_affected_rows, 0, 0, 1)
     204             :         ZEND_ARG_INFO(0, result)
     205             : ZEND_END_ARG_INFO()
     206             : #endif
     207             : 
     208             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_last_notice, 0, 0, 1)
     209             :         ZEND_ARG_INFO(0, connection)
     210             : ZEND_END_ARG_INFO()
     211             : 
     212             : #ifdef HAVE_PQFTABLE
     213             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_table, 0, 0, 2)
     214             :         ZEND_ARG_INFO(0, result)
     215             :         ZEND_ARG_INFO(0, field_number)
     216             :         ZEND_ARG_INFO(0, oid_only)
     217             : ZEND_END_ARG_INFO()
     218             : #endif
     219             : 
     220             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_name, 0, 0, 2)
     221             :         ZEND_ARG_INFO(0, result)
     222             :         ZEND_ARG_INFO(0, field_number)
     223             : ZEND_END_ARG_INFO()
     224             : 
     225             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_size, 0, 0, 2)
     226             :         ZEND_ARG_INFO(0, result)
     227             :         ZEND_ARG_INFO(0, field_number)
     228             : ZEND_END_ARG_INFO()
     229             : 
     230             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_type, 0, 0, 2)
     231             :         ZEND_ARG_INFO(0, result)
     232             :         ZEND_ARG_INFO(0, field_number)
     233             : ZEND_END_ARG_INFO()
     234             : 
     235             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_type_oid, 0, 0, 2)
     236             :         ZEND_ARG_INFO(0, result)
     237             :         ZEND_ARG_INFO(0, field_number)
     238             : ZEND_END_ARG_INFO()
     239             : 
     240             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_num, 0, 0, 2)
     241             :         ZEND_ARG_INFO(0, result)
     242             :         ZEND_ARG_INFO(0, field_name)
     243             : ZEND_END_ARG_INFO()
     244             : 
     245             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_result, 0, 0, 1)
     246             :         ZEND_ARG_INFO(0, result)
     247             :         ZEND_ARG_INFO(0, row_number)
     248             :         ZEND_ARG_INFO(0, field_name)
     249             : ZEND_END_ARG_INFO()
     250             : 
     251             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_row, 0, 0, 1)
     252             :         ZEND_ARG_INFO(0, result)
     253             :         ZEND_ARG_INFO(0, row)
     254             :         ZEND_ARG_INFO(0, result_type)
     255             : ZEND_END_ARG_INFO()
     256             : 
     257             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_assoc, 0, 0, 1)
     258             :         ZEND_ARG_INFO(0, result)
     259             :         ZEND_ARG_INFO(0, row)
     260             : ZEND_END_ARG_INFO()
     261             : 
     262             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_array, 0, 0, 1)
     263             :         ZEND_ARG_INFO(0, result)
     264             :         ZEND_ARG_INFO(0, row)
     265             :         ZEND_ARG_INFO(0, result_type)
     266             : ZEND_END_ARG_INFO()
     267             : 
     268             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_object, 0, 0, 1)
     269             :         ZEND_ARG_INFO(0, result)
     270             :         ZEND_ARG_INFO(0, row)
     271             :         ZEND_ARG_INFO(0, class_name)
     272             :         ZEND_ARG_INFO(0, l)
     273             :         ZEND_ARG_INFO(0, ctor_params)
     274             : ZEND_END_ARG_INFO()
     275             : 
     276             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_all, 0, 0, 1)
     277             :         ZEND_ARG_INFO(0, result)
     278             : ZEND_END_ARG_INFO()
     279             : 
     280             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_all_columns, 0, 0, 1)
     281             :         ZEND_ARG_INFO(0, result)
     282             :         ZEND_ARG_INFO(0, column_number)
     283             : ZEND_END_ARG_INFO()
     284             : 
     285             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_seek, 0, 0, 2)
     286             :         ZEND_ARG_INFO(0, result)
     287             :         ZEND_ARG_INFO(0, offset)
     288             : ZEND_END_ARG_INFO()
     289             : 
     290             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_prtlen, 0, 0, 1)
     291             :         ZEND_ARG_INFO(0, result)
     292             :         ZEND_ARG_INFO(0, row)
     293             :         ZEND_ARG_INFO(0, field_name_or_number)
     294             : ZEND_END_ARG_INFO()
     295             : 
     296             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_is_null, 0, 0, 1)
     297             :         ZEND_ARG_INFO(0, result)
     298             :         ZEND_ARG_INFO(0, row)
     299             :         ZEND_ARG_INFO(0, field_name_or_number)
     300             : ZEND_END_ARG_INFO()
     301             : 
     302             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_free_result, 0, 0, 1)
     303             :         ZEND_ARG_INFO(0, result)
     304             : ZEND_END_ARG_INFO()
     305             : 
     306             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_last_oid, 0, 0, 1)
     307             :         ZEND_ARG_INFO(0, result)
     308             : ZEND_END_ARG_INFO()
     309             : 
     310             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_trace, 0, 0, 1)
     311             :         ZEND_ARG_INFO(0, filename)
     312             :         ZEND_ARG_INFO(0, mode)
     313             :         ZEND_ARG_INFO(0, connection)
     314             : ZEND_END_ARG_INFO()
     315             : 
     316             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_untrace, 0, 0, 0)
     317             :         ZEND_ARG_INFO(0, connection)
     318             : ZEND_END_ARG_INFO()
     319             : 
     320             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_create, 0, 0, 0)
     321             :         ZEND_ARG_INFO(0, connection)
     322             :         ZEND_ARG_INFO(0, large_object_id)
     323             : ZEND_END_ARG_INFO()
     324             : 
     325             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_unlink, 0, 0, 0)
     326             :         ZEND_ARG_INFO(0, connection)
     327             :         ZEND_ARG_INFO(0, large_object_oid)
     328             : ZEND_END_ARG_INFO()
     329             : 
     330             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_open, 0, 0, 0)
     331             :         ZEND_ARG_INFO(0, connection)
     332             :         ZEND_ARG_INFO(0, large_object_oid)
     333             :         ZEND_ARG_INFO(0, mode)
     334             : ZEND_END_ARG_INFO()
     335             : 
     336             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_close, 0, 0, 1)
     337             :         ZEND_ARG_INFO(0, large_object)
     338             : ZEND_END_ARG_INFO()
     339             : 
     340             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_read, 0, 0, 1)
     341             :         ZEND_ARG_INFO(0, large_object)
     342             :         ZEND_ARG_INFO(0, len)
     343             : ZEND_END_ARG_INFO()
     344             : 
     345             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_write, 0, 0, 2)
     346             :         ZEND_ARG_INFO(0, large_object)
     347             :         ZEND_ARG_INFO(0, buf)
     348             :         ZEND_ARG_INFO(0, len)
     349             : ZEND_END_ARG_INFO()
     350             : 
     351             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_read_all, 0, 0, 1)
     352             :         ZEND_ARG_INFO(0, large_object)
     353             : ZEND_END_ARG_INFO()
     354             : 
     355             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_import, 0, 0, 0)
     356             :         ZEND_ARG_INFO(0, connection)
     357             :         ZEND_ARG_INFO(0, filename)
     358             :         ZEND_ARG_INFO(0, large_object_oid)
     359             : ZEND_END_ARG_INFO()
     360             : 
     361             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_export, 0, 0, 0)
     362             :         ZEND_ARG_INFO(0, connection)
     363             :         ZEND_ARG_INFO(0, objoid)
     364             :         ZEND_ARG_INFO(0, filename)
     365             : ZEND_END_ARG_INFO()
     366             : 
     367             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_seek, 0, 0, 2)
     368             :         ZEND_ARG_INFO(0, large_object)
     369             :         ZEND_ARG_INFO(0, offset)
     370             :         ZEND_ARG_INFO(0, whence)
     371             : ZEND_END_ARG_INFO()
     372             : 
     373             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_tell, 0, 0, 1)
     374             :         ZEND_ARG_INFO(0, large_object)
     375             : ZEND_END_ARG_INFO()
     376             : 
     377             : #if HAVE_PG_LO_TRUNCATE
     378             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_truncate, 0, 0, 1)
     379             :         ZEND_ARG_INFO(0, large_object)
     380             :         ZEND_ARG_INFO(0, size)
     381             : ZEND_END_ARG_INFO()
     382             : #endif
     383             : 
     384             : #if HAVE_PQSETERRORVERBOSITY
     385             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_set_error_verbosity, 0, 0, 0)
     386             :         ZEND_ARG_INFO(0, connection)
     387             :         ZEND_ARG_INFO(0, verbosity)
     388             : ZEND_END_ARG_INFO()
     389             : #endif
     390             : 
     391             : #if HAVE_PQCLIENTENCODING
     392             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_set_client_encoding, 0, 0, 0)
     393             :         ZEND_ARG_INFO(0, connection)
     394             :         ZEND_ARG_INFO(0, encoding)
     395             : ZEND_END_ARG_INFO()
     396             : 
     397             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_client_encoding, 0, 0, 0)
     398             :         ZEND_ARG_INFO(0, connection)
     399             : ZEND_END_ARG_INFO()
     400             : #endif
     401             : 
     402             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_end_copy, 0, 0, 0)
     403             :         ZEND_ARG_INFO(0, connection)
     404             : ZEND_END_ARG_INFO()
     405             : 
     406             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_put_line, 0, 0, 0)
     407             :         ZEND_ARG_INFO(0, connection)
     408             :         ZEND_ARG_INFO(0, query)
     409             : ZEND_END_ARG_INFO()
     410             : 
     411             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_copy_to, 0, 0, 2)
     412             :         ZEND_ARG_INFO(0, connection)
     413             :         ZEND_ARG_INFO(0, table_name)
     414             :         ZEND_ARG_INFO(0, delimiter)
     415             :         ZEND_ARG_INFO(0, null_as)
     416             : ZEND_END_ARG_INFO()
     417             : 
     418             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_copy_from, 0, 0, 3)
     419             :         ZEND_ARG_INFO(0, connection)
     420             :         ZEND_ARG_INFO(0, table_name)
     421             :         ZEND_ARG_INFO(0, rows)
     422             :         ZEND_ARG_INFO(0, delimiter)
     423             :         ZEND_ARG_INFO(0, null_as)
     424             : ZEND_END_ARG_INFO()
     425             : 
     426             : #if HAVE_PQESCAPE
     427             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_string, 0, 0, 0)
     428             :         ZEND_ARG_INFO(0, connection)
     429             :         ZEND_ARG_INFO(0, data)
     430             : ZEND_END_ARG_INFO()
     431             : 
     432             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_bytea, 0, 0, 0)
     433             :         ZEND_ARG_INFO(0, connection)
     434             :         ZEND_ARG_INFO(0, data)
     435             : ZEND_END_ARG_INFO()
     436             : 
     437             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_unescape_bytea, 0, 0, 1)
     438             :         ZEND_ARG_INFO(0, data)
     439             : ZEND_END_ARG_INFO()
     440             : #endif
     441             : 
     442             : #if HAVE_PQESCAPE
     443             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_literal, 0, 0, 0)
     444             :         ZEND_ARG_INFO(0, connection)
     445             :         ZEND_ARG_INFO(0, data)
     446             : ZEND_END_ARG_INFO()
     447             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_identifier, 0, 0, 0)
     448             :         ZEND_ARG_INFO(0, connection)
     449             :         ZEND_ARG_INFO(0, data)
     450             : ZEND_END_ARG_INFO()
     451             : #endif
     452             : 
     453             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_error, 0, 0, 1)
     454             :         ZEND_ARG_INFO(0, result)
     455             : ZEND_END_ARG_INFO()
     456             : 
     457             : #if HAVE_PQRESULTERRORFIELD
     458             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_error_field, 0, 0, 2)
     459             :         ZEND_ARG_INFO(0, result)
     460             :         ZEND_ARG_INFO(0, fieldcode)
     461             : ZEND_END_ARG_INFO()
     462             : #endif
     463             : 
     464             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connection_status, 0, 0, 1)
     465             :         ZEND_ARG_INFO(0, connection)
     466             : ZEND_END_ARG_INFO()
     467             : 
     468             : #if HAVE_PGTRANSACTIONSTATUS
     469             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_transaction_status, 0, 0, 1)
     470             :         ZEND_ARG_INFO(0, connection)
     471             : ZEND_END_ARG_INFO()
     472             : #endif
     473             : 
     474             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connection_reset, 0, 0, 1)
     475             :         ZEND_ARG_INFO(0, connection)
     476             : ZEND_END_ARG_INFO()
     477             : 
     478             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_cancel_query, 0, 0, 1)
     479             :         ZEND_ARG_INFO(0, connection)
     480             : ZEND_END_ARG_INFO()
     481             : 
     482             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connection_busy, 0, 0, 1)
     483             :         ZEND_ARG_INFO(0, connection)
     484             : ZEND_END_ARG_INFO()
     485             : 
     486             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_query, 0, 0, 2)
     487             :         ZEND_ARG_INFO(0, connection)
     488             :         ZEND_ARG_INFO(0, query)
     489             : ZEND_END_ARG_INFO()
     490             : 
     491             : #if HAVE_PQSENDQUERYPARAMS
     492             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_query_params, 0, 0, 3)
     493             :         ZEND_ARG_INFO(0, connection)
     494             :         ZEND_ARG_INFO(0, query)
     495             :         ZEND_ARG_INFO(0, params)
     496             : ZEND_END_ARG_INFO()
     497             : #endif
     498             : 
     499             : #if HAVE_PQSENDPREPARE
     500             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_prepare, 0, 0, 3)
     501             :         ZEND_ARG_INFO(0, connection)
     502             :         ZEND_ARG_INFO(0, stmtname)
     503             :         ZEND_ARG_INFO(0, query)
     504             : ZEND_END_ARG_INFO()
     505             : #endif
     506             : 
     507             : #if HAVE_PQSENDQUERYPREPARED
     508             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_execute, 0, 0, 3)
     509             :         ZEND_ARG_INFO(0, connection)
     510             :         ZEND_ARG_INFO(0, stmtname)
     511             :         ZEND_ARG_INFO(0, params)
     512             : ZEND_END_ARG_INFO()
     513             : #endif
     514             : 
     515             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_get_result, 0, 0, 1)
     516             :         ZEND_ARG_INFO(0, connection)
     517             : ZEND_END_ARG_INFO()
     518             : 
     519             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_status, 0, 0, 1)
     520             :         ZEND_ARG_INFO(0, result)
     521             :         ZEND_ARG_INFO(0, result_type)
     522             : ZEND_END_ARG_INFO()
     523             : 
     524             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_get_notify, 0, 0, 0)
     525             :         ZEND_ARG_INFO(0, connection)
     526             :         ZEND_ARG_INFO(0, e)
     527             : ZEND_END_ARG_INFO()
     528             : 
     529             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_get_pid, 0, 0, 0)
     530             :         ZEND_ARG_INFO(0, connection)
     531             : ZEND_END_ARG_INFO()
     532             : 
     533             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_socket, 0, 0, 1)
     534             :         ZEND_ARG_INFO(0, connection)
     535             : ZEND_END_ARG_INFO()
     536             : 
     537             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_consume_input, 0, 0, 1)
     538             :         ZEND_ARG_INFO(0, connection)
     539             : ZEND_END_ARG_INFO()
     540             : 
     541             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_flush, 0, 0, 1)
     542             :         ZEND_ARG_INFO(0, connection)
     543             : ZEND_END_ARG_INFO()
     544             : 
     545             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_meta_data, 0, 0, 2)
     546             :         ZEND_ARG_INFO(0, db)
     547             :         ZEND_ARG_INFO(0, table)
     548             : ZEND_END_ARG_INFO()
     549             : 
     550             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_convert, 0, 0, 3)
     551             :         ZEND_ARG_INFO(0, db)
     552             :         ZEND_ARG_INFO(0, table)
     553             :         ZEND_ARG_INFO(0, values)
     554             :         ZEND_ARG_INFO(0, options)
     555             : ZEND_END_ARG_INFO()
     556             : 
     557             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_insert, 0, 0, 3)
     558             :         ZEND_ARG_INFO(0, db)
     559             :         ZEND_ARG_INFO(0, table)
     560             :         ZEND_ARG_INFO(0, values)
     561             :         ZEND_ARG_INFO(0, options)
     562             : ZEND_END_ARG_INFO()
     563             : 
     564             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_update, 0, 0, 4)
     565             :         ZEND_ARG_INFO(0, db)
     566             :         ZEND_ARG_INFO(0, table)
     567             :         ZEND_ARG_INFO(0, fields)
     568             :         ZEND_ARG_INFO(0, ids)
     569             :         ZEND_ARG_INFO(0, options)
     570             : ZEND_END_ARG_INFO()
     571             : 
     572             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_delete, 0, 0, 3)
     573             :         ZEND_ARG_INFO(0, db)
     574             :         ZEND_ARG_INFO(0, table)
     575             :         ZEND_ARG_INFO(0, ids)
     576             :         ZEND_ARG_INFO(0, options)
     577             : ZEND_END_ARG_INFO()
     578             : 
     579             : ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_select, 0, 0, 3)
     580             :         ZEND_ARG_INFO(0, db)
     581             :         ZEND_ARG_INFO(0, table)
     582             :         ZEND_ARG_INFO(0, ids)
     583             :         ZEND_ARG_INFO(0, options)
     584             : ZEND_END_ARG_INFO()
     585             : /* }}} */
     586             : 
     587             : /* {{{ pgsql_functions[]
     588             :  */
     589             : const zend_function_entry pgsql_functions[] = {
     590             :         /* connection functions */
     591             :         PHP_FE(pg_connect,              arginfo_pg_connect)
     592             :         PHP_FE(pg_pconnect,             arginfo_pg_pconnect)
     593             :         PHP_FE(pg_connect_poll, arginfo_pg_connect_poll)
     594             :         PHP_FE(pg_close,                arginfo_pg_close)
     595             :         PHP_FE(pg_connection_status,    arginfo_pg_connection_status)
     596             :         PHP_FE(pg_connection_busy,              arginfo_pg_connection_busy)
     597             :         PHP_FE(pg_connection_reset,             arginfo_pg_connection_reset)
     598             :         PHP_FE(pg_host,                 arginfo_pg_host)
     599             :         PHP_FE(pg_dbname,               arginfo_pg_dbname)
     600             :         PHP_FE(pg_port,                 arginfo_pg_port)
     601             :         PHP_FE(pg_tty,                  arginfo_pg_tty)
     602             :         PHP_FE(pg_options,              arginfo_pg_options)
     603             :         PHP_FE(pg_version,              arginfo_pg_version)
     604             :         PHP_FE(pg_ping,                 arginfo_pg_ping)
     605             : #if HAVE_PQPARAMETERSTATUS
     606             :         PHP_FE(pg_parameter_status, arginfo_pg_parameter_status)
     607             : #endif
     608             : #if HAVE_PGTRANSACTIONSTATUS
     609             :         PHP_FE(pg_transaction_status, arginfo_pg_transaction_status)
     610             : #endif
     611             :         /* query functions */
     612             :         PHP_FE(pg_query,                arginfo_pg_query)
     613             : #if HAVE_PQEXECPARAMS
     614             :         PHP_FE(pg_query_params,         arginfo_pg_query_params)
     615             : #endif
     616             : #if HAVE_PQPREPARE
     617             :         PHP_FE(pg_prepare,              arginfo_pg_prepare)
     618             : #endif
     619             : #if HAVE_PQEXECPREPARED
     620             :         PHP_FE(pg_execute,              arginfo_pg_execute)
     621             : #endif
     622             :         PHP_FE(pg_send_query,   arginfo_pg_send_query)
     623             : #if HAVE_PQSENDQUERYPARAMS
     624             :         PHP_FE(pg_send_query_params,    arginfo_pg_send_query_params)
     625             : #endif
     626             : #if HAVE_PQSENDPREPARE
     627             :         PHP_FE(pg_send_prepare, arginfo_pg_send_prepare)
     628             : #endif
     629             : #if HAVE_PQSENDQUERYPREPARED
     630             :         PHP_FE(pg_send_execute, arginfo_pg_send_execute)
     631             : #endif
     632             :         PHP_FE(pg_cancel_query, arginfo_pg_cancel_query)
     633             :         /* result functions */
     634             :         PHP_FE(pg_fetch_result, arginfo_pg_fetch_result)
     635             :         PHP_FE(pg_fetch_row,    arginfo_pg_fetch_row)
     636             :         PHP_FE(pg_fetch_assoc,  arginfo_pg_fetch_assoc)
     637             :         PHP_FE(pg_fetch_array,  arginfo_pg_fetch_array)
     638             :         PHP_FE(pg_fetch_object, arginfo_pg_fetch_object)
     639             :         PHP_FE(pg_fetch_all,    arginfo_pg_fetch_all)
     640             :         PHP_FE(pg_fetch_all_columns,    arginfo_pg_fetch_all_columns)
     641             : #if HAVE_PQCMDTUPLES
     642             :         PHP_FE(pg_affected_rows,arginfo_pg_affected_rows)
     643             : #endif
     644             :         PHP_FE(pg_get_result,   arginfo_pg_get_result)
     645             :         PHP_FE(pg_result_seek,  arginfo_pg_result_seek)
     646             :         PHP_FE(pg_result_status,arginfo_pg_result_status)
     647             :         PHP_FE(pg_free_result,  arginfo_pg_free_result)
     648             :         PHP_FE(pg_last_oid,         arginfo_pg_last_oid)
     649             :         PHP_FE(pg_num_rows,             arginfo_pg_num_rows)
     650             :         PHP_FE(pg_num_fields,   arginfo_pg_num_fields)
     651             :         PHP_FE(pg_field_name,   arginfo_pg_field_name)
     652             :         PHP_FE(pg_field_num,    arginfo_pg_field_num)
     653             :         PHP_FE(pg_field_size,   arginfo_pg_field_size)
     654             :         PHP_FE(pg_field_type,   arginfo_pg_field_type)
     655             :         PHP_FE(pg_field_type_oid, arginfo_pg_field_type_oid)
     656             :         PHP_FE(pg_field_prtlen, arginfo_pg_field_prtlen)
     657             :         PHP_FE(pg_field_is_null,arginfo_pg_field_is_null)
     658             : #ifdef HAVE_PQFTABLE
     659             :         PHP_FE(pg_field_table,  arginfo_pg_field_table)
     660             : #endif
     661             :         /* async message function */
     662             :         PHP_FE(pg_get_notify,   arginfo_pg_get_notify)
     663             :         PHP_FE(pg_socket,               arginfo_pg_socket)
     664             :         PHP_FE(pg_consume_input,arginfo_pg_consume_input)
     665             :         PHP_FE(pg_flush,                arginfo_pg_flush)
     666             :         PHP_FE(pg_get_pid,      arginfo_pg_get_pid)
     667             :         /* error message functions */
     668             :         PHP_FE(pg_result_error, arginfo_pg_result_error)
     669             : #if HAVE_PQRESULTERRORFIELD
     670             :         PHP_FE(pg_result_error_field, arginfo_pg_result_error_field)
     671             : #endif
     672             :         PHP_FE(pg_last_error,   arginfo_pg_last_error)
     673             :         PHP_FE(pg_last_notice,  arginfo_pg_last_notice)
     674             :         /* copy functions */
     675             :         PHP_FE(pg_put_line,             arginfo_pg_put_line)
     676             :         PHP_FE(pg_end_copy,             arginfo_pg_end_copy)
     677             :         PHP_FE(pg_copy_to,      arginfo_pg_copy_to)
     678             :         PHP_FE(pg_copy_from,    arginfo_pg_copy_from)
     679             :         /* debug functions */
     680             :         PHP_FE(pg_trace,                arginfo_pg_trace)
     681             :         PHP_FE(pg_untrace,              arginfo_pg_untrace)
     682             :         /* large object functions */
     683             :         PHP_FE(pg_lo_create,    arginfo_pg_lo_create)
     684             :         PHP_FE(pg_lo_unlink,    arginfo_pg_lo_unlink)
     685             :         PHP_FE(pg_lo_open,              arginfo_pg_lo_open)
     686             :         PHP_FE(pg_lo_close,             arginfo_pg_lo_close)
     687             :         PHP_FE(pg_lo_read,              arginfo_pg_lo_read)
     688             :         PHP_FE(pg_lo_write,             arginfo_pg_lo_write)
     689             :         PHP_FE(pg_lo_read_all,  arginfo_pg_lo_read_all)
     690             :         PHP_FE(pg_lo_import,    arginfo_pg_lo_import)
     691             :         PHP_FE(pg_lo_export,    arginfo_pg_lo_export)
     692             :         PHP_FE(pg_lo_seek,              arginfo_pg_lo_seek)
     693             :         PHP_FE(pg_lo_tell,              arginfo_pg_lo_tell)
     694             : #if HAVE_PG_LO_TRUNCATE
     695             :         PHP_FE(pg_lo_truncate,  arginfo_pg_lo_truncate)
     696             : #endif
     697             :         /* utility functions */
     698             : #if HAVE_PQESCAPE
     699             :         PHP_FE(pg_escape_string,        arginfo_pg_escape_string)
     700             :         PHP_FE(pg_escape_bytea,         arginfo_pg_escape_bytea)
     701             :         PHP_FE(pg_unescape_bytea,       arginfo_pg_unescape_bytea)
     702             :         PHP_FE(pg_escape_literal,       arginfo_pg_escape_literal)
     703             :         PHP_FE(pg_escape_identifier,    arginfo_pg_escape_identifier)
     704             : #endif
     705             : #if HAVE_PQSETERRORVERBOSITY
     706             :         PHP_FE(pg_set_error_verbosity,  arginfo_pg_set_error_verbosity)
     707             : #endif
     708             : #if HAVE_PQCLIENTENCODING
     709             :         PHP_FE(pg_client_encoding,              arginfo_pg_client_encoding)
     710             :         PHP_FE(pg_set_client_encoding,  arginfo_pg_set_client_encoding)
     711             : #endif
     712             :         /* misc function */
     713             :         PHP_FE(pg_meta_data,    arginfo_pg_meta_data)
     714             :         PHP_FE(pg_convert,      arginfo_pg_convert)
     715             :         PHP_FE(pg_insert,       arginfo_pg_insert)
     716             :         PHP_FE(pg_update,       arginfo_pg_update)
     717             :         PHP_FE(pg_delete,       arginfo_pg_delete)
     718             :         PHP_FE(pg_select,       arginfo_pg_select)
     719             :         /* aliases for downwards compatibility */
     720             :         PHP_FALIAS(pg_exec,          pg_query,          arginfo_pg_query)
     721             :         PHP_FALIAS(pg_getlastoid,    pg_last_oid,       arginfo_pg_last_oid)
     722             : #if HAVE_PQCMDTUPLES
     723             :         PHP_FALIAS(pg_cmdtuples,         pg_affected_rows,  arginfo_pg_affected_rows)
     724             : #endif
     725             :         PHP_FALIAS(pg_errormessage,      pg_last_error,     arginfo_pg_last_error)
     726             :         PHP_FALIAS(pg_numrows,           pg_num_rows,       arginfo_pg_num_rows)
     727             :         PHP_FALIAS(pg_numfields,         pg_num_fields,     arginfo_pg_num_fields)
     728             :         PHP_FALIAS(pg_fieldname,         pg_field_name,     arginfo_pg_field_name)
     729             :         PHP_FALIAS(pg_fieldsize,     pg_field_size,     arginfo_pg_field_size)
     730             :         PHP_FALIAS(pg_fieldtype,         pg_field_type,     arginfo_pg_field_type)
     731             :         PHP_FALIAS(pg_fieldnum,      pg_field_num,      arginfo_pg_field_num)
     732             :         PHP_FALIAS(pg_fieldprtlen,       pg_field_prtlen,   arginfo_pg_field_prtlen)
     733             :         PHP_FALIAS(pg_fieldisnull,       pg_field_is_null,  arginfo_pg_field_is_null)
     734             :         PHP_FALIAS(pg_freeresult,    pg_free_result,    arginfo_pg_free_result)
     735             :         PHP_FALIAS(pg_result,        pg_fetch_result,   arginfo_pg_get_result)
     736             :         PHP_FALIAS(pg_loreadall,         pg_lo_read_all,    arginfo_pg_lo_read_all)
     737             :         PHP_FALIAS(pg_locreate,      pg_lo_create,      arginfo_pg_lo_create)
     738             :         PHP_FALIAS(pg_lounlink,      pg_lo_unlink,      arginfo_pg_lo_unlink)
     739             :         PHP_FALIAS(pg_loopen,        pg_lo_open,        arginfo_pg_lo_open)
     740             :         PHP_FALIAS(pg_loclose,       pg_lo_close,       arginfo_pg_lo_close)
     741             :         PHP_FALIAS(pg_loread,        pg_lo_read,        arginfo_pg_lo_read)
     742             :         PHP_FALIAS(pg_lowrite,       pg_lo_write,       arginfo_pg_lo_write)
     743             :         PHP_FALIAS(pg_loimport,      pg_lo_import,      arginfo_pg_lo_import)
     744             :         PHP_FALIAS(pg_loexport,      pg_lo_export,      arginfo_pg_lo_export)
     745             : #if HAVE_PQCLIENTENCODING
     746             :         PHP_FALIAS(pg_clientencoding,           pg_client_encoding,             arginfo_pg_client_encoding)
     747             :         PHP_FALIAS(pg_setclientencoding,        pg_set_client_encoding, arginfo_pg_set_client_encoding)
     748             : #endif
     749             :         PHP_FE_END
     750             : };
     751             : /* }}} */
     752             : 
     753             : /* {{{ pgsql_module_entry
     754             :  */
     755             : zend_module_entry pgsql_module_entry = {
     756             :         STANDARD_MODULE_HEADER,
     757             :         "pgsql",
     758             :         pgsql_functions,
     759             :         PHP_MINIT(pgsql),
     760             :         PHP_MSHUTDOWN(pgsql),
     761             :         PHP_RINIT(pgsql),
     762             :         PHP_RSHUTDOWN(pgsql),
     763             :         PHP_MINFO(pgsql),
     764             :         NO_VERSION_YET,
     765             :         PHP_MODULE_GLOBALS(pgsql),
     766             :         PHP_GINIT(pgsql),
     767             :         NULL,
     768             :         NULL,
     769             :         STANDARD_MODULE_PROPERTIES_EX
     770             : };
     771             : /* }}} */
     772             : 
     773             : #ifdef COMPILE_DL_PGSQL
     774             : ZEND_GET_MODULE(pgsql)
     775             : #endif
     776             : 
     777             : static int le_link, le_plink, le_result, le_lofp, le_string;
     778             : 
     779             : /* Compatibility definitions */
     780             : 
     781             : #ifndef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT
     782             : #define pg_encoding_to_char(x) "SQL_ASCII"
     783             : #endif
     784             : 
     785             : #if !HAVE_PQESCAPE_CONN
     786             : #define PQescapeStringConn(conn, to, from, len, error) PQescapeString(to, from, len)
     787             : #endif
     788             : 
     789             : #if HAVE_PQESCAPELITERAL
     790             : #define PGSQLescapeLiteral(conn, str, len) PQescapeLiteral(conn, str, len)
     791             : #define PGSQLescapeIdentifier(conn, str, len) PQescapeIdentifier(conn, str, len)
     792             : #define PGSQLfree(a) PQfreemem(a)
     793             : #else
     794             : #define PGSQLescapeLiteral(conn, str, len) php_pgsql_PQescapeInternal(conn, str, len, 1, 0)
     795             : #define PGSQLescapeLiteral2(conn, str, len) php_pgsql_PQescapeInternal(conn, str, len, 1, 1)
     796             : #define PGSQLescapeIdentifier(conn, str, len) php_pgsql_PQescapeInternal(conn, str, len, 0, 0)
     797             : #define PGSQLfree(a) efree(a)
     798             : 
     799             : /* emulate libpq's PQescapeInternal() 9.0 or later */
     800         146 : static char* php_pgsql_PQescapeInternal(PGconn *conn, const char *str, size_t len, int escape_literal, int safe) {
     801             :         char *result, *rp, *s;
     802             :         size_t tmp_len;
     803             : 
     804         146 :         if (!conn) {
     805           0 :                 return NULL;
     806             :         }
     807             : 
     808             :         /* allocate enough memory */
     809         146 :         rp = result = (char *)safe_emalloc(len, 2, 5); /* leading " E" needs extra 2 bytes + quote_chars on both end for 2 bytes + NULL */
     810             : 
     811         146 :         if (escape_literal) {
     812             :                 size_t new_len;
     813             : 
     814           1 :                 if (safe) {
     815           0 :                         char *tmp = (char *)safe_emalloc(len, 2, 1);
     816           0 :                         *rp++ = '\'';
     817             :                         /* PQescapeString does not escape \, but it handles multibyte chars safely.
     818             :                            This escape is incompatible with PQescapeLiteral. */
     819           0 :                         new_len = PQescapeStringConn(conn, tmp, str, len, NULL);
     820           0 :                         strncpy(rp, tmp, new_len);
     821           0 :                         efree(tmp);
     822           0 :                         rp += new_len;
     823             :                 } else {
     824             :                         char *encoding;
     825             :                         /* This is compatible with PQescapeLiteral, but it cannot handle multbyte chars
     826             :                            such as SJIS, BIG5. Raise warning and return NULL by checking
     827             :                            client_encoding. */
     828           1 :                         encoding = (char *) pg_encoding_to_char(PQclientEncoding(conn));
     829           7 :                         if (!strncmp(encoding, "SJIS", sizeof("SJIS")-1) ||
     830           1 :                                 !strncmp(encoding, "SHIFT_JIS_2004", sizeof("SHIFT_JIS_2004")-1) ||
     831           1 :                                 !strncmp(encoding, "BIG5", sizeof("BIG5")-1) ||
     832           1 :                                 !strncmp(encoding, "GB18030", sizeof("GB18030")-1) ||
     833           1 :                                 !strncmp(encoding, "GBK", sizeof("GBK")-1) ||
     834           1 :                                 !strncmp(encoding, "JOHAB", sizeof("JOHAB")-1) ||
     835           1 :                                 !strncmp(encoding, "UHC", sizeof("UHC")-1) ) {
     836             :                                 TSRMLS_FETCH();
     837             : 
     838           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unsafe encoding is used. Do not use '%s' encoding or use PostgreSQL 9.0 or later libpq.", encoding);
     839             :                         }
     840             :                         /* check backslashes */
     841           1 :                         tmp_len = strspn(str, "\\");
     842           1 :                         if (tmp_len != len) {
     843             :                                 /* add " E" for escaping slashes */
     844           1 :                                 *rp++ = ' ';
     845           1 :                                 *rp++ = 'E';
     846             :                         }
     847           1 :                         *rp++ = '\'';
     848          10 :                         for (s = (char *)str; s - str < len; ++s) {
     849          12 :                                 if (*s == '\'' || *s == '\\') {
     850           3 :                                         *rp++ = *s;
     851           3 :                                         *rp++ = *s;
     852             :                                 } else {
     853           6 :                                         *rp++ = *s;
     854             :                                 }
     855             :                         }
     856             :                 }
     857           1 :                 *rp++ = '\'';
     858             :         } else {
     859             :                 /* Identifier escape. */
     860         145 :                 *rp++ = '"';
     861         878 :                 for (s = (char *)str; s - str < len; ++s) {
     862         733 :                         if (*s == '"') {
     863           0 :                                 *rp++ = '"';
     864           0 :                                 *rp++ = '"';
     865             :                         } else {
     866         733 :                                 *rp++ = *s;
     867             :                         }
     868             :                 }
     869         145 :                 *rp++ = '"';
     870             :         }
     871         146 :         *rp = '\0';
     872             : 
     873         146 :         return result;
     874             : }
     875             : #endif
     876             : 
     877             : 
     878             : /* {{{ _php_pgsql_trim_message */
     879          20 : static char * _php_pgsql_trim_message(const char *message, int *len)
     880             : {
     881          20 :         register int i = strlen(message)-1;
     882             : 
     883          20 :         if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
     884           0 :                 --i;
     885             :         }
     886          57 :         while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
     887          17 :                 --i;
     888             :         }
     889          20 :         ++i;
     890          20 :         if (len) {
     891           6 :                 *len = i;
     892             :         }
     893          20 :         return estrndup(message, i);
     894             : }
     895             : /* }}} */
     896             : 
     897             : /* {{{ _php_pgsql_trim_result */
     898           3 : static inline char * _php_pgsql_trim_result(PGconn * pgsql, char **buf)
     899             : {
     900           3 :         return *buf = _php_pgsql_trim_message(PQerrorMessage(pgsql), NULL);
     901             : }
     902             : /* }}} */
     903             : 
     904             : #define PQErrorMessageTrim(pgsql, buf) _php_pgsql_trim_result(pgsql, buf)
     905             : 
     906             : #define PHP_PQ_ERROR(text, pgsql) {                                                                             \
     907             :                 char *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql), NULL); \
     908             :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, text, msgbuf);              \
     909             :                 efree(msgbuf);                                                                                                  \
     910             : } \
     911             : 
     912             : /* {{{ php_pgsql_set_default_link
     913             :  */
     914         113 : static void php_pgsql_set_default_link(int id TSRMLS_DC)
     915             : {
     916         113 :         zend_list_addref(id);
     917             : 
     918         113 :         if (PGG(default_link) != -1) {
     919           0 :                 zend_list_delete(PGG(default_link));
     920             :         }
     921             : 
     922         113 :         PGG(default_link) = id;
     923         113 : }
     924             : /* }}} */
     925             : 
     926             : /* {{{ _close_pgsql_link
     927             :  */
     928         112 : static void _close_pgsql_link(zend_rsrc_list_entry *rsrc TSRMLS_DC)
     929             : {
     930         112 :         PGconn *link = (PGconn *)rsrc->ptr;
     931             :         PGresult *res;
     932             : 
     933         227 :         while ((res = PQgetResult(link))) {
     934           3 :                 PQclear(res);
     935             :         }
     936         112 :         PQfinish(link);
     937         112 :         PGG(num_links)--;
     938         112 : }
     939             : /* }}} */
     940             : 
     941             : /* {{{ _close_pgsql_plink
     942             :  */
     943           1 : static void _close_pgsql_plink(zend_rsrc_list_entry *rsrc TSRMLS_DC)
     944             : {
     945           1 :         PGconn *link = (PGconn *)rsrc->ptr;
     946             :         PGresult *res;
     947             : 
     948           2 :         while ((res = PQgetResult(link))) {
     949           0 :                 PQclear(res);
     950             :         }
     951           1 :         PQfinish(link);
     952           1 :         PGG(num_persistent)--;
     953           1 :         PGG(num_links)--;
     954           1 : }
     955             : /* }}} */
     956             : 
     957             : /* {{{ _php_pgsql_notice_handler
     958             :  */
     959           6 : static void _php_pgsql_notice_handler(void *resource_id, const char *message)
     960             : {
     961             :         php_pgsql_notice *notice;
     962             :         
     963             :         TSRMLS_FETCH();
     964           6 :         if (! PGG(ignore_notices)) {
     965           6 :                 notice = (php_pgsql_notice *)emalloc(sizeof(php_pgsql_notice));
     966           6 :                 notice->message = _php_pgsql_trim_message(message, (int *)&notice->len);
     967           6 :                 if (PGG(log_notices)) {
     968           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s", notice->message);
     969             :                 }
     970           6 :                 zend_hash_index_update(&PGG(notices), (ulong)resource_id, (void **)&notice, sizeof(php_pgsql_notice *), NULL);
     971             :         }
     972           6 : }
     973             : /* }}} */
     974             : 
     975             : #define PHP_PGSQL_NOTICE_PTR_DTOR (void (*)(void *))_php_pgsql_notice_ptr_dtor
     976             : 
     977             : /* {{{ _php_pgsql_notice_dtor
     978             :  */
     979           6 : static void _php_pgsql_notice_ptr_dtor(void **ptr) 
     980             : {
     981           6 :         php_pgsql_notice *notice = (php_pgsql_notice *)*ptr;
     982           6 :         if (notice) {
     983           6 :                 efree(notice->message);
     984           6 :                 efree(notice);
     985           6 :                 notice = NULL;
     986             :         }
     987           6 : }
     988             : /* }}} */
     989             : 
     990             : /* {{{ _rollback_transactions
     991             :  */
     992         625 : static int _rollback_transactions(zend_rsrc_list_entry *rsrc TSRMLS_DC)
     993             : {
     994             :         PGconn *link;
     995             :         PGresult *res;
     996             :         int orig;
     997             : 
     998         625 :         if (Z_TYPE_P(rsrc) != le_plink) 
     999         624 :                 return 0;
    1000             : 
    1001           1 :         link = (PGconn *) rsrc->ptr;
    1002             : 
    1003           1 :         if (PQ_SETNONBLOCKING(link, 0)) {
    1004           0 :                 php_error_docref("ref.pgsql" TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
    1005           0 :                 return -1;
    1006             :         }
    1007             :         
    1008           2 :         while ((res = PQgetResult(link))) {
    1009           0 :                 PQclear(res);
    1010             :         }
    1011             : #if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION
    1012           1 :         if ((PQprotocolVersion(link) >= 3 && PQtransactionStatus(link) != PQTRANS_IDLE) || PQprotocolVersion(link) < 3)
    1013             : #endif
    1014             :         {
    1015           0 :                 orig = PGG(ignore_notices);
    1016           0 :                 PGG(ignore_notices) = 1;
    1017             : #if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION
    1018           0 :                 res = PQexec(link,"ROLLBACK;");
    1019             : #else
    1020             :                 res = PQexec(link,"BEGIN;");
    1021             :                 PQclear(res);
    1022             :                 res = PQexec(link,"ROLLBACK;");
    1023             : #endif
    1024           0 :                 PQclear(res);
    1025           0 :                 PGG(ignore_notices) = orig;
    1026             :         }
    1027             : 
    1028           1 :         return 0;
    1029             : }
    1030             : /* }}} */
    1031             : 
    1032             : /* {{{ _free_ptr
    1033             :  */
    1034        2903 : static void _free_ptr(zend_rsrc_list_entry *rsrc TSRMLS_DC)
    1035             : {
    1036        2903 :         pgLofp *lofp = (pgLofp *)rsrc->ptr;
    1037        2903 :         efree(lofp);
    1038        2903 : }
    1039             : /* }}} */
    1040             : 
    1041             : /* {{{ _free_result
    1042             :  */
    1043        1174 : static void _free_result(zend_rsrc_list_entry *rsrc TSRMLS_DC)
    1044             : {
    1045        1174 :         pgsql_result_handle *pg_result = (pgsql_result_handle *)rsrc->ptr;
    1046             : 
    1047        1174 :         PQclear(pg_result->result);
    1048        1174 :         efree(pg_result);
    1049        1174 : }
    1050             : /* }}} */
    1051             : 
    1052             : 
    1053         139 : static int _php_pgsql_detect_identifier_escape(const char *identifier, size_t len)
    1054             : {
    1055             :         size_t i;
    1056             : 
    1057             :         /* Handle edge case. Cannot be a escaped string */
    1058         139 :         if (len <= 2) {
    1059          30 :                 return FAILURE;
    1060             :         }
    1061             :         /* Detect double qoutes */
    1062         109 :         if (identifier[0] == '"' && identifier[len-1] == '"') {
    1063             :                 /* Detect wrong format of " inside of escaped string */
    1064           0 :                 for (i = 1; i < len-1; i++) {
    1065           0 :                         if (identifier[i] == '"' && (identifier[++i] != '"' || i == len-1)) {
    1066           0 :                                 return FAILURE;
    1067             :                         }
    1068             :                 }
    1069             :         } else {
    1070         109 :                 return FAILURE;
    1071             :         }
    1072             :         /* Escaped properly */
    1073           0 :         return SUCCESS;
    1074             : }
    1075             : 
    1076             : 
    1077             : 
    1078             : /* {{{ PHP_INI
    1079             :  */
    1080             : PHP_INI_BEGIN()
    1081             : STD_PHP_INI_BOOLEAN( "pgsql.allow_persistent",      "1",  PHP_INI_SYSTEM, OnUpdateBool, allow_persistent,      zend_pgsql_globals, pgsql_globals)
    1082             : STD_PHP_INI_ENTRY_EX("pgsql.max_persistent",       "-1",  PHP_INI_SYSTEM, OnUpdateLong, max_persistent,        zend_pgsql_globals, pgsql_globals, display_link_numbers)
    1083             : STD_PHP_INI_ENTRY_EX("pgsql.max_links",            "-1",  PHP_INI_SYSTEM, OnUpdateLong, max_links,             zend_pgsql_globals, pgsql_globals, display_link_numbers)
    1084             : STD_PHP_INI_BOOLEAN( "pgsql.auto_reset_persistent", "0",  PHP_INI_SYSTEM, OnUpdateBool, auto_reset_persistent, zend_pgsql_globals, pgsql_globals)
    1085             : STD_PHP_INI_BOOLEAN( "pgsql.ignore_notice",         "0",  PHP_INI_ALL,    OnUpdateBool, ignore_notices,        zend_pgsql_globals, pgsql_globals)
    1086             : STD_PHP_INI_BOOLEAN( "pgsql.log_notice",            "0",  PHP_INI_ALL,    OnUpdateBool, log_notices,           zend_pgsql_globals, pgsql_globals)
    1087             : PHP_INI_END()
    1088             : /* }}} */
    1089             : 
    1090             : /* {{{ PHP_GINIT_FUNCTION
    1091             :  */
    1092       21257 : static PHP_GINIT_FUNCTION(pgsql)
    1093             : {
    1094       21257 :         memset(pgsql_globals, 0, sizeof(zend_pgsql_globals));
    1095             :         /* Initilize notice message hash at MINIT only */
    1096       21257 :         zend_hash_init_ex(&pgsql_globals->notices, 0, NULL, PHP_PGSQL_NOTICE_PTR_DTOR, 1, 0); 
    1097       21257 : }
    1098             : /* }}} */
    1099             : 
    1100             : /* {{{ PHP_MINIT_FUNCTION
    1101             :  */
    1102       21257 : PHP_MINIT_FUNCTION(pgsql)
    1103             : {
    1104       21257 :         REGISTER_INI_ENTRIES();
    1105             : 
    1106       21257 :         le_link = zend_register_list_destructors_ex(_close_pgsql_link, NULL, "pgsql link", module_number);
    1107       21257 :         le_plink = zend_register_list_destructors_ex(NULL, _close_pgsql_plink, "pgsql link persistent", module_number);
    1108       21257 :         le_result = zend_register_list_destructors_ex(_free_result, NULL, "pgsql result", module_number);
    1109       21257 :         le_lofp = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql large object", module_number);
    1110       21257 :         le_string = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql string", module_number);
    1111             : #if HAVE_PG_CONFIG_H
    1112             :         /* PG_VERSION - libpq version */
    1113       21257 :         REGISTER_STRING_CONSTANT("PGSQL_LIBPQ_VERSION", PG_VERSION, CONST_CS | CONST_PERSISTENT);
    1114       21257 :         REGISTER_STRING_CONSTANT("PGSQL_LIBPQ_VERSION_STR", PG_VERSION_STR, CONST_CS | CONST_PERSISTENT);
    1115             : #endif
    1116             :         /* For connection option */
    1117       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECT_FORCE_NEW", PGSQL_CONNECT_FORCE_NEW, CONST_CS | CONST_PERSISTENT);
    1118       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECT_ASYNC", PGSQL_CONNECT_ASYNC, CONST_CS | CONST_PERSISTENT);
    1119             :         /* For pg_fetch_array() */
    1120       21257 :         REGISTER_LONG_CONSTANT("PGSQL_ASSOC", PGSQL_ASSOC, CONST_CS | CONST_PERSISTENT);
    1121       21257 :         REGISTER_LONG_CONSTANT("PGSQL_NUM", PGSQL_NUM, CONST_CS | CONST_PERSISTENT);
    1122       21257 :         REGISTER_LONG_CONSTANT("PGSQL_BOTH", PGSQL_BOTH, CONST_CS | CONST_PERSISTENT);
    1123             :         /* For pg_connection_status() */
    1124       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_BAD", CONNECTION_BAD, CONST_CS | CONST_PERSISTENT);
    1125       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_OK", CONNECTION_OK, CONST_CS | CONST_PERSISTENT);
    1126       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_STARTED", CONNECTION_STARTED, CONST_CS | CONST_PERSISTENT);
    1127       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_MADE", CONNECTION_MADE, CONST_CS | CONST_PERSISTENT);
    1128       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_AWAITING_RESPONSE", CONNECTION_AWAITING_RESPONSE, CONST_CS | CONST_PERSISTENT);
    1129       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_AUTH_OK", CONNECTION_AUTH_OK, CONST_CS | CONST_PERSISTENT);
    1130             : #ifdef CONNECTION_SSL_STARTUP
    1131             :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_SSL_STARTUP", CONNECTION_SSL_STARTUP, CONST_CS | CONST_PERSISTENT);
    1132             : #endif
    1133       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_SETENV", CONNECTION_SETENV, CONST_CS | CONST_PERSISTENT);
    1134             :         /* For pg_connect_poll() */
    1135       21257 :         REGISTER_LONG_CONSTANT("PGSQL_POLLING_FAILED", PGRES_POLLING_FAILED, CONST_CS | CONST_PERSISTENT);
    1136       21257 :         REGISTER_LONG_CONSTANT("PGSQL_POLLING_READING", PGRES_POLLING_READING, CONST_CS | CONST_PERSISTENT);
    1137       21257 :         REGISTER_LONG_CONSTANT("PGSQL_POLLING_WRITING", PGRES_POLLING_WRITING, CONST_CS | CONST_PERSISTENT);
    1138       21257 :         REGISTER_LONG_CONSTANT("PGSQL_POLLING_OK", PGRES_POLLING_OK, CONST_CS | CONST_PERSISTENT);
    1139       21257 :         REGISTER_LONG_CONSTANT("PGSQL_POLLING_ACTIVE", PGRES_POLLING_ACTIVE, CONST_CS | CONST_PERSISTENT);
    1140             : #if HAVE_PGTRANSACTIONSTATUS
    1141             :         /* For pg_transaction_status() */
    1142       21257 :         REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_IDLE", PQTRANS_IDLE, CONST_CS | CONST_PERSISTENT);
    1143       21257 :         REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_ACTIVE", PQTRANS_ACTIVE, CONST_CS | CONST_PERSISTENT);
    1144       21257 :         REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INTRANS", PQTRANS_INTRANS, CONST_CS | CONST_PERSISTENT);
    1145       21257 :         REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INERROR", PQTRANS_INERROR, CONST_CS | CONST_PERSISTENT);
    1146       21257 :         REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_UNKNOWN", PQTRANS_UNKNOWN, CONST_CS | CONST_PERSISTENT);
    1147             : #endif
    1148             : #if HAVE_PQSETERRORVERBOSITY
    1149             :         /* For pg_set_error_verbosity() */
    1150       21257 :         REGISTER_LONG_CONSTANT("PGSQL_ERRORS_TERSE", PQERRORS_TERSE, CONST_CS | CONST_PERSISTENT);
    1151       21257 :         REGISTER_LONG_CONSTANT("PGSQL_ERRORS_DEFAULT", PQERRORS_DEFAULT, CONST_CS | CONST_PERSISTENT);
    1152       21257 :         REGISTER_LONG_CONSTANT("PGSQL_ERRORS_VERBOSE", PQERRORS_VERBOSE, CONST_CS | CONST_PERSISTENT);
    1153             : #endif
    1154             :         /* For lo_seek() */
    1155       21257 :         REGISTER_LONG_CONSTANT("PGSQL_SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT);
    1156       21257 :         REGISTER_LONG_CONSTANT("PGSQL_SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT);
    1157       21257 :         REGISTER_LONG_CONSTANT("PGSQL_SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT);
    1158             :         /* For pg_result_status() return value type */
    1159       21257 :         REGISTER_LONG_CONSTANT("PGSQL_STATUS_LONG", PGSQL_STATUS_LONG, CONST_CS | CONST_PERSISTENT);
    1160       21257 :         REGISTER_LONG_CONSTANT("PGSQL_STATUS_STRING", PGSQL_STATUS_STRING, CONST_CS | CONST_PERSISTENT);
    1161             :         /* For pg_result_status() return value */
    1162       21257 :         REGISTER_LONG_CONSTANT("PGSQL_EMPTY_QUERY", PGRES_EMPTY_QUERY, CONST_CS | CONST_PERSISTENT);
    1163       21257 :         REGISTER_LONG_CONSTANT("PGSQL_COMMAND_OK", PGRES_COMMAND_OK, CONST_CS | CONST_PERSISTENT);
    1164       21257 :         REGISTER_LONG_CONSTANT("PGSQL_TUPLES_OK", PGRES_TUPLES_OK, CONST_CS | CONST_PERSISTENT);
    1165       21257 :         REGISTER_LONG_CONSTANT("PGSQL_COPY_OUT", PGRES_COPY_OUT, CONST_CS | CONST_PERSISTENT);
    1166       21257 :         REGISTER_LONG_CONSTANT("PGSQL_COPY_IN", PGRES_COPY_IN, CONST_CS | CONST_PERSISTENT);
    1167       21257 :         REGISTER_LONG_CONSTANT("PGSQL_BAD_RESPONSE", PGRES_BAD_RESPONSE, CONST_CS | CONST_PERSISTENT);
    1168       21257 :         REGISTER_LONG_CONSTANT("PGSQL_NONFATAL_ERROR", PGRES_NONFATAL_ERROR, CONST_CS | CONST_PERSISTENT);
    1169       21257 :         REGISTER_LONG_CONSTANT("PGSQL_FATAL_ERROR", PGRES_FATAL_ERROR, CONST_CS | CONST_PERSISTENT);
    1170             : #if HAVE_PQRESULTERRORFIELD
    1171             :         /* For pg_result_error_field() field codes */
    1172       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_SEVERITY", PG_DIAG_SEVERITY, CONST_CS | CONST_PERSISTENT);
    1173       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_SQLSTATE", PG_DIAG_SQLSTATE, CONST_CS | CONST_PERSISTENT);
    1174       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_PRIMARY", PG_DIAG_MESSAGE_PRIMARY, CONST_CS | CONST_PERSISTENT);
    1175       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_DETAIL", PG_DIAG_MESSAGE_DETAIL, CONST_CS | CONST_PERSISTENT);
    1176       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_HINT", PG_DIAG_MESSAGE_HINT, CONST_CS | CONST_PERSISTENT);
    1177       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_STATEMENT_POSITION", PG_DIAG_STATEMENT_POSITION, CONST_CS | CONST_PERSISTENT);
    1178             : #ifdef PG_DIAG_INTERNAL_POSITION
    1179       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_POSITION", PG_DIAG_INTERNAL_POSITION, CONST_CS | CONST_PERSISTENT);
    1180             : #endif
    1181             : #ifdef PG_DIAG_INTERNAL_QUERY
    1182       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_QUERY", PG_DIAG_INTERNAL_QUERY, CONST_CS | CONST_PERSISTENT);
    1183             : #endif
    1184       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_CONTEXT", PG_DIAG_CONTEXT, CONST_CS | CONST_PERSISTENT);
    1185       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FILE", PG_DIAG_SOURCE_FILE, CONST_CS | CONST_PERSISTENT);
    1186       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_LINE", PG_DIAG_SOURCE_LINE, CONST_CS | CONST_PERSISTENT);
    1187       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FUNCTION", PG_DIAG_SOURCE_FUNCTION, CONST_CS | CONST_PERSISTENT);
    1188             : #endif
    1189             :         /* pg_convert options */
    1190       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_DEFAULT", PGSQL_CONV_IGNORE_DEFAULT, CONST_CS | CONST_PERSISTENT);
    1191       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONV_FORCE_NULL", PGSQL_CONV_FORCE_NULL, CONST_CS | CONST_PERSISTENT);
    1192       21257 :         REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_NOT_NULL", PGSQL_CONV_IGNORE_NOT_NULL, CONST_CS | CONST_PERSISTENT);
    1193             :         /* pg_insert/update/delete/select options */
    1194       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DML_ESCAPE", PGSQL_DML_ESCAPE, CONST_CS | CONST_PERSISTENT);
    1195       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DML_NO_CONV", PGSQL_DML_NO_CONV, CONST_CS | CONST_PERSISTENT);
    1196       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DML_EXEC", PGSQL_DML_EXEC, CONST_CS | CONST_PERSISTENT);
    1197       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DML_ASYNC", PGSQL_DML_ASYNC, CONST_CS | CONST_PERSISTENT);
    1198       21257 :         REGISTER_LONG_CONSTANT("PGSQL_DML_STRING", PGSQL_DML_STRING, CONST_CS | CONST_PERSISTENT);
    1199       21257 :         return SUCCESS;
    1200             : }
    1201             : /* }}} */
    1202             : 
    1203             : /* {{{ PHP_MSHUTDOWN_FUNCTION
    1204             :  */
    1205       21290 : PHP_MSHUTDOWN_FUNCTION(pgsql)
    1206             : {
    1207       21290 :         UNREGISTER_INI_ENTRIES();
    1208       21290 :         zend_hash_destroy(&PGG(notices));
    1209             : 
    1210       21290 :         return SUCCESS;
    1211             : }
    1212             : /* }}} */
    1213             : 
    1214             : /* {{{ PHP_RINIT_FUNCTION
    1215             :  */
    1216       21214 : PHP_RINIT_FUNCTION(pgsql)
    1217             : {
    1218       21214 :         PGG(default_link)=-1;
    1219       21214 :         PGG(num_links) = PGG(num_persistent);
    1220       21214 :         return SUCCESS;
    1221             : }
    1222             : /* }}} */
    1223             : 
    1224             : /* {{{ PHP_RSHUTDOWN_FUNCTION
    1225             :  */
    1226       21249 : PHP_RSHUTDOWN_FUNCTION(pgsql)
    1227             : {
    1228             :         /* clean up notice messages */
    1229       21249 :         zend_hash_clean(&PGG(notices));
    1230             :         /* clean up persistent connection */
    1231       21249 :         zend_hash_apply(&EG(persistent_list), (apply_func_t) _rollback_transactions TSRMLS_CC);
    1232       21249 :         return SUCCESS;
    1233             : }
    1234             : /* }}} */
    1235             : 
    1236             : /* {{{ PHP_MINFO_FUNCTION
    1237             :  */
    1238         150 : PHP_MINFO_FUNCTION(pgsql)
    1239             : {
    1240             :         char buf[256];
    1241             : 
    1242         150 :         php_info_print_table_start();
    1243         150 :         php_info_print_table_header(2, "PostgreSQL Support", "enabled");
    1244             : #if HAVE_PG_CONFIG_H
    1245         150 :         php_info_print_table_row(2, "PostgreSQL(libpq) Version", PG_VERSION);
    1246         150 :         php_info_print_table_row(2, "PostgreSQL(libpq) ", PG_VERSION_STR);
    1247             : #ifdef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT
    1248         150 :         php_info_print_table_row(2, "Multibyte character support", "enabled");
    1249             : #else
    1250             :         php_info_print_table_row(2, "Multibyte character support", "disabled");
    1251             : #endif
    1252             : #ifdef USE_SSL
    1253         150 :         php_info_print_table_row(2, "SSL support", "enabled");
    1254             : #else
    1255             :         php_info_print_table_row(2, "SSL support", "disabled");
    1256             : #endif
    1257             : #endif /* HAVE_PG_CONFIG_H */
    1258         150 :         snprintf(buf, sizeof(buf), "%ld", PGG(num_persistent));
    1259         150 :         php_info_print_table_row(2, "Active Persistent Links", buf);
    1260         150 :         snprintf(buf, sizeof(buf), "%ld", PGG(num_links));
    1261         150 :         php_info_print_table_row(2, "Active Links", buf);
    1262         150 :         php_info_print_table_end();
    1263             : 
    1264         150 :         DISPLAY_INI_ENTRIES();
    1265         150 : }
    1266             : /* }}} */
    1267             : 
    1268             : 
    1269             : /* {{{ php_pgsql_do_connect
    1270             :  */
    1271         113 : static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
    1272             : {
    1273         113 :         char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL;
    1274             :         PGconn *pgsql;
    1275         113 :         smart_str str = {0};
    1276             :         zval **args[5];
    1277         113 :         int i, connect_type = 0;
    1278             :         PGresult *pg_result;
    1279             : 
    1280         226 :         if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5
    1281         113 :                         || zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) {
    1282           0 :                 WRONG_PARAM_COUNT;
    1283             :         }
    1284             : 
    1285         113 :         smart_str_appends(&str, "pgsql");
    1286             :         
    1287         227 :         for (i = 0; i < ZEND_NUM_ARGS(); i++) {
    1288             :                 /* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections
    1289             :                  * can re-use this connection. Bug #39979
    1290             :                  */ 
    1291         114 :                 if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE_PP(args[i]) == IS_LONG) {
    1292           1 :                         if (Z_LVAL_PP(args[1]) == PGSQL_CONNECT_FORCE_NEW) {
    1293           0 :                                 continue;
    1294           1 :                         } else if (Z_LVAL_PP(args[1]) & PGSQL_CONNECT_FORCE_NEW) {
    1295           0 :                                 smart_str_append_long(&str, Z_LVAL_PP(args[1]) ^ PGSQL_CONNECT_FORCE_NEW);
    1296             :                         }
    1297             :                 }
    1298         117 :                 convert_to_string_ex(args[i]);
    1299         114 :                 smart_str_appendc(&str, '_');
    1300         114 :                 smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i]));
    1301             :         }
    1302             : 
    1303         113 :         smart_str_0(&str);
    1304             : 
    1305         113 :         if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */
    1306         112 :                 connstring = Z_STRVAL_PP(args[0]);
    1307           1 :         } else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */
    1308           1 :                 connstring = Z_STRVAL_PP(args[0]);
    1309           4 :                 convert_to_long_ex(args[1]);
    1310           1 :                 connect_type = Z_LVAL_PP(args[1]);
    1311             :         } else {
    1312           0 :                 host = Z_STRVAL_PP(args[0]);
    1313           0 :                 port = Z_STRVAL_PP(args[1]);
    1314           0 :                 dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]);
    1315             : 
    1316           0 :                 switch (ZEND_NUM_ARGS()) {
    1317             :                 case 5:
    1318           0 :                         tty = Z_STRVAL_PP(args[3]);
    1319             :                         /* fall through */
    1320             :                 case 4:
    1321           0 :                         options = Z_STRVAL_PP(args[2]);
    1322             :                         break;
    1323             :                 }
    1324             :         }
    1325             : 
    1326         114 :         if (persistent && PGG(allow_persistent)) {
    1327             :                 zend_rsrc_list_entry *le;
    1328             :                 
    1329             :                 /* try to find if we already have this link in our persistent list */
    1330           1 :                 if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) {  /* we don't */
    1331             :                         zend_rsrc_list_entry new_le;
    1332             :                         
    1333           1 :                         if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
    1334           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1335             :                                                                  "Cannot create new link. Too many open links (%ld)", PGG(num_links));
    1336           0 :                                 goto err;
    1337             :                         }
    1338           1 :                         if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) {
    1339           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1340             :                                                                  "Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent));
    1341           0 :                                 goto err;
    1342             :                         }
    1343             : 
    1344             :                         /* create the link */
    1345           1 :                         if (connstring) {
    1346           1 :                                 pgsql=PQconnectdb(connstring);
    1347             :                         } else {
    1348           0 :                                 pgsql=PQsetdb(host,port,options,tty,dbname);
    1349             :                         }
    1350           1 :                         if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
    1351           0 :                                 PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql)
    1352           0 :                                 if (pgsql) {
    1353           0 :                                         PQfinish(pgsql);
    1354             :                                 }
    1355           0 :                                 goto err;
    1356             :                         }
    1357             : 
    1358             :                         /* hash it up */
    1359           1 :                         Z_TYPE(new_le) = le_plink;
    1360           1 :                         new_le.ptr = pgsql;
    1361           1 :                         if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
    1362           0 :                                 goto err;
    1363             :                         }
    1364           1 :                         PGG(num_links)++;
    1365           1 :                         PGG(num_persistent)++;
    1366             :                 } else {  /* we do */
    1367           0 :                         if (Z_TYPE_P(le) != le_plink) {
    1368           0 :                                 RETURN_FALSE;
    1369             :                         }
    1370             :                         /* ensure that the link did not die */
    1371           0 :                         if (PGG(auto_reset_persistent) & 1) {
    1372             :                                 /* need to send & get something from backend to
    1373             :                                    make sure we catch CONNECTION_BAD everytime */
    1374             :                                 PGresult *pg_result;
    1375           0 :                                 pg_result = PQexec(le->ptr, "select 1");
    1376           0 :                                 PQclear(pg_result);
    1377             :                         }
    1378           0 :                         if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */
    1379           0 :                                 if (le->ptr == NULL) {
    1380           0 :                                         if (connstring) {
    1381           0 :                                                 le->ptr=PQconnectdb(connstring);
    1382             :                                         } else {
    1383           0 :                                                 le->ptr=PQsetdb(host,port,options,tty,dbname);
    1384             :                                         }
    1385             :                                 }
    1386             :                                 else {
    1387           0 :                                         PQreset(le->ptr);
    1388             :                                 }
    1389           0 :                                 if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) {
    1390           0 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect");
    1391           0 :                                         zend_hash_del(&EG(persistent_list),str.c,str.len+1);
    1392           0 :                                         goto err;
    1393             :                                 }
    1394             :                         }
    1395           0 :                         pgsql = (PGconn *) le->ptr;
    1396             : #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
    1397           0 :                         if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) {
    1398             : #else
    1399             :                         if (atof(PG_VERSION) >= 7.2) {
    1400             : #endif
    1401           0 :                                 pg_result = PQexec(pgsql, "RESET ALL;");
    1402           0 :                                 PQclear(pg_result);
    1403             :                         }
    1404             :                 }
    1405           1 :                 ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink);
    1406             :         } else { /* Non persistent connection */
    1407             :                 zend_rsrc_list_entry *index_ptr,new_index_ptr;
    1408             : 
    1409             :                 /* first we check the hash for the hashed_details key.  if it exists,
    1410             :                  * it should point us to the right offset where the actual pgsql link sits.
    1411             :                  * if it doesn't, open a new pgsql link, add it to the resource list,
    1412             :                  * and add a pointer to it with hashed_details as the key.
    1413             :                  */
    1414         224 :                 if (!(connect_type & PGSQL_CONNECT_FORCE_NEW)
    1415         112 :                         && zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) {
    1416             :                         int type;
    1417             :                         ulong link;
    1418             :                         void *ptr;
    1419             : 
    1420           1 :                         if (Z_TYPE_P(index_ptr) != le_index_ptr) {
    1421           0 :                                 RETURN_FALSE;
    1422             :                         }
    1423           1 :                         link = (ulong) index_ptr->ptr;
    1424           1 :                         ptr = zend_list_find(link,&type);   /* check if the link is still there */
    1425           1 :                         if (ptr && (type==le_link || type==le_plink)) {
    1426           0 :                                 Z_LVAL_P(return_value) = link;
    1427           0 :                                 zend_list_addref(link);
    1428           0 :                                 php_pgsql_set_default_link(link TSRMLS_CC);
    1429           0 :                                 Z_TYPE_P(return_value) = IS_RESOURCE;
    1430           0 :                                 goto cleanup;
    1431             :                         } else {
    1432           1 :                                 zend_hash_del(&EG(regular_list),str.c,str.len+1);
    1433             :                         }
    1434             :                 }
    1435         112 :                 if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
    1436           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links));
    1437           0 :                         goto err;
    1438             :                 }
    1439             : 
    1440             :                 /* Non-blocking connect */
    1441         112 :                 if (connect_type & PGSQL_CONNECT_ASYNC) {
    1442           1 :                         if (connstring) {
    1443           1 :                                 pgsql = PQconnectStart(connstring);
    1444           1 :                                 if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
    1445           0 :                                         PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
    1446           0 :                                         if (pgsql) {
    1447           0 :                                                 PQfinish(pgsql);
    1448             :                                         }
    1449           0 :                                         goto err;
    1450             :                                 }
    1451             :                         } else {
    1452           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Connection string required for async connections");
    1453           0 :                                 goto err;
    1454             :                         }
    1455             :                 } else {
    1456         111 :                         if (connstring) {
    1457         111 :                                 pgsql = PQconnectdb(connstring);
    1458             :                         } else {
    1459           0 :                                 pgsql = PQsetdb(host,port,options,tty,dbname);
    1460             :                         }
    1461         111 :                         if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
    1462           0 :                                 PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
    1463           0 :                                 if (pgsql) {
    1464           0 :                                         PQfinish(pgsql);
    1465             :                                 }
    1466           0 :                                 goto err;
    1467             :                         }
    1468             :                 }
    1469             : 
    1470             :                 /* add it to the list */
    1471         112 :                 ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link);
    1472             : 
    1473             :                 /* add it to the hash */
    1474         112 :                 new_index_ptr.ptr = (void *) Z_LVAL_P(return_value);
    1475         112 :                 Z_TYPE(new_index_ptr) = le_index_ptr;
    1476         112 :                 if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) {
    1477           0 :                         goto err;
    1478             :                 }
    1479         112 :                 PGG(num_links)++;
    1480             :         }
    1481             :         /* set notice processer */
    1482         113 :         if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) {
    1483         113 :                 PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RESVAL_P(return_value));
    1484             :         }
    1485         113 :         php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC);
    1486             :         
    1487             : cleanup:
    1488         113 :         smart_str_free(&str);
    1489         113 :         return;
    1490             : 
    1491             : err:
    1492           0 :         smart_str_free(&str);
    1493           0 :         RETURN_FALSE;
    1494             : }
    1495             : /* }}} */
    1496             : 
    1497             : #if 0
    1498             : /* {{{ php_pgsql_get_default_link
    1499             :  */
    1500             : static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS)
    1501             : {
    1502             :         if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */
    1503             :                 ht = 0;
    1504             :                 php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
    1505             :         }
    1506             :         return PGG(default_link);
    1507             : }
    1508             : /* }}} */
    1509             : #endif
    1510             : 
    1511             : /* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)
    1512             :    Open a PostgreSQL connection */
    1513         112 : PHP_FUNCTION(pg_connect)
    1514             : {
    1515         112 :         php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
    1516         112 : }
    1517             : /* }}} */
    1518             : 
    1519             : /* {{{ proto resource pg_connect_poll(resource connection)
    1520             :    Poll the status of an in-progress async PostgreSQL connection attempt*/
    1521           1 : PHP_FUNCTION(pg_connect_poll)
    1522             : {
    1523             :         zval *pgsql_link;
    1524           1 :         int id = -1;
    1525             :         PGconn *pgsql;
    1526             :         int ret;
    1527             : 
    1528           1 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
    1529           0 :                 return;
    1530             :         }
    1531             : 
    1532           1 :         if (pgsql_link == NULL && id == -1) {
    1533           0 :                 RETURN_FALSE;
    1534             :         }
    1535             : 
    1536           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1537             : 
    1538           1 :         ret = PQconnectPoll(pgsql);
    1539             : 
    1540           1 :         RETURN_LONG(ret);
    1541             : }
    1542             : /* }}} */
    1543             : 
    1544             : /* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)
    1545             :    Open a persistent PostgreSQL connection */
    1546           1 : PHP_FUNCTION(pg_pconnect)
    1547             : {
    1548           1 :         php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1);
    1549           1 : }
    1550             : /* }}} */
    1551             : 
    1552             : /* {{{ proto bool pg_close([resource connection])
    1553             :    Close a PostgreSQL connection */ 
    1554          23 : PHP_FUNCTION(pg_close)
    1555             : {
    1556          23 :         zval *pgsql_link = NULL;
    1557          23 :         int id = -1, argc = ZEND_NUM_ARGS();
    1558             :         PGconn *pgsql;
    1559             : 
    1560          23 :         if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
    1561           0 :                 return;
    1562             :         }
    1563             : 
    1564          23 :         if (argc == 0) {
    1565           0 :                 id = PGG(default_link);
    1566           0 :                 CHECK_DEFAULT_LINK(id);
    1567             :         }
    1568             : 
    1569          23 :         if (pgsql_link == NULL && id == -1) {
    1570           0 :                 RETURN_FALSE;
    1571             :         }
    1572             : 
    1573          23 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1574             : 
    1575          23 :         if (id==-1) { /* explicit resource number */
    1576          23 :                 zend_list_delete(Z_RESVAL_P(pgsql_link));
    1577             :         }
    1578             : 
    1579          69 :         if (id!=-1
    1580          46 :                 || (pgsql_link && Z_RESVAL_P(pgsql_link)==PGG(default_link))) {
    1581          23 :                 zend_list_delete(PGG(default_link));
    1582          23 :                 PGG(default_link) = -1;
    1583             :         }
    1584             : 
    1585          23 :         RETURN_TRUE;
    1586             : }
    1587             : /* }}} */
    1588             : 
    1589             : 
    1590             : #define PHP_PG_DBNAME 1
    1591             : #define PHP_PG_ERROR_MESSAGE 2
    1592             : #define PHP_PG_OPTIONS 3
    1593             : #define PHP_PG_PORT 4
    1594             : #define PHP_PG_TTY 5
    1595             : #define PHP_PG_HOST 6
    1596             : #define PHP_PG_VERSION 7
    1597             : 
    1598             : 
    1599             : /* {{{ php_pgsql_get_link_info
    1600             :  */
    1601          19 : static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
    1602             : {
    1603          19 :         zval *pgsql_link = NULL;
    1604          19 :         int id = -1, argc = ZEND_NUM_ARGS();
    1605             :         PGconn *pgsql;
    1606             :         char *msgbuf;
    1607             : 
    1608          19 :         if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
    1609           0 :                 return;
    1610             :         }
    1611             :         
    1612          19 :         if (argc == 0) {
    1613           4 :                 id = PGG(default_link);
    1614           4 :                 CHECK_DEFAULT_LINK(id);
    1615             :         }
    1616             :         
    1617          19 :         if (pgsql_link == NULL && id == -1) {
    1618           0 :                 RETURN_FALSE;
    1619             :         }
    1620             : 
    1621          19 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1622             : 
    1623          19 :         switch(entry_type) {
    1624             :                 case PHP_PG_DBNAME:
    1625           1 :                         Z_STRVAL_P(return_value) = PQdb(pgsql);
    1626           1 :                         break;
    1627             :                 case PHP_PG_ERROR_MESSAGE:
    1628           3 :                         RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0);
    1629             :                         return;
    1630             :                 case PHP_PG_OPTIONS:
    1631           1 :                         Z_STRVAL_P(return_value) = PQoptions(pgsql);
    1632           1 :                         break;
    1633             :                 case PHP_PG_PORT:
    1634           1 :                         Z_STRVAL_P(return_value) = PQport(pgsql);
    1635           1 :                         break;
    1636             :                 case PHP_PG_TTY:
    1637           1 :                         Z_STRVAL_P(return_value) = PQtty(pgsql);
    1638           1 :                         break;
    1639             :                 case PHP_PG_HOST:
    1640           1 :                         Z_STRVAL_P(return_value) = PQhost(pgsql);
    1641           1 :                         break;
    1642             :                 case PHP_PG_VERSION:
    1643          11 :                         array_init(return_value);
    1644          11 :                         add_assoc_string(return_value, "client", PG_VERSION, 1);
    1645             : #if HAVE_PQPROTOCOLVERSION
    1646          11 :                         add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql));
    1647             : #if HAVE_PQPARAMETERSTATUS
    1648          11 :                         if (PQprotocolVersion(pgsql) >= 3) {
    1649             :                                 /* 8.0 or grater supports protorol version 3 */
    1650             :                                 char *tmp;
    1651          11 :                                 add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1);
    1652          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "server_encoding");
    1653          11 :                                 add_assoc_string(return_value, "server_encoding", tmp, 1);
    1654          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "client_encoding");
    1655          11 :                                 add_assoc_string(return_value, "client_encoding", tmp, 1);
    1656          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "is_superuser");
    1657          11 :                                 add_assoc_string(return_value, "is_superuser", tmp, 1);
    1658          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "session_authorization");
    1659          11 :                                 add_assoc_string(return_value, "session_authorization", tmp, 1);
    1660          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "DateStyle");
    1661          11 :                                 add_assoc_string(return_value, "DateStyle", tmp, 1);
    1662          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "IntervalStyle");
    1663          11 :                                 add_assoc_string(return_value, "IntervalStyle", tmp ? tmp : "", 1);
    1664          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "TimeZone");
    1665          11 :                                 add_assoc_string(return_value, "TimeZone", tmp ? tmp : "", 1);
    1666          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "integer_datetimes");
    1667          11 :                                 add_assoc_string(return_value, "integer_datetimes", tmp ? tmp : "", 1);
    1668          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "standard_conforming_strings");
    1669          11 :                                 add_assoc_string(return_value, "standard_conforming_strings", tmp ? tmp : "", 1);
    1670          11 :                                 tmp = (char*)PQparameterStatus(pgsql, "application_name");
    1671          11 :                                 add_assoc_string(return_value, "application_name", tmp ? tmp : "", 1);
    1672             :                         }
    1673             : #endif
    1674             : #endif
    1675          11 :                         return;
    1676             :                 default:
    1677           0 :                         RETURN_FALSE;
    1678             :         }
    1679           5 :         if (Z_STRVAL_P(return_value)) {
    1680           5 :                 Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
    1681           5 :                 Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
    1682             :         } else {
    1683           0 :                 Z_STRLEN_P(return_value) = 0;
    1684           0 :                 Z_STRVAL_P(return_value) = (char *) estrdup("");
    1685             :         }
    1686           5 :         Z_TYPE_P(return_value) = IS_STRING;
    1687             : }
    1688             : /* }}} */
    1689             : 
    1690             : /* {{{ proto string pg_dbname([resource connection])
    1691             :    Get the database name */ 
    1692           1 : PHP_FUNCTION(pg_dbname)
    1693             : {
    1694           1 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME);
    1695           1 : }
    1696             : /* }}} */
    1697             : 
    1698             : /* {{{ proto string pg_last_error([resource connection])
    1699             :    Get the error message string */
    1700           3 : PHP_FUNCTION(pg_last_error)
    1701             : {
    1702           3 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE);
    1703           3 : }
    1704             : /* }}} */
    1705             : 
    1706             : /* {{{ proto string pg_options([resource connection])
    1707             :    Get the options associated with the connection */
    1708           1 : PHP_FUNCTION(pg_options)
    1709             : {
    1710           1 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS);
    1711           1 : }
    1712             : /* }}} */
    1713             : 
    1714             : /* {{{ proto int pg_port([resource connection])
    1715             :    Return the port number associated with the connection */
    1716           1 : PHP_FUNCTION(pg_port)
    1717             : {
    1718           1 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT);
    1719           1 : }
    1720             : /* }}} */
    1721             : 
    1722             : /* {{{ proto string pg_tty([resource connection])
    1723             :    Return the tty name associated with the connection */
    1724           1 : PHP_FUNCTION(pg_tty)
    1725             : {
    1726           1 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY);
    1727           1 : }
    1728             : /* }}} */
    1729             : 
    1730             : /* {{{ proto string pg_host([resource connection])
    1731             :    Returns the host name associated with the connection */
    1732           1 : PHP_FUNCTION(pg_host)
    1733             : {
    1734           1 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST);
    1735           1 : }
    1736             : /* }}} */
    1737             : 
    1738             : /* {{{ proto array pg_version([resource connection])
    1739             :    Returns an array with client, protocol and server version (when available) */
    1740          11 : PHP_FUNCTION(pg_version)
    1741             : {
    1742          11 :         php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION);
    1743          11 : }
    1744             : /* }}} */
    1745             : 
    1746             : #if HAVE_PQPARAMETERSTATUS
    1747             : /* {{{ proto string|false pg_parameter_status([resource connection,] string param_name)
    1748             :    Returns the value of a server parameter */
    1749           4 : PHP_FUNCTION(pg_parameter_status)
    1750             : {
    1751             :         zval *pgsql_link;
    1752             :         int id;
    1753             :         PGconn *pgsql;
    1754             :         char *param;
    1755             :         int len;
    1756             : 
    1757           4 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &param, &len) == SUCCESS) {
    1758           0 :                 id = -1;
    1759           4 :         } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &param, &len) == SUCCESS) {
    1760           4 :                 pgsql_link = NULL;
    1761           4 :                 id = PGG(default_link);
    1762             :         } else {
    1763           0 :                 RETURN_FALSE;
    1764             :         }
    1765           4 :         if (pgsql_link == NULL && id == -1) {
    1766           0 :                 RETURN_FALSE;
    1767             :         }
    1768             : 
    1769           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1770             : 
    1771           4 :         param = (char*)PQparameterStatus(pgsql, param);
    1772           4 :         if (param) {
    1773           4 :                 RETURN_STRING(param, 1);
    1774             :         } else {
    1775           0 :                 RETURN_FALSE;
    1776             :         }
    1777             : }
    1778             : /* }}} */
    1779             : #endif
    1780             : 
    1781             : /* {{{ proto bool pg_ping([resource connection])
    1782             :    Ping database. If connection is bad, try to reconnect. */
    1783           1 : PHP_FUNCTION(pg_ping)
    1784             : {
    1785             :         zval *pgsql_link;
    1786             :         int id;
    1787             :         PGconn *pgsql;
    1788             :         PGresult *res;
    1789             : 
    1790           1 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) {
    1791           1 :                 id = -1;
    1792             :         } else {
    1793           0 :                 pgsql_link = NULL;
    1794           0 :                 id = PGG(default_link);
    1795             :         }
    1796           1 :         if (pgsql_link == NULL && id == -1) {
    1797           0 :                 RETURN_FALSE;
    1798             :         }
    1799             : 
    1800           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1801             : 
    1802             :         /* ping connection */
    1803           1 :         res = PQexec(pgsql, "SELECT 1;");
    1804           1 :         PQclear(res);
    1805             : 
    1806             :         /* check status. */
    1807           1 :         if (PQstatus(pgsql) == CONNECTION_OK)
    1808           1 :                 RETURN_TRUE;
    1809             : 
    1810             :         /* reset connection if it's broken */
    1811           0 :         PQreset(pgsql);
    1812           0 :         if (PQstatus(pgsql) == CONNECTION_OK) {
    1813           0 :                 RETURN_TRUE;
    1814             :         }
    1815           0 :         RETURN_FALSE;
    1816             : }
    1817             : /* }}} */
    1818             : 
    1819             : /* {{{ proto resource pg_query([resource connection,] string query)
    1820             :    Execute a query */
    1821        1137 : PHP_FUNCTION(pg_query)
    1822             : {
    1823        1137 :         zval *pgsql_link = NULL;
    1824             :         char *query;
    1825        1137 :         int id = -1, query_len, argc = ZEND_NUM_ARGS();
    1826        1137 :         int leftover = 0;
    1827             :         PGconn *pgsql;
    1828             :         PGresult *pgsql_result;
    1829             :         ExecStatusType status;
    1830             :         pgsql_result_handle *pg_result;
    1831             : 
    1832        1137 :         if (argc == 1) {
    1833          83 :                 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
    1834           0 :                         return;
    1835             :                 }
    1836          83 :                 id = PGG(default_link);
    1837          83 :                 CHECK_DEFAULT_LINK(id);
    1838             :         } else {
    1839        1054 :                 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
    1840           0 :                         return;
    1841             :                 }
    1842             :         }
    1843             : 
    1844        1137 :         if (pgsql_link == NULL && id == -1) {
    1845           0 :                 RETURN_FALSE;
    1846             :         }
    1847             : 
    1848        1137 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1849             : 
    1850        1137 :         if (PQ_SETNONBLOCKING(pgsql, 0)) {
    1851           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
    1852           0 :                 RETURN_FALSE;
    1853             :         }
    1854        2274 :         while ((pgsql_result = PQgetResult(pgsql))) {
    1855           0 :                 PQclear(pgsql_result);
    1856           0 :                 leftover = 1;
    1857             :         }
    1858        1137 :         if (leftover) {
    1859           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
    1860             :         }
    1861        1137 :         pgsql_result = PQexec(pgsql, query);
    1862        1137 :         if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    1863           0 :                 PQclear(pgsql_result);
    1864           0 :                 PQreset(pgsql);
    1865           0 :                 pgsql_result = PQexec(pgsql, query);
    1866             :         }
    1867             : 
    1868        1137 :         if (pgsql_result) {
    1869        1137 :                 status = PQresultStatus(pgsql_result);
    1870             :         } else {
    1871           0 :                 status = (ExecStatusType) PQstatus(pgsql);
    1872             :         }
    1873             : 
    1874        1137 :         switch (status) {
    1875             :                 case PGRES_EMPTY_QUERY:
    1876             :                 case PGRES_BAD_RESPONSE:
    1877             :                 case PGRES_NONFATAL_ERROR:
    1878             :                 case PGRES_FATAL_ERROR:
    1879          11 :                         PHP_PQ_ERROR("Query failed: %s", pgsql);
    1880          11 :                         PQclear(pgsql_result);
    1881          11 :                         RETURN_FALSE;
    1882             :                         break;
    1883             :                 case PGRES_COMMAND_OK: /* successful command that did not return rows */
    1884             :                 default:
    1885        1126 :                         if (pgsql_result) {
    1886        1126 :                                 pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
    1887        1126 :                                 pg_result->conn = pgsql;
    1888        1126 :                                 pg_result->result = pgsql_result;
    1889        1126 :                                 pg_result->row = 0;
    1890        1126 :                                 ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
    1891             :                         } else {
    1892           0 :                                 PQclear(pgsql_result);
    1893           0 :                                 RETURN_FALSE;
    1894             :                         }
    1895             :                         break;
    1896             :         }
    1897             : }
    1898             : /* }}} */
    1899             : 
    1900             : #if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED
    1901             : /* {{{ _php_pgsql_free_params */
    1902          25 : static void _php_pgsql_free_params(char **params, int num_params)
    1903             : {
    1904          25 :         if (num_params > 0) {
    1905             :                 int i;
    1906          56 :                 for (i = 0; i < num_params; i++) {
    1907          31 :                         if (params[i]) {
    1908          31 :                                 efree(params[i]);
    1909             :                         }
    1910             :                 }
    1911          25 :                 efree(params);
    1912             :         }
    1913          25 : }
    1914             : /* }}} */
    1915             : #endif
    1916             : 
    1917             : #if HAVE_PQEXECPARAMS
    1918             : /* {{{ proto resource pg_query_params([resource connection,] string query, array params)
    1919             :    Execute a query */
    1920          13 : PHP_FUNCTION(pg_query_params)
    1921             : {
    1922          13 :         zval *pgsql_link = NULL;
    1923             :         zval *pv_param_arr, **tmp;
    1924             :         char *query;
    1925          13 :         int query_len, id = -1, argc = ZEND_NUM_ARGS();
    1926          13 :         int leftover = 0;
    1927          13 :         int num_params = 0;
    1928          13 :         char **params = NULL;
    1929             :         PGconn *pgsql;
    1930             :         PGresult *pgsql_result;
    1931             :         ExecStatusType status;
    1932             :         pgsql_result_handle *pg_result;
    1933             :         
    1934          13 :         if (argc == 2) {
    1935           1 :                 if (zend_parse_parameters(argc TSRMLS_CC, "sa", &query, &query_len, &pv_param_arr) == FAILURE) {
    1936           0 :                         return;
    1937             :                 }
    1938           1 :                 id = PGG(default_link);
    1939           1 :                 CHECK_DEFAULT_LINK(id);
    1940             :         } else {
    1941          12 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
    1942           0 :                         return;
    1943             :                 }
    1944             :         }
    1945             : 
    1946          13 :         if (pgsql_link == NULL && id == -1) {
    1947           0 :                 RETURN_FALSE;
    1948             :         }
    1949             : 
    1950          13 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    1951             : 
    1952          13 :         if (PQ_SETNONBLOCKING(pgsql, 0)) {
    1953           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
    1954           0 :                 RETURN_FALSE;
    1955             :         }
    1956          26 :         while ((pgsql_result = PQgetResult(pgsql))) {
    1957           0 :                 PQclear(pgsql_result);
    1958           0 :                 leftover = 1;
    1959             :         }
    1960          13 :         if (leftover) {
    1961           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
    1962             :         }
    1963             : 
    1964          13 :         zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
    1965          13 :         num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
    1966          13 :         if (num_params > 0) {
    1967          13 :                 int i = 0;
    1968          13 :                 params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
    1969             : 
    1970          27 :                 for(i = 0; i < num_params; i++) {
    1971          14 :                         if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
    1972           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
    1973           0 :                                 _php_pgsql_free_params(params, num_params);
    1974           0 :                                 RETURN_FALSE;
    1975             :                         }
    1976             : 
    1977          14 :                         if (Z_TYPE_PP(tmp) == IS_NULL) {
    1978           0 :                                 params[i] = NULL;
    1979             :                         } else {
    1980          14 :                                 zval tmp_val = **tmp;
    1981             :                                 zval_copy_ctor(&tmp_val);
    1982          14 :                                 convert_to_cstring(&tmp_val);
    1983          14 :                                 if (Z_TYPE(tmp_val) != IS_STRING) {
    1984           0 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
    1985             :                                         zval_dtor(&tmp_val);
    1986           0 :                                         _php_pgsql_free_params(params, num_params);
    1987           0 :                                         RETURN_FALSE;
    1988             :                                 }
    1989          14 :                                 params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
    1990             :                                 zval_dtor(&tmp_val);
    1991             :                         }
    1992             : 
    1993          14 :                         zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
    1994             :                 }
    1995             :         }
    1996             : 
    1997          13 :         pgsql_result = PQexecParams(pgsql, query, num_params, 
    1998             :                                         NULL, (const char * const *)params, NULL, NULL, 0);
    1999          13 :         if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    2000           0 :                 PQclear(pgsql_result);
    2001           0 :                 PQreset(pgsql);
    2002           0 :                 pgsql_result = PQexecParams(pgsql, query, num_params, 
    2003             :                                                 NULL, (const char * const *)params, NULL, NULL, 0);
    2004             :         }
    2005             : 
    2006          13 :         if (pgsql_result) {
    2007          13 :                 status = PQresultStatus(pgsql_result);
    2008             :         } else {
    2009           0 :                 status = (ExecStatusType) PQstatus(pgsql);
    2010             :         }
    2011             :         
    2012          13 :         _php_pgsql_free_params(params, num_params);
    2013             : 
    2014          13 :         switch (status) {
    2015             :                 case PGRES_EMPTY_QUERY:
    2016             :                 case PGRES_BAD_RESPONSE:
    2017             :                 case PGRES_NONFATAL_ERROR:
    2018             :                 case PGRES_FATAL_ERROR:
    2019           0 :                         PHP_PQ_ERROR("Query failed: %s", pgsql);
    2020           0 :                         PQclear(pgsql_result);
    2021           0 :                         RETURN_FALSE;
    2022             :                         break;
    2023             :                 case PGRES_COMMAND_OK: /* successful command that did not return rows */
    2024             :                 default:
    2025          13 :                         if (pgsql_result) {
    2026          13 :                                 pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
    2027          13 :                                 pg_result->conn = pgsql;
    2028          13 :                                 pg_result->result = pgsql_result;
    2029          13 :                                 pg_result->row = 0;
    2030          13 :                                 ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
    2031             :                         } else {
    2032           0 :                                 PQclear(pgsql_result);
    2033           0 :                                 RETURN_FALSE;
    2034             :                         }
    2035             :                         break;
    2036             :         }
    2037             : }
    2038             : /* }}} */
    2039             : #endif
    2040             : 
    2041             : #if HAVE_PQPREPARE
    2042             : /* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query)
    2043             :    Prepare a query for future execution */
    2044           2 : PHP_FUNCTION(pg_prepare)
    2045             : {
    2046           2 :         zval *pgsql_link = NULL;
    2047             :         char *query, *stmtname;
    2048           2 :         int query_len, stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
    2049           2 :         int leftover = 0;
    2050             :         PGconn *pgsql;
    2051             :         PGresult *pgsql_result;
    2052             :         ExecStatusType status;
    2053             :         pgsql_result_handle *pg_result;
    2054             : 
    2055           2 :         if (argc == 2) {
    2056           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
    2057           0 :                         return;
    2058             :                 }
    2059           0 :                 id = PGG(default_link);
    2060           0 :                 CHECK_DEFAULT_LINK(id);
    2061             :         } else {
    2062           2 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
    2063           0 :                         return;
    2064             :                 }
    2065             :         }
    2066             : 
    2067           2 :         if (pgsql_link == NULL && id == -1) {
    2068           0 :                 RETURN_FALSE;
    2069             :         }
    2070             : 
    2071           2 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    2072             : 
    2073           2 :         if (PQ_SETNONBLOCKING(pgsql, 0)) {
    2074           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
    2075           0 :                 RETURN_FALSE;
    2076             :         }
    2077           4 :         while ((pgsql_result = PQgetResult(pgsql))) {
    2078           0 :                 PQclear(pgsql_result);
    2079           0 :                 leftover = 1;
    2080             :         }
    2081           2 :         if (leftover) {
    2082           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
    2083             :         }
    2084           2 :         pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
    2085           2 :         if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    2086           0 :                 PQclear(pgsql_result);
    2087           0 :                 PQreset(pgsql);
    2088           0 :                 pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
    2089             :         }
    2090             : 
    2091           2 :         if (pgsql_result) {
    2092           2 :                 status = PQresultStatus(pgsql_result);
    2093             :         } else {
    2094           0 :                 status = (ExecStatusType) PQstatus(pgsql);
    2095             :         }
    2096             : 
    2097           2 :         switch (status) {
    2098             :                 case PGRES_EMPTY_QUERY:
    2099             :                 case PGRES_BAD_RESPONSE:
    2100             :                 case PGRES_NONFATAL_ERROR:
    2101             :                 case PGRES_FATAL_ERROR:
    2102           0 :                         PHP_PQ_ERROR("Query failed: %s", pgsql);
    2103           0 :                         PQclear(pgsql_result);
    2104           0 :                         RETURN_FALSE;
    2105             :                         break;
    2106             :                 case PGRES_COMMAND_OK: /* successful command that did not return rows */
    2107             :                 default:
    2108           2 :                         if (pgsql_result) {
    2109           2 :                                 pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
    2110           2 :                                 pg_result->conn = pgsql;
    2111           2 :                                 pg_result->result = pgsql_result;
    2112           2 :                                 pg_result->row = 0;
    2113           2 :                                 ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
    2114             :                         } else {
    2115           0 :                                 PQclear(pgsql_result);
    2116           0 :                                 RETURN_FALSE;
    2117             :                         }
    2118             :                         break;
    2119             :         }
    2120             : }
    2121             : /* }}} */
    2122             : #endif
    2123             : 
    2124             : #if HAVE_PQEXECPREPARED
    2125             : /* {{{ proto resource pg_execute([resource connection,] string stmtname, array params)
    2126             :    Execute a prepared query  */
    2127           4 : PHP_FUNCTION(pg_execute)
    2128             : {
    2129           4 :         zval *pgsql_link = NULL;
    2130             :         zval *pv_param_arr, **tmp;
    2131             :         char *stmtname;
    2132           4 :         int stmtname_len, id = -1, argc = ZEND_NUM_ARGS();
    2133           4 :         int leftover = 0;
    2134           4 :         int num_params = 0;
    2135           4 :         char **params = NULL;
    2136             :         PGconn *pgsql;
    2137             :         PGresult *pgsql_result;
    2138             :         ExecStatusType status;
    2139             :         pgsql_result_handle *pg_result;
    2140             : 
    2141           4 :         if (argc == 2) {
    2142           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) {
    2143           0 :                         return;
    2144             :                 }
    2145           0 :                 id = PGG(default_link);
    2146           0 :                 CHECK_DEFAULT_LINK(id);
    2147             :         } else {
    2148           4 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
    2149           0 :                         return;
    2150             :                 }
    2151             :         }
    2152             : 
    2153           4 :         if (pgsql_link == NULL && id == -1) {
    2154           0 :                 RETURN_FALSE;
    2155             :         }
    2156             : 
    2157           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    2158             : 
    2159           4 :         if (PQ_SETNONBLOCKING(pgsql, 0)) {
    2160           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
    2161           0 :                 RETURN_FALSE;
    2162             :         }
    2163           8 :         while ((pgsql_result = PQgetResult(pgsql))) {
    2164           0 :                 PQclear(pgsql_result);
    2165           0 :                 leftover = 1;
    2166             :         }
    2167           4 :         if (leftover) {
    2168           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
    2169             :         }
    2170             : 
    2171           4 :         zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
    2172           4 :         num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
    2173           4 :         if (num_params > 0) {
    2174           4 :                 int i = 0;
    2175           4 :                 params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
    2176             : 
    2177           9 :                 for(i = 0; i < num_params; i++) {
    2178           5 :                         if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
    2179           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
    2180           0 :                                 _php_pgsql_free_params(params, num_params);
    2181           0 :                                 RETURN_FALSE;
    2182             :                         }
    2183             : 
    2184           5 :                         if (Z_TYPE_PP(tmp) == IS_NULL) {
    2185           0 :                                 params[i] = NULL;
    2186             :                         } else {
    2187           5 :                                 zval tmp_val = **tmp;
    2188             :                                 zval_copy_ctor(&tmp_val);
    2189           5 :                                 convert_to_string(&tmp_val);
    2190           5 :                                 if (Z_TYPE(tmp_val) != IS_STRING) {
    2191           0 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
    2192             :                                         zval_dtor(&tmp_val);
    2193           0 :                                         _php_pgsql_free_params(params, num_params);
    2194           0 :                                         RETURN_FALSE;
    2195             :                                 }
    2196           5 :                                 params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
    2197             :                                 zval_dtor(&tmp_val);
    2198             :                         }
    2199             : 
    2200           5 :                         zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
    2201             :                 }
    2202             :         }
    2203             : 
    2204           4 :         pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, 
    2205             :                                         (const char * const *)params, NULL, NULL, 0);
    2206           4 :         if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    2207           0 :                 PQclear(pgsql_result);
    2208           0 :                 PQreset(pgsql);
    2209           0 :                 pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, 
    2210             :                                                 (const char * const *)params, NULL, NULL, 0);
    2211             :         }
    2212             : 
    2213           4 :         if (pgsql_result) {
    2214           4 :                 status = PQresultStatus(pgsql_result);
    2215             :         } else {
    2216           0 :                 status = (ExecStatusType) PQstatus(pgsql);
    2217             :         }
    2218             : 
    2219           4 :         _php_pgsql_free_params(params, num_params);
    2220             : 
    2221           4 :         switch (status) {
    2222             :                 case PGRES_EMPTY_QUERY:
    2223             :                 case PGRES_BAD_RESPONSE:
    2224             :                 case PGRES_NONFATAL_ERROR:
    2225             :                 case PGRES_FATAL_ERROR:
    2226           0 :                         PHP_PQ_ERROR("Query failed: %s", pgsql);
    2227           0 :                         PQclear(pgsql_result);
    2228           0 :                         RETURN_FALSE;
    2229             :                         break;
    2230             :                 case PGRES_COMMAND_OK: /* successful command that did not return rows */
    2231             :                 default:
    2232           4 :                         if (pgsql_result) {
    2233           4 :                                 pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
    2234           4 :                                 pg_result->conn = pgsql;
    2235           4 :                                 pg_result->result = pgsql_result;
    2236           4 :                                 pg_result->row = 0;
    2237           4 :                                 ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
    2238             :                         } else {
    2239           0 :                                 PQclear(pgsql_result);
    2240           0 :                                 RETURN_FALSE;
    2241             :                         }
    2242             :                         break;
    2243             :         }
    2244             : }
    2245             : /* }}} */
    2246             : #endif
    2247             : 
    2248             : #define PHP_PG_NUM_ROWS 1
    2249             : #define PHP_PG_NUM_FIELDS 2
    2250             : #define PHP_PG_CMD_TUPLES 3
    2251             : 
    2252             : /* {{{ php_pgsql_get_result_info
    2253             :  */
    2254          33 : static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
    2255             : {
    2256             :         zval *result;
    2257             :         PGresult *pgsql_result;
    2258             :         pgsql_result_handle *pg_result;
    2259             : 
    2260          33 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
    2261           1 :                 return;
    2262             :         }
    2263             :         
    2264          32 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2265             : 
    2266          32 :         pgsql_result = pg_result->result;
    2267             : 
    2268          32 :         switch (entry_type) {
    2269             :                 case PHP_PG_NUM_ROWS:
    2270          21 :                         Z_LVAL_P(return_value) = PQntuples(pgsql_result);
    2271          21 :                         break;
    2272             :                 case PHP_PG_NUM_FIELDS:
    2273          10 :                         Z_LVAL_P(return_value) = PQnfields(pgsql_result);
    2274          10 :                         break;
    2275             :                 case PHP_PG_CMD_TUPLES:
    2276             : #if HAVE_PQCMDTUPLES
    2277           1 :                         Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result));
    2278             : #else
    2279             :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build");
    2280             :                         Z_LVAL_P(return_value) = 0;
    2281             : #endif
    2282           1 :                         break;
    2283             :                 default:
    2284           0 :                         RETURN_FALSE;
    2285             :         }
    2286          32 :         Z_TYPE_P(return_value) = IS_LONG;
    2287             : }
    2288             : /* }}} */
    2289             : 
    2290             : /* {{{ proto int pg_num_rows(resource result)
    2291             :    Return the number of rows in the result */
    2292          22 : PHP_FUNCTION(pg_num_rows)
    2293             : {
    2294          22 :         php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS);
    2295          22 : }
    2296             : /* }}} */
    2297             : 
    2298             : /* {{{ proto int pg_num_fields(resource result)
    2299             :    Return the number of fields in the result */
    2300          10 : PHP_FUNCTION(pg_num_fields)
    2301             : {
    2302          10 :         php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
    2303          10 : }
    2304             : /* }}} */
    2305             : 
    2306             : #if HAVE_PQCMDTUPLES
    2307             : /* {{{ proto int pg_affected_rows(resource result)
    2308             :    Returns the number of affected tuples */
    2309           1 : PHP_FUNCTION(pg_affected_rows)
    2310             : {
    2311           1 :         php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES);
    2312           1 : }
    2313             : /* }}} */
    2314             : #endif
    2315             : 
    2316             : /* {{{ proto string pg_last_notice(resource connection)
    2317             :    Returns the last notice set by the backend */
    2318           0 : PHP_FUNCTION(pg_last_notice) 
    2319             : {
    2320             :         zval *pgsql_link;
    2321             :         PGconn *pg_link;
    2322           0 :         int id = -1;
    2323             :         php_pgsql_notice **notice;
    2324             :         
    2325           0 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
    2326           0 :                 return;
    2327             :         }
    2328             :         /* Just to check if user passed valid resoruce */
    2329           0 :         ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    2330             : 
    2331           0 :         if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)&notice) == FAILURE) {
    2332           0 :                 RETURN_FALSE;
    2333             :         }
    2334           0 :         RETURN_STRINGL((*notice)->message, (*notice)->len, 1);
    2335             : }
    2336             : /* }}} */
    2337             : 
    2338             : /* {{{ get_field_name
    2339             :  */
    2340          10 : static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC)
    2341             : {
    2342             :         PGresult *result;
    2343          10 :         smart_str str = {0};
    2344             :         zend_rsrc_list_entry *field_type;
    2345          10 :         char *ret=NULL;
    2346             : 
    2347             :         /* try to lookup the type in the resource list */
    2348          10 :         smart_str_appends(&str, "pgsql_oid_");
    2349          10 :         smart_str_append_unsigned(&str, oid);
    2350          10 :         smart_str_0(&str);
    2351             : 
    2352          10 :         if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) {
    2353           0 :                 ret = estrdup((char *)field_type->ptr);
    2354             :         } else { /* hash all oid's */
    2355             :                 int i,num_rows;
    2356             :                 int oid_offset,name_offset;
    2357             :                 char *tmp_oid, *end_ptr, *tmp_name;
    2358             :                 zend_rsrc_list_entry new_oid_entry;
    2359             : 
    2360          10 :                 if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) {
    2361           0 :                         if (result) {
    2362           0 :                                 PQclear(result);
    2363             :                         }
    2364           0 :                         smart_str_free(&str);
    2365           0 :                         return STR_EMPTY_ALLOC();
    2366             :                 }
    2367          10 :                 num_rows = PQntuples(result);
    2368          10 :                 oid_offset = PQfnumber(result,"oid");
    2369          10 :                 name_offset = PQfnumber(result,"typname");
    2370             : 
    2371        2910 :                 for (i=0; i<num_rows; i++) {
    2372        2900 :                         if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) {
    2373           0 :                                 continue;
    2374             :                         }
    2375             :                         
    2376        2900 :                         str.len = 0;
    2377        2900 :                         smart_str_appends(&str, "pgsql_oid_");
    2378        2900 :                         smart_str_appends(&str, tmp_oid);
    2379        2900 :                         smart_str_0(&str);
    2380             : 
    2381        2900 :                         if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) {
    2382           0 :                                 continue;
    2383             :                         }
    2384        2900 :                         Z_TYPE(new_oid_entry) = le_string;
    2385        2900 :                         new_oid_entry.ptr = estrdup(tmp_name);
    2386        2900 :                         zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(zend_rsrc_list_entry), NULL);
    2387        2900 :                         if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) {
    2388          10 :                                 ret = estrdup(tmp_name);
    2389             :                         }
    2390             :                 }
    2391          10 :                 PQclear(result);
    2392             :         }
    2393             : 
    2394          10 :         smart_str_free(&str);
    2395          10 :         return ret;
    2396             : }
    2397             : /* }}} */
    2398             : 
    2399             : #ifdef HAVE_PQFTABLE
    2400             : /* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only])
    2401             :    Returns the name of the table field belongs to, or table's oid if oid_only is true */
    2402           0 : PHP_FUNCTION(pg_field_table)
    2403             : {
    2404             :         zval *result;
    2405             :         pgsql_result_handle *pg_result;
    2406           0 :         long fnum = -1;
    2407           0 :         zend_bool return_oid = 0;
    2408             :         Oid oid;
    2409           0 :         smart_str hash_key = {0};
    2410             :         char *table_name;
    2411             :         zend_rsrc_list_entry *field_table;
    2412             : 
    2413           0 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|b", &result, &fnum, &return_oid) == FAILURE) {
    2414           0 :                 return;
    2415             :         }
    2416             : 
    2417           0 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2418             : 
    2419           0 :         if (fnum < 0 || fnum >= PQnfields(pg_result->result)) {
    2420           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
    2421           0 :                 RETURN_FALSE;
    2422             :         }
    2423             : 
    2424           0 :         oid = PQftable(pg_result->result, fnum);
    2425             : 
    2426           0 :         if (InvalidOid == oid) {
    2427           0 :                 RETURN_FALSE;
    2428             :         }
    2429             : 
    2430           0 :         if (return_oid) {
    2431             : #if UINT_MAX > LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */
    2432             :                 if (oid > LONG_MAX) {
    2433             :                         smart_str oidstr = {0};
    2434             :                         smart_str_append_unsigned(&oidstr, oid);
    2435             :                         smart_str_0(&oidstr);
    2436             :                         RETURN_STRINGL(oidstr.c, oidstr.len, 0);
    2437             :                 } else
    2438             : #endif
    2439           0 :                         RETURN_LONG((long)oid);
    2440             :         }
    2441             : 
    2442             :         /* try to lookup the table name in the resource list */
    2443           0 :         smart_str_appends(&hash_key, "pgsql_table_oid_");
    2444           0 :         smart_str_append_unsigned(&hash_key, oid);
    2445           0 :         smart_str_0(&hash_key);
    2446             : 
    2447           0 :         if (zend_hash_find(&EG(regular_list), hash_key.c, hash_key.len+1, (void **) &field_table) == SUCCESS) {
    2448           0 :                 smart_str_free(&hash_key);
    2449           0 :                 RETURN_STRING((char *)field_table->ptr, 1);
    2450             :         } else { /* Not found, lookup by querying PostgreSQL system tables */
    2451             :                 PGresult *tmp_res;
    2452           0 :                 smart_str querystr = {0};
    2453             :                 zend_rsrc_list_entry new_field_table;
    2454             : 
    2455           0 :                 smart_str_appends(&querystr, "select relname from pg_class where oid=");
    2456           0 :                 smart_str_append_unsigned(&querystr, oid);
    2457           0 :                 smart_str_0(&querystr);
    2458             : 
    2459           0 :                 if ((tmp_res = PQexec(pg_result->conn, querystr.c)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
    2460           0 :                         if (tmp_res) {
    2461           0 :                                 PQclear(tmp_res);
    2462             :                         }
    2463           0 :                         smart_str_free(&querystr);
    2464           0 :                         smart_str_free(&hash_key);
    2465           0 :                         RETURN_FALSE;
    2466             :                 }
    2467             : 
    2468           0 :                 smart_str_free(&querystr);
    2469             : 
    2470           0 :                 if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
    2471           0 :                         PQclear(tmp_res);
    2472           0 :                         smart_str_free(&hash_key);
    2473           0 :                         RETURN_FALSE;
    2474             :                 }
    2475             : 
    2476           0 :                 Z_TYPE(new_field_table) = le_string;
    2477           0 :                 new_field_table.ptr = estrdup(table_name);
    2478           0 :                 zend_hash_update(&EG(regular_list), hash_key.c, hash_key.len+1, (void *) &new_field_table, sizeof(zend_rsrc_list_entry), NULL);
    2479             : 
    2480           0 :                 smart_str_free(&hash_key);
    2481           0 :                 PQclear(tmp_res);
    2482           0 :                 RETURN_STRING(table_name, 1);
    2483             :         }
    2484             : 
    2485             : }
    2486             : /* }}} */
    2487             : #endif
    2488             : 
    2489             : #define PHP_PG_FIELD_NAME 1
    2490             : #define PHP_PG_FIELD_SIZE 2
    2491             : #define PHP_PG_FIELD_TYPE 3
    2492             : #define PHP_PG_FIELD_TYPE_OID 4
    2493             : 
    2494             : /* {{{ php_pgsql_get_field_info
    2495             :  */
    2496          30 : static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
    2497             : {
    2498             :         zval *result;
    2499             :         long field;
    2500             :         PGresult *pgsql_result;
    2501             :         pgsql_result_handle *pg_result;
    2502             :         Oid oid;
    2503             : 
    2504          30 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &field) == FAILURE) {
    2505           0 :                 return;
    2506             :         }
    2507             : 
    2508          30 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2509             : 
    2510          30 :         pgsql_result = pg_result->result;
    2511             :         
    2512          30 :         if (field < 0 || field >= PQnfields(pgsql_result)) {
    2513           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
    2514           0 :                 RETURN_FALSE;
    2515             :         }
    2516             : 
    2517          30 :         switch (entry_type) {
    2518             :                 case PHP_PG_FIELD_NAME:
    2519          10 :                         Z_STRVAL_P(return_value) = PQfname(pgsql_result, field);
    2520          10 :                         Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
    2521          10 :                         Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value));
    2522          10 :                         Z_TYPE_P(return_value) = IS_STRING;
    2523          10 :                         break;
    2524             :                 case PHP_PG_FIELD_SIZE:
    2525          10 :                         Z_LVAL_P(return_value) = PQfsize(pgsql_result, field);
    2526          10 :                         Z_TYPE_P(return_value) = IS_LONG;
    2527          10 :                         break;
    2528             :                 case PHP_PG_FIELD_TYPE:
    2529          10 :                         Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, field), &EG(regular_list) TSRMLS_CC);
    2530          10 :                         Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
    2531          10 :                         Z_TYPE_P(return_value) = IS_STRING;
    2532          10 :                         break;
    2533             :                 case PHP_PG_FIELD_TYPE_OID:
    2534             :                         
    2535           0 :                         oid = PQftype(pgsql_result, field);
    2536             : #if UINT_MAX > LONG_MAX
    2537             :                         if (oid > LONG_MAX) {
    2538             :                                 smart_str s = {0};
    2539             :                                 smart_str_append_unsigned(&s, oid);
    2540             :                                 smart_str_0(&s);
    2541             :                                 Z_STRVAL_P(return_value) = s.c;
    2542             :                                 Z_STRLEN_P(return_value) = s.len;
    2543             :                                 Z_TYPE_P(return_value) = IS_STRING;
    2544             :                         } else
    2545             : #endif
    2546             :                         {
    2547           0 :                                 Z_LVAL_P(return_value) = (long)oid;
    2548           0 :                                 Z_TYPE_P(return_value) = IS_LONG;
    2549             :                         }
    2550           0 :                         break;
    2551             :                 default:
    2552           0 :                         RETURN_FALSE;
    2553             :         }
    2554             : }
    2555             : /* }}} */
    2556             : 
    2557             : /* {{{ proto string pg_field_name(resource result, int field_number)
    2558             :    Returns the name of the field */
    2559          10 : PHP_FUNCTION(pg_field_name)
    2560             : {
    2561          10 :         php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME);
    2562          10 : }
    2563             : /* }}} */
    2564             : 
    2565             : /* {{{ proto int pg_field_size(resource result, int field_number)
    2566             :    Returns the internal size of the field */ 
    2567          10 : PHP_FUNCTION(pg_field_size)
    2568             : {
    2569          10 :         php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE);
    2570          10 : }
    2571             : /* }}} */
    2572             : 
    2573             : /* {{{ proto string pg_field_type(resource result, int field_number)
    2574             :    Returns the type name for the given field */
    2575          10 : PHP_FUNCTION(pg_field_type)
    2576             : {
    2577          10 :         php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE);
    2578          10 : }
    2579             : /* }}} */
    2580             : 
    2581             : 
    2582             : /* {{{ proto string pg_field_type_oid(resource result, int field_number)
    2583             :    Returns the type oid for the given field */
    2584           0 : PHP_FUNCTION(pg_field_type_oid)
    2585             : {
    2586           0 :         php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID);
    2587           0 : }
    2588             : /* }}} */
    2589             : 
    2590             : /* {{{ proto int pg_field_num(resource result, string field_name)
    2591             :    Returns the field number of the named field */
    2592           9 : PHP_FUNCTION(pg_field_num)
    2593             : {
    2594             :         zval *result;
    2595             :         char *field;
    2596             :         int field_len;
    2597             :         PGresult *pgsql_result;
    2598             :         pgsql_result_handle *pg_result;
    2599             : 
    2600           9 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result, &field, &field_len) == FAILURE) {
    2601           0 :                 return;
    2602             :         }
    2603             : 
    2604           9 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2605             : 
    2606           9 :         pgsql_result = pg_result->result;
    2607             : 
    2608           9 :         Z_LVAL_P(return_value) = PQfnumber(pgsql_result, field);
    2609           9 :         Z_TYPE_P(return_value) = IS_LONG;
    2610             : }
    2611             : /* }}} */
    2612             : 
    2613             : /* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)
    2614             :    Returns values from a result identifier */
    2615        8451 : PHP_FUNCTION(pg_fetch_result)
    2616             : {
    2617        8451 :         zval *result, **field=NULL;
    2618             :         long row;
    2619             :         PGresult *pgsql_result;
    2620             :         pgsql_result_handle *pg_result;
    2621        8451 :         int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
    2622             : 
    2623        8451 :         if (argc == 2) {
    2624           2 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
    2625           0 :                         return;
    2626             :                 }
    2627             :         } else {
    2628        8449 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
    2629           0 :                         return;
    2630             :                 }
    2631             :         }
    2632             :         
    2633        8451 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2634             : 
    2635        8451 :         pgsql_result = pg_result->result;
    2636        8451 :         if (argc == 2) {
    2637           2 :                 if (pg_result->row < 0) {
    2638           0 :                         pg_result->row = 0;
    2639             :                 }
    2640           2 :                 pgsql_row = pg_result->row;
    2641           2 :                 if (pgsql_row >= PQntuples(pgsql_result)) {
    2642           0 :                         RETURN_FALSE;
    2643             :                 }
    2644             :         } else {
    2645        8449 :                 pgsql_row = row;
    2646        8449 :                 if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
    2647           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
    2648           0 :                                                         row, Z_LVAL_P(result));
    2649           0 :                         RETURN_FALSE;
    2650             :                 }
    2651             :         }
    2652        8451 :         switch(Z_TYPE_PP(field)) {
    2653             :                 case IS_STRING:
    2654           0 :                         field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
    2655           0 :                         break;
    2656             :                 default:
    2657        8451 :                         convert_to_long_ex(field);
    2658        8451 :                         field_offset = Z_LVAL_PP(field);
    2659             :                         break;
    2660             :         }
    2661        8451 :         if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) {
    2662           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
    2663           0 :                 RETURN_FALSE;
    2664             :         }
    2665             : 
    2666        8451 :         if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
    2667           0 :                 Z_TYPE_P(return_value) = IS_NULL;
    2668             :         } else {
    2669        8451 :                 char *value = PQgetvalue(pgsql_result, pgsql_row, field_offset);
    2670        8451 :                 int value_len = PQgetlength(pgsql_result, pgsql_row, field_offset);
    2671        8451 :                 ZVAL_STRINGL(return_value, value, value_len, 1);
    2672             :         }
    2673             : }
    2674             : /* }}} */
    2675             : 
    2676             : /* {{{ void php_pgsql_fetch_hash */
    2677       25361 : static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object)
    2678             : {
    2679       25361 :         zval                *result, *zrow = NULL;
    2680             :         PGresult            *pgsql_result;
    2681             :         pgsql_result_handle *pg_result;
    2682             :         int             i, num_fields, pgsql_row, use_row;
    2683       25361 :         long            row = -1;
    2684             :         char            *field_name;
    2685       25361 :         zval            *ctor_params = NULL;
    2686       25361 :         zend_class_entry *ce = NULL;
    2687             : 
    2688       25361 :         if (into_object) {
    2689        8450 :                 char *class_name = NULL;
    2690             :                 int class_name_len;
    2691             : 
    2692        8450 :                 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!sz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) {
    2693           0 :                         return;
    2694             :                 }
    2695        8450 :                 if (!class_name) {
    2696        8449 :                         ce = zend_standard_class_def;
    2697             :                 } else {
    2698           1 :                         ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
    2699             :                 }
    2700        8450 :                 if (!ce) {
    2701           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name);
    2702           0 :                         return;
    2703             :                 }
    2704        8450 :                 result_type = PGSQL_ASSOC;
    2705             :         } else {
    2706       16911 :                 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!l", &result, &zrow, &result_type) == FAILURE) {
    2707           0 :                         return;
    2708             :                 }
    2709             :         }
    2710       25361 :         if (zrow == NULL) {
    2711        8459 :                 row = -1;
    2712             :         } else {
    2713       16902 :                 convert_to_long(zrow);
    2714       16902 :                 row = Z_LVAL_P(zrow);
    2715       16902 :                 if (row < 0) {
    2716           4 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "The row parameter must be greater or equal to zero");
    2717           4 :                         RETURN_FALSE;
    2718             :                 }
    2719             :         }
    2720       25357 :         use_row = ZEND_NUM_ARGS() > 1 && row != -1;
    2721             : 
    2722       25357 :         if (!(result_type & PGSQL_BOTH)) {
    2723           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
    2724           0 :                 RETURN_FALSE;
    2725             :         }
    2726             :         
    2727       25357 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2728             : 
    2729       25357 :         pgsql_result = pg_result->result;
    2730             : 
    2731       25357 :         if (use_row) { 
    2732       16898 :                 pgsql_row = row;
    2733       16898 :                 pg_result->row = pgsql_row;
    2734       16898 :                 if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
    2735           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
    2736           0 :                                                         row, Z_LVAL_P(result));
    2737           0 :                         RETURN_FALSE;
    2738             :                 }
    2739             :         } else {
    2740             :                 /* If 2nd param is NULL, use internal row counter to access next row */
    2741        8459 :                 pgsql_row = pg_result->row;
    2742        8459 :                 if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
    2743        8438 :                         RETURN_FALSE;
    2744             :                 }
    2745          21 :                 pg_result->row++;
    2746             :         }
    2747             : 
    2748       16919 :         array_init(return_value);
    2749       67649 :         for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) {
    2750       50730 :                 if (PQgetisnull(pgsql_result, pgsql_row, i)) {
    2751       16904 :                         if (result_type & PGSQL_NUM) {
    2752       16892 :                                 add_index_null(return_value, i);
    2753             :                         }
    2754       16904 :                         if (result_type & PGSQL_ASSOC) {
    2755          13 :                                 field_name = PQfname(pgsql_result, i);
    2756          13 :                                 add_assoc_null(return_value, field_name);
    2757             :                         }
    2758             :                 } else {
    2759       33826 :                         char *element = PQgetvalue(pgsql_result, pgsql_row, i);
    2760       33826 :                         if (element) {
    2761             :                                 char *data;
    2762             :                                 int data_len;
    2763       33826 :                                 int should_copy=0;
    2764       33826 :                                 const uint element_len = strlen(element);
    2765             : 
    2766       33826 :                                 data = safe_estrndup(element, element_len);
    2767       33826 :                                 data_len = element_len;
    2768             : 
    2769       33826 :                                 if (result_type & PGSQL_NUM) {
    2770       33788 :                                         add_index_stringl(return_value, i, data, data_len, should_copy);
    2771       33788 :                                         should_copy=1;
    2772             :                                 }
    2773             : 
    2774       33826 :                                 if (result_type & PGSQL_ASSOC) {
    2775          43 :                                         field_name = PQfname(pgsql_result, i);
    2776          43 :                                         add_assoc_stringl(return_value, field_name, data, data_len, should_copy);
    2777             :                                 }
    2778             :                         }
    2779             :                 }
    2780             :         }
    2781             : 
    2782       16919 :         if (into_object) {
    2783          13 :                 zval dataset = *return_value;
    2784             :                 zend_fcall_info fci;
    2785             :                 zend_fcall_info_cache fcc;
    2786             :                 zval *retval_ptr;
    2787             : 
    2788          13 :                 object_and_properties_init(return_value, ce, NULL);
    2789          13 :                 zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
    2790             : 
    2791          13 :                 if (ce->constructor) {
    2792           1 :                         fci.size = sizeof(fci);
    2793           1 :                         fci.function_table = &ce->function_table;
    2794           1 :                         fci.function_name = NULL;
    2795           1 :                         fci.symbol_table = NULL;
    2796           1 :                         fci.object_ptr = return_value;
    2797           1 :                         fci.retval_ptr_ptr = &retval_ptr;
    2798           1 :                         fci.params = NULL;
    2799           1 :                         fci.param_count = 0;
    2800           1 :                         fci.no_separation = 1;
    2801             : 
    2802           1 :                         if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
    2803           1 :                                 if (zend_fcall_info_args(&fci, ctor_params TSRMLS_CC) == FAILURE) {
    2804             :                                         /* Two problems why we throw exceptions here: PHP is typeless
    2805             :                                          * and hence passing one argument that's not an array could be
    2806             :                                          * by mistake and the other way round is possible, too. The
    2807             :                                          * single value is an array. Also we'd have to make that one
    2808             :                                          * argument passed by reference.
    2809             :                                          */
    2810           0 :                                         zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC);
    2811           0 :                                         return;
    2812             :                                 }
    2813             :                         }
    2814             : 
    2815           1 :                         fcc.initialized = 1;
    2816           1 :                         fcc.function_handler = ce->constructor;
    2817           1 :                         fcc.calling_scope = EG(scope);
    2818           1 :                         fcc.called_scope = Z_OBJCE_P(return_value);
    2819           1 :                         fcc.object_ptr = return_value;
    2820             : 
    2821           1 :                         if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
    2822           0 :                                 zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name);
    2823             :                         } else {
    2824           1 :                                 if (retval_ptr) {
    2825           1 :                                         zval_ptr_dtor(&retval_ptr);
    2826             :                                 }
    2827             :                         }
    2828           1 :                         if (fci.params) {
    2829           1 :                                 efree(fci.params);
    2830             :                         }
    2831          12 :                 } else if (ctor_params) {
    2832           0 :                         zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name);
    2833             :                 }
    2834             :         }
    2835             : }
    2836             : /* }}} */
    2837             : 
    2838             : /* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]])
    2839             :    Get a row as an enumerated array */ 
    2840        8448 : PHP_FUNCTION(pg_fetch_row)
    2841             : {
    2842        8448 :         php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0);
    2843        8448 : }
    2844             : /* }}} */
    2845             : 
    2846             : /* {{{ proto array pg_fetch_assoc(resource result [, int row])
    2847             :    Fetch a row as an assoc array */
    2848           7 : PHP_FUNCTION(pg_fetch_assoc)
    2849             : {
    2850             :         /* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when
    2851             :            there is 3rd parameter */
    2852           7 :         if (ZEND_NUM_ARGS() > 2)
    2853           0 :                 WRONG_PARAM_COUNT;
    2854           7 :         php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0);
    2855             : }
    2856             : /* }}} */
    2857             : 
    2858             : /* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]])
    2859             :    Fetch a row as an array */
    2860        8456 : PHP_FUNCTION(pg_fetch_array)
    2861             : {
    2862        8456 :         php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0);
    2863        8456 : }
    2864             : /* }}} */
    2865             : 
    2866             : /* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])
    2867             :    Fetch a row as an object */
    2868        8450 : PHP_FUNCTION(pg_fetch_object)
    2869             : {
    2870             :         /* pg_fetch_object() allowed result_type used to be. 3rd parameter
    2871             :            must be allowed for compatibility */
    2872        8450 :         php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1);
    2873        8450 : }
    2874             : /* }}} */
    2875             : 
    2876             : /* {{{ proto array pg_fetch_all(resource result)
    2877             :    Fetch all rows into array */
    2878           6 : PHP_FUNCTION(pg_fetch_all)
    2879             : {
    2880             :         zval *result;
    2881             :         PGresult *pgsql_result;
    2882             :         pgsql_result_handle *pg_result;
    2883             : 
    2884           6 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
    2885           0 :                 return;
    2886             :         }
    2887             : 
    2888           6 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2889             : 
    2890           6 :         pgsql_result = pg_result->result;
    2891           6 :         array_init(return_value);
    2892           6 :         if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) {
    2893             :                 zval_dtor(return_value);
    2894           0 :                 RETURN_FALSE;
    2895             :         }
    2896             : }
    2897             : /* }}} */
    2898             : 
    2899             : /* {{{ proto array pg_fetch_all_columns(resource result [, int column_number])
    2900             :    Fetch all rows into array */
    2901           0 : PHP_FUNCTION(pg_fetch_all_columns)
    2902             : {
    2903             :         zval *result;
    2904             :         PGresult *pgsql_result;
    2905             :         pgsql_result_handle *pg_result;
    2906           0 :         unsigned long colno=0;
    2907             :         int pg_numrows, pg_row;
    2908             :         size_t num_fields;
    2909             : 
    2910           0 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) {
    2911           0 :                 RETURN_FALSE;
    2912             :         }
    2913             : 
    2914           0 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2915             : 
    2916           0 :         pgsql_result = pg_result->result;
    2917             : 
    2918           0 :         num_fields = PQnfields(pgsql_result);
    2919           0 :         if (colno >= num_fields || colno < 0) {
    2920           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno);
    2921           0 :                 RETURN_FALSE;
    2922             :         }
    2923             : 
    2924           0 :         array_init(return_value);
    2925             : 
    2926           0 :         if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
    2927           0 :                 return;
    2928             :         }
    2929             : 
    2930           0 :         for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
    2931           0 :                 if (PQgetisnull(pgsql_result, pg_row, colno)) {
    2932           0 :                         add_next_index_null(return_value);
    2933             :                 } else {
    2934           0 :                         add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1); 
    2935             :                 }
    2936             :         }
    2937             : }
    2938             : /* }}} */
    2939             : 
    2940             : /* {{{ proto bool pg_result_seek(resource result, int offset)
    2941             :    Set internal row offset */
    2942           2 : PHP_FUNCTION(pg_result_seek)
    2943             : {
    2944             :         zval *result;
    2945             :         long row;
    2946             :         pgsql_result_handle *pg_result;
    2947             : 
    2948           2 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) {
    2949           0 :                 return;
    2950             :         }
    2951             : 
    2952           2 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2953             : 
    2954           2 :         if (row < 0 || row >= PQntuples(pg_result->result)) {
    2955           0 :                 RETURN_FALSE;
    2956             :         }
    2957             : 
    2958             :         /* seek to offset */
    2959           2 :         pg_result->row = row;
    2960           2 :         RETURN_TRUE;
    2961             : }
    2962             : /* }}} */
    2963             : 
    2964             : 
    2965             : #define PHP_PG_DATA_LENGTH 1
    2966             : #define PHP_PG_DATA_ISNULL 2
    2967             : 
    2968             : /* {{{ php_pgsql_data_info
    2969             :  */
    2970          20 : static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
    2971             : {
    2972             :         zval *result, **field;
    2973             :         long row;
    2974             :         PGresult *pgsql_result;
    2975             :         pgsql_result_handle *pg_result;
    2976          20 :         int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
    2977             : 
    2978          20 :         if (argc == 2) {
    2979          20 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) {
    2980           0 :                         return;
    2981             :                 }
    2982             :         } else {
    2983           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) {
    2984           0 :                         return;
    2985             :                 }
    2986             :         }
    2987             : 
    2988          20 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    2989             : 
    2990          20 :         pgsql_result = pg_result->result;
    2991          20 :         if (argc == 2) {
    2992          20 :                 if (pg_result->row < 0) {
    2993           0 :                         pg_result->row = 0;
    2994             :                 }
    2995          20 :                 pgsql_row = pg_result->row;
    2996          20 :                 if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
    2997           0 :                         RETURN_FALSE;
    2998             :                 }
    2999             :         } else {
    3000           0 :                 pgsql_row = row;
    3001           0 :                 if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
    3002           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
    3003           0 :                                                         row, Z_LVAL_P(result));
    3004           0 :                         RETURN_FALSE;
    3005             :                 }
    3006             :         }
    3007             : 
    3008          20 :         switch(Z_TYPE_PP(field)) {
    3009             :                 case IS_STRING:
    3010           0 :                         convert_to_string_ex(field);
    3011           0 :                         field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
    3012           0 :                         break;
    3013             :                 default:
    3014          20 :                         convert_to_long_ex(field);
    3015          20 :                         field_offset = Z_LVAL_PP(field);
    3016             :                         break;
    3017             :         }
    3018          20 :         if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
    3019           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
    3020           0 :                 RETURN_FALSE;
    3021             :         }
    3022             : 
    3023          20 :         switch (entry_type) {
    3024             :                 case PHP_PG_DATA_LENGTH:
    3025          10 :                         Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset);
    3026          10 :                         break;
    3027             :                 case PHP_PG_DATA_ISNULL:
    3028          10 :                         Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset);
    3029             :                         break;
    3030             :         }
    3031          20 :         Z_TYPE_P(return_value) = IS_LONG;
    3032             : }
    3033             : /* }}} */
    3034             : 
    3035             : /* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)
    3036             :    Returns the printed length */
    3037          10 : PHP_FUNCTION(pg_field_prtlen)
    3038             : {
    3039          10 :         php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH);
    3040          10 : }
    3041             : /* }}} */
    3042             : 
    3043             : /* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)
    3044             :    Test if a field is NULL */
    3045          10 : PHP_FUNCTION(pg_field_is_null)
    3046             : {
    3047          10 :         php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL);
    3048          10 : }
    3049             : /* }}} */
    3050             : 
    3051             : /* {{{ proto bool pg_free_result(resource result)
    3052             :    Free result memory */
    3053          16 : PHP_FUNCTION(pg_free_result)
    3054             : {
    3055             :         zval *result;
    3056             :         pgsql_result_handle *pg_result;
    3057             : 
    3058          16 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
    3059           0 :                 return;
    3060             :         }
    3061             : 
    3062          16 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    3063          16 :         if (Z_LVAL_P(result) == 0) {
    3064           0 :                 RETURN_FALSE;
    3065             :         }
    3066          16 :         zend_list_delete(Z_RESVAL_P(result));
    3067          16 :         RETURN_TRUE;
    3068             : }
    3069             : /* }}} */
    3070             : 
    3071             : /* {{{ proto string pg_last_oid(resource result)
    3072             :    Returns the last object identifier */
    3073          10 : PHP_FUNCTION(pg_last_oid)
    3074             : {
    3075             :         zval *result;
    3076             :         PGresult *pgsql_result;
    3077             :         pgsql_result_handle *pg_result;
    3078             : #ifdef HAVE_PQOIDVALUE
    3079             :         Oid oid;
    3080             : #endif
    3081             : 
    3082          10 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
    3083           0 :                 return;
    3084             :         }
    3085             : 
    3086          10 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    3087          10 :         pgsql_result = pg_result->result;
    3088             : #ifdef HAVE_PQOIDVALUE
    3089          10 :         oid = PQoidValue(pgsql_result);
    3090          10 :         if (oid == InvalidOid) {
    3091          10 :                 RETURN_FALSE;
    3092             :         }
    3093           0 :         PGSQL_RETURN_OID(oid);
    3094             : #else
    3095             :         Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result);
    3096             :         if (Z_STRVAL_P(return_value)) {
    3097             :                 RETURN_STRING(Z_STRVAL_P(return_value), 1);
    3098             :         }
    3099             :         RETURN_STRING("", 1);
    3100             : #endif
    3101             : }
    3102             : /* }}} */
    3103             : 
    3104             : /* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]])
    3105             :    Enable tracing a PostgreSQL connection */
    3106           1 : PHP_FUNCTION(pg_trace)
    3107             : {
    3108           1 :         char *z_filename, *mode = "w";
    3109             :         int z_filename_len, mode_len;
    3110           1 :         zval *pgsql_link = NULL;
    3111           1 :         int id = -1, argc = ZEND_NUM_ARGS();
    3112             :         PGconn *pgsql;
    3113           1 :         FILE *fp = NULL;
    3114             :         php_stream *stream;
    3115           1 :         id = PGG(default_link);
    3116             : 
    3117           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
    3118           0 :                 return;
    3119             :         }
    3120             : 
    3121           1 :         if (argc < 3) {
    3122           0 :                 CHECK_DEFAULT_LINK(id);
    3123             :         }
    3124             : 
    3125           1 :         if (pgsql_link == NULL && id == -1) {
    3126           0 :                 RETURN_FALSE;
    3127             :         }
    3128             : 
    3129           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3130             : 
    3131           1 :         stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
    3132             : 
    3133           1 :         if (!stream) {
    3134           0 :                 RETURN_FALSE;
    3135             :         }
    3136             : 
    3137           1 :         if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS))    {
    3138           0 :                 php_stream_close(stream);
    3139           0 :                 RETURN_FALSE;
    3140             :         }
    3141             :         php_stream_auto_cleanup(stream);
    3142           1 :         PQtrace(pgsql, fp);
    3143           1 :         RETURN_TRUE;
    3144             : }
    3145             : /* }}} */
    3146             : 
    3147             : /* {{{ proto bool pg_untrace([resource connection])
    3148             :    Disable tracing of a PostgreSQL connection */
    3149           0 : PHP_FUNCTION(pg_untrace)
    3150             : {
    3151           0 :         zval *pgsql_link = NULL;
    3152           0 :         int id = -1, argc = ZEND_NUM_ARGS();
    3153             :         PGconn *pgsql;
    3154             :         
    3155           0 :         if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
    3156           0 :                 return;
    3157             :         }
    3158             : 
    3159           0 :         if (argc == 0) { 
    3160           0 :                 id = PGG(default_link);
    3161           0 :                 CHECK_DEFAULT_LINK(id);
    3162             :         }
    3163             : 
    3164           0 :         if (pgsql_link == NULL && id == -1) {
    3165           0 :                 RETURN_FALSE;
    3166             :         }
    3167             : 
    3168           0 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3169           0 :         PQuntrace(pgsql);
    3170           0 :         RETURN_TRUE;
    3171             : }
    3172             : /* }}} */
    3173             : 
    3174             : /* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid])
    3175             :    Create a large object */
    3176           6 : PHP_FUNCTION(pg_lo_create)
    3177             : {
    3178           6 :         zval *pgsql_link = NULL, *oid = NULL;
    3179             :         PGconn *pgsql;
    3180           6 :         Oid pgsql_oid, wanted_oid = InvalidOid;
    3181           6 :         int id = -1, argc = ZEND_NUM_ARGS();
    3182             : 
    3183           6 :         if (zend_parse_parameters(argc TSRMLS_CC, "|zz", &pgsql_link, &oid) == FAILURE) {
    3184           0 :                 return;
    3185             :         }
    3186             : 
    3187           6 :         if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) {
    3188           1 :                 oid = pgsql_link;
    3189           1 :                 pgsql_link = NULL;
    3190             :         }
    3191             :         
    3192           6 :         if (pgsql_link == NULL) {
    3193           1 :                 id = PGG(default_link);
    3194           1 :                 CHECK_DEFAULT_LINK(id);
    3195           1 :                 if (id == -1) {
    3196           0 :                         RETURN_FALSE;
    3197             :                 }
    3198             :         }
    3199             : 
    3200           6 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3201             :         
    3202           6 :         if (oid) {
    3203             : #ifndef HAVE_PG_LO_CREATE
    3204             :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL");
    3205             : #else
    3206           3 :                 switch (Z_TYPE_P(oid)) {
    3207             :                 case IS_STRING:
    3208             :                         {
    3209             :                                 char *end_ptr;
    3210           1 :                                 wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
    3211           1 :                                 if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
    3212             :                                 /* wrong integer format */
    3213           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
    3214           0 :                                 RETURN_FALSE;
    3215             :                                 }
    3216             :                         }
    3217           1 :                         break;
    3218             :                 case IS_LONG:
    3219           2 :                         if (Z_LVAL_P(oid) < (long)InvalidOid) {
    3220           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
    3221           0 :                                 RETURN_FALSE;
    3222             :                         }
    3223           2 :                         wanted_oid = (Oid)Z_LVAL_P(oid);
    3224           2 :                         break;
    3225             :                 default:
    3226           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
    3227           0 :                         RETURN_FALSE;
    3228             :         }
    3229           3 :                 if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) {
    3230           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
    3231           0 :                         RETURN_FALSE;
    3232             :                 }
    3233             : 
    3234           3 :                 PGSQL_RETURN_OID(pgsql_oid);
    3235             : #endif
    3236             :         }
    3237             : 
    3238           3 :         if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) {
    3239           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
    3240           0 :                 RETURN_FALSE;
    3241             :         }
    3242             : 
    3243           3 :         PGSQL_RETURN_OID(pgsql_oid);
    3244             : }
    3245             : /* }}} */
    3246             : 
    3247             : /* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid)
    3248             :    Delete a large object */
    3249           9 : PHP_FUNCTION(pg_lo_unlink)
    3250             : {
    3251           9 :         zval *pgsql_link = NULL;
    3252             :         long oid_long;
    3253             :         char *oid_string, *end_ptr;
    3254             :         int oid_strlen;
    3255             :         PGconn *pgsql;
    3256             :         Oid oid;
    3257           9 :         int id = -1;
    3258           9 :         int argc = ZEND_NUM_ARGS();
    3259             : 
    3260             :         /* accept string type since Oid type is unsigned int */
    3261           9 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3262             :                                                                  "rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) {
    3263           6 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3264           6 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3265             :                         /* wrong integer format */
    3266           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3267           0 :                         RETURN_FALSE;
    3268             :                 }
    3269             :         }
    3270           3 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3271             :                                                                  "rl", &pgsql_link, &oid_long) == SUCCESS) {
    3272           0 :                 if (oid_long <= InvalidOid) {
    3273           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
    3274           0 :                         RETURN_FALSE;
    3275             :                 }
    3276           0 :                 oid = (Oid)oid_long;
    3277             :         }
    3278           3 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3279             :                                                                  "s", &oid_string, &oid_strlen) == SUCCESS) {
    3280           3 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3281           3 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3282             :                         /* wrong integer format */
    3283           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3284           0 :                         RETURN_FALSE;
    3285             :                 }
    3286           3 :                 id = PGG(default_link);
    3287           3 :                 CHECK_DEFAULT_LINK(id);
    3288             :         }
    3289           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3290             :                                                                  "l", &oid_long) == SUCCESS) {
    3291           0 :                 if (oid_long <= InvalidOid) {
    3292           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified");
    3293           0 :                         RETURN_FALSE;
    3294             :                 }
    3295           0 :                 oid = (Oid)oid_long;
    3296           0 :                 id = PGG(default_link);
    3297           0 :                 CHECK_DEFAULT_LINK(id);
    3298             :         }
    3299             :         else {
    3300           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
    3301           0 :                 RETURN_FALSE;
    3302             :         }
    3303           9 :         if (pgsql_link == NULL && id == -1) {
    3304           0 :                 RETURN_FALSE;
    3305             :         }
    3306             : 
    3307           9 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3308             : 
    3309           9 :         if (lo_unlink(pgsql, oid) == -1) {
    3310           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid);
    3311           0 :                 RETURN_FALSE;
    3312             :         }
    3313           9 :         RETURN_TRUE;
    3314             : }
    3315             : /* }}} */
    3316             : 
    3317             : /* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode)
    3318             :    Open a large object and return fd */
    3319           3 : PHP_FUNCTION(pg_lo_open)
    3320             : {
    3321           3 :         zval *pgsql_link = NULL;
    3322             :         long oid_long;
    3323             :         char *oid_string, *end_ptr, *mode_string;
    3324             :         int oid_strlen, mode_strlen;
    3325             :         PGconn *pgsql;
    3326             :         Oid oid;
    3327           3 :         int id = -1, pgsql_mode=0, pgsql_lofd;
    3328           3 :         int create=0;
    3329             :         pgLofp *pgsql_lofp;
    3330           3 :         int argc = ZEND_NUM_ARGS();
    3331             : 
    3332             :         /* accept string type since Oid is unsigned int */
    3333           3 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3334             :                                                                  "rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
    3335           3 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3336           3 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3337             :                         /* wrong integer format */
    3338           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3339           0 :                         RETURN_FALSE;
    3340             :                 }
    3341             :         }
    3342           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3343             :                                                                  "rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
    3344           0 :                 if (oid_long <= InvalidOid) {
    3345           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
    3346           0 :                         RETURN_FALSE;
    3347             :                 }
    3348           0 :                 oid = (Oid)oid_long;
    3349             :         }
    3350           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3351             :                                                                  "ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
    3352           0 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3353           0 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3354             :                         /* wrong integer format */
    3355           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3356           0 :                         RETURN_FALSE;
    3357             :                 }
    3358           0 :                 id = PGG(default_link);
    3359           0 :                 CHECK_DEFAULT_LINK(id);
    3360             :         }
    3361           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3362             :                                                                  "ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
    3363           0 :                 if (oid_long <= InvalidOid) {
    3364           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
    3365           0 :                         RETURN_FALSE;
    3366             :                 }
    3367           0 :                 oid = (Oid)oid_long;
    3368           0 :                 id = PGG(default_link);
    3369           0 :                 CHECK_DEFAULT_LINK(id);
    3370             :         }
    3371             :         else {
    3372           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
    3373           0 :                 RETURN_FALSE;
    3374             :         }
    3375           3 :         if (pgsql_link == NULL && id == -1) {
    3376           0 :                 RETURN_FALSE;
    3377             :         }
    3378             : 
    3379           3 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3380             :         
    3381             :         /* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of
    3382             :            faster to type. Unfortunately, doesn't behave the same way as fopen()...
    3383             :            (Jouni)
    3384             :         */
    3385             : 
    3386           3 :         if (strchr(mode_string, 'r') == mode_string) {
    3387           0 :                 pgsql_mode |= INV_READ;
    3388           0 :                 if (strchr(mode_string, '+') == mode_string+1) {
    3389           0 :                         pgsql_mode |= INV_WRITE;
    3390             :                 }
    3391             :         }
    3392           3 :         if (strchr(mode_string, 'w') == mode_string) {
    3393           3 :                 pgsql_mode |= INV_WRITE;
    3394           3 :                 create = 1;
    3395           3 :                 if (strchr(mode_string, '+') == mode_string+1) {
    3396           0 :                         pgsql_mode |= INV_READ;
    3397             :                 }
    3398             :         }
    3399             : 
    3400           3 :         pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp));
    3401             : 
    3402           3 :         if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
    3403           0 :                 if (create) {
    3404           0 :                         if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) {
    3405           0 :                                 efree(pgsql_lofp);
    3406           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
    3407           0 :                                 RETURN_FALSE;
    3408             :                         } else {
    3409           0 :                                 if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
    3410           0 :                                         if (lo_unlink(pgsql, oid) == -1) {
    3411           0 :                                                 efree(pgsql_lofp);
    3412           0 :                                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP");
    3413           0 :                                                 RETURN_FALSE;
    3414             :                                         }
    3415           0 :                                         efree(pgsql_lofp);
    3416           0 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
    3417           0 :                                         RETURN_FALSE;
    3418             :                                 } else {
    3419           0 :                                         pgsql_lofp->conn = pgsql;
    3420           0 :                                         pgsql_lofp->lofd = pgsql_lofd;
    3421           0 :                                         Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC);
    3422           0 :                                         Z_TYPE_P(return_value) = IS_LONG;
    3423             :                                 }
    3424             :                         }
    3425             :                 } else {
    3426           0 :                         efree(pgsql_lofp);
    3427           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
    3428           0 :                         RETURN_FALSE;
    3429             :                 }
    3430             :         } else {
    3431           3 :                 pgsql_lofp->conn = pgsql;
    3432           3 :                 pgsql_lofp->lofd = pgsql_lofd;
    3433           3 :                 ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
    3434             :         }
    3435             : }
    3436             : /* }}} */
    3437             : 
    3438             : /* {{{ proto bool pg_lo_close(resource large_object)
    3439             :    Close a large object */
    3440           3 : PHP_FUNCTION(pg_lo_close)
    3441             : {
    3442             :         zval *pgsql_lofp;
    3443             :         pgLofp *pgsql;
    3444             : 
    3445           3 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_lofp) == FAILURE) {
    3446           0 :                 return;
    3447             :         }
    3448             : 
    3449           3 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_lofp, -1, "PostgreSQL large object", le_lofp);
    3450             :         
    3451           3 :         if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) {
    3452           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd);
    3453           0 :                 RETVAL_FALSE;
    3454             :         } else {
    3455           3 :                 RETVAL_TRUE;
    3456             :         }
    3457             : 
    3458           3 :         zend_list_delete(Z_RESVAL_P(pgsql_lofp));
    3459           3 :         return;
    3460             : }
    3461             : /* }}} */
    3462             : 
    3463             : #define PGSQL_LO_READ_BUF_SIZE  8192
    3464             : 
    3465             : /* {{{ proto string pg_lo_read(resource large_object [, int len])
    3466             :    Read a large object */
    3467           1 : PHP_FUNCTION(pg_lo_read)
    3468             : {
    3469             :         zval *pgsql_id;
    3470             :         long len;
    3471           1 :         int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes, argc = ZEND_NUM_ARGS();
    3472             :         char *buf;
    3473             :         pgLofp *pgsql;
    3474             : 
    3475           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &pgsql_id, &len) == FAILURE) {
    3476           0 :                 return;
    3477             :         }
    3478             : 
    3479           1 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
    3480             : 
    3481           1 :         if (argc > 1) {
    3482           1 :                 buf_len = len;
    3483             :         }
    3484             :         
    3485           1 :         buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0);
    3486           1 :         if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) {
    3487           0 :                 efree(buf);
    3488           0 :                 RETURN_FALSE;
    3489             :         }
    3490             : 
    3491           1 :         buf[nbytes] = '\0';
    3492           1 :         RETURN_STRINGL(buf, nbytes, 0);
    3493             : }
    3494             : /* }}} */
    3495             : 
    3496             : /* {{{ proto int pg_lo_write(resource large_object, string buf [, int len])
    3497             :    Write a large object */
    3498           1 : PHP_FUNCTION(pg_lo_write)
    3499             : {
    3500             :         zval *pgsql_id;
    3501             :         char *str;
    3502             :         long z_len;
    3503             :         int str_len, nbytes;
    3504             :         int len;
    3505             :         pgLofp *pgsql;
    3506           1 :         int argc = ZEND_NUM_ARGS();
    3507             : 
    3508           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) {
    3509           0 :                 return;
    3510             :         }
    3511             : 
    3512           1 :         if (argc > 2) {
    3513           0 :                 if (z_len > str_len) {
    3514           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld", str_len, z_len);
    3515           0 :                         RETURN_FALSE;
    3516             :                 }
    3517           0 :                 if (z_len < 0) {
    3518           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", z_len);
    3519           0 :                         RETURN_FALSE;
    3520             :                 }
    3521           0 :                 len = z_len;
    3522             :         }
    3523             :         else {
    3524           1 :                 len = str_len;
    3525             :         }
    3526             : 
    3527           1 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
    3528             : 
    3529           1 :         if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) {
    3530           0 :                 RETURN_FALSE;
    3531             :         }
    3532             : 
    3533           1 :         RETURN_LONG(nbytes);
    3534             : }
    3535             : /* }}} */
    3536             : 
    3537             : /* {{{ proto int pg_lo_read_all(resource large_object)
    3538             :    Read a large object and send straight to browser */
    3539           1 : PHP_FUNCTION(pg_lo_read_all)
    3540             : {
    3541             :         zval *pgsql_id;
    3542             :         int tbytes;
    3543             :         volatile int nbytes;
    3544             :         char buf[PGSQL_LO_READ_BUF_SIZE];
    3545             :         pgLofp *pgsql;
    3546             :         
    3547           1 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
    3548           0 :                 return;
    3549             :         }
    3550             : 
    3551           1 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
    3552             : 
    3553           1 :         tbytes = 0;
    3554           3 :         while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) {
    3555           1 :                 PHPWRITE(buf, nbytes);
    3556           1 :                 tbytes += nbytes;
    3557             :         }
    3558           1 :         RETURN_LONG(tbytes);
    3559             : }
    3560             : /* }}} */
    3561             : 
    3562             : /* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid])
    3563             :    Import large object direct from filesystem */
    3564           4 : PHP_FUNCTION(pg_lo_import)
    3565             : {
    3566           4 :         zval *pgsql_link = NULL, *oid = NULL;
    3567             :         char *file_in;
    3568           4 :         int id = -1, name_len;
    3569           4 :         int argc = ZEND_NUM_ARGS();
    3570             :         PGconn *pgsql;
    3571             :         Oid returned_oid;
    3572             : 
    3573           4 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3574             :                                                                  "rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) {
    3575             :                 ;
    3576             :         }
    3577           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3578             :                                                                           "p|z", &file_in, &name_len, &oid) == SUCCESS) {
    3579           0 :                 id = PGG(default_link);
    3580           0 :                 CHECK_DEFAULT_LINK(id);
    3581             :         }
    3582             :         /* old calling convention, deprecated since PHP 4.2 */
    3583           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3584             :                                                                           "pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) {
    3585           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
    3586             :         }
    3587             :         else {
    3588           0 :                 WRONG_PARAM_COUNT;
    3589             :         }
    3590             :         
    3591           4 :         if (php_check_open_basedir(file_in TSRMLS_CC)) {
    3592           0 :                 RETURN_FALSE;
    3593             :         }
    3594             : 
    3595           4 :         if (pgsql_link == NULL && id == -1) {
    3596           0 :                 RETURN_FALSE;
    3597             :         }
    3598             : 
    3599           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3600             : 
    3601           4 :         if (oid) {
    3602             : #ifndef HAVE_PG_LO_IMPORT_WITH_OID
    3603             :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "OID value passing not supported");
    3604             : #else
    3605             :                 Oid wanted_oid;
    3606           3 :                 switch (Z_TYPE_P(oid)) {
    3607             :                 case IS_STRING:
    3608             :                         {
    3609             :                                 char *end_ptr;
    3610           1 :                                 wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
    3611           1 :                                 if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
    3612             :                                 /* wrong integer format */
    3613           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
    3614           0 :                                 RETURN_FALSE;
    3615             :                                 }
    3616             :                         }
    3617           1 :                         break;
    3618             :                 case IS_LONG:
    3619           2 :                         if (Z_LVAL_P(oid) < (long)InvalidOid) {
    3620           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
    3621           0 :                                 RETURN_FALSE;
    3622             :                         }
    3623           2 :                         wanted_oid = (Oid)Z_LVAL_P(oid);
    3624           2 :                         break;
    3625             :                 default:
    3626           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed");
    3627           0 :                         RETURN_FALSE;
    3628             :         }
    3629             : 
    3630           3 :        returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid);
    3631             : 
    3632           3 :            if (returned_oid == InvalidOid) {
    3633           0 :                    RETURN_FALSE;
    3634             :            }
    3635             : 
    3636           3 :            PGSQL_RETURN_OID(returned_oid);
    3637             : #endif
    3638             :         }
    3639             : 
    3640           1 :         returned_oid = lo_import(pgsql, file_in);
    3641             : 
    3642           1 :         if (returned_oid == InvalidOid) {
    3643           0 :                 RETURN_FALSE;
    3644             :         }
    3645           1 :         PGSQL_RETURN_OID(returned_oid);
    3646             : }
    3647             : /* }}} */
    3648             : 
    3649             : /* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename)
    3650             :    Export large object direct to filesystem */
    3651           1 : PHP_FUNCTION(pg_lo_export)
    3652             : {
    3653           1 :         zval *pgsql_link = NULL;
    3654             :         char *file_out, *oid_string, *end_ptr;
    3655             :         int oid_strlen;
    3656           1 :         int id = -1, name_len;
    3657             :         long oid_long;
    3658             :         Oid oid;
    3659             :         PGconn *pgsql;
    3660           1 :         int argc = ZEND_NUM_ARGS();
    3661             : 
    3662             :         /* allow string to handle large OID value correctly */
    3663           1 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3664             :                                                                  "rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) {
    3665           0 :                 if (oid_long <= InvalidOid) {
    3666           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
    3667           0 :                         RETURN_FALSE;
    3668             :                 }
    3669           0 :                 oid = (Oid)oid_long;
    3670             :         }
    3671           1 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3672             :                                                                  "rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
    3673           0 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3674           0 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3675             :                         /* wrong integer format */
    3676           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3677           0 :                         RETURN_FALSE;
    3678             :                 }
    3679             :         }
    3680           1 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3681             :                                                                           "lp",  &oid_long, &file_out, &name_len) == SUCCESS) {
    3682           0 :                 if (oid_long <= InvalidOid) {
    3683           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
    3684           0 :                         RETURN_FALSE;
    3685             :                 }
    3686           0 :                 oid = (Oid)oid_long;
    3687           0 :                 id = PGG(default_link);
    3688           0 :                 CHECK_DEFAULT_LINK(id);
    3689             :         }
    3690           1 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3691             :                                                                  "sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
    3692           0 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3693           0 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3694             :                         /* wrong integer format */
    3695           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3696           0 :                         RETURN_FALSE;
    3697             :                 }
    3698           0 :                 id = PGG(default_link);
    3699           0 :                 CHECK_DEFAULT_LINK(id);
    3700             :         }
    3701           1 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3702             :                                                                  "spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) {
    3703           1 :                 oid = (Oid)strtoul(oid_string, &end_ptr, 10);
    3704           1 :                 if ((oid_string+oid_strlen) != end_ptr) {
    3705             :                         /* wrong integer format */
    3706           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
    3707           0 :                         RETURN_FALSE;
    3708             :                 }
    3709             :         }
    3710           0 :         else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
    3711             :                                                                           "lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) {
    3712           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
    3713           0 :                 if (oid_long <= InvalidOid) {
    3714           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
    3715           0 :                         RETURN_FALSE;
    3716             :                 }
    3717           0 :                 oid = (Oid)oid_long;
    3718             :         }
    3719             :         else {
    3720           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments");
    3721           0 :                 RETURN_FALSE;
    3722             :         }
    3723             :         
    3724           1 :         if (php_check_open_basedir(file_out TSRMLS_CC)) {
    3725           0 :                 RETURN_FALSE;
    3726             :         }
    3727             : 
    3728           1 :         if (pgsql_link == NULL && id == -1) {
    3729           0 :                 RETURN_FALSE;
    3730             :         }
    3731             : 
    3732           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3733             : 
    3734           1 :         if (lo_export(pgsql, oid, file_out)) {
    3735           1 :                 RETURN_TRUE;
    3736             :         }
    3737           0 :         RETURN_FALSE;
    3738             : }
    3739             : /* }}} */
    3740             : 
    3741             : /* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence])
    3742             :    Seeks position of large object */
    3743           1 : PHP_FUNCTION(pg_lo_seek)
    3744             : {
    3745           1 :         zval *pgsql_id = NULL;
    3746           1 :         long result, offset = 0, whence = SEEK_CUR;
    3747             :         pgLofp *pgsql;
    3748           1 :         int argc = ZEND_NUM_ARGS();
    3749             : 
    3750           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) {
    3751           0 :                 return;
    3752             :         }
    3753           1 :         if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
    3754           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter");
    3755           0 :                 return;
    3756             :         }
    3757             : 
    3758           1 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
    3759             : 
    3760             : #if HAVE_PG_LO64
    3761             :         if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) {
    3762             :                 result = lo_lseek64((PGconn *)pgsql->conn, pgsql->lofd, offset, whence);
    3763             :         } else {
    3764             :                 result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence);
    3765             :         }
    3766             : #else
    3767           1 :         result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence);
    3768             : #endif
    3769           1 :         if (result > -1) {
    3770           1 :                 RETURN_TRUE;
    3771             :         } else {
    3772           0 :                 RETURN_FALSE;
    3773             :         }
    3774             : }
    3775             : /* }}} */
    3776             : 
    3777             : /* {{{ proto int pg_lo_tell(resource large_object)
    3778             :    Returns current position of large object */
    3779           1 : PHP_FUNCTION(pg_lo_tell)
    3780             : {
    3781           1 :         zval *pgsql_id = NULL;
    3782           1 :         long offset = 0;
    3783             :         pgLofp *pgsql;
    3784           1 :         int argc = ZEND_NUM_ARGS();
    3785             : 
    3786           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
    3787           0 :                 return;
    3788             :         }
    3789             : 
    3790           1 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
    3791             : 
    3792             : #if HAVE_PG_LO64
    3793             :         if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) {
    3794             :                 offset = lo_tell64((PGconn *)pgsql->conn, pgsql->lofd);
    3795             :         } else {
    3796             :                 offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
    3797             :         }
    3798             : #else
    3799           1 :         offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
    3800             : #endif
    3801           1 :         RETURN_LONG(offset);
    3802             : }
    3803             : /* }}} */
    3804             : 
    3805             : #if HAVE_PG_LO_TRUNCATE
    3806             : /* {{{ proto bool pg_lo_truncate(resource large_object, int size)
    3807             :    Truncate large object to size */
    3808           0 : PHP_FUNCTION(pg_lo_truncate)
    3809             : {
    3810           0 :         zval *pgsql_id = NULL;
    3811             :         size_t size;
    3812             :         pgLofp *pgsql;
    3813           0 :         int argc = ZEND_NUM_ARGS();
    3814             :         int result;
    3815             : 
    3816           0 :         if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_id, &size) == FAILURE) {
    3817           0 :                 return;
    3818             :         }
    3819             : 
    3820           0 :         ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
    3821             : 
    3822             : #if HAVE_PG_LO64
    3823             :         if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) {
    3824             :                 result = lo_truncate64((PGconn *)pgsql->conn, pgsql->lofd, size);
    3825             :         } else {
    3826             :                 result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size);
    3827             :         }
    3828             : #else
    3829           0 :         result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size);
    3830             : #endif
    3831           0 :         if (!result) {
    3832           0 :                 RETURN_TRUE;
    3833             :         } else {
    3834           0 :                 RETURN_FALSE;
    3835             :         }
    3836             : }
    3837             : /* }}} */
    3838             : #endif
    3839             : 
    3840             : #if HAVE_PQSETERRORVERBOSITY
    3841             : /* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity)
    3842             :    Set error verbosity */
    3843           3 : PHP_FUNCTION(pg_set_error_verbosity)
    3844             : {
    3845           3 :         zval *pgsql_link = NULL;
    3846             :         long verbosity;
    3847           3 :         int id = -1, argc = ZEND_NUM_ARGS();
    3848             :         PGconn *pgsql;
    3849             : 
    3850           3 :         if (argc == 1) {
    3851           3 :                 if (zend_parse_parameters(argc TSRMLS_CC, "l", &verbosity) == FAILURE) {
    3852           0 :                         return;
    3853             :                 }
    3854           3 :                 id = PGG(default_link);
    3855           3 :                 CHECK_DEFAULT_LINK(id);
    3856             :         } else {
    3857           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_link, &verbosity) == FAILURE) {
    3858           0 :                         return;
    3859             :                 }
    3860             :         }
    3861             : 
    3862           3 :         if (pgsql_link == NULL && id == -1) {
    3863           0 :                 RETURN_FALSE;
    3864             :         }       
    3865             : 
    3866           3 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3867             : 
    3868           3 :         if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) {
    3869           2 :                 Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, verbosity);
    3870           2 :                 Z_TYPE_P(return_value) = IS_LONG;
    3871             :         } else {
    3872           1 :                 RETURN_FALSE;
    3873             :         }
    3874             : }
    3875             : /* }}} */
    3876             : #endif
    3877             : 
    3878             : #ifdef HAVE_PQCLIENTENCODING
    3879             : /* {{{ proto int pg_set_client_encoding([resource connection,] string encoding)
    3880             :    Set client encoding */
    3881           1 : PHP_FUNCTION(pg_set_client_encoding)
    3882             : {
    3883             :         char *encoding;
    3884             :         int encoding_len;
    3885           1 :         zval *pgsql_link = NULL;
    3886           1 :         int id = -1, argc = ZEND_NUM_ARGS();
    3887             :         PGconn *pgsql;
    3888             : 
    3889           1 :         if (argc == 1) {
    3890           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "s", &encoding, &encoding_len) == FAILURE) {
    3891           0 :                         return;
    3892             :                 }
    3893           0 :                 id = PGG(default_link);
    3894           0 :                 CHECK_DEFAULT_LINK(id);
    3895             :         } else {
    3896           1 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) {
    3897           0 :                         return;
    3898             :                 }
    3899             :         }
    3900             : 
    3901           1 :         if (pgsql_link == NULL && id == -1) {
    3902           0 :                 RETURN_FALSE;
    3903             :         }
    3904             : 
    3905           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3906             : 
    3907           1 :         Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, encoding);
    3908           1 :         Z_TYPE_P(return_value) = IS_LONG;
    3909             : }
    3910             : /* }}} */
    3911             : 
    3912             : /* {{{ proto string pg_client_encoding([resource connection])
    3913             :    Get the current client encoding */
    3914           1 : PHP_FUNCTION(pg_client_encoding)
    3915             : {
    3916           1 :         zval *pgsql_link = NULL;
    3917           1 :         int id = -1, argc = ZEND_NUM_ARGS();
    3918             :         PGconn *pgsql;
    3919             : 
    3920           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
    3921           0 :                 return;
    3922             :         }
    3923             :         
    3924           1 :         if (argc == 0) {
    3925           0 :                 id = PGG(default_link);
    3926           0 :                 CHECK_DEFAULT_LINK(id);
    3927             :         }
    3928             : 
    3929           1 :         if (pgsql_link == NULL && id == -1) {
    3930           0 :                 RETURN_FALSE;
    3931             :         }       
    3932             : 
    3933           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3934             : 
    3935             :         /* Just do the same as found in PostgreSQL sources... */
    3936             : 
    3937           1 :         Z_STRVAL_P(return_value) = (char *) pg_encoding_to_char(PQclientEncoding(pgsql));
    3938           1 :         Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
    3939           1 :         Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
    3940           1 :         Z_TYPE_P(return_value) = IS_STRING;
    3941             : }
    3942             : /* }}} */
    3943             : #endif
    3944             : 
    3945             : #if !HAVE_PQGETCOPYDATA
    3946             : #define COPYBUFSIZ      8192
    3947             : #endif
    3948             : 
    3949             : /* {{{ proto bool pg_end_copy([resource connection])
    3950             :    Sync with backend. Completes the Copy command */
    3951           0 : PHP_FUNCTION(pg_end_copy)
    3952             : {
    3953           0 :         zval *pgsql_link = NULL;
    3954           0 :         int id = -1, argc = ZEND_NUM_ARGS();
    3955             :         PGconn *pgsql;
    3956           0 :         int result = 0;
    3957             : 
    3958           0 :         if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) {
    3959           0 :                 return;
    3960             :         }
    3961             :         
    3962           0 :         if (argc == 0) {
    3963           0 :                 id = PGG(default_link);
    3964           0 :                 CHECK_DEFAULT_LINK(id);
    3965             :         }
    3966             : 
    3967           0 :         if (pgsql_link == NULL && id == -1) {
    3968           0 :                 RETURN_FALSE;
    3969             :         }
    3970             : 
    3971           0 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    3972             : 
    3973           0 :         result = PQendcopy(pgsql);
    3974             : 
    3975           0 :         if (result!=0) {
    3976           0 :                 PHP_PQ_ERROR("Query failed: %s", pgsql);
    3977           0 :                 RETURN_FALSE;
    3978             :         }
    3979           0 :         RETURN_TRUE;
    3980             : }
    3981             : /* }}} */
    3982             : 
    3983             : 
    3984             : /* {{{ proto bool pg_put_line([resource connection,] string query)
    3985             :    Send null-terminated string to backend server*/
    3986           0 : PHP_FUNCTION(pg_put_line)
    3987             : {
    3988             :         char *query;
    3989           0 :         zval *pgsql_link = NULL;
    3990           0 :         int query_len, id = -1;
    3991             :         PGconn *pgsql;
    3992           0 :         int result = 0, argc = ZEND_NUM_ARGS();
    3993             : 
    3994           0 :         if (argc == 1) {
    3995           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
    3996           0 :                         return;
    3997             :                 }
    3998           0 :                 id = PGG(default_link);
    3999           0 :                 CHECK_DEFAULT_LINK(id);
    4000             :         } else {
    4001           0 :                 if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
    4002           0 :                         return;
    4003             :                 }
    4004             :         }
    4005             : 
    4006           0 :         if (pgsql_link == NULL && id == -1) {
    4007           0 :                 RETURN_FALSE;
    4008             :         }       
    4009             : 
    4010           0 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4011             : 
    4012           0 :         result = PQputline(pgsql, query);
    4013           0 :         if (result==EOF) {
    4014           0 :                 PHP_PQ_ERROR("Query failed: %s", pgsql);
    4015           0 :                 RETURN_FALSE;
    4016             :         }
    4017           0 :         RETURN_TRUE;
    4018             : }
    4019             : /* }}} */
    4020             : 
    4021             : /* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])
    4022             :    Copy table to array */
    4023           1 : PHP_FUNCTION(pg_copy_to)
    4024             : {
    4025             :         zval *pgsql_link;
    4026           1 :         char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
    4027           1 :         int table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0;
    4028             :         char *query;
    4029           1 :         int id = -1;
    4030             :         PGconn *pgsql;
    4031             :         PGresult *pgsql_result;
    4032             :         ExecStatusType status;
    4033           1 :         int copydone = 0;
    4034             : #if !HAVE_PQGETCOPYDATA
    4035             :         char copybuf[COPYBUFSIZ];
    4036             : #endif
    4037           1 :         char *csv = (char *)NULL;
    4038             :         int ret;
    4039           1 :         int argc = ZEND_NUM_ARGS();
    4040             : 
    4041           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss",
    4042             :                                                           &pgsql_link, &table_name, &table_name_len,
    4043             :                                                           &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
    4044           0 :                 return;
    4045             :         }
    4046           1 :         if (!pg_delim) {
    4047           1 :                 pg_delim = "\t";
    4048             :         }
    4049             : 
    4050           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4051             : 
    4052           1 :         if (!pg_null_as) {
    4053           1 :                 pg_null_as = safe_estrdup("\\\\N");
    4054           1 :                 free_pg_null = 1;
    4055             :         }
    4056             : 
    4057           1 :         spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
    4058             : 
    4059           2 :         while ((pgsql_result = PQgetResult(pgsql))) {
    4060           0 :                 PQclear(pgsql_result);
    4061             :         }
    4062           1 :         pgsql_result = PQexec(pgsql, query);
    4063           1 :         if (free_pg_null) {
    4064           1 :                 efree(pg_null_as);
    4065             :         }
    4066           1 :         efree(query);
    4067             : 
    4068           1 :         if (pgsql_result) {
    4069           1 :                 status = PQresultStatus(pgsql_result);
    4070             :         } else {
    4071           0 :                 status = (ExecStatusType) PQstatus(pgsql);
    4072             :         }
    4073             : 
    4074           1 :         switch (status) {
    4075             :                 case PGRES_COPY_OUT:
    4076           1 :                         if (pgsql_result) {
    4077           1 :                                 PQclear(pgsql_result);
    4078           1 :                                 array_init(return_value);
    4079             : #if HAVE_PQGETCOPYDATA
    4080        1005 :                                 while (!copydone)
    4081             :                                 {
    4082        1003 :                                         ret = PQgetCopyData(pgsql, &csv, 0);
    4083        1003 :                                         switch (ret) {
    4084             :                                                 case -1:
    4085           1 :                                                         copydone = 1;
    4086           1 :                                                         break;
    4087             :                                                 case 0:
    4088             :                                                 case -2:
    4089           0 :                                                         PHP_PQ_ERROR("getline failed: %s", pgsql);
    4090           0 :                                                         RETURN_FALSE;
    4091             :                                                         break;
    4092             :                                                 default:
    4093        1002 :                                                         add_next_index_string(return_value, csv, 1);
    4094        1002 :                                                         PQfreemem(csv);
    4095             :                                                         break;
    4096             :                                         }
    4097             :                                 }
    4098             : #else
    4099             :                                 while (!copydone)
    4100             :                                 {
    4101             :                                         if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) {
    4102             :                                                 PHP_PQ_ERROR("getline failed: %s", pgsql);
    4103             :                                                 RETURN_FALSE;
    4104             :                                         }
    4105             : 
    4106             :                                         if (copybuf[0] == '\\' &&
    4107             :                                                 copybuf[1] == '.' &&
    4108             :                                                 copybuf[2] == '\0')
    4109             :                                         {
    4110             :                                                 copydone = 1;
    4111             :                                         }
    4112             :                                         else
    4113             :                                         {
    4114             :                                                 if (csv == (char *)NULL) {
    4115             :                                                         csv = estrdup(copybuf);
    4116             :                                                 } else {
    4117             :                                                         csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1));
    4118             :                                                         strcat(csv, copybuf);
    4119             :                                                 }
    4120             :                                                         
    4121             :                                                 switch (ret)
    4122             :                                                 {
    4123             :                                                         case EOF:
    4124             :                                                                 copydone = 1;
    4125             :                                                         case 0:
    4126             :                                                                 add_next_index_string(return_value, csv, 1);
    4127             :                                                                 efree(csv);
    4128             :                                                                 csv = (char *)NULL;
    4129             :                                                                 break;
    4130             :                                                         case 1:
    4131             :                                                                 break;
    4132             :                                                 }
    4133             :                                         }
    4134             :                                 }
    4135             :                                 if (PQendcopy(pgsql)) {
    4136             :                                         PHP_PQ_ERROR("endcopy failed: %s", pgsql);
    4137             :                                         RETURN_FALSE;
    4138             :                                 }
    4139             : #endif
    4140           3 :                                 while ((pgsql_result = PQgetResult(pgsql))) {
    4141           1 :                                         PQclear(pgsql_result);
    4142             :                                 }
    4143             :                         } else {
    4144           0 :                                 PQclear(pgsql_result);
    4145           0 :                                 RETURN_FALSE;
    4146             :                         }
    4147           1 :                         break;
    4148             :                 default:
    4149           0 :                         PQclear(pgsql_result);
    4150           0 :                         PHP_PQ_ERROR("Copy command failed: %s", pgsql);
    4151           0 :                         RETURN_FALSE;
    4152             :                         break;
    4153             :         }
    4154             : }
    4155             : /* }}} */
    4156             : 
    4157             : /* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])
    4158             :    Copy table from array */
    4159           1 : PHP_FUNCTION(pg_copy_from)
    4160             : {
    4161           1 :         zval *pgsql_link = NULL, *pg_rows;
    4162             :         zval **tmp;
    4163           1 :         char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
    4164             :         int  table_name_len, pg_delim_len, pg_null_as_len;
    4165           1 :         int  pg_null_as_free = 0;
    4166             :         char *query;
    4167             :         HashPosition pos;
    4168           1 :         int id = -1;
    4169             :         PGconn *pgsql;
    4170             :         PGresult *pgsql_result;
    4171             :         ExecStatusType status;
    4172           1 :         int argc = ZEND_NUM_ARGS();
    4173             : 
    4174           1 :         if (zend_parse_parameters(argc TSRMLS_CC, "rsa|ss",
    4175             :                                                           &pgsql_link, &table_name, &table_name_len, &pg_rows,
    4176             :                                                           &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
    4177           0 :                 return;
    4178             :         }
    4179           1 :         if (!pg_delim) {
    4180           1 :                 pg_delim = "\t";
    4181             :         }
    4182           1 :         if (!pg_null_as) {
    4183           1 :                 pg_null_as = safe_estrdup("\\\\N");
    4184           1 :                 pg_null_as_free = 1;
    4185             :         }
    4186             : 
    4187           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4188             : 
    4189           1 :         spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
    4190           2 :         while ((pgsql_result = PQgetResult(pgsql))) {
    4191           0 :                 PQclear(pgsql_result);
    4192             :         }
    4193           1 :         pgsql_result = PQexec(pgsql, query);
    4194             : 
    4195           1 :         if (pg_null_as_free) {
    4196           1 :                 efree(pg_null_as);
    4197             :         }
    4198           1 :         efree(query);
    4199             : 
    4200           1 :         if (pgsql_result) {
    4201           1 :                 status = PQresultStatus(pgsql_result);
    4202             :         } else {
    4203           0 :                 status = (ExecStatusType) PQstatus(pgsql);
    4204             :         }
    4205             : 
    4206           1 :         switch (status) {
    4207             :                 case PGRES_COPY_IN:
    4208           1 :                         if (pgsql_result) {
    4209           1 :                                 int command_failed = 0;
    4210           1 :                                 PQclear(pgsql_result);
    4211           1 :                                 zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
    4212             : #if HAVE_PQPUTCOPYDATA
    4213        1004 :                                 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
    4214        1002 :                                         convert_to_string_ex(tmp);
    4215        1002 :                                         query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
    4216        1002 :                                         strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
    4217        1002 :                                         if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
    4218           0 :                                                 strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
    4219             :                                         }
    4220        1002 :                                         if (PQputCopyData(pgsql, query, strlen(query)) != 1) {
    4221           0 :                                                 efree(query);
    4222           0 :                                                 PHP_PQ_ERROR("copy failed: %s", pgsql);
    4223           0 :                                                 RETURN_FALSE;
    4224             :                                         }
    4225        1002 :                                         efree(query);
    4226        1002 :                                         zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
    4227             :                                 }
    4228           1 :                                 if (PQputCopyEnd(pgsql, NULL) != 1) {
    4229           0 :                                         PHP_PQ_ERROR("putcopyend failed: %s", pgsql);
    4230           0 :                                         RETURN_FALSE;
    4231             :                                 }
    4232             : #else
    4233             :                                 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
    4234             :                                         convert_to_string_ex(tmp);
    4235             :                                         query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2);
    4236             :                                         strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2);
    4237             :                                         if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') {
    4238             :                                                 strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2);
    4239             :                                         }
    4240             :                                         if (PQputline(pgsql, query)==EOF) {
    4241             :                                                 efree(query);
    4242             :                                                 PHP_PQ_ERROR("copy failed: %s", pgsql);
    4243             :                                                 RETURN_FALSE;
    4244             :                                         }
    4245             :                                         efree(query);
    4246             :                                         zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
    4247             :                                 }
    4248             :                                 if (PQputline(pgsql, "\\.\n") == EOF) {
    4249             :                                         PHP_PQ_ERROR("putline failed: %s", pgsql);
    4250             :                                         RETURN_FALSE;
    4251             :                                 }
    4252             :                                 if (PQendcopy(pgsql)) {
    4253             :                                         PHP_PQ_ERROR("endcopy failed: %s", pgsql);
    4254             :                                         RETURN_FALSE;
    4255             :                                 }
    4256             : #endif
    4257           3 :                                 while ((pgsql_result = PQgetResult(pgsql))) {
    4258           1 :                                         if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
    4259           0 :                                                 PHP_PQ_ERROR("Copy command failed: %s", pgsql);
    4260           0 :                                                 command_failed = 1;
    4261             :                                         }
    4262           1 :                                         PQclear(pgsql_result);
    4263             :                                 }
    4264           1 :                                 if (command_failed) {
    4265           0 :                                         RETURN_FALSE;
    4266             :                                 }
    4267             :                         } else {
    4268           0 :                                 PQclear(pgsql_result);
    4269           0 :                                 RETURN_FALSE;
    4270             :                         }
    4271           1 :                         RETURN_TRUE;
    4272             :                         break;
    4273             :                 default:
    4274           0 :                         PQclear(pgsql_result);
    4275           0 :                         PHP_PQ_ERROR("Copy command failed: %s", pgsql);
    4276           0 :                         RETURN_FALSE;
    4277             :                         break;
    4278             :         }
    4279             : }
    4280             : /* }}} */
    4281             : 
    4282             : #ifdef HAVE_PQESCAPE
    4283             : /* {{{ proto string pg_escape_string([resource connection,] string data)
    4284             :    Escape string for text/char type */
    4285           1 : PHP_FUNCTION(pg_escape_string)
    4286             : {
    4287           1 :         char *from = NULL, *to = NULL;
    4288             :         zval *pgsql_link;
    4289             : #ifdef HAVE_PQESCAPE_CONN
    4290             :         PGconn *pgsql;
    4291             : #endif
    4292             :         int to_len;
    4293             :         int from_len;
    4294           1 :         int id = -1;
    4295             : 
    4296           1 :         switch (ZEND_NUM_ARGS()) {
    4297             :                 case 1:
    4298           1 :                         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
    4299           0 :                                 return;
    4300             :                         }
    4301           1 :                         pgsql_link = NULL;
    4302           1 :                         id = PGG(default_link);
    4303           1 :                         break;
    4304             : 
    4305             :                 default:
    4306           0 :                         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
    4307           0 :                                 return;
    4308             :                         }
    4309             :                         break;
    4310             :         }
    4311             : 
    4312           1 :         to = (char *) safe_emalloc(from_len, 2, 1);
    4313             : #ifdef HAVE_PQESCAPE_CONN
    4314           1 :         if (pgsql_link != NULL || id != -1) {
    4315           0 :                 ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4316           0 :                 to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL);
    4317             :         } else
    4318             : #endif
    4319           1 :                 to_len = (int) PQescapeString(to, from, (size_t)from_len);
    4320             : 
    4321           1 :         RETURN_STRINGL(to, to_len, 0);
    4322             : }
    4323             : /* }}} */
    4324             : 
    4325             : /* {{{ proto string pg_escape_bytea([resource connection,] string data)
    4326             :    Escape binary for bytea type  */
    4327          13 : PHP_FUNCTION(pg_escape_bytea)
    4328             : {
    4329          13 :         char *from = NULL, *to = NULL;
    4330             :         size_t to_len;
    4331          13 :         int from_len, id = -1;
    4332             : #ifdef HAVE_PQESCAPE_BYTEA_CONN
    4333             :         PGconn *pgsql;
    4334             : #endif
    4335             :         zval *pgsql_link;
    4336             : 
    4337          13 :         switch (ZEND_NUM_ARGS()) {
    4338             :                 case 1:
    4339          13 :                         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
    4340           0 :                                 return;
    4341             :                         }
    4342          13 :                         pgsql_link = NULL;
    4343          13 :                         id = PGG(default_link);
    4344          13 :                         break;
    4345             : 
    4346             :                 default:
    4347           0 :                         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
    4348           0 :                                 return;
    4349             :                         }
    4350             :                         break;
    4351             :         }
    4352             : 
    4353             : #ifdef HAVE_PQESCAPE_BYTEA_CONN
    4354          24 :         if (pgsql_link != NULL || id != -1) {
    4355          11 :                 ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4356          11 :                 to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len);
    4357             :         } else
    4358             : #endif
    4359           2 :                 to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
    4360             : 
    4361          13 :         RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */
    4362          13 :         PQfreemem(to);
    4363             : }
    4364             : /* }}} */
    4365             : 
    4366             : #if !HAVE_PQUNESCAPEBYTEA
    4367             : /* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users.
    4368             :    Renamed to php_pgsql_unescape_bytea() */
    4369             : /*
    4370             :  *              PQunescapeBytea - converts the null terminated string representation
    4371             :  *              of a bytea, strtext, into binary, filling a buffer. It returns a
    4372             :  *              pointer to the buffer which is NULL on error, and the size of the
    4373             :  *              buffer in retbuflen. The pointer may subsequently be used as an
    4374             :  *              argument to the function free(3). It is the reverse of PQescapeBytea.
    4375             :  *
    4376             :  *              The following transformations are reversed:
    4377             :  *              '\0' == ASCII  0 == \000
    4378             :  *              '\'' == ASCII 39 == \'
    4379             :  *              '\\' == ASCII 92 == \\
    4380             :  *
    4381             :  *              States:
    4382             :  *              0       normal          0->1->2->3->4
    4383             :  *              1       \                          1->5
    4384             :  *              2       \0                         1->6
    4385             :  *              3       \00
    4386             :  *              4       \000
    4387             :  *              5       \'
    4388             :  *              6       \\
    4389             :  */
    4390             : static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen)
    4391             : {
    4392             :         size_t     buflen;
    4393             :         unsigned char *buffer,
    4394             :                            *sp,
    4395             :                            *bp;
    4396             :         unsigned int state = 0;
    4397             : 
    4398             :         if (strtext == NULL)
    4399             :                 return NULL;
    4400             :         buflen = strlen(strtext);       /* will shrink, also we discover if
    4401             :                                                                  * strtext */
    4402             :         buffer = (unsigned char *) emalloc(buflen);     /* isn't NULL terminated */
    4403             :         for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++)
    4404             :         {
    4405             :                 switch (state)
    4406             :                 {
    4407             :                         case 0:
    4408             :                                 if (*sp == '\\')
    4409             :                                         state = 1;
    4410             :                                 *bp = *sp;
    4411             :                                 break;
    4412             :                         case 1:
    4413             :                                 if (*sp == '\'')        /* state=5 */
    4414             :                                 {                               /* replace \' with 39 */
    4415             :                                         bp--;
    4416             :                                         *bp = '\'';
    4417             :                                         buflen--;
    4418             :                                         state = 0;
    4419             :                                 }
    4420             :                                 else if (*sp == '\\')   /* state=6 */
    4421             :                                 {                               /* replace \\ with 92 */
    4422             :                                         bp--;
    4423             :                                         *bp = '\\';
    4424             :                                         buflen--;
    4425             :                                         state = 0;
    4426             :                                 }
    4427             :                                 else
    4428             :                                 {
    4429             :                                         if (isdigit(*sp))
    4430             :                                                 state = 2;
    4431             :                                         else
    4432             :                                                 state = 0;
    4433             :                                         *bp = *sp;
    4434             :                                 }
    4435             :                                 break;
    4436             :                         case 2:
    4437             :                                 if (isdigit(*sp))
    4438             :                                         state = 3;
    4439             :                                 else
    4440             :                                         state = 0;
    4441             :                                 *bp = *sp;
    4442             :                                 break;
    4443             :                         case 3:
    4444             :                                 if (isdigit(*sp))               /* state=4 */
    4445             :                                 {
    4446             :                                         unsigned char *start, *end, buf[4]; /* 000 + '\0' */
    4447             :                                         
    4448             :                                         bp -= 3;
    4449             :                                         memcpy(buf, sp-2, 3);
    4450             :                                         buf[3] = '\0';
    4451             :                                         start = buf;
    4452             :                                         *bp = (unsigned char)strtoul(start, (char **)&end, 8);
    4453             :                                         buflen -= 3;
    4454             :                                         state = 0;
    4455             :                                 }
    4456             :                                 else
    4457             :                                 {
    4458             :                                         *bp = *sp;
    4459             :                                         state = 0;
    4460             :                                 }
    4461             :                                 break;
    4462             :                 }
    4463             :         }
    4464             :         buffer = erealloc(buffer, buflen+1);
    4465             :         buffer[buflen] = '\0';
    4466             : 
    4467             :         *retbuflen = buflen;
    4468             :         return buffer;
    4469             : }
    4470             : #endif
    4471             : 
    4472             : /* {{{ proto string pg_unescape_bytea(string data)
    4473             :    Unescape binary for bytea type  */
    4474           4 : PHP_FUNCTION(pg_unescape_bytea)
    4475             : {
    4476           4 :         char *from = NULL, *to = NULL, *tmp = NULL;
    4477             :         size_t to_len;
    4478             :         int from_len;
    4479           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
    4480             :                                                           &from, &from_len) == FAILURE) {
    4481           0 :                 return;
    4482             :         }
    4483             : 
    4484             : #if HAVE_PQUNESCAPEBYTEA
    4485           4 :         tmp = (char *)PQunescapeBytea((unsigned char*)from, &to_len);
    4486           4 :         to = estrndup(tmp, to_len);
    4487           4 :         PQfreemem(tmp);
    4488             : #else
    4489             :         to = (char *)php_pgsql_unescape_bytea((unsigned char*)from, &to_len);
    4490             : #endif
    4491           4 :         if (!to) {
    4492           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Invalid parameter");
    4493           0 :                 RETURN_FALSE;
    4494             :         }
    4495           4 :         RETVAL_STRINGL(to, to_len, 0);
    4496             : }
    4497             : /* }}} */
    4498             : #endif
    4499             : 
    4500             : #ifdef HAVE_PQESCAPE
    4501           2 : static void php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAMETERS, int escape_literal) {
    4502           2 :         char *from = NULL, *to = NULL;
    4503           2 :         zval *pgsql_link = NULL;
    4504             :         PGconn *pgsql;
    4505             :         int from_len;
    4506           2 :         int id = -1;
    4507             :         char *tmp;
    4508             : 
    4509           2 :         switch (ZEND_NUM_ARGS()) {
    4510             :                 case 1:
    4511           2 :                         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) {
    4512           0 :                                 return;
    4513             :                         }
    4514           2 :                         pgsql_link = NULL;
    4515           2 :                         id = PGG(default_link);
    4516           2 :                         break;
    4517             : 
    4518             :                 default:
    4519           0 :                         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) {
    4520           0 :                                 return;
    4521             :                         }
    4522             :                         break;
    4523             :         }
    4524             : 
    4525           2 :         if (pgsql_link == NULL && id == -1) {
    4526           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot get default pgsql link");
    4527           0 :                 RETURN_FALSE;
    4528             :         }
    4529             : 
    4530           2 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4531           2 :         if (pgsql == NULL) {
    4532           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot get pgsql link");
    4533           0 :                 RETURN_FALSE;
    4534             :         }
    4535             : 
    4536           2 :         if (escape_literal) {
    4537           1 :                 tmp = PGSQLescapeLiteral(pgsql, from, (size_t)from_len);
    4538             :         } else {
    4539           1 :                 tmp = PGSQLescapeIdentifier(pgsql, from, (size_t)from_len);
    4540             :         }
    4541           2 :         if (!tmp) {
    4542           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Failed to escape");
    4543           0 :                 RETURN_FALSE;
    4544             :         }
    4545           2 :         to = estrdup(tmp);
    4546           2 :         PGSQLfree(tmp);
    4547             : 
    4548           2 :         RETURN_STRING(to, 0);
    4549             : }
    4550             : 
    4551             : /* {{{ proto string pg_escape_literal([resource connection,] string data)
    4552             :    Escape parameter as string literal (i.e. parameter)  */
    4553           1 : PHP_FUNCTION(pg_escape_literal)
    4554             : {
    4555           1 :         php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
    4556           1 : }
    4557             : /* }}} */
    4558             : 
    4559             : /* {{{ proto string pg_escape_identifier([resource connection,] string data)
    4560             :    Escape identifier (i.e. table name, field name)      */
    4561           1 : PHP_FUNCTION(pg_escape_identifier)
    4562             : {
    4563           1 :         php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
    4564           1 : }
    4565             : /* }}} */
    4566             : #endif
    4567             : 
    4568             : 
    4569             : /* {{{ proto string pg_result_error(resource result)
    4570             :    Get error message associated with result */
    4571           5 : PHP_FUNCTION(pg_result_error)
    4572             : {
    4573             :         zval *result;
    4574             :         PGresult *pgsql_result;
    4575             :         pgsql_result_handle *pg_result;
    4576           5 :         char *err = NULL;
    4577             : 
    4578           5 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
    4579             :                                                                  &result) == FAILURE) {
    4580           0 :                 RETURN_FALSE;
    4581             :         }
    4582             :         
    4583           5 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    4584             : 
    4585           5 :         pgsql_result = pg_result->result;
    4586           5 :         if (!pgsql_result) {
    4587           0 :                 RETURN_FALSE;
    4588             :         }
    4589           5 :         err = (char *)PQresultErrorMessage(pgsql_result);
    4590           5 :         RETURN_STRING(err,1);
    4591             : }
    4592             : /* }}} */
    4593             : 
    4594             : 
    4595             : #if HAVE_PQRESULTERRORFIELD
    4596             : /* {{{ proto string pg_result_error_field(resource result, int fieldcode)
    4597             :    Get error message field associated with result */
    4598          12 : PHP_FUNCTION(pg_result_error_field)
    4599             : {
    4600             :         zval *result;
    4601             :         long fieldcode;
    4602             :         PGresult *pgsql_result;
    4603             :         pgsql_result_handle *pg_result;
    4604          12 :         char *field = NULL;
    4605             : 
    4606          12 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rl",
    4607             :                                                                  &result, &fieldcode) == FAILURE) {
    4608           0 :                 RETURN_FALSE;
    4609             :         }
    4610             :         
    4611          12 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    4612             : 
    4613          12 :         pgsql_result = pg_result->result;
    4614          12 :         if (!pgsql_result) {
    4615           0 :                 RETURN_FALSE;
    4616             :         }
    4617          12 :         if (fieldcode & (PG_DIAG_SEVERITY|PG_DIAG_SQLSTATE|PG_DIAG_MESSAGE_PRIMARY|PG_DIAG_MESSAGE_DETAIL
    4618             :                                 |PG_DIAG_MESSAGE_HINT|PG_DIAG_STATEMENT_POSITION
    4619             : #if PG_DIAG_INTERNAL_POSITION
    4620             :                                 |PG_DIAG_INTERNAL_POSITION
    4621             : #endif
    4622             : #if PG_DIAG_INTERNAL_QUERY
    4623             :                                 |PG_DIAG_INTERNAL_QUERY
    4624             : #endif
    4625             :                                 |PG_DIAG_CONTEXT|PG_DIAG_SOURCE_FILE|PG_DIAG_SOURCE_LINE
    4626             :                                 |PG_DIAG_SOURCE_FUNCTION)) {
    4627          12 :                 field = (char *)PQresultErrorField(pgsql_result, fieldcode);
    4628          12 :                 if (field == NULL) {
    4629          12 :                         RETURN_NULL();
    4630             :                 } else {
    4631           0 :                         RETURN_STRING(field, 1);
    4632             :                 }
    4633             :         } else {
    4634           0 :                 RETURN_FALSE;
    4635             :         }
    4636             : }
    4637             : /* }}} */
    4638             : #endif
    4639             : 
    4640             : 
    4641             : /* {{{ proto int pg_connection_status(resource connection)
    4642             :    Get connection status */
    4643           9 : PHP_FUNCTION(pg_connection_status)
    4644             : {
    4645           9 :         zval *pgsql_link = NULL;
    4646           9 :         int id = -1;
    4647             :         PGconn *pgsql;
    4648             : 
    4649           9 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
    4650             :                                                                  &pgsql_link) == FAILURE) {
    4651           0 :                 RETURN_FALSE;
    4652             :         }
    4653             : 
    4654           9 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4655             : 
    4656           9 :         RETURN_LONG(PQstatus(pgsql));
    4657             : }
    4658             : 
    4659             : /* }}} */
    4660             : 
    4661             : 
    4662             : #if HAVE_PGTRANSACTIONSTATUS
    4663             : /* {{{ proto int pg_transaction_status(resource connection)
    4664             :    Get transaction status */
    4665           1 : PHP_FUNCTION(pg_transaction_status)
    4666             : {
    4667           1 :         zval *pgsql_link = NULL;
    4668           1 :         int id = -1;
    4669             :         PGconn *pgsql;
    4670             : 
    4671           1 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
    4672             :                                                                  &pgsql_link) == FAILURE) {
    4673           0 :                 RETURN_FALSE;
    4674             :         }
    4675             : 
    4676           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4677             : 
    4678           1 :         RETURN_LONG(PQtransactionStatus(pgsql));
    4679             : }
    4680             : #endif
    4681             : 
    4682             : /* }}} */
    4683             : 
    4684             : 
    4685             : /* {{{ proto bool pg_connection_reset(resource connection)
    4686             :    Reset connection (reconnect) */
    4687           1 : PHP_FUNCTION(pg_connection_reset)
    4688             : {
    4689             :         zval *pgsql_link;
    4690           1 :         int id = -1;
    4691             :         PGconn *pgsql;
    4692             :         
    4693           1 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
    4694             :                                                                  &pgsql_link) == FAILURE) {
    4695           0 :                 RETURN_FALSE;
    4696             :         }
    4697             : 
    4698           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4699             :         
    4700           1 :         PQreset(pgsql);
    4701           1 :         if (PQstatus(pgsql) == CONNECTION_BAD) {
    4702           0 :                 RETURN_FALSE;
    4703             :         }
    4704           1 :         RETURN_TRUE;
    4705             : }
    4706             : /* }}} */
    4707             : 
    4708             : 
    4709             : #define PHP_PG_ASYNC_IS_BUSY            1
    4710             : #define PHP_PG_ASYNC_REQUEST_CANCEL 2
    4711             : 
    4712             : 
    4713             : /* {{{ php_pgsql_flush_query
    4714             :  */
    4715          49 : static int php_pgsql_flush_query(PGconn *pgsql TSRMLS_DC) 
    4716             : {
    4717             :         PGresult *res;
    4718          49 :         int leftover = 0;
    4719             :         
    4720          49 :         if (PQ_SETNONBLOCKING(pgsql, 1)) {
    4721           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to nonblocking mode");
    4722           0 :                 return -1;
    4723             :         }
    4724          98 :         while ((res = PQgetResult(pgsql))) {
    4725           0 :                 PQclear(res);
    4726           0 :                 leftover++;
    4727             :         }
    4728          49 :         PQ_SETNONBLOCKING(pgsql, 0);
    4729          49 :         return leftover;
    4730             : }
    4731             : /* }}} */
    4732             : 
    4733             : 
    4734             : /* {{{ php_pgsql_do_async
    4735             :  */
    4736          42 : static void php_pgsql_do_async(INTERNAL_FUNCTION_PARAMETERS, int entry_type) 
    4737             : {
    4738             :         zval *pgsql_link;
    4739          42 :         int id = -1;
    4740             :         PGconn *pgsql;
    4741             :         PGresult *pgsql_result;
    4742             : 
    4743          42 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
    4744             :                                                                  &pgsql_link) == FAILURE) {
    4745           0 :                 RETURN_FALSE;
    4746             :         }
    4747             : 
    4748          42 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4749             : 
    4750          42 :         if (PQ_SETNONBLOCKING(pgsql, 1)) {
    4751           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
    4752           0 :                 RETURN_FALSE;
    4753             :         }
    4754          42 :         switch(entry_type) {
    4755             :                 case PHP_PG_ASYNC_IS_BUSY:
    4756          42 :                         PQconsumeInput(pgsql);
    4757          42 :                         Z_LVAL_P(return_value) = PQisBusy(pgsql);
    4758          42 :                         Z_TYPE_P(return_value) = IS_LONG;
    4759          42 :                         break;
    4760             :                 case PHP_PG_ASYNC_REQUEST_CANCEL:
    4761           0 :                         Z_LVAL_P(return_value) = PQrequestCancel(pgsql);
    4762           0 :                         Z_TYPE_P(return_value) = IS_LONG;
    4763           0 :                         while ((pgsql_result = PQgetResult(pgsql))) {
    4764           0 :                                 PQclear(pgsql_result);
    4765             :                         }
    4766           0 :                         break;
    4767             :                 default:
    4768           0 :                         php_error_docref(NULL TSRMLS_CC, E_ERROR, "PostgreSQL module error, please report this error");
    4769             :                         break;
    4770             :         }
    4771          42 :         if (PQ_SETNONBLOCKING(pgsql, 0)) {
    4772           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
    4773             :         }
    4774         168 :         convert_to_boolean_ex(&return_value);
    4775             : }
    4776             : /* }}} */
    4777             : 
    4778             : /* {{{ proto bool pg_cancel_query(resource connection)
    4779             :    Cancel request */
    4780           0 : PHP_FUNCTION(pg_cancel_query)
    4781             : {
    4782           0 :         php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_REQUEST_CANCEL);
    4783           0 : }
    4784             : /* }}} */
    4785             : 
    4786             : /* {{{ proto bool pg_connection_busy(resource connection)
    4787             :    Get connection is busy or not */
    4788          42 : PHP_FUNCTION(pg_connection_busy)
    4789             : {
    4790          42 :         php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_IS_BUSY);
    4791          42 : }
    4792             : /* }}} */
    4793             : 
    4794          16 : static int _php_pgsql_link_has_results(PGconn *pgsql)
    4795             : {
    4796             :         PGresult *result;
    4797          32 :         while ((result = PQgetResult(pgsql))) {
    4798           0 :                 PQclear(result);
    4799           0 :                 return 1;
    4800             :         }
    4801          16 :         return 0;
    4802             : }
    4803             : 
    4804             : /* {{{ proto bool pg_send_query(resource connection, string query)
    4805             :    Send asynchronous query */
    4806           4 : PHP_FUNCTION(pg_send_query)
    4807             : {
    4808             :         zval *pgsql_link;
    4809             :         char *query;
    4810             :         int len;
    4811           4 :         int id = -1;
    4812             :         PGconn *pgsql;
    4813             :         int is_non_blocking;
    4814             :         int ret;
    4815             : 
    4816           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &len) == FAILURE) {
    4817           0 :                 return;
    4818             :         }
    4819             : 
    4820           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4821             : 
    4822           4 :         is_non_blocking = PQisnonblocking(pgsql);
    4823             : 
    4824           4 :         if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
    4825           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
    4826           0 :                 RETURN_FALSE;
    4827             :         }
    4828             : 
    4829           4 :         if (_php_pgsql_link_has_results(pgsql)) {
    4830           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,
    4831             :                         "There are results on this connection. Call pg_get_result() until it returns FALSE");
    4832             :         }
    4833             : 
    4834           4 :         if (is_non_blocking) {
    4835           0 :                 if (!PQsendQuery(pgsql, query)) {
    4836           0 :                         RETURN_FALSE;
    4837             :                 }
    4838           0 :                 ret = PQflush(pgsql);
    4839             :         } else {
    4840           4 :                 if (!PQsendQuery(pgsql, query)) {
    4841           0 :                         if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    4842           0 :                                 PQreset(pgsql);
    4843             :                         }
    4844           0 :                         if (!PQsendQuery(pgsql, query)) {
    4845           0 :                                 RETURN_FALSE;
    4846             :                         }
    4847             :                 }
    4848             : 
    4849             :                 /* Wait to finish sending buffer */
    4850           8 :                 while ((ret = PQflush(pgsql))) {
    4851           0 :                         if (ret == -1) {
    4852           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Could not empty PostgreSQL send buffer");
    4853           0 :                                 break;
    4854             :                         }
    4855           0 :                         usleep(10000);
    4856             :                 }
    4857             : 
    4858           4 :                 if (PQ_SETNONBLOCKING(pgsql, 0)) {
    4859           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
    4860             :                 }
    4861             :         }
    4862             : 
    4863           4 :         if (ret == 0) {
    4864           4 :                 RETURN_TRUE;
    4865           0 :         } else if (ret == -1) {
    4866           0 :                 RETURN_FALSE;
    4867             :         } else {
    4868           0 :                 RETURN_LONG(0);
    4869             :         }
    4870             : }
    4871             : /* }}} */
    4872             : 
    4873             : #if HAVE_PQSENDQUERYPARAMS
    4874             : /* {{{ proto bool pg_send_query_params(resource connection, string query, array params)
    4875             :    Send asynchronous parameterized query */
    4876           4 : PHP_FUNCTION(pg_send_query_params)
    4877             : {
    4878             :         zval *pgsql_link, *pv_param_arr, **tmp;
    4879           4 :         int num_params = 0;
    4880           4 :         char **params = NULL;
    4881             :         char *query;
    4882           4 :         int query_len, id = -1;
    4883             :         PGconn *pgsql;
    4884             :         int is_non_blocking;
    4885             :         int ret;
    4886             : 
    4887           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsa/", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
    4888           0 :                 return;
    4889             :         }
    4890             : 
    4891           4 :         if (pgsql_link == NULL && id == -1) {
    4892           0 :                 RETURN_FALSE;
    4893             :         }
    4894             : 
    4895           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    4896             : 
    4897           4 :         is_non_blocking = PQisnonblocking(pgsql);
    4898             : 
    4899           4 :         if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
    4900           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
    4901           0 :                 RETURN_FALSE;
    4902             :         }
    4903             : 
    4904           4 :         if (_php_pgsql_link_has_results(pgsql)) {
    4905           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,
    4906             :                         "There are results on this connection. Call pg_get_result() until it returns FALSE");
    4907             :         }
    4908             : 
    4909           4 :         zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
    4910           4 :         num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
    4911           4 :         if (num_params > 0) {
    4912           4 :                 int i = 0;
    4913           4 :                 params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
    4914             :                 
    4915          10 :                 for(i = 0; i < num_params; i++) {
    4916           6 :                         if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
    4917           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
    4918           0 :                                 _php_pgsql_free_params(params, num_params);
    4919           0 :                                 RETURN_FALSE;
    4920             :                         }
    4921             : 
    4922           6 :                         if (Z_TYPE_PP(tmp) == IS_NULL) {
    4923           0 :                                 params[i] = NULL;
    4924             :                         } else {
    4925           6 :                                 zval tmp_val = **tmp;
    4926             :                                 zval_copy_ctor(&tmp_val);
    4927           6 :                                 convert_to_string(&tmp_val);
    4928           6 :                                 if (Z_TYPE(tmp_val) != IS_STRING) {
    4929           0 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
    4930             :                                         zval_dtor(&tmp_val);
    4931           0 :                                         _php_pgsql_free_params(params, num_params);
    4932           0 :                                         RETURN_FALSE;
    4933             :                                 }
    4934           6 :                                 params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
    4935             :                                 zval_dtor(&tmp_val);
    4936             :                         }
    4937             : 
    4938           6 :                         zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
    4939             :                 }
    4940             :         }
    4941             : 
    4942           4 :         if (PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) {
    4943           4 :                 _php_pgsql_free_params(params, num_params);
    4944           0 :         } else if (is_non_blocking) {
    4945           0 :                 _php_pgsql_free_params(params, num_params);
    4946           0 :                 RETURN_FALSE;
    4947             :         } else {
    4948           0 :                 if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    4949           0 :                         PQreset(pgsql);
    4950             :                 }
    4951           0 :                 if (!PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) {
    4952           0 :                         _php_pgsql_free_params(params, num_params);
    4953           0 :                         RETURN_FALSE;
    4954             :                 }
    4955             :         }
    4956             : 
    4957           4 :         if (is_non_blocking) {
    4958           0 :                 ret = PQflush(pgsql);
    4959             :         } else {
    4960             :                 /* Wait to finish sending buffer */
    4961           8 :                 while ((ret = PQflush(pgsql))) {
    4962           0 :                         if (ret == -1) {
    4963           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Could not empty PostgreSQL send buffer");
    4964           0 :                                 break;
    4965             :                         }
    4966           0 :                         usleep(10000);
    4967             :                 }
    4968             : 
    4969           4 :                 if (PQ_SETNONBLOCKING(pgsql, 0) != 0) {
    4970           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
    4971             :                 }
    4972             :         }
    4973             : 
    4974           4 :         if (ret == 0) {
    4975           4 :                 RETURN_TRUE;
    4976           0 :         } else if (ret == -1) {
    4977           0 :                 RETURN_FALSE;
    4978             :         } else {
    4979           0 :                 RETURN_LONG(0);
    4980             :         }
    4981             : }
    4982             : /* }}} */
    4983             : #endif
    4984             : 
    4985             : #if HAVE_PQSENDPREPARE
    4986             : /* {{{ proto bool pg_send_prepare(resource connection, string stmtname, string query)
    4987             :    Asynchronously prepare a query for future execution */
    4988           4 : PHP_FUNCTION(pg_send_prepare)
    4989             : {
    4990             :         zval *pgsql_link;
    4991             :         char *query, *stmtname;
    4992           4 :         int stmtname_len, query_len, id = -1;
    4993             :         PGconn *pgsql;
    4994             :         int is_non_blocking;
    4995             :         int ret;
    4996             : 
    4997           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
    4998           0 :                 return;
    4999             :         }
    5000             : 
    5001           4 :         if (pgsql_link == NULL && id == -1) {
    5002           0 :                 RETURN_FALSE;
    5003             :         }
    5004             : 
    5005           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5006             : 
    5007           4 :         is_non_blocking = PQisnonblocking(pgsql);
    5008             : 
    5009           4 :         if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
    5010           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
    5011           0 :                 RETURN_FALSE;
    5012             :         }
    5013             : 
    5014           4 :         if (_php_pgsql_link_has_results(pgsql)) {
    5015           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,
    5016             :                         "There are results on this connection. Call pg_get_result() until it returns FALSE");
    5017             :         }
    5018             : 
    5019           4 :         if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) {
    5020           0 :                 if (is_non_blocking) {
    5021           0 :                         RETURN_FALSE;
    5022             :                 } else {
    5023           0 :                         if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    5024           0 :                                 PQreset(pgsql);
    5025             :                         }
    5026           0 :                         if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) {
    5027           0 :                                 RETURN_FALSE;
    5028             :                         }
    5029             :                 }
    5030             :         }
    5031             : 
    5032           4 :         if (is_non_blocking) {
    5033           0 :                 ret = PQflush(pgsql);
    5034             :         } else {
    5035             :                 /* Wait to finish sending buffer */
    5036           8 :                 while ((ret = PQflush(pgsql))) {
    5037           0 :                         if (ret == -1) {
    5038           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Could not empty PostgreSQL send buffer");
    5039           0 :                                 break;
    5040             :                         }
    5041           0 :                         usleep(10000);
    5042             :                 }
    5043           4 :                 if (PQ_SETNONBLOCKING(pgsql, 0) != 0) {
    5044           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
    5045             :                 }
    5046             :         }
    5047             : 
    5048           4 :         if (ret == 0) {
    5049           4 :                 RETURN_TRUE;
    5050           0 :         } else if (ret == -1) {
    5051           0 :                 RETURN_FALSE;
    5052             :         } else {
    5053           0 :                 RETURN_LONG(0);
    5054             :         }
    5055             : }
    5056             : /* }}} */
    5057             : #endif
    5058             : 
    5059             : #if HAVE_PQSENDQUERYPREPARED
    5060             : /* {{{ proto bool pg_send_execute(resource connection, string stmtname, array params)
    5061             :    Executes prevriously prepared stmtname asynchronously */
    5062           4 : PHP_FUNCTION(pg_send_execute)
    5063             : {
    5064             :         zval *pgsql_link;
    5065             :         zval *pv_param_arr, **tmp;
    5066           4 :         int num_params = 0;
    5067           4 :         char **params = NULL;
    5068             :         char *stmtname;
    5069           4 :         int stmtname_len, id = -1;
    5070             :         PGconn *pgsql;
    5071             :         int is_non_blocking;
    5072             :         int ret;
    5073             : 
    5074           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsa", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
    5075           0 :                 return;
    5076             :         }
    5077             : 
    5078           4 :         if (pgsql_link == NULL && id == -1) {
    5079           0 :                 RETURN_FALSE;
    5080             :         }
    5081             : 
    5082           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5083             : 
    5084           4 :         is_non_blocking = PQisnonblocking(pgsql);
    5085             : 
    5086           4 :         if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
    5087           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
    5088           0 :                 RETURN_FALSE;
    5089             :         }
    5090             : 
    5091           4 :         if (_php_pgsql_link_has_results(pgsql)) {
    5092           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE,
    5093             :                         "There are results on this connection. Call pg_get_result() until it returns FALSE");
    5094             :         }
    5095             : 
    5096           4 :         zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
    5097           4 :         num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
    5098           4 :         if (num_params > 0) {
    5099           4 :                 int i = 0;
    5100           4 :                 params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
    5101             : 
    5102          10 :                 for (i = 0; i < num_params; i++) {
    5103           6 :                         if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) {
    5104           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
    5105           0 :                                 _php_pgsql_free_params(params, num_params);
    5106           0 :                                 RETURN_FALSE;
    5107             :                         }
    5108             : 
    5109           6 :                         if (Z_TYPE_PP(tmp) == IS_NULL) {
    5110           0 :                                 params[i] = NULL;
    5111             :                         } else {
    5112           6 :                                 zval tmp_val = **tmp;
    5113             :                                 zval_copy_ctor(&tmp_val);
    5114           6 :                                 convert_to_string(&tmp_val);
    5115           6 :                                 if (Z_TYPE(tmp_val) != IS_STRING) {
    5116           0 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
    5117             :                                         zval_dtor(&tmp_val);
    5118           0 :                                         _php_pgsql_free_params(params, num_params);
    5119           0 :                                         RETURN_FALSE;
    5120             :                                 }
    5121           6 :                                 params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
    5122             :                                 zval_dtor(&tmp_val);
    5123             :                         }
    5124             : 
    5125           6 :                         zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
    5126             :                 }
    5127             :         }
    5128             : 
    5129           4 :         if (PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) {
    5130           4 :                 _php_pgsql_free_params(params, num_params);
    5131           0 :         } else if (is_non_blocking) {
    5132           0 :                 _php_pgsql_free_params(params, num_params);
    5133           0 :                 RETURN_FALSE;
    5134             :         } else {
    5135           0 :                 if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
    5136           0 :                         PQreset(pgsql);
    5137             :                 }
    5138           0 :                 if (!PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) {
    5139           0 :                         _php_pgsql_free_params(params, num_params);
    5140           0 :                         RETURN_FALSE;
    5141             :                 }
    5142             :         }
    5143             : 
    5144           4 :         if (is_non_blocking) {
    5145           0 :                 ret = PQflush(pgsql);
    5146             :         } else {
    5147             :                 /* Wait to finish sending buffer */
    5148           8 :                 while ((ret = PQflush(pgsql))) {
    5149           0 :                         if (ret == -1) {
    5150           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Could not empty PostgreSQL send buffer");
    5151           0 :                                 break;
    5152             :                         }
    5153           0 :                         usleep(10000);
    5154             :                 }
    5155           4 :                 if (PQ_SETNONBLOCKING(pgsql, 0) != 0) {
    5156           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
    5157             :                 }
    5158             :         }
    5159             : 
    5160           4 :         if (ret == 0) {
    5161           4 :                 RETURN_TRUE;
    5162           0 :         } else if (ret == -1) {
    5163           0 :                 RETURN_FALSE;
    5164             :         } else {
    5165           0 :                 RETURN_LONG(0);
    5166             :         }
    5167             : }
    5168             : /* }}} */
    5169             : #endif
    5170             : 
    5171             : /* {{{ proto resource pg_get_result(resource connection)
    5172             :    Get asynchronous query result */
    5173          13 : PHP_FUNCTION(pg_get_result)
    5174             : {
    5175             :         zval *pgsql_link;
    5176          13 :         int id = -1;
    5177             :         PGconn *pgsql;
    5178             :         PGresult *pgsql_result;
    5179             :         pgsql_result_handle *pg_result;
    5180             : 
    5181          13 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
    5182           0 :                 RETURN_FALSE;
    5183             :         }
    5184             : 
    5185          13 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5186             :         
    5187          13 :         pgsql_result = PQgetResult(pgsql);
    5188          13 :         if (!pgsql_result) {
    5189             :                 /* no result */
    5190           0 :                 RETURN_FALSE;
    5191             :         }
    5192          13 :         pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
    5193          13 :         pg_result->conn = pgsql;
    5194          13 :         pg_result->result = pgsql_result;
    5195          13 :         pg_result->row = 0;
    5196          13 :         ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
    5197             : }
    5198             : /* }}} */
    5199             : 
    5200             : /* {{{ proto mixed pg_result_status(resource result[, long result_type])
    5201             :    Get status of query result */
    5202           2 : PHP_FUNCTION(pg_result_status)
    5203             : {
    5204             :         zval *result;
    5205           2 :         long result_type = PGSQL_STATUS_LONG;
    5206             :         ExecStatusType status;
    5207             :         PGresult *pgsql_result;
    5208             :         pgsql_result_handle *pg_result;
    5209             : 
    5210           2 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l",
    5211             :                                                                  &result, &result_type) == FAILURE) {
    5212           0 :                 RETURN_FALSE;
    5213             :         }
    5214             : 
    5215           2 :         ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
    5216             : 
    5217           2 :         pgsql_result = pg_result->result;
    5218           2 :         if (result_type == PGSQL_STATUS_LONG) {
    5219           1 :                 status = PQresultStatus(pgsql_result);
    5220           1 :                 RETURN_LONG((int)status);
    5221             :         }
    5222           1 :         else if (result_type == PGSQL_STATUS_STRING) {
    5223           1 :                 RETURN_STRING(PQcmdStatus(pgsql_result), 1);
    5224             :         }
    5225             :         else {
    5226           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Optional 2nd parameter should be PGSQL_STATUS_LONG or PGSQL_STATUS_STRING");
    5227           0 :                 RETURN_FALSE;
    5228             :         }
    5229             : }
    5230             : /* }}} */
    5231             : 
    5232             : 
    5233             : /* {{{ proto array pg_get_notify([resource connection[, result_type]])
    5234             :    Get asynchronous notification */
    5235           1 : PHP_FUNCTION(pg_get_notify)
    5236             : {
    5237             :         zval *pgsql_link;
    5238           1 :         int id = -1;
    5239           1 :         long result_type = PGSQL_ASSOC;
    5240             :         PGconn *pgsql;
    5241             :         PGnotify *pgsql_notify;
    5242             : 
    5243           1 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l",
    5244             :                                                                  &pgsql_link, &result_type) == FAILURE) {
    5245           0 :                 RETURN_FALSE;
    5246             :         }
    5247             : 
    5248           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5249             : 
    5250           1 :         if (!(result_type & PGSQL_BOTH)) {
    5251           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
    5252           0 :                 RETURN_FALSE;
    5253             :         }
    5254             : 
    5255           1 :         PQconsumeInput(pgsql);
    5256           1 :         pgsql_notify = PQnotifies(pgsql);
    5257           1 :         if (!pgsql_notify) {
    5258             :                 /* no notify message */
    5259           0 :                 RETURN_FALSE;
    5260             :         }
    5261           1 :         array_init(return_value);
    5262           1 :         if (result_type & PGSQL_NUM) {
    5263           0 :                 add_index_string(return_value, 0, pgsql_notify->relname, 1);
    5264           0 :                 add_index_long(return_value, 1, pgsql_notify->be_pid);
    5265             : #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS 
    5266           0 :                 if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
    5267             : #else 
    5268             :                 if (atof(PG_VERSION) >= 9.0) {
    5269             : #endif 
    5270             : #if HAVE_PQPARAMETERSTATUS
    5271           0 :                         add_index_string(return_value, 2, pgsql_notify->extra, 1);
    5272             : #endif
    5273             :                 }
    5274             :         }
    5275           1 :         if (result_type & PGSQL_ASSOC) {
    5276           1 :                 add_assoc_string(return_value, "message", pgsql_notify->relname, 1);
    5277           1 :                 add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
    5278             : #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS 
    5279           1 :                 if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
    5280             : #else 
    5281             :                 if (atof(PG_VERSION) >= 9.0) {
    5282             : #endif 
    5283             : #if HAVE_PQPARAMETERSTATUS
    5284           0 :                         add_assoc_string(return_value, "payload", pgsql_notify->extra, 1);
    5285             : #endif
    5286             :                 }
    5287             :         }
    5288           1 :         PQfreemem(pgsql_notify);
    5289             : }
    5290             : /* }}} */
    5291             : 
    5292             : /* {{{ proto int pg_get_pid([resource connection)
    5293             :    Get backend(server) pid */
    5294           1 : PHP_FUNCTION(pg_get_pid)
    5295             : {
    5296             :         zval *pgsql_link;
    5297           1 :         int id = -1;
    5298             :         PGconn *pgsql;
    5299             : 
    5300           1 :         if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
    5301             :                                                                  &pgsql_link) == FAILURE) {
    5302           0 :                 RETURN_FALSE;
    5303             :         }
    5304             : 
    5305           1 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5306             : 
    5307           1 :         RETURN_LONG(PQbackendPID(pgsql));
    5308             : }
    5309             : /* }}} */
    5310             : 
    5311           0 : static size_t php_pgsql_fd_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
    5312             : {
    5313           0 :         return 0;
    5314             : }
    5315             : 
    5316           0 : static size_t php_pgsql_fd_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
    5317             : {
    5318           0 :         return 0;
    5319             : }
    5320             : 
    5321           4 : static int php_pgsql_fd_close(php_stream *stream, int close_handle TSRMLS_DC)
    5322             : {
    5323           4 :         return EOF;
    5324             : }
    5325             : 
    5326           4 : static int php_pgsql_fd_flush(php_stream *stream TSRMLS_DC)
    5327             : {
    5328           4 :         return FAILURE;
    5329             : }
    5330             : 
    5331           4 : static int php_pgsql_fd_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC)
    5332             : {
    5333           4 :         PGconn *pgsql = (PGconn *) stream->abstract;
    5334           4 :         switch (option) {
    5335             :                 case PHP_STREAM_OPTION_BLOCKING:
    5336           4 :                         return PQ_SETNONBLOCKING(pgsql, value);
    5337             :                 default:
    5338           0 :                         return FAILURE;
    5339             :         }
    5340             : }
    5341             : 
    5342          22 : static int php_pgsql_fd_cast(php_stream *stream, int cast_as, void **ret TSRMLS_DC)
    5343             : {
    5344          22 :         PGconn *pgsql = (PGconn *) stream->abstract;
    5345             :         int fd_number;
    5346             : 
    5347          22 :         switch (cast_as)        {
    5348             :                 case PHP_STREAM_AS_FD_FOR_SELECT:
    5349             :                 case PHP_STREAM_AS_FD:
    5350             :                 case PHP_STREAM_AS_SOCKETD:
    5351          22 :                         if (ret) {
    5352          22 :                                 fd_number = PQsocket(pgsql);
    5353          22 :                                 if (fd_number == -1) {
    5354           0 :                                         return FAILURE;
    5355             :                                 }
    5356             : 
    5357          22 :                                 *(php_socket_t *)ret = fd_number;
    5358          22 :                                 return SUCCESS;
    5359             :                         }
    5360             :                 default:
    5361           0 :                         return FAILURE;
    5362             :         }
    5363             : }
    5364             : 
    5365             : /* {{{ proto resource pg_socket(resource)
    5366             :    Get a read-only handle to the socket underlying the pgsql connection */
    5367           4 : PHP_FUNCTION(pg_socket)
    5368             : {
    5369             :         zval *pgsql_link;
    5370             :         php_stream *stream;
    5371             :         PGconn *pgsql;
    5372           4 :         int id = -1;
    5373             : 
    5374           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
    5375           0 :                 return;
    5376             :         }
    5377             : 
    5378           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5379             : 
    5380           4 :         stream = php_stream_alloc(&php_stream_pgsql_fd_ops, pgsql, NULL, "r");
    5381             : 
    5382           4 :         if (stream) {
    5383           4 :                 php_stream_to_zval(stream, return_value);
    5384           4 :                 return;
    5385             :         }
    5386             : 
    5387           0 :         RETURN_FALSE;
    5388             : }
    5389             : /* }}} */
    5390             : 
    5391             : /* {{{ proto bool pg_consume_input(resource)
    5392             :    Reads input on the connection */
    5393          10 : PHP_FUNCTION(pg_consume_input)
    5394             : {
    5395             :         zval *pgsql_link;
    5396          10 :         int id = -1;
    5397             :         PGconn *pgsql;
    5398             : 
    5399          10 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
    5400           0 :                 return;
    5401             :         }
    5402             : 
    5403          10 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5404             : 
    5405          10 :         RETURN_BOOL(PQconsumeInput(pgsql));
    5406             : }
    5407             : /* }}} */
    5408             : 
    5409             : /* {{{ proto mixed pg_flush(resource)
    5410             :    Flush outbound query data on the connection */
    5411           0 : PHP_FUNCTION(pg_flush)
    5412             : {
    5413             :         zval *pgsql_link;
    5414           0 :         int id = -1;
    5415             :         PGconn *pgsql;
    5416             :         int ret;
    5417             :         int is_non_blocking;
    5418             : 
    5419           0 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
    5420           0 :                 return;
    5421             :         }
    5422             : 
    5423           0 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5424             : 
    5425           0 :         is_non_blocking = PQisnonblocking(pgsql);
    5426             : 
    5427           0 :         if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
    5428           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
    5429           0 :                 RETURN_FALSE;
    5430             :         }
    5431             : 
    5432           0 :         ret = PQflush(pgsql);
    5433             : 
    5434           0 :         if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 0) == -1) {
    5435           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed resetting connection to blocking mode");
    5436             :         }
    5437             : 
    5438           0 :         switch (ret) {
    5439           0 :                 case 0: RETURN_TRUE; break;
    5440           0 :                 case 1: RETURN_LONG(0); break;
    5441           0 :                 default: RETURN_FALSE;
    5442             :         }
    5443             : }
    5444             : /* }}} */
    5445             : 
    5446             : /* {{{ php_pgsql_meta_data
    5447             :  * TODO: Add meta_data cache for better performance
    5448             :  */
    5449          58 : PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta, zend_bool extended TSRMLS_DC)
    5450             : {
    5451             :         PGresult *pg_result;
    5452          58 :         char *src, *tmp_name, *tmp_name2 = NULL;
    5453             :         char *escaped;
    5454          58 :         smart_str querystr = {0};
    5455             :         size_t new_len;
    5456             :         int i, num_rows;
    5457             :         zval *elem;
    5458             : 
    5459          58 :         if (!*table_name) {
    5460           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified");
    5461           0 :                 return FAILURE;
    5462             :         }
    5463             : 
    5464          58 :         src = estrdup(table_name);
    5465          58 :         tmp_name = php_strtok_r(src, ".", &tmp_name2);
    5466             :         
    5467          58 :         if (!tmp_name2 || !*tmp_name2) {
    5468             :                 /* Default schema */
    5469          38 :                 tmp_name2 = tmp_name;
    5470          38 :                 tmp_name = "public";
    5471             :         }
    5472             : 
    5473          58 :         if (extended) {
    5474           1 :                 smart_str_appends(&querystr,
    5475             :                                                   "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims, t.typtype, "
    5476             :                                                   "d.description "
    5477             :                                                   "FROM pg_class as c "
    5478             :                                                   " JOIN pg_attribute a ON (a.attrelid = c.oid) "
    5479             :                                                   " JOIN pg_type t ON (a.atttypid = t.oid) "
    5480             :                                                   " JOIN pg_namespace n ON (c.relnamespace = n.oid) "
    5481             :                                                   " LEFT JOIN pg_description d ON (d.objoid=a.attrelid AND d.objsubid=a.attnum AND c.oid=d.objoid) "
    5482             :                                                   "WHERE a.attnum > 0  AND c.relname = '");
    5483             :         } else {
    5484          57 :                 smart_str_appends(&querystr,
    5485             :                                                   "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype "
    5486             :                                                   "FROM pg_class as c "
    5487             :                                                   " JOIN pg_attribute a ON (a.attrelid = c.oid) "
    5488             :                                                   " JOIN pg_type t ON (a.atttypid = t.oid) "
    5489             :                                                   " JOIN pg_namespace n ON (c.relnamespace = n.oid) "
    5490             :                                                   "WHERE a.attnum > 0 AND c.relname = '");
    5491             :         }
    5492          58 :         escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1);
    5493          58 :         new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL);
    5494          58 :         if (new_len) {
    5495          58 :                 smart_str_appendl(&querystr, escaped, new_len);
    5496             :         }
    5497          58 :         efree(escaped);
    5498             : 
    5499          58 :         smart_str_appends(&querystr, "' AND n.nspname = '");
    5500          58 :         escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1);
    5501          58 :         new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL);
    5502          58 :         if (new_len) {
    5503          58 :                 smart_str_appendl(&querystr, escaped, new_len);
    5504             :         }
    5505          58 :         efree(escaped);
    5506             : 
    5507          58 :         smart_str_appends(&querystr, "' ORDER BY a.attnum;");
    5508          58 :         smart_str_0(&querystr);
    5509          58 :         efree(src);
    5510             : 
    5511          58 :         pg_result = PQexec(pg_link, querystr.c);
    5512          58 :         if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) {
    5513           4 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Table '%s' doesn't exists", table_name);
    5514           4 :                 smart_str_free(&querystr);
    5515           4 :                 PQclear(pg_result);
    5516           4 :                 return FAILURE;
    5517             :         }
    5518          54 :         smart_str_free(&querystr);
    5519             : 
    5520         173 :         for (i = 0; i < num_rows; i++) {
    5521             :                 char *name;
    5522         119 :                 MAKE_STD_ZVAL(elem);
    5523         119 :                 array_init(elem);
    5524             :                 /* pg_attribute.attnum */
    5525         119 :                 add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1)));
    5526             :                 /* pg_type.typname */
    5527         119 :                 add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1);
    5528             :                 /* pg_attribute.attlen */
    5529         119 :                 add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3)));
    5530             :                 /* pg_attribute.attnonull */
    5531         119 :                 add_assoc_bool(elem, "not null", !strcmp(PQgetvalue(pg_result,i,4), "t"));
    5532             :                 /* pg_attribute.atthasdef */
    5533         119 :                 add_assoc_bool(elem, "has default", !strcmp(PQgetvalue(pg_result,i,5), "t"));
    5534             :                 /* pg_attribute.attndims */
    5535         119 :                 add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6)));
    5536             :                 /* pg_type.typtype */
    5537         119 :                 add_assoc_bool(elem, "is enum", !strcmp(PQgetvalue(pg_result,i,7), "e"));
    5538         119 :                 if (extended) {
    5539             :                         /* pg_type.typtype */
    5540           2 :                         add_assoc_bool(elem, "is base", !strcmp(PQgetvalue(pg_result,i,7), "b"));
    5541           2 :                         add_assoc_bool(elem, "is composite", !strcmp(PQgetvalue(pg_result,i,7), "c"));
    5542           2 :                         add_assoc_bool(elem, "is pesudo", !strcmp(PQgetvalue(pg_result,i,7), "p"));
    5543             :                         /* pg_description.description */
    5544           2 :                         add_assoc_string(elem, "description", PQgetvalue(pg_result,i,8), 1);
    5545             :                 }
    5546             :                 /* pg_attribute.attname */
    5547         119 :                 name = PQgetvalue(pg_result,i,0);
    5548         119 :                 add_assoc_zval(meta, name, elem);
    5549             :         }
    5550          54 :         PQclear(pg_result);
    5551             :         
    5552          54 :         return SUCCESS;
    5553             : }
    5554             : 
    5555             : /* }}} */
    5556             : 
    5557             : 
    5558             : /* {{{ proto array pg_meta_data(resource db, string table [, bool extended])
    5559             :    Get meta_data */
    5560           4 : PHP_FUNCTION(pg_meta_data)
    5561             : {
    5562             :         zval *pgsql_link;
    5563             :         char *table_name;
    5564             :         uint table_name_len;
    5565           4 :         zend_bool extended=0;
    5566             :         PGconn *pgsql;
    5567           4 :         int id = -1;
    5568             : 
    5569           4 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|b",
    5570             :                                                           &pgsql_link, &table_name, &table_name_len, &extended) == FAILURE) {
    5571           0 :                 return;
    5572             :         }
    5573             : 
    5574           4 :         ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    5575             : 
    5576           4 :         array_init(return_value);
    5577           4 :         if (php_pgsql_meta_data(pgsql, table_name, return_value, extended TSRMLS_CC) == FAILURE) {
    5578             :                 zval_dtor(return_value); /* destroy array */
    5579           0 :                 RETURN_FALSE;
    5580             :         }
    5581             : }
    5582             : /* }}} */
    5583             : 
    5584             : 
    5585             : /* {{{ php_pgsql_get_data_type
    5586             :  */
    5587          81 : static php_pgsql_data_type php_pgsql_get_data_type(const char *type_name, size_t len)
    5588             : {
    5589             :         /* This is stupid way to do. I'll fix it when I decied how to support
    5590             :            user defined types. (Yasuo) */
    5591             : 
    5592             :         /* boolean */
    5593          81 :         if (!strcmp(type_name, "bool")|| !strcmp(type_name, "boolean"))
    5594           0 :                 return PG_BOOL;
    5595             :         /* object id */
    5596          81 :         if (!strcmp(type_name, "oid"))
    5597           0 :                 return PG_OID;
    5598             :         /* integer */
    5599          81 :         if (!strcmp(type_name, "int2") || !strcmp(type_name, "smallint"))
    5600           0 :                 return PG_INT2;
    5601          81 :         if (!strcmp(type_name, "int4") || !strcmp(type_name, "integer"))
    5602          69 :                 return PG_INT4;
    5603          12 :         if (!strcmp(type_name, "int8") || !strcmp(type_name, "bigint"))
    5604           0 :                 return PG_INT8;
    5605             :         /* real and other */
    5606          12 :         if (!strcmp(type_name, "float4") || !strcmp(type_name, "real"))
    5607           0 :                 return PG_FLOAT4;
    5608          12 :         if (!strcmp(type_name, "float8") || !strcmp(type_name, "double precision"))
    5609           0 :                 return PG_FLOAT8;
    5610          12 :         if (!strcmp(type_name, "numeric"))
    5611           0 :                 return PG_NUMERIC;
    5612          12 :         if (!strcmp(type_name, "money"))
    5613           0 :                 return PG_MONEY;
    5614             :         /* character */
    5615          12 :         if (!strcmp(type_name, "text"))
    5616           5 :                 return PG_TEXT;
    5617           7 :         if (!strcmp(type_name, "bpchar") || !strcmp(type_name, "character"))
    5618           0 :                 return PG_CHAR;
    5619           7 :         if (!strcmp(type_name, "varchar") || !strcmp(type_name, "character varying"))
    5620           0 :                 return PG_VARCHAR;
    5621             :         /* time and interval */
    5622           7 :         if (!strcmp(type_name, "abstime"))
    5623           0 :                 return PG_UNIX_TIME;
    5624           7 :         if (!strcmp(type_name, "reltime"))
    5625           0 :                 return PG_UNIX_TIME_INTERVAL;
    5626           7 :         if (!strcmp(type_name, "tinterval"))
    5627           0 :                 return PG_UNIX_TIME_INTERVAL;
    5628           7 :         if (!strcmp(type_name, "date"))
    5629           0 :                 return PG_DATE;
    5630           7 :         if (!strcmp(type_name, "time"))
    5631           0 :                 return PG_TIME;
    5632           7 :         if (!strcmp(type_name, "time with time zone") || !strcmp(type_name, "timetz"))
    5633           0 :                 return PG_TIME_WITH_TIMEZONE;
    5634           7 :         if (!strcmp(type_name, "timestamp without time zone") || !strcmp(type_name, "timestamp"))
    5635           2 :                 return PG_TIMESTAMP;
    5636           5 :         if (!strcmp(type_name, "timestamp with time zone") || !strcmp(type_name, "timestamptz"))
    5637           0 :                 return PG_TIMESTAMP_WITH_TIMEZONE;
    5638           5 :         if (!strcmp(type_name, "interval"))
    5639           0 :                 return PG_INTERVAL;
    5640             :         /* binary */
    5641           5 :         if (!strcmp(type_name, "bytea"))
    5642           5 :                 return PG_BYTEA;
    5643             :         /* network */
    5644           0 :         if (!strcmp(type_name, "cidr"))
    5645           0 :                 return PG_CIDR;
    5646           0 :         if (!strcmp(type_name, "inet"))
    5647           0 :                 return PG_INET;
    5648           0 :         if (!strcmp(type_name, "macaddr"))
    5649           0 :                 return PG_MACADDR;
    5650             :         /* bit */
    5651           0 :         if (!strcmp(type_name, "bit"))
    5652           0 :                 return PG_BIT;
    5653           0 :         if (!strcmp(type_name, "bit varying"))
    5654           0 :                 return PG_VARBIT;
    5655             :         /* geometric */
    5656           0 :         if (!strcmp(type_name, "line"))
    5657           0 :                 return PG_LINE;
    5658           0 :         if (!strcmp(type_name, "lseg"))
    5659           0 :                 return PG_LSEG;
    5660           0 :         if (!strcmp(type_name, "box"))
    5661           0 :                 return PG_BOX;
    5662           0 :         if (!strcmp(type_name, "path"))
    5663           0 :                 return PG_PATH;
    5664           0 :         if (!strcmp(type_name, "point"))
    5665           0 :                 return PG_POINT;
    5666           0 :         if (!strcmp(type_name, "polygon"))
    5667           0 :                 return PG_POLYGON;
    5668           0 :         if (!strcmp(type_name, "circle"))
    5669           0 :                 return PG_CIRCLE;
    5670             : 
    5671           0 :         return PG_UNKNOWN;
    5672             : }
    5673             : /* }}} */
    5674             : 
    5675             : /* {{{ php_pgsql_convert_match
    5676             :  * test field value with regular expression specified.
    5677             :  */
    5678          11 : static int php_pgsql_convert_match(const char *str, size_t str_len, const char *regex , int icase TSRMLS_DC)
    5679             : {
    5680             :         regex_t re;
    5681             :         regmatch_t *subs;
    5682          11 :         int regopt = REG_EXTENDED;
    5683          11 :         int regerr, ret = SUCCESS;
    5684             :         int i;
    5685             : 
    5686             :         /* Check invalid chars for POSIX regex */
    5687          55 :         for (i = 0; i < str_len; i++) {
    5688         132 :                 if (str[i] == '\n' ||
    5689          44 :                         str[i] == '\r' ||
    5690          44 :                         str[i] == '\0' ) {
    5691           0 :                         return FAILURE;
    5692             :                 }
    5693             :         }
    5694             : 
    5695          11 :         if (icase) {
    5696           0 :                 regopt |= REG_ICASE;
    5697             :         }
    5698             : 
    5699          11 :         regerr = regcomp(&re, regex, regopt);
    5700          11 :         if (regerr) {
    5701           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot compile regex");
    5702           0 :                 regfree(&re);
    5703           0 :                 return FAILURE;
    5704             :         }
    5705          11 :         subs = (regmatch_t *)ecalloc(sizeof(regmatch_t), re.re_nsub+1);
    5706             : 
    5707          11 :         regerr = regexec(&re, str, re.re_nsub+1, subs, 0);
    5708          11 :         if (regerr == REG_NOMATCH) {
    5709             : #ifdef PHP_DEBUG
    5710           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "'%s' does not match with '%s'", str, regex);
    5711             : #endif
    5712           0 :                 ret = FAILURE;
    5713             :         }
    5714          11 :         else if (regerr) {
    5715           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot exec regex");
    5716           0 :                 ret = FAILURE;
    5717             :         }
    5718          11 :         regfree(&re);
    5719          11 :         efree(subs);
    5720          11 :         return ret;
    5721             : }
    5722             : 
    5723             : /* }}} */
    5724             : 
    5725             : /* {{{ php_pgsql_add_quote
    5726             :  * add quotes around string.
    5727             :  */
    5728          11 : static int php_pgsql_add_quotes(zval *src, zend_bool should_free TSRMLS_DC) 
    5729             : {
    5730          11 :         smart_str str = {0};
    5731             : 
    5732             :         assert(Z_TYPE_P(src) == IS_STRING);
    5733             :         assert(should_free == 1 || should_free == 0);
    5734             : 
    5735          11 :         smart_str_appendc(&str, 'E');
    5736          11 :         smart_str_appendc(&str, '\'');
    5737          11 :         smart_str_appendl(&str, Z_STRVAL_P(src), Z_STRLEN_P(src));
    5738          11 :         smart_str_appendc(&str, '\'');
    5739          11 :         smart_str_0(&str);
    5740             : 
    5741          11 :         if (should_free) {
    5742          11 :                 efree(Z_STRVAL_P(src));
    5743             :         }
    5744          11 :         Z_STRVAL_P(src) = str.c;
    5745          11 :         Z_STRLEN_P(src) = str.len;
    5746             : 
    5747          11 :         return SUCCESS;
    5748             : }
    5749             : /* }}} */
    5750             : 
    5751             : #define PGSQL_CONV_CHECK_IGNORE() \
    5752             :                                 if (!err && Z_TYPE_P(new_val) == IS_STRING && !strcmp(Z_STRVAL_P(new_val), "NULL")) { \
    5753             :                                         /* if new_value is string "NULL" and field has default value, remove element to use default value */ \
    5754             :                                         if (!(opt & PGSQL_CONV_IGNORE_DEFAULT) && Z_BVAL_PP(has_default)) { \
    5755             :                                                 zval_dtor(new_val); \
    5756             :                                                 FREE_ZVAL(new_val); \
    5757             :                                                 skip_field = 1; \
    5758             :                                         } \
    5759             :                                         /* raise error if it's not null and cannot be ignored */ \
    5760             :                                         else if (!(opt & PGSQL_CONV_IGNORE_NOT_NULL) && Z_BVAL_PP(not_null)) { \
    5761             :                                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected NULL for 'NOT NULL' field '%s'", field ); \
    5762             :                                                 err = 1; \
    5763             :                                         } \
    5764             :                                 }
    5765             : 
    5766             : /* {{{ php_pgsql_convert
    5767             :  * check and convert array values (fieldname=>vlaue pair) for sql
    5768             :  */
    5769          54 : PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, const zval *values, zval *result, ulong opt TSRMLS_DC) 
    5770             : {
    5771             :         HashPosition pos;
    5772          54 :         char *field = NULL;
    5773          54 :         uint field_len = -1;
    5774          54 :         ulong num_idx = -1;
    5775             :         zval *meta, **def, **type, **not_null, **has_default, **is_enum, **val, *new_val;
    5776          54 :         int key_type, err = 0, skip_field;
    5777             :         php_pgsql_data_type data_type;
    5778             : 
    5779             :         assert(pg_link != NULL);
    5780             :         assert(Z_TYPE_P(values) == IS_ARRAY);
    5781             :         assert(Z_TYPE_P(result) == IS_ARRAY);
    5782             :         assert(!(opt & ~PGSQL_CONV_OPTS));
    5783             : 
    5784          54 :         if (!table_name) {
    5785           0 :                 return FAILURE;
    5786             :         }
    5787          54 :         MAKE_STD_ZVAL(meta);
    5788          54 :         array_init(meta);
    5789             : 
    5790             : /* table_name is escaped by php_pgsql_meta_data */
    5791          54 :         if (php_pgsql_meta_data(pg_link, table_name, meta, 0 TSRMLS_CC) == FAILURE) {
    5792             :                 zval_dtor(meta);
    5793           4 :                 FREE_ZVAL(meta);
    5794           4 :                 return FAILURE;
    5795             :         }
    5796         182 :         for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos);
    5797         132 :                  zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&val, &pos) == SUCCESS;
    5798          82 :                  zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos)) {
    5799          83 :                 skip_field = 0;
    5800          83 :                 new_val = NULL;
    5801             : 
    5802          83 :                 if ((key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(values), &field, &field_len, &num_idx, 0, &pos)) == HASH_KEY_NON_EXISTENT) {
    5803           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to get array key type");
    5804           0 :                         err = 1;
    5805             :                 }
    5806          83 :                 if (!err && key_type == HASH_KEY_IS_LONG) {
    5807           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Accepts only string key for values");
    5808           0 :                         err = 1;
    5809             :                 }
    5810          83 :                 if (!err && key_type == HASH_KEY_NON_EXISTENT) {
    5811           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Accepts only string key for values");
    5812           0 :                         err = 1;
    5813             :                 }
    5814          83 :                 if (!err && zend_hash_find(Z_ARRVAL_P(meta), field, field_len, (void **)&def) == FAILURE) {
    5815           1 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid field name (%s) in values", field);
    5816           1 :                         err = 1;
    5817             :                 }
    5818          83 :                 if (!err && zend_hash_find(Z_ARRVAL_PP(def), "type", sizeof("type"), (void **)&type) == FAILURE) {
    5819           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'type'");
    5820           0 :                         err = 1;
    5821             :                 }
    5822          83 :                 if (!err && zend_hash_find(Z_ARRVAL_PP(def), "not null", sizeof("not null"), (void **)&not_null) == FAILURE) {
    5823           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'not null'");
    5824           0 :                         err = 1;
    5825             :                 }
    5826          83 :                 if (!err && zend_hash_find(Z_ARRVAL_PP(def), "has default", sizeof("has default"), (void **)&has_default) == FAILURE) {
    5827           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'has default'");
    5828           0 :                         err = 1;
    5829             :                 }
    5830          83 :                 if (!err && zend_hash_find(Z_ARRVAL_PP(def), "is enum", sizeof("is enum"), (void **)&is_enum) == FAILURE) {
    5831           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'is enum'");
    5832           0 :                         err = 1;
    5833             :                 }
    5834          83 :                 if (!err && (Z_TYPE_PP(val) == IS_ARRAY || Z_TYPE_PP(val) == IS_OBJECT)) {
    5835           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects scalar values as field values");
    5836           0 :                         err = 1;
    5837             :                 }
    5838          83 :                 if (err) {
    5839           1 :                         break; /* break out for() */
    5840             :                 }
    5841          82 :                 ALLOC_INIT_ZVAL(new_val);
    5842             : 
    5843          82 :                 if (Z_BVAL_PP(is_enum)) {
    5844             :                         /* enums need to be treated like strings */
    5845           1 :                         data_type = PG_TEXT;
    5846             :                 }
    5847             :                 else {
    5848          81 :                         data_type = php_pgsql_get_data_type(Z_STRVAL_PP(type), Z_STRLEN_PP(type));
    5849             :                 }
    5850             : 
    5851          82 :                 switch(data_type)
    5852             :                 {
    5853             :                         case PG_BOOL:
    5854           0 :                                 switch (Z_TYPE_PP(val)) {
    5855             :                                         case IS_STRING:
    5856           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    5857           0 :                                                         ZVAL_STRING(new_val, "NULL", 1);
    5858             :                                                 }
    5859             :                                                 else {
    5860           0 :                                                         if (!strcmp(Z_STRVAL_PP(val), "t") || !strcmp(Z_STRVAL_PP(val), "T") ||
    5861           0 :                                                                 !strcmp(Z_STRVAL_PP(val), "y") || !strcmp(Z_STRVAL_PP(val), "Y") ||
    5862           0 :                                                                 !strcmp(Z_STRVAL_PP(val), "true") || !strcmp(Z_STRVAL_PP(val), "True") ||
    5863           0 :                                                                 !strcmp(Z_STRVAL_PP(val), "yes") || !strcmp(Z_STRVAL_PP(val), "Yes") ||
    5864           0 :                                                                 !strcmp(Z_STRVAL_PP(val), "1")) {
    5865           0 :                                                                 ZVAL_STRINGL(new_val, "'t'", sizeof("'t'")-1, 1);
    5866             :                                                         }
    5867           0 :                                                         else if (!strcmp(Z_STRVAL_PP(val), "f") || !strcmp(Z_STRVAL_PP(val), "F") ||
    5868           0 :                                                                          !strcmp(Z_STRVAL_PP(val), "n") || !strcmp(Z_STRVAL_PP(val), "N") ||
    5869           0 :                                                                          !strcmp(Z_STRVAL_PP(val), "false") ||  !strcmp(Z_STRVAL_PP(val), "False") ||
    5870           0 :                                                                          !strcmp(Z_STRVAL_PP(val), "no") ||  !strcmp(Z_STRVAL_PP(val), "No") ||
    5871           0 :                                                                          !strcmp(Z_STRVAL_PP(val), "0")) {
    5872           0 :                                                                 ZVAL_STRINGL(new_val, "'f'", sizeof("'f'")-1, 1);
    5873             :                                                         }
    5874             :                                                         else {
    5875           0 :                                                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected invalid value (%s) for PostgreSQL %s field (%s)", Z_STRVAL_PP(val), Z_STRVAL_PP(type), field);
    5876           0 :                                                                 err = 1;
    5877             :                                                         }
    5878             :                                                 }
    5879           0 :                                                 break;
    5880             : 
    5881             :                                         case IS_LONG:
    5882             :                                         case IS_BOOL:
    5883           0 :                                                 if (Z_LVAL_PP(val)) {
    5884           0 :                                                         ZVAL_STRINGL(new_val, "'t'", sizeof("'t'")-1, 1);
    5885             :                                                 }
    5886             :                                                 else {
    5887           0 :                                                         ZVAL_STRINGL(new_val, "'f'", sizeof("'f'")-1, 1);
    5888             :                                                 }
    5889           0 :                                                 break;
    5890             : 
    5891             :                                         case IS_NULL:
    5892           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    5893           0 :                                                 break;
    5894             : 
    5895             :                                         default:
    5896           0 :                                                 err = 1;
    5897             :                                 }
    5898           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    5899           0 :                                 if (err) {
    5900           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects string, null, long or boolelan value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
    5901             :                                 }
    5902           0 :                                 break;
    5903             : 
    5904             :                         case PG_OID:
    5905             :                         case PG_INT2:
    5906             :                         case PG_INT4:
    5907             :                         case PG_INT8:
    5908          69 :                                 switch (Z_TYPE_PP(val)) {
    5909             :                                         case IS_STRING:
    5910          12 :                                                 if (Z_STRLEN_PP(val) == 0) {
    5911           1 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    5912             :                                                 }
    5913             :                                                 else {
    5914             :                                                         /* FIXME: better regex must be used */
    5915          11 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^([+-]{0,1}[0-9]+)$", 0 TSRMLS_CC) == FAILURE) {
    5916           0 :                                                                 err = 1;
    5917             :                                                         }
    5918             :                                                         else {
    5919          11 :                                                                 ZVAL_STRINGL(new_val, Z_STRVAL_PP(val), Z_STRLEN_PP(val), 1);
    5920             :                                                         }
    5921             :                                                 }
    5922          12 :                                                 break;
    5923             : 
    5924             :                                         case IS_DOUBLE:
    5925           0 :                                                 ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
    5926           0 :                                                 convert_to_long_ex(&new_val);
    5927           0 :                                                 break;
    5928             :                                                 
    5929             :                                         case IS_LONG:
    5930          53 :                                                 ZVAL_LONG(new_val, Z_LVAL_PP(val));
    5931          53 :                                                 break;
    5932             :                                                 
    5933             :                                         case IS_NULL:
    5934           4 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    5935           4 :                                                 break;
    5936             : 
    5937             :                                         default:
    5938           0 :                                                 err = 1;
    5939             :                                 }
    5940          69 :                                 PGSQL_CONV_CHECK_IGNORE();
    5941          69 :                                 if (err) {
    5942           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for pgsql '%s' (%s)", Z_STRVAL_PP(type), field);
    5943             :                                 }
    5944          69 :                                 break;
    5945             : 
    5946             :                         case PG_NUMERIC:
    5947             :                         case PG_MONEY:
    5948             :                         case PG_FLOAT4:
    5949             :                         case PG_FLOAT8:
    5950           0 :                                 switch (Z_TYPE_PP(val)) {
    5951             :                                         case IS_STRING:
    5952           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    5953           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    5954             :                                                 }
    5955             :                                                 else {
    5956             :                                                         /* better regex? */
    5957           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", 0 TSRMLS_CC) == FAILURE) {
    5958           0 :                                                                 err = 1;
    5959             :                                                         }
    5960             :                                                         else {
    5961           0 :                                                                 ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
    5962             :                                                         }
    5963             :                                                 }
    5964           0 :                                                 break;
    5965             : 
    5966             :                                         case IS_LONG:
    5967           0 :                                                 ZVAL_LONG(new_val, Z_LVAL_PP(val));
    5968           0 :                                                 break;
    5969             : 
    5970             :                                         case IS_DOUBLE:
    5971           0 :                                                 ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
    5972           0 :                                                 break;
    5973             : 
    5974             :                                         case IS_NULL:
    5975           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    5976           0 :                                                 break;
    5977             : 
    5978             :                                         default:
    5979           0 :                                                 err = 1;
    5980             :                                 }
    5981           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    5982           0 :                                 if (err) {
    5983           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
    5984             :                                 }
    5985           0 :                                 break;
    5986             : 
    5987             :                                 /* Exotic types are handled as string also.
    5988             :                                    Please feel free to add more valitions. Invalid query fails
    5989             :                                    at execution anyway. */
    5990             :                         case PG_TEXT:
    5991             :                         case PG_CHAR:
    5992             :                         case PG_VARCHAR:
    5993             :                                 /* bit */
    5994             :                         case PG_BIT:
    5995             :                         case PG_VARBIT:
    5996             :                                 /* geometric */
    5997             :                         case PG_LINE:
    5998             :                         case PG_LSEG:
    5999             :                         case PG_POINT:
    6000             :                         case PG_BOX:
    6001             :                         case PG_PATH:
    6002             :                         case PG_POLYGON:
    6003             :                         case PG_CIRCLE:
    6004             :                                 /* unknown. JSON, Array etc */
    6005             :                         case PG_UNKNOWN:
    6006           6 :                                 switch (Z_TYPE_PP(val)) {
    6007             :                                         case IS_STRING:
    6008           6 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6009           0 :                                                         if (opt & PGSQL_CONV_FORCE_NULL) {
    6010           0 :                                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6011             :                                                         } else {
    6012           0 :                                                                 ZVAL_STRINGL(new_val, "''", sizeof("''")-1, 1);
    6013             :                                                         }
    6014             :                                                 }
    6015             :                                                 else {
    6016             :                                                         char *tmp;
    6017             :                                                         /* PostgreSQL ignores \0 */
    6018           6 :                                                         Z_TYPE_P(new_val) = IS_STRING;
    6019           6 :                                                         tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
    6020             :                                                         /* better to use PGSQLescapeLiteral since PGescapeStringConn does not handle special \ */
    6021           6 :                                                         Z_STRLEN_P(new_val) = (int)PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), NULL);
    6022           6 :                                                         Z_STRVAL_P(new_val) = tmp;
    6023           6 :                                                         php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6024             :                                                 }
    6025           6 :                                                 break;
    6026             : 
    6027             :                                         case IS_LONG:
    6028           0 :                                                 ZVAL_LONG(new_val, Z_LVAL_PP(val));
    6029           0 :                                                 convert_to_string_ex(&new_val);
    6030           0 :                                                 break;
    6031             : 
    6032             :                                         case IS_DOUBLE:
    6033           0 :                                                 ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
    6034           0 :                                                 convert_to_string_ex(&new_val);
    6035           0 :                                                 break;
    6036             : 
    6037             :                                         case IS_NULL:
    6038           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6039           0 :                                                 break;
    6040             : 
    6041             :                                         default:
    6042           0 :                                                 err = 1;
    6043             :                                 }
    6044           6 :                                 PGSQL_CONV_CHECK_IGNORE();
    6045           6 :                                 if (err) {
    6046           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
    6047             :                                 }
    6048           6 :                                 break;
    6049             : 
    6050             :                         case PG_UNIX_TIME:
    6051             :                         case PG_UNIX_TIME_INTERVAL:
    6052             :                                 /* these are the actallay a integer */
    6053           0 :                                 switch (Z_TYPE_PP(val)) {
    6054             :                                         case IS_STRING:
    6055           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6056           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6057             :                                                 }
    6058             :                                                 else {
    6059             :                                                         /* better regex? */
    6060           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^[0-9]+$", 0 TSRMLS_CC) == FAILURE) {
    6061           0 :                                                                 err = 1;
    6062             :                                                         }
    6063             :                                                         else {
    6064           0 :                                                                 ZVAL_STRINGL(new_val, Z_STRVAL_PP(val), Z_STRLEN_PP(val), 1);
    6065           0 :                                                                 convert_to_long_ex(&new_val);
    6066             :                                                         }
    6067             :                                                 }
    6068           0 :                                                 break;
    6069             : 
    6070             :                                         case IS_DOUBLE:
    6071           0 :                                                 ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
    6072           0 :                                                 convert_to_long_ex(&new_val);
    6073           0 :                                                 break;
    6074             : 
    6075             :                                         case IS_LONG:
    6076           0 :                                                 ZVAL_LONG(new_val, Z_LVAL_PP(val));
    6077           0 :                                                 break;
    6078             : 
    6079             :                                         case IS_NULL:
    6080           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6081           0 :                                                 break;
    6082             : 
    6083             :                                         default:
    6084           0 :                                                 err = 1;
    6085             :                                 }
    6086           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    6087           0 :                                 if (err) {
    6088           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for '%s' (%s)", Z_STRVAL_PP(type), field);
    6089             :                                 }
    6090           0 :                                 break;
    6091             : 
    6092             :                         case PG_CIDR:
    6093             :                         case PG_INET:
    6094           0 :                                 switch (Z_TYPE_PP(val)) {
    6095             :                                         case IS_STRING:
    6096           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6097           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6098             :                                                 }
    6099             :                                                 else {
    6100             :                                                         /* better regex? IPV6 and IPV4 */
    6101           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$", 0 TSRMLS_CC) == FAILURE) {
    6102           0 :                                                                 err = 1;
    6103             :                                                         }
    6104             :                                                         else {
    6105           0 :                                                                 ZVAL_STRINGL(new_val, Z_STRVAL_PP(val), Z_STRLEN_PP(val), 1);
    6106           0 :                                                                 php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6107             :                                                         }
    6108             :                                                 }
    6109           0 :                                                 break;
    6110             :                                                 
    6111             :                                         case IS_NULL:
    6112           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6113           0 :                                                 break;
    6114             : 
    6115             :                                         default:
    6116           0 :                                                 err = 1;
    6117             :                                 }
    6118           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    6119           0 :                                 if (err) {
    6120           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for '%s' (%s)", Z_STRVAL_PP(type), field);
    6121             :                                 }
    6122           0 :                                 break;
    6123             : 
    6124             :                         case PG_TIME_WITH_TIMEZONE:
    6125             :                         case PG_TIMESTAMP:
    6126             :                         case PG_TIMESTAMP_WITH_TIMEZONE:
    6127           2 :                                 switch(Z_TYPE_PP(val)) {
    6128             :                                         case IS_STRING:
    6129           2 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6130           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6131           2 :                                                 } else if (!strcasecmp(Z_STRVAL_PP(val), "now()")) {
    6132           2 :                                                         ZVAL_STRINGL(new_val, "NOW()", sizeof("NOW()")-1, 1);
    6133             :                                                 } else {
    6134             :                                                         /* better regex? */
    6135           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^([0-9]{4}[/-][0-9]{1,2}[/-][0-9]{1,2})([ \\t]+(([0-9]{1,2}:[0-9]{1,2}){1}(:[0-9]{1,2}){0,1}(\\.[0-9]+){0,1}([ \\t]*([+-][0-9]{1,4}(:[0-9]{1,2}){0,1}|[-a-zA-Z_/+]{1,50})){0,1})){0,1}$", 1 TSRMLS_CC) == FAILURE) {
    6136           0 :                                                                 err = 1;
    6137             :                                                         } else {
    6138           0 :                                                                 ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
    6139           0 :                                                                 php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6140             :                                                         }
    6141             :                                                 }
    6142           2 :                                                 break;
    6143             : 
    6144             :                                         case IS_NULL:
    6145           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6146           0 :                                                 break;
    6147             : 
    6148             :                                         default:
    6149           0 :                                                 err = 1;
    6150             :                                 }
    6151           2 :                                 PGSQL_CONV_CHECK_IGNORE();
    6152           2 :                                 if (err) {
    6153           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
    6154             :                                 }
    6155           2 :                                 break;
    6156             : 
    6157             :                         case PG_DATE:
    6158           0 :                                 switch(Z_TYPE_PP(val)) {
    6159             :                                         case IS_STRING:
    6160           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6161           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6162             :                                                 }
    6163             :                                                 else {
    6164             :                                                         /* FIXME: better regex must be used */
    6165           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^([0-9]{4}[/-][0-9]{1,2}[/-][0-9]{1,2})$", 1 TSRMLS_CC) == FAILURE) {
    6166           0 :                                                                 err = 1;
    6167             :                                                         }
    6168             :                                                         else {
    6169           0 :                                                                 ZVAL_STRINGL(new_val, Z_STRVAL_PP(val), Z_STRLEN_PP(val), 1);
    6170           0 :                                                                 php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6171             :                                                         }
    6172             :                                                 }
    6173           0 :                                                 break;
    6174             : 
    6175             :                                         case IS_NULL:
    6176           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6177           0 :                                                 break;
    6178             : 
    6179             :                                         default:
    6180           0 :                                                 err = 1;
    6181             :                                 }
    6182           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    6183           0 :                                 if (err) {
    6184           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
    6185             :                                 }
    6186           0 :                                 break;
    6187             : 
    6188             :                         case PG_TIME:
    6189           0 :                                 switch(Z_TYPE_PP(val)) {
    6190             :                                         case IS_STRING:
    6191           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6192           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6193             :                                                 }
    6194             :                                                 else {
    6195             :                                                         /* FIXME: better regex must be used */
    6196           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^(([0-9]{1,2}:[0-9]{1,2}){1}(:[0-9]{1,2}){0,1})){0,1}$", 1 TSRMLS_CC) == FAILURE) {
    6197           0 :                                                                 err = 1;
    6198             :                                                         }
    6199             :                                                         else {
    6200           0 :                                                                 ZVAL_STRINGL(new_val, Z_STRVAL_PP(val), Z_STRLEN_PP(val), 1);
    6201           0 :                                                                 php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6202             :                                                         }
    6203             :                                                 }
    6204           0 :                                                 break;
    6205             : 
    6206             :                                         case IS_NULL:
    6207           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6208           0 :                                                 break;
    6209             : 
    6210             :                                         default:
    6211           0 :                                                 err = 1;
    6212             :                                 }
    6213           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    6214           0 :                                 if (err) {
    6215           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
    6216             :                                 }
    6217           0 :                                 break;
    6218             : 
    6219             :                         case PG_INTERVAL:
    6220           0 :                                 switch(Z_TYPE_PP(val)) {
    6221             :                                         case IS_STRING:
    6222           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6223           0 :                                                         ZVAL_STRING(new_val, "NULL", 1);
    6224             :                                                 }
    6225             :                                                 else {
    6226             : 
    6227             :                                                         /* From the Postgres docs:
    6228             : 
    6229             :                                                            interval values can be written with the following syntax:
    6230             :                                                            [@] quantity unit [quantity unit...] [direction]
    6231             :                                                            
    6232             :                                                            Where: quantity is a number (possibly signed); unit is second, minute, hour,
    6233             :                                                            day, week, month, year, decade, century, millennium, or abbreviations or
    6234             :                                                            plurals of these units [note not *all* abbreviations] ; direction can be
    6235             :                                                            ago or empty. The at sign (@) is optional noise.
    6236             :                                                            
    6237             :                                                            ...
    6238             :                                                            
    6239             :                                                            Quantities of days, hours, minutes, and seconds can be specified without explicit
    6240             :                                                            unit markings. For example, '1 12:59:10' is read the same as '1 day 12 hours 59 min 10
    6241             :                                                            sec'.
    6242             :                                                         */
    6243           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val),
    6244             :                                                                                                                 "^(@?[ \\t]+)?("
    6245             : 
    6246             :                                                                                                                 /* Textual time units and their abbreviations: */
    6247             :                                                                                                                 "(([-+]?[ \\t]+)?"
    6248             :                                                                                                                 "[0-9]+(\\.[0-9]*)?[ \\t]*"
    6249             :                                                                                                                 "(millenniums|millennia|millennium|mil|mils|"
    6250             :                                                                                                                 "centuries|century|cent|c|"
    6251             :                                                                                                                 "decades|decade|dec|decs|"
    6252             :                                                                                                                 "years|year|y|"
    6253             :                                                                                                                 "months|month|mon|"
    6254             :                                                                                                                 "weeks|week|w|" 
    6255             :                                                                                                                 "days|day|d|"
    6256             :                                                                                                                 "hours|hour|hr|hrs|h|"
    6257             :                                                                                                                 "minutes|minute|mins|min|m|"
    6258             :                                                                                                                 "seconds|second|secs|sec|s))+|"
    6259             : 
    6260             :                                                                                                                 /* Textual time units plus (dd)* hh[:mm[:ss]] */
    6261             :                                                                                                                 "((([-+]?[ \\t]+)?"
    6262             :                                                                                                                 "[0-9]+(\\.[0-9]*)?[ \\t]*"
    6263             :                                                                                                                 "(millenniums|millennia|millennium|mil|mils|"
    6264             :                                                                                                                 "centuries|century|cent|c|"
    6265             :                                                                                                                 "decades|decade|dec|decs|"
    6266             :                                                                                                                 "years|year|y|"
    6267             :                                                                                                                 "months|month|mon|"
    6268             :                                                                                                                 "weeks|week|w|"
    6269             :                                                                                                                 "days|day|d))+" 
    6270             :                                                                                                                 "([-+]?[ \\t]+"
    6271             :                                                                                                                 "([0-9]+[ \\t]+)+"                             /* dd */
    6272             :                                                                                                                 "(([0-9]{1,2}:){0,2}[0-9]{0,2})" /* hh:[mm:[ss]] */
    6273             :                                                                                                                 ")?))"
    6274             :                                                                                                                 "([ \\t]+ago)?$",
    6275             :                                                                                                                 1 TSRMLS_CC) == FAILURE) {
    6276           0 :                                                                 err = 1;
    6277             :                                                         }
    6278             :                                                         else {
    6279           0 :                                                                 ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
    6280           0 :                                                                 php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6281             :                                                         }
    6282             :                                                 }
    6283           0 :                                                 break;
    6284             : 
    6285             :                                         case IS_NULL:
    6286           0 :                                                 ZVAL_STRING(new_val, "NULL", 1);
    6287           0 :                                                 break;
    6288             : 
    6289             :                                         default:
    6290           0 :                                                 err = 1;
    6291             :                                 }
    6292           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    6293           0 :                                 if (err) {
    6294           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
    6295             :                                 }
    6296           0 :                                 break;
    6297             : #ifdef HAVE_PQESCAPE
    6298             :                         case PG_BYTEA:
    6299           5 :                                 switch (Z_TYPE_PP(val)) {
    6300             :                                         case IS_STRING:
    6301           5 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6302           0 :                                                         ZVAL_STRING(new_val, "NULL", 1);
    6303             :                                                 }
    6304             :                                                 else {
    6305             :                                                         unsigned char *tmp;
    6306             :                                                         size_t to_len;
    6307           5 :                                                         smart_str s = {0};
    6308             : #ifdef HAVE_PQESCAPE_BYTEA_CONN
    6309           5 :                                                         tmp = PQescapeByteaConn(pg_link, (unsigned char *)Z_STRVAL_PP(val), Z_STRLEN_PP(val), &to_len);
    6310             : #else
    6311             :                                                         tmp = PQescapeBytea(Z_STRVAL_PP(val), (unsigned char *)Z_STRLEN_PP(val), &to_len);
    6312             : #endif
    6313           5 :                                                         Z_TYPE_P(new_val) = IS_STRING;
    6314           5 :                                                         Z_STRLEN_P(new_val) = to_len-1; /* PQescapeBytea's to_len includes additional '\0' */
    6315           5 :                                                         Z_STRVAL_P(new_val) = emalloc(to_len);
    6316           5 :                                                         memcpy(Z_STRVAL_P(new_val), tmp, to_len);
    6317           5 :                                                         PQfreemem(tmp);
    6318           5 :                                                         php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6319           5 :                                                         smart_str_appendl(&s, Z_STRVAL_P(new_val), Z_STRLEN_P(new_val));
    6320           5 :                                                         smart_str_0(&s);
    6321           5 :                                                         efree(Z_STRVAL_P(new_val));
    6322           5 :                                                         Z_STRVAL_P(new_val) = s.c;
    6323           5 :                                                         Z_STRLEN_P(new_val) = s.len;
    6324             :                                                 }
    6325           5 :                                                 break;
    6326             : 
    6327             :                                         case IS_LONG:
    6328           0 :                                                 ZVAL_LONG(new_val, Z_LVAL_PP(val));
    6329           0 :                                                 convert_to_string_ex(&new_val);
    6330           0 :                                                 break;
    6331             : 
    6332             :                                         case IS_DOUBLE:
    6333           0 :                                                 ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
    6334           0 :                                                 convert_to_string_ex(&new_val);
    6335           0 :                                                 break;
    6336             : 
    6337             :                                         case IS_NULL:
    6338           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6339           0 :                                                 break;
    6340             : 
    6341             :                                         default:
    6342           0 :                                                 err = 1;
    6343             :                                 }
    6344           5 :                                 PGSQL_CONV_CHECK_IGNORE();
    6345           5 :                                 if (err) {
    6346           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
    6347             :                                 }
    6348           5 :                                 break;
    6349             :                                 
    6350             : #endif
    6351             :                         case PG_MACADDR:
    6352           0 :                                 switch(Z_TYPE_PP(val)) {
    6353             :                                         case IS_STRING:
    6354           0 :                                                 if (Z_STRLEN_PP(val) == 0) {
    6355           0 :                                                         ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6356             :                                                 }
    6357             :                                                 else {
    6358           0 :                                                         if (php_pgsql_convert_match(Z_STRVAL_PP(val), Z_STRLEN_PP(val), "^([0-9a-f]{2,2}:){5,5}[0-9a-f]{2,2}$", 1 TSRMLS_CC) == FAILURE) {
    6359           0 :                                                                 err = 1;
    6360             :                                                         }
    6361             :                                                         else {
    6362           0 :                                                                 ZVAL_STRINGL(new_val, Z_STRVAL_PP(val), Z_STRLEN_PP(val), 1);
    6363           0 :                                                                 php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
    6364             :                                                         }
    6365             :                                                 }
    6366           0 :                                                 break;
    6367             : 
    6368             :                                         case IS_NULL:
    6369           0 :                                                 ZVAL_STRINGL(new_val, "NULL", sizeof("NULL")-1, 1);
    6370           0 :                                                 break;
    6371             : 
    6372             :                                         default:
    6373           0 :                                                 err = 1;
    6374             :                                 }
    6375           0 :                                 PGSQL_CONV_CHECK_IGNORE();
    6376           0 :                                 if (err) {
    6377           0 :                                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
    6378             :                                 }
    6379           0 :                                 break;
    6380             : 
    6381             :                         default:
    6382             :                                 /* should not happen */
    6383           0 :                                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unknown or system data type '%s' for '%s'. Report error", Z_STRVAL_PP(type), field);
    6384           0 :                                 err = 1;
    6385             :                                 break;
    6386             :                 } /* switch */
    6387             : 
    6388          82 :                 if (err) {
    6389           0 :                         zval_dtor(new_val);
    6390           0 :                         FREE_ZVAL(new_val);
    6391           0 :                         break; /* break out for() */
    6392             :                 }
    6393             :                 /* If field is NULL and HAS DEFAULT, should be skipped */
    6394          82 :                 if (!skip_field) {
    6395             :                         char *escaped;
    6396          82 :                         size_t field_len = strlen(field);
    6397             : 
    6398          82 :                         if (_php_pgsql_detect_identifier_escape(field, field_len) == SUCCESS) {
    6399           0 :                                 add_assoc_zval(result, field, new_val);
    6400             :                         } else {
    6401          82 :                                 escaped = PGSQLescapeIdentifier(pg_link, field, field_len);
    6402          82 :                                 add_assoc_zval(result, escaped, new_val);
    6403          82 :                                 PGSQLfree(escaped);
    6404             :                         }
    6405             :                 }
    6406             :         } /* for */
    6407             :         zval_dtor(meta);
    6408          50 :         FREE_ZVAL(meta);
    6409             : 
    6410          50 :         if (err) {
    6411             :                 /* shouldn't destroy & free zval here */
    6412           1 :                 return FAILURE;
    6413             :         }
    6414          49 :         return SUCCESS;
    6415             : }
    6416             : /* }}} */
    6417             : 
    6418             : 
    6419             : /* {{{ proto array pg_convert(resource db, string table, array values[, int options])
    6420             :    Check and convert values for PostgreSQL SQL statement */
    6421           2 : PHP_FUNCTION(pg_convert)
    6422             : {
    6423             :         zval *pgsql_link, *values;
    6424             :         char *table_name;
    6425             :         int table_name_len;
    6426           2 :         ulong option = 0;
    6427             :         PGconn *pg_link;
    6428           2 :         int id = -1;
    6429             : 
    6430           2 :         if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
    6431             :                                                           "rsa|l", &pgsql_link, &table_name, &table_name_len, &values, &option) == FAILURE) {
    6432           0 :                 return;
    6433             :         }
    6434           2 :         if (option & ~PGSQL_CONV_OPTS) {
    6435           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
    6436           0 :                 RETURN_FALSE;
    6437             :         }
    6438           2 :         if (!table_name_len) {
    6439           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Table name is invalid");
    6440           0 :                 RETURN_FALSE;
    6441             :         }
    6442             : 
    6443           2 :         ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    6444             : 
    6445           2 :         if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
    6446           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
    6447             :         }
    6448           2 :         array_init(return_value);
    6449           2 :         if (php_pgsql_convert(pg_link, table_name, values, return_value, option TSRMLS_CC) == FAILURE) {
    6450             :                 zval_dtor(return_value);
    6451           0 :                 RETURN_FALSE;
    6452             :         }
    6453             : }
    6454             : /* }}} */
    6455             : 
    6456          11 : static int do_exec(smart_str *querystr, int expect, PGconn *pg_link, ulong opt TSRMLS_DC)
    6457             : {
    6458          11 :         if (opt & PGSQL_DML_ASYNC) {
    6459           0 :                 if (PQsendQuery(pg_link, querystr->c)) {
    6460           0 :                         return 0;
    6461             :                 }
    6462             :         }
    6463             :         else {
    6464             :                 PGresult *pg_result;
    6465             : 
    6466          11 :                 pg_result = PQexec(pg_link, querystr->c);
    6467          11 :                 if (PQresultStatus(pg_result) == expect) {
    6468          11 :                         PQclear(pg_result);
    6469          11 :                         return 0;
    6470             :                 } else {
    6471           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", PQresultErrorMessage(pg_result));
    6472           0 :                         PQclear(pg_result);
    6473             :                 }
    6474             :         }
    6475             : 
    6476           0 :         return -1;
    6477             : }
    6478             : 
    6479          42 : static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table)
    6480             : {
    6481             :         char *table_copy, *escaped, *token, *tmp;
    6482             :         size_t len;
    6483             : 
    6484             :         /* schame.table should be "schame"."table" */
    6485          42 :         table_copy = estrdup(table);
    6486          42 :         token = php_strtok_r(table_copy, ".", &tmp);
    6487          42 :         len = strlen(token);
    6488          42 :         if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) {
    6489           0 :                 smart_str_appendl(querystr, token, len);
    6490             :         } else {
    6491          42 :                 escaped = PGSQLescapeIdentifier(pg_link, token, len);
    6492          42 :                 smart_str_appends(querystr, escaped);
    6493          42 :                 PGSQLfree(escaped);
    6494             :         }
    6495          42 :         if (tmp && *tmp) {
    6496          15 :                 len = strlen(tmp);
    6497             :                 /* "schema"."table" format */
    6498          15 :                 if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) {
    6499           0 :                         smart_str_appendc(querystr, '.');
    6500           0 :                         smart_str_appendl(querystr, tmp, len);
    6501             :                 } else {
    6502          15 :                         escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
    6503          15 :                         smart_str_appendc(querystr, '.');
    6504          15 :                         smart_str_appends(querystr, escaped);
    6505          15 :                         PGSQLfree(escaped);
    6506             :                 }
    6507             :         }
    6508          42 :         efree(table_copy);
    6509          42 : }
    6510             : 
    6511             : /* {{{ php_pgsql_insert
    6512             :  */
    6513          19 : PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var_array, ulong opt, char **sql TSRMLS_DC)
    6514             : {
    6515          19 :         zval **val, *converted = NULL;
    6516             :         char buf[256];
    6517             :         char *fld, *tmp;
    6518          19 :         smart_str querystr = {0};
    6519          19 :         int key_type, ret = FAILURE;
    6520             :         uint fld_len;
    6521             :         ulong num_idx;
    6522             :         HashPosition pos;
    6523             : 
    6524             :         assert(pg_link != NULL);
    6525             :         assert(table != NULL);
    6526             :         assert(Z_TYPE_P(var_array) == IS_ARRAY);
    6527             : 
    6528          19 :         if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0) {
    6529           1 :                 smart_str_appends(&querystr, "INSERT INTO ");
    6530           1 :                 build_tablename(&querystr, pg_link, table);
    6531           1 :                 smart_str_appends(&querystr, " DEFAULT VALUES");
    6532             : 
    6533           1 :                 goto no_values;
    6534             :         }
    6535             : 
    6536             :         /* convert input array if needed */
    6537          18 :         if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) {
    6538          18 :                 MAKE_STD_ZVAL(converted);
    6539          18 :                 array_init(converted);
    6540          18 :                 if (php_pgsql_convert(pg_link, table, var_array, converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
    6541           1 :                         goto cleanup;
    6542             :                 }
    6543          17 :                 var_array = converted;
    6544             :         }
    6545             : 
    6546          17 :         smart_str_appends(&querystr, "INSERT INTO ");
    6547          17 :         build_tablename(&querystr, pg_link, table);
    6548          17 :         smart_str_appends(&querystr, " (");
    6549             : 
    6550          17 :         zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos);
    6551          69 :         while ((key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &fld,
    6552             :                                         &fld_len, &num_idx, 0, &pos)) != HASH_KEY_NON_EXISTENT) {
    6553          35 :                 if (key_type == HASH_KEY_IS_LONG) {
    6554           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects associative array for values to be inserted");
    6555           0 :                         goto cleanup;
    6556             :                 }
    6557          35 :                 if (opt & PGSQL_DML_ESCAPE) {
    6558           0 :                         tmp = PGSQLescapeIdentifier(pg_link, fld, fld_len);
    6559           0 :                         smart_str_appends(&querystr, tmp);
    6560           0 :                         PGSQLfree(tmp);
    6561             :                 } else {
    6562          35 :                         smart_str_appendl(&querystr, fld, fld_len - 1);
    6563             :                 }
    6564          35 :                 smart_str_appendc(&querystr, ',');
    6565          35 :                 zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos);
    6566             :         }
    6567          17 :         querystr.len--;
    6568          17 :         smart_str_appends(&querystr, ") VALUES (");
    6569             :         
    6570             :         /* make values string */
    6571          69 :         for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos);
    6572          52 :                  zend_hash_get_current_data_ex(Z_ARRVAL_P(var_array), (void **)&val, &pos) == SUCCESS;
    6573          35 :                  zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos)) {
    6574             :                 
    6575             :                 /* we can avoid the key_type check here, because we tested it in the other loop */
    6576          35 :                 switch(Z_TYPE_PP(val)) {
    6577             :                         case IS_STRING:
    6578           9 :                                 if (opt & PGSQL_DML_ESCAPE) {
    6579             :                                         size_t new_len;
    6580             :                                         char *tmp;
    6581           0 :                                         tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
    6582           0 :                                         new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), NULL);
    6583           0 :                                         smart_str_appendc(&querystr, '\'');
    6584           0 :                                         smart_str_appendl(&querystr, tmp, new_len);
    6585           0 :                                         smart_str_appendc(&querystr, '\'');
    6586           0 :                                         efree(tmp);
    6587             :                                 } else {
    6588           9 :                                         smart_str_appendl(&querystr, Z_STRVAL_PP(val), Z_STRLEN_PP(val));
    6589             :                                 }
    6590           9 :                                 break;
    6591             :                         case IS_LONG:
    6592          26 :                                 smart_str_append_long(&querystr, Z_LVAL_PP(val));
    6593          26 :                                 break;
    6594             :                         case IS_DOUBLE:
    6595           0 :                                 smart_str_appendl(&querystr, buf, snprintf(buf, sizeof(buf), "%F", Z_DVAL_PP(val)));
    6596           0 :                                 break;
    6597             :                         case IS_NULL:
    6598           0 :                                 smart_str_appendl(&querystr, "NULL", sizeof("NULL")-1);
    6599           0 :                                 break;
    6600             :                         default:
    6601           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expects scaler values. type = %d", Z_TYPE_PP(val));
    6602           0 :                                 goto cleanup;
    6603             :                                 break;
    6604             :                 }
    6605          35 :                 smart_str_appendc(&querystr, ',');
    6606             :         }
    6607             :         /* Remove the trailing "," */
    6608          17 :         querystr.len--;
    6609          17 :         smart_str_appends(&querystr, ");");
    6610             : 
    6611             : no_values:
    6612             : 
    6613          18 :         smart_str_0(&querystr);
    6614             : 
    6615          18 :         if ((opt & (PGSQL_DML_EXEC|PGSQL_DML_ASYNC)) &&
    6616           0 :                 do_exec(&querystr, PGRES_COMMAND_OK, pg_link, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == 0) {
    6617           0 :                 ret = SUCCESS;
    6618             :         }
    6619          18 :         else if (opt & PGSQL_DML_STRING) {
    6620          18 :                 ret = SUCCESS;
    6621             :         }
    6622             :         
    6623             : cleanup:
    6624          19 :         if (!(opt & PGSQL_DML_NO_CONV) && converted) {
    6625             :                 zval_dtor(converted);
    6626          18 :                 FREE_ZVAL(converted);
    6627             :         }
    6628          37 :         if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
    6629          18 :                 *sql = querystr.c;
    6630             :         }
    6631             :         else {
    6632           1 :                 smart_str_free(&querystr);
    6633             :         }
    6634          19 :         return ret;
    6635             : }
    6636             : /* }}} */
    6637             : 
    6638             : /* {{{ proto mixed pg_insert(resource db, string table, array values[, int options])
    6639             :    Insert values (filed=>value) to table */
    6640          19 : PHP_FUNCTION(pg_insert)
    6641             : {
    6642             :         zval *pgsql_link, *values;
    6643          19 :         char *table, *sql = NULL;
    6644             :         int table_len;
    6645          19 :         ulong option = PGSQL_DML_EXEC, return_sql;
    6646             :         PGconn *pg_link;
    6647             :         PGresult *pg_result;
    6648             :         ExecStatusType status;
    6649             :         pgsql_result_handle *pgsql_handle;
    6650          19 :         int id = -1, argc = ZEND_NUM_ARGS();
    6651             : 
    6652          19 :         if (zend_parse_parameters(argc TSRMLS_CC, "rsa|l",
    6653             :                                                           &pgsql_link, &table, &table_len, &values, &option) == FAILURE) {
    6654           0 :                 return;
    6655             :         }
    6656          19 :         if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) {
    6657           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
    6658           0 :                 RETURN_FALSE;
    6659             :         }
    6660             :         
    6661          19 :         ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    6662             : 
    6663          19 :         if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
    6664           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
    6665             :         }
    6666          19 :         return_sql = option & PGSQL_DML_STRING;
    6667          19 :         if (option & PGSQL_DML_EXEC) {
    6668             :                 /* return resource when executed */
    6669          17 :                 option = option & ~PGSQL_DML_EXEC;
    6670          17 :                 if (php_pgsql_insert(pg_link, table, values, option|PGSQL_DML_STRING, &sql TSRMLS_CC) == FAILURE) {
    6671           1 :                         RETURN_FALSE;
    6672             :                 }
    6673          16 :                 pg_result = PQexec(pg_link, sql);
    6674          16 :                 if ((PGG(auto_reset_persistent) & 2) && PQstatus(pg_link) != CONNECTION_OK) {
    6675           0 :                         PQclear(pg_result);
    6676           0 :                         PQreset(pg_link);
    6677           0 :                         pg_result = PQexec(pg_link, sql);
    6678             :                 }
    6679          16 :                 efree(sql);
    6680             : 
    6681          16 :                 if (pg_result) {
    6682          16 :                         status = PQresultStatus(pg_result);
    6683             :                 } else {
    6684           0 :                         status = (ExecStatusType) PQstatus(pg_link);
    6685             :                 }
    6686             : 
    6687          16 :                 switch (status) {
    6688             :                         case PGRES_EMPTY_QUERY:
    6689             :                         case PGRES_BAD_RESPONSE:
    6690             :                         case PGRES_NONFATAL_ERROR:
    6691             :                         case PGRES_FATAL_ERROR:
    6692           0 :                                 PHP_PQ_ERROR("Query failed: %s", pg_link);
    6693           0 :                                 PQclear(pg_result);
    6694           0 :                                 RETURN_FALSE;
    6695             :                                 break;
    6696             :                         case PGRES_COMMAND_OK: /* successful command that did not return rows */
    6697             :                         default:
    6698          16 :                                 if (pg_result) {
    6699          16 :                                         pgsql_handle = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
    6700          16 :                                         pgsql_handle->conn = pg_link;
    6701          16 :                                         pgsql_handle->result = pg_result;
    6702          16 :                                         pgsql_handle->row = 0;
    6703          16 :                                         ZEND_REGISTER_RESOURCE(return_value, pgsql_handle, le_result);
    6704          16 :                                         return;
    6705             :                                 } else {
    6706           0 :                                         PQclear(pg_result);
    6707           0 :                                         RETURN_FALSE;
    6708             :                                 }
    6709             :                         break;
    6710             :                 }
    6711           2 :         } else if (php_pgsql_insert(pg_link, table, values, option, &sql TSRMLS_CC) == FAILURE) {
    6712           0 :                 RETURN_FALSE;
    6713             :         }
    6714           2 :         if (return_sql) {
    6715           2 :                 RETURN_STRING(sql, 0);
    6716             :         }
    6717           0 :         RETURN_TRUE;
    6718             : }
    6719             : /* }}} */
    6720             : 
    6721          33 : static inline int build_assignment_string(PGconn *pg_link, smart_str *querystr, HashTable *ht, int where_cond, const char *pad, int pad_len, ulong opt TSRMLS_DC)
    6722             : {
    6723             :         HashPosition pos;
    6724             :         uint fld_len;
    6725             :         int key_type;
    6726             :         ulong num_idx;
    6727             :         char *fld, *tmp;
    6728             :         char buf[256];
    6729             :         zval **val;
    6730             : 
    6731         114 :         for (zend_hash_internal_pointer_reset_ex(ht, &pos);
    6732          81 :                  zend_hash_get_current_data_ex(ht, (void **)&val, &pos) == SUCCESS;
    6733          48 :                  zend_hash_move_forward_ex(ht, &pos)) {
    6734          48 :                  key_type = zend_hash_get_current_key_ex(ht, &fld, &fld_len, &num_idx, 0, &pos);
    6735          48 :                 if (key_type == HASH_KEY_IS_LONG) {
    6736           0 :                         php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects associative array for values to be inserted");
    6737           0 :                         return -1;
    6738             :                 }
    6739          48 :                 if (opt & PGSQL_DML_ESCAPE) {
    6740           5 :                         tmp = PGSQLescapeIdentifier(pg_link, fld, fld_len);
    6741           5 :                         smart_str_appends(querystr, tmp);
    6742           5 :                         PGSQLfree(tmp);
    6743             :                 } else {
    6744          43 :                         smart_str_appendl(querystr, fld, fld_len - 1);
    6745             :                 }
    6746          50 :                 if (where_cond && (Z_TYPE_PP(val) == IS_BOOL || (Z_TYPE_PP(val) == IS_STRING && !strcmp(Z_STRVAL_PP(val), "NULL")))) {
    6747           2 :                         smart_str_appends(querystr, " IS ");
    6748             :                 } else {
    6749          46 :                         smart_str_appendc(querystr, '=');
    6750             :                 }
    6751             : 
    6752          48 :                 switch(Z_TYPE_PP(val)) {
    6753             :                         case IS_STRING:
    6754          21 :                                 if (opt & PGSQL_DML_ESCAPE) {
    6755             :                                         size_t new_len;
    6756           5 :                                         tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
    6757           5 :                                         new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), NULL);
    6758           5 :                                         smart_str_appendc(querystr, '\'');
    6759           5 :                                         smart_str_appendl(querystr, tmp, new_len);
    6760           5 :                                         smart_str_appendc(querystr, '\'');
    6761           5 :                                         efree(tmp);
    6762             :                                 } else {
    6763          16 :                                         smart_str_appendl(querystr, Z_STRVAL_PP(val), Z_STRLEN_PP(val));
    6764             :                                 }
    6765          21 :                                 break;
    6766             :                         case IS_LONG:
    6767          27 :                                 smart_str_append_long(querystr, Z_LVAL_PP(val));
    6768          27 :                                 break;
    6769             :                         case IS_DOUBLE:
    6770           0 :                                 smart_str_appendl(querystr, buf, MIN(snprintf(buf, sizeof(buf), "%F", Z_DVAL_PP(val)), sizeof(buf)-1));
    6771           0 :                                 break;
    6772             :                         case IS_NULL:
    6773           0 :                                 smart_str_appendl(querystr, "NULL", sizeof("NULL")-1);
    6774           0 :                                 break;
    6775             :                         default:
    6776           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expects scaler values. type=%d", Z_TYPE_PP(val));
    6777           0 :                                 return -1;
    6778             :                 }
    6779          48 :                 smart_str_appendl(querystr, pad, pad_len);
    6780             :         }
    6781          33 :         querystr->len -= pad_len;
    6782             : 
    6783          33 :         return 0;
    6784             : }
    6785             : 
    6786             : /* {{{ php_pgsql_update
    6787             :  */
    6788           9 : PHP_PGSQL_API int php_pgsql_update(PGconn *pg_link, const char *table, zval *var_array, zval *ids_array, ulong opt, char **sql TSRMLS_DC) 
    6789             : {
    6790           9 :         zval *var_converted = NULL, *ids_converted = NULL;
    6791           9 :         smart_str querystr = {0};
    6792           9 :         int ret = FAILURE;
    6793             : 
    6794             :         assert(pg_link != NULL);
    6795             :         assert(table != NULL);
    6796             :         assert(Z_TYPE_P(var_array) == IS_ARRAY);
    6797             :         assert(Z_TYPE_P(ids_array) == IS_ARRAY);
    6798             :         assert(!(opt & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)));
    6799             : 
    6800          27 :         if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0
    6801          18 :                         || zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) {
    6802           0 :                 return FAILURE;
    6803             :         }
    6804             : 
    6805           9 :         if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) {
    6806           8 :                 MAKE_STD_ZVAL(var_converted);
    6807           8 :                 array_init(var_converted);
    6808           8 :                 if (php_pgsql_convert(pg_link, table, var_array, var_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
    6809           0 :                         goto cleanup;
    6810             :                 }
    6811           8 :                 var_array = var_converted;
    6812           8 :                 MAKE_STD_ZVAL(ids_converted);
    6813           8 :                 array_init(ids_converted);
    6814           8 :                 if (php_pgsql_convert(pg_link, table, ids_array, ids_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
    6815           0 :                         goto cleanup;
    6816             :                 }
    6817           8 :                 ids_array = ids_converted;
    6818             :         }
    6819             : 
    6820           9 :         smart_str_appends(&querystr, "UPDATE ");
    6821           9 :         build_tablename(&querystr, pg_link, table);
    6822           9 :         smart_str_appends(&querystr, " SET ");
    6823             : 
    6824           9 :         if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(var_array), 0, ",", 1, opt TSRMLS_CC))
    6825           0 :                 goto cleanup;
    6826             :         
    6827           9 :         smart_str_appends(&querystr, " WHERE ");
    6828             :         
    6829           9 :         if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt TSRMLS_CC))
    6830           0 :                 goto cleanup;
    6831             : 
    6832           9 :         smart_str_appendc(&querystr, ';');
    6833           9 :         smart_str_0(&querystr);
    6834             : 
    6835          14 :         if ((opt & PGSQL_DML_EXEC) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, opt TSRMLS_CC) == 0) {
    6836           5 :                 ret = SUCCESS;
    6837           4 :         } else if (opt & PGSQL_DML_STRING) {
    6838           4 :                 ret = SUCCESS;
    6839             :         }
    6840             : 
    6841             : cleanup:
    6842           9 :         if (var_converted) {
    6843             :                 zval_dtor(var_converted);
    6844           8 :                 FREE_ZVAL(var_converted);
    6845             :         }
    6846           9 :         if (ids_converted) {
    6847             :                 zval_dtor(ids_converted);
    6848           8 :                 FREE_ZVAL(ids_converted);
    6849             :         }
    6850          14 :         if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
    6851           5 :                 *sql = querystr.c;
    6852             :         }
    6853             :         else {
    6854           4 :                 smart_str_free(&querystr);
    6855             :         }
    6856           9 :         return ret;
    6857             : }
    6858             : /* }}} */
    6859             : 
    6860             : /* {{{ proto mixed pg_update(resource db, string table, array fields, array ids[, int options])
    6861             :    Update table using values (field=>value) and ids (id=>value) */
    6862           9 : PHP_FUNCTION(pg_update)
    6863             : {
    6864             :         zval *pgsql_link, *values, *ids;
    6865           9 :         char *table, *sql = NULL;
    6866             :         int table_len;
    6867           9 :         ulong option =  PGSQL_DML_EXEC;
    6868             :         PGconn *pg_link;
    6869           9 :         int id = -1, argc = ZEND_NUM_ARGS();
    6870             : 
    6871           9 :         if (zend_parse_parameters(argc TSRMLS_CC, "rsaa|l",
    6872             :                                                           &pgsql_link, &table, &table_len, &values, &ids, &option) == FAILURE) {
    6873           0 :                 return;
    6874             :         }
    6875           9 :         if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) {
    6876           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
    6877           0 :                 RETURN_FALSE;
    6878             :         }
    6879             :         
    6880           9 :         ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    6881             : 
    6882           9 :         if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
    6883           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
    6884             :         }
    6885           9 :         if (php_pgsql_update(pg_link, table, values, ids, option, &sql TSRMLS_CC) == FAILURE) {
    6886           0 :                 RETURN_FALSE;
    6887             :         }
    6888           9 :         if (option & PGSQL_DML_STRING) {
    6889           5 :                 RETURN_STRING(sql, 0);
    6890             :         }
    6891           4 :         RETURN_TRUE;
    6892             : }
    6893             : /* }}} */
    6894             : 
    6895             : /* {{{ php_pgsql_delete
    6896             :  */
    6897          12 : PHP_PGSQL_API int php_pgsql_delete(PGconn *pg_link, const char *table, zval *ids_array, ulong opt, char **sql TSRMLS_DC) 
    6898             : {
    6899          12 :         zval *ids_converted = NULL;
    6900          12 :         smart_str querystr = {0};
    6901          12 :         int ret = FAILURE;
    6902             : 
    6903             :         assert(pg_link != NULL);
    6904             :         assert(table != NULL);
    6905             :         assert(Z_TYPE_P(ids_array) == IS_ARRAY);
    6906             :         assert(!(opt & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)));
    6907             : 
    6908          12 :         if (zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) {
    6909           0 :                 return FAILURE;
    6910             :         }
    6911             : 
    6912          12 :         if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) {
    6913          11 :                 MAKE_STD_ZVAL(ids_converted);
    6914          11 :                 array_init(ids_converted);
    6915          11 :                 if (php_pgsql_convert(pg_link, table, ids_array, ids_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
    6916           2 :                         goto cleanup;
    6917             :                 }
    6918           9 :                 ids_array = ids_converted;
    6919             :         }
    6920             : 
    6921          10 :         smart_str_appends(&querystr, "DELETE FROM ");
    6922          10 :         build_tablename(&querystr, pg_link, table);
    6923          10 :         smart_str_appends(&querystr, " WHERE ");
    6924             : 
    6925          10 :         if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt TSRMLS_CC))
    6926           0 :                 goto cleanup;
    6927             : 
    6928          10 :         smart_str_appendc(&querystr, ';');
    6929          10 :         smart_str_0(&querystr);
    6930             : 
    6931          16 :         if ((opt & PGSQL_DML_EXEC) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, opt TSRMLS_CC) == 0) {
    6932           6 :                 ret = SUCCESS;
    6933           4 :         } else if (opt & PGSQL_DML_STRING) {
    6934           4 :                 ret = SUCCESS;
    6935             :         }
    6936             : 
    6937             : cleanup:
    6938          12 :         if (ids_converted) {
    6939             :                 zval_dtor(ids_converted);
    6940          11 :                 FREE_ZVAL(ids_converted);
    6941             :         }
    6942          17 :         if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
    6943           5 :                 *sql = querystr.c;
    6944             :         }
    6945             :         else {
    6946           7 :                 smart_str_free(&querystr);
    6947             :         }
    6948          12 :         return ret;
    6949             : }
    6950             : /* }}} */
    6951             : 
    6952             : /* {{{ proto mixed pg_delete(resource db, string table, array ids[, int options])
    6953             :    Delete records has ids (id=>value) */
    6954          12 : PHP_FUNCTION(pg_delete)
    6955             : {
    6956             :         zval *pgsql_link, *ids;
    6957          12 :         char *table, *sql = NULL;
    6958             :         int table_len;
    6959          12 :         ulong option = PGSQL_DML_EXEC;
    6960             :         PGconn *pg_link;
    6961          12 :         int id = -1, argc = ZEND_NUM_ARGS();
    6962             : 
    6963          12 :         if (zend_parse_parameters(argc TSRMLS_CC, "rsa|l",
    6964             :                                                           &pgsql_link, &table, &table_len, &ids, &option) == FAILURE) {
    6965           0 :                 return;
    6966             :         }
    6967          12 :         if (option & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) {
    6968           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
    6969           0 :                 RETURN_FALSE;
    6970             :         }
    6971             :         
    6972          12 :         ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    6973             : 
    6974          12 :         if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
    6975           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
    6976             :         }
    6977          12 :         if (php_pgsql_delete(pg_link, table, ids, option, &sql TSRMLS_CC) == FAILURE) {
    6978           2 :                 RETURN_FALSE;
    6979             :         }
    6980          10 :         if (option & PGSQL_DML_STRING) {
    6981           5 :                 RETURN_STRING(sql, 0);
    6982             :         }
    6983           5 :         RETURN_TRUE;
    6984             : } 
    6985             : /* }}} */
    6986             : 
    6987             : /* {{{ php_pgsql_result2array
    6988             :  */
    6989          11 : PHP_PGSQL_API int php_pgsql_result2array(PGresult *pg_result, zval *ret_array TSRMLS_DC) 
    6990             : {
    6991             :         zval *row;
    6992             :         char *field_name;
    6993             :         size_t num_fields;
    6994             :         int pg_numrows, pg_row;
    6995             :         uint i;
    6996             :         assert(Z_TYPE_P(ret_array) == IS_ARRAY);
    6997             : 
    6998          11 :         if ((pg_numrows = PQntuples(pg_result)) <= 0) {
    6999           0 :                 return FAILURE;
    7000             :         }
    7001          26 :         for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
    7002          15 :                 MAKE_STD_ZVAL(row);
    7003          15 :                 array_init(row);
    7004          15 :                 add_index_zval(ret_array, pg_row, row);
    7005          50 :                 for (i = 0, num_fields = PQnfields(pg_result); i < num_fields; i++) {
    7006          35 :                         if (PQgetisnull(pg_result, pg_row, i)) {
    7007           6 :                                 field_name = PQfname(pg_result, i);
    7008           6 :                                 add_assoc_null(row, field_name);
    7009             :                         } else {
    7010          29 :                                 char *element = PQgetvalue(pg_result, pg_row, i);
    7011          29 :                                 if (element) {
    7012             :                                         char *data;
    7013             :                                         size_t data_len;
    7014          29 :                                         const size_t element_len = strlen(element);
    7015             : 
    7016          29 :                                         data = safe_estrndup(element, element_len);
    7017          29 :                                         data_len = element_len;
    7018             :                                         
    7019          29 :                                         field_name = PQfname(pg_result, i);
    7020          29 :                                         add_assoc_stringl(row, field_name, data, data_len, 0);
    7021             :                                 }
    7022             :                         }
    7023             :                 }
    7024             :         }
    7025          11 :         return SUCCESS;
    7026             : }
    7027             : /* }}} */
    7028             : 
    7029             : /* {{{ php_pgsql_select
    7030             :  */
    7031           7 : PHP_PGSQL_API int php_pgsql_select(PGconn *pg_link, const char *table, zval *ids_array, zval *ret_array, ulong opt, char **sql TSRMLS_DC)
    7032             : {
    7033           7 :         zval *ids_converted = NULL;
    7034           7 :         smart_str querystr = {0};
    7035           7 :         int ret = FAILURE;
    7036             :         PGresult *pg_result;
    7037             : 
    7038             :         assert(pg_link != NULL);
    7039             :         assert(table != NULL);
    7040             :         assert(Z_TYPE_P(ids_array) == IS_ARRAY);
    7041             :         assert(Z_TYPE_P(ret_array) == IS_ARRAY);
    7042             :         assert(!(opt & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)));
    7043             : 
    7044           7 :         if (zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) {
    7045           0 :                 return FAILURE;
    7046             :         }
    7047             : 
    7048           7 :         if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) {
    7049           7 :                 MAKE_STD_ZVAL(ids_converted);
    7050           7 :                 array_init(ids_converted);
    7051           7 :                 if (php_pgsql_convert(pg_link, table, ids_array, ids_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
    7052           2 :                         goto cleanup;
    7053             :                 }
    7054           5 :                 ids_array = ids_converted;
    7055             :         }
    7056             : 
    7057           5 :         smart_str_appends(&querystr, "SELECT * FROM ");
    7058           5 :         build_tablename(&querystr, pg_link, table);
    7059           5 :         smart_str_appends(&querystr, " WHERE ");
    7060             : 
    7061           5 :         if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt TSRMLS_CC))
    7062           0 :                 goto cleanup;
    7063             : 
    7064           5 :         smart_str_appendc(&querystr, ';');
    7065           5 :         smart_str_0(&querystr);
    7066             : 
    7067           5 :         pg_result = PQexec(pg_link, querystr.c);
    7068           5 :         if (PQresultStatus(pg_result) == PGRES_TUPLES_OK) {
    7069           5 :                 ret = php_pgsql_result2array(pg_result, ret_array TSRMLS_CC);
    7070             :         } else {
    7071           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to execute '%s'", querystr.c);
    7072             :         }
    7073           5 :         PQclear(pg_result);
    7074             : 
    7075             : cleanup:
    7076           7 :         if (ids_converted) {
    7077             :                 zval_dtor(ids_converted);
    7078           7 :                 FREE_ZVAL(ids_converted);
    7079             :         }
    7080           8 :         if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
    7081           1 :                 *sql = querystr.c;
    7082             :         }
    7083             :         else {
    7084           6 :                 smart_str_free(&querystr);
    7085             :         }
    7086           7 :         return ret;
    7087             : }
    7088             : /* }}} */
    7089             : 
    7090             : /* {{{ proto mixed pg_select(resource db, string table, array ids[, int options])
    7091             :    Select records that has ids (id=>value) */
    7092           7 : PHP_FUNCTION(pg_select)
    7093             : {
    7094             :         zval *pgsql_link, *ids;
    7095           7 :         char *table, *sql = NULL;
    7096             :         int table_len;
    7097           7 :         ulong option = PGSQL_DML_EXEC;
    7098             :         PGconn *pg_link;
    7099           7 :         int id = -1, argc = ZEND_NUM_ARGS();
    7100             : 
    7101           7 :         if (zend_parse_parameters(argc TSRMLS_CC, "rsa|l",
    7102             :                                                           &pgsql_link, &table, &table_len, &ids, &option) == FAILURE) {
    7103           0 :                 return;
    7104             :         }
    7105           7 :         if (option & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) {
    7106           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
    7107           0 :                 RETURN_FALSE;
    7108             :         }
    7109             :         
    7110           7 :         ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
    7111             : 
    7112           7 :         if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
    7113           0 :                 php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
    7114             :         }
    7115           7 :         array_init(return_value);
    7116           7 :         if (php_pgsql_select(pg_link, table, ids, return_value, option, &sql TSRMLS_CC) == FAILURE) {
    7117             :                 zval_dtor(return_value);
    7118           2 :                 RETURN_FALSE;
    7119             :         }
    7120           5 :         if (option & PGSQL_DML_STRING) {
    7121             :                 zval_dtor(return_value);
    7122           1 :                 RETURN_STRING(sql, 0);
    7123             :         }
    7124           4 :         return;
    7125             : }
    7126             : /* }}} */
    7127             : 
    7128             : #endif
    7129             : 
    7130             : /*
    7131             :  * Local variables:
    7132             :  * tab-width: 4
    7133             :  * c-basic-offset: 4
    7134             :  * End:
    7135             :  * vim600: sw=4 ts=4 fdm=marker
    7136             :  * vim<600: sw=4 ts=4
    7137             :  */

Generated by: LCOV version 1.10

Generated at Tue, 22 Jul 2014 01:33:16 +0000 (38 hours ago)

Copyright © 2005-2014 The PHP Group
All rights reserved.