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

Generated by: LCOV version 1.10

Generated at Sun, 29 May 2016 00:48:30 +0000 (3 days ago)

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