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: 1701 2788 61.0 %
Date: 2014-12-13 Functions: 126 138 91.3 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Sat, 13 Dec 2014 06:16:19 +0000 (7 days ago)

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