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: 1749 2835 61.7 %
Date: 2016-09-27 Functions: 125 137 91.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Tue, 27 Sep 2016 10:26:04 +0000 (47 hours ago)

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