MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file ibase.php

Documentation is available at ibase.php

  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5                                                 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
  7. // | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |
  8. // | All rights reserved.                                                 |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  11. // | API as well as database abstraction for PHP applications.            |
  12. // | This LICENSE is in the BSD license style.                            |
  13. // |                                                                      |
  14. // | Redistribution and use in source and binary forms, with or without   |
  15. // | modification, are permitted provided that the following conditions   |
  16. // | are met:                                                             |
  17. // |                                                                      |
  18. // | Redistributions of source code must retain the above copyright       |
  19. // | notice, this list of conditions and the following disclaimer.        |
  20. // |                                                                      |
  21. // | Redistributions in binary form must reproduce the above copyright    |
  22. // | notice, this list of conditions and the following disclaimer in the  |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // |                                                                      |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission.                                                  |
  29. // |                                                                      |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  41. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lorenzo Alberton <l.alberton@quipo.it>                       |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: ibase.php 328145 2012-10-25 20:20:57Z danielc $
  47.  
  48. /**
  49.  * MDB2 FireBird/InterBase driver
  50.  *
  51.  * @package MDB2
  52.  * @category Database
  53.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  54.  */
  55. class MDB2_Driver_ibase extends MDB2_Driver_Common
  56. {
  57.     // {{{ properties
  58.  
  59.     var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
  60.  
  61.     var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => false);
  62.  
  63.     var $transaction_id = 0;
  64.  
  65.     var $query_parameters = array();
  66.  
  67.     var $query_parameter_values = array();
  68.  
  69.     // }}}
  70.     // {{{ constructor
  71.  
  72.     /**
  73.      * Constructor
  74.      */
  75.     function __construct()
  76.     {
  77.         parent::__construct();
  78.  
  79.         $this->phptype  = 'ibase';
  80.         $this->dbsyntax = 'ibase';
  81.  
  82.         $this->supported['sequences'] = true;
  83.         $this->supported['indexes'] = true;
  84.         $this->supported['affected_rows'] = function_exists('ibase_affected_rows');
  85.         $this->supported['summary_functions'] = true;
  86.         $this->supported['order_by_text'] = true;
  87.         $this->supported['transactions'] = true;
  88.         $this->supported['savepoints'] = true;
  89.         $this->supported['current_id'] = true;
  90.         $this->supported['limit_queries'] = 'emulated';
  91.         $this->supported['LOBs'] = true;
  92.         $this->supported['replace'] = false;
  93.         $this->supported['sub_selects'] = true;
  94.         $this->supported['triggers'] = true;
  95.         $this->supported['auto_increment'] = true;
  96.         $this->supported['primary_key'] = true;
  97.         $this->supported['result_introspection'] = true;
  98.         $this->supported['prepared_statements'] = true;
  99.         $this->supported['identifier_quoting'] = true;
  100.         $this->supported['pattern_escaping'] = true;
  101.         $this->supported['new_link'] = false;
  102.  
  103.         $this->options['DBA_username'] = false;
  104.         $this->options['DBA_password'] = false;
  105.         $this->options['database_path'] = '';
  106.         $this->options['database_extension'] = '.gdb';
  107.         $this->options['server_version'] = '';
  108.         $this->options['max_identifiers_length'] = 31;
  109.     }
  110.  
  111.     // }}}
  112.     // {{{ errorInfo()
  113.  
  114.     /**
  115.      * This method is used to collect information about an error
  116.      *
  117.      * @param integer $error 
  118.      * @return array 
  119.      * @access public
  120.      */
  121.     function errorInfo($error = null)
  122.     {
  123.         $native_msg = @ibase_errmsg();
  124.  
  125.         if (function_exists('ibase_errcode')) {
  126.             $native_code = @ibase_errcode();
  127.         } else {
  128.             // memo for the interbase php module hackers: we need something similar
  129.             // to mysql_errno() to retrieve error codes instead of this ugly hack
  130.             if (preg_match('/^([^0-9\-]+)([0-9\-]+)\s+(.*)$/', $native_msg, $m)) {
  131.                 $native_code = (int)$m[2];
  132.             } else {
  133.                 $native_code = null;
  134.             }
  135.         }
  136.         if (null === $error) {
  137.             $error = MDB2_ERROR;
  138.             if ($native_code) {
  139.                 // try to interpret Interbase error code (that's why we need ibase_errno()
  140.                 // in the interbase module to return the real error code)
  141.                 switch ($native_code) {
  142.                 case -204:
  143.                     if (isset($m[3]) && is_int(strpos($m[3], 'Table unknown'))) {
  144.                         $errno = MDB2_ERROR_NOSUCHTABLE;
  145.                     }
  146.                 break;
  147.                 default:
  148.                     static $ecode_map;
  149.                     if (empty($ecode_map)) {
  150.                         $ecode_map = array(
  151.                             -104 => MDB2_ERROR_SYNTAX,
  152.                             -150 => MDB2_ERROR_ACCESS_VIOLATION,
  153.                             -151 => MDB2_ERROR_ACCESS_VIOLATION,
  154.                             -155 => MDB2_ERROR_NOSUCHTABLE,
  155.                             -157 => MDB2_ERROR_NOSUCHFIELD,
  156.                             -158 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  157.                             -170 => MDB2_ERROR_MISMATCH,
  158.                             -171 => MDB2_ERROR_MISMATCH,
  159.                             -172 => MDB2_ERROR_INVALID,
  160.                             // -204 =>  // Covers too many errors, need to use regex on msg
  161.                             -205 => MDB2_ERROR_NOSUCHFIELD,
  162.                             -206 => MDB2_ERROR_NOSUCHFIELD,
  163.                             -208 => MDB2_ERROR_INVALID,
  164.                             -219 => MDB2_ERROR_NOSUCHTABLE,
  165.                             -297 => MDB2_ERROR_CONSTRAINT,
  166.                             -303 => MDB2_ERROR_INVALID,
  167.                             -413 => MDB2_ERROR_INVALID_NUMBER,
  168.                             -530 => MDB2_ERROR_CONSTRAINT,
  169.                             -551 => MDB2_ERROR_ACCESS_VIOLATION,
  170.                             -552 => MDB2_ERROR_ACCESS_VIOLATION,
  171.                             // -607 =>  // Covers too many errors, need to use regex on msg
  172.                             -625 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  173.                             -803 => MDB2_ERROR_CONSTRAINT,
  174.                             -804 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  175.                             // -902 =>  // Covers too many errors, need to use regex on msg
  176.                             -904 => MDB2_ERROR_CONNECT_FAILED,
  177.                             -922 => MDB2_ERROR_NOSUCHDB,
  178.                             -923 => MDB2_ERROR_CONNECT_FAILED,
  179.                             -924 => MDB2_ERROR_CONNECT_FAILED
  180.                         );
  181.                     }
  182.                     if (isset($ecode_map[$native_code])) {
  183.                         $error = $ecode_map[$native_code];
  184.                     }
  185.                     break;
  186.                 }
  187.             } else {
  188.                 static $error_regexps;
  189.                 if (!isset($error_regexps)) {
  190.                     $error_regexps = array(
  191.                         '/generator .* is not defined/'
  192.                             => MDB2_ERROR_SYNTAX,  // for compat. w ibase_errcode()
  193.                         '/table.*(not exist|not found|unknown)/i'
  194.                             => MDB2_ERROR_NOSUCHTABLE,
  195.                         '/table .* already exists/i'
  196.                             => MDB2_ERROR_ALREADY_EXISTS,
  197.                         '/unsuccessful metadata update .* failed attempt to store duplicate value/i'
  198.                             => MDB2_ERROR_ALREADY_EXISTS,
  199.                         '/unsuccessful metadata update .* not found/i'
  200.                             => MDB2_ERROR_NOT_FOUND,
  201.                         '/validation error for column .* value "\*\*\* null/i'
  202.                             => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  203.                         '/violation of [\w ]+ constraint/i'
  204.                             => MDB2_ERROR_CONSTRAINT,
  205.                         '/conversion error from string/i'
  206.                             => MDB2_ERROR_INVALID_NUMBER,
  207.                         '/no permission for/i'
  208.                             => MDB2_ERROR_ACCESS_VIOLATION,
  209.                         '/arithmetic exception, numeric overflow, or string truncation/i'
  210.                             => MDB2_ERROR_INVALID,
  211.                         '/feature is not supported/i'
  212.                             => MDB2_ERROR_NOT_CAPABLE,
  213.                     );
  214.                 }
  215.                 foreach ($error_regexps as $regexp => $code) {
  216.                     if (preg_match($regexp, $native_msg, $m)) {
  217.                         $error = $code;
  218.                         break;
  219.                     }
  220.                 }
  221.             }
  222.         }
  223.         return array($error, $native_code, $native_msg);
  224.     }
  225.     // {{{ escape()
  226.  
  227.     /**
  228.      * Quotes a string so it can be safely used in a query. It will quote
  229.      * the text so it can safely be used within a query.
  230.      *
  231.      * @param   string  the input string to quote
  232.      * @param   bool    escape wildcards
  233.      *
  234.      * @return  string  quoted string
  235.      *
  236.      * @access  public
  237.      */
  238.     function escape($text, $escape_wildcards = false)
  239.     {
  240.         //Remove a NULL-character (may break queries when inserted):
  241.         $text = str_replace("\x00", '', $text);
  242.         
  243.         return parent::escape($text, $escape_wildcards);
  244.     }
  245.  
  246.     // }}}
  247.     // }}}
  248.     // {{{ quoteIdentifier()
  249.  
  250.     /**
  251.      * Delimited identifiers are a nightmare with InterBase, so they're disabled
  252.      *
  253.      * @param string $str  identifier name to be quoted
  254.      * @param bool   $check_option  check the 'quote_identifier' option
  255.      *
  256.      * @return string  quoted identifier string
  257.      *
  258.      * @access public
  259.      */
  260.     function quoteIdentifier($str, $check_option = false)
  261.     {
  262.         if ($check_option && !$this->options['quote_identifier']) {
  263.             return $str;
  264.         }
  265.  
  266.         return parent::quoteIdentifier(strtoupper($str), $check_option);
  267.     }
  268.  
  269.     // }}}
  270.     // {{{ getConnection()
  271.  
  272.     /**
  273.      * Returns a native connection
  274.      *
  275.      * @return  mixed   a valid MDB2 connection object,
  276.      *                   or a MDB2 error object on error
  277.      * @access  public
  278.      */
  279.     function getConnection()
  280.     {
  281.         $result = $this->connect();
  282.         if (MDB2::isError($result)) {
  283.             return $result;
  284.         }
  285.         if ($this->in_transaction) {
  286.             return $this->transaction_id;
  287.         }
  288.         return $this->connection;
  289.     }
  290.  
  291.     // }}}
  292.     // {{{ beginTransaction()
  293.  
  294.     /**
  295.      * Start a transaction or set a savepoint.
  296.      *
  297.      * @param   string  name of a savepoint to set
  298.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  299.      *
  300.      * @access  public
  301.      */
  302.     function beginTransaction($savepoint = null)
  303.     {
  304.         $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  305.         if (null !== $savepoint) {
  306.             if (!$this->in_transaction) {
  307.                 return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  308.                     'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  309.             }
  310.             $query = 'SAVEPOINT '.$savepoint;
  311.             return $this->_doQuery($query, true);
  312.         }
  313.         if ($this->in_transaction) {
  314.             return MDB2_OK;  //nothing to do
  315.         }
  316.         $connection = $this->getConnection();
  317.         if (MDB2::isError($connection)) {
  318.             return $connection;
  319.         }
  320.         $result = @ibase_trans(IBASE_DEFAULT, $connection);
  321.         if (!$result) {
  322.             return $this->raiseError(null, null, null,
  323.                 'could not start a transaction', __FUNCTION__);
  324.         }
  325.         $this->transaction_id = $result;
  326.         $this->in_transaction = true;
  327.         return MDB2_OK;
  328.     }
  329.  
  330.     // }}}
  331.     // {{{ commit()
  332.  
  333.     /**
  334.      * Commit the database changes done during a transaction that is in
  335.      * progress or release a savepoint. This function may only be called when
  336.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  337.      * transaction is implicitly started after committing the pending changes.
  338.      *
  339.      * @param   string  name of a savepoint to release
  340.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  341.      *
  342.      * @access  public
  343.      */
  344.     function commit($savepoint = null)
  345.     {
  346.         $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  347.         if (!$this->in_transaction) {
  348.             return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  349.                 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  350.         }
  351.         if (null !== $savepoint) {
  352.             $query = 'RELEASE SAVEPOINT '.$savepoint;
  353.             return $this->_doQuery($query, true);
  354.         }
  355.  
  356.         if (!@ibase_commit($this->transaction_id)) {
  357.             return $this->raiseError(null, null, null,
  358.                 'could not commit a transaction', __FUNCTION__);
  359.         }
  360.         $this->in_transaction = false;
  361.         $this->transaction_id = 0;
  362.         return MDB2_OK;
  363.     }
  364.  
  365.     // }}}
  366.     // {{{ rollback()
  367.  
  368.     /**
  369.      * Cancel any database changes done during a transaction or since a specific
  370.      * savepoint that is in progress. This function may only be called when
  371.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  372.      * transaction is implicitly started after canceling the pending changes.
  373.      *
  374.      * @param   string  name of a savepoint to rollback to
  375.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  376.      *
  377.      * @access  public
  378.      */
  379.     function rollback($savepoint = null)
  380.     {
  381.         $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  382.         if (!$this->in_transaction) {
  383.             return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  384.                 'rollback cannot be done changes are auto committed', __FUNCTION__);
  385.         }
  386.         if (null !== $savepoint) {
  387.             $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  388.             return $this->_doQuery($query, true);
  389.         }
  390.  
  391.         if ($this->transaction_id && !@ibase_rollback($this->transaction_id)) {
  392.             return $this->raiseError(null, null, null,
  393.                 'Could not rollback a pending transaction: '.@ibase_errmsg(), __FUNCTION__);
  394.         }
  395.         $this->in_transaction = false;
  396.         $this->transaction_id = 0;
  397.         return MDB2_OK;
  398.     }
  399.  
  400.     // }}}
  401.     // {{{ setTransactionIsolation()
  402.  
  403.     /**
  404.      * Set the transacton isolation level.
  405.      *
  406.      * @param   string  standard isolation level (SQL-92)
  407.      *                   READ UNCOMMITTED (allows dirty reads)
  408.      *                   READ COMMITTED (prevents dirty reads)
  409.      *                   REPEATABLE READ (prevents nonrepeatable reads)
  410.      *                   SERIALIZABLE (prevents phantom reads)
  411.      * @param   array some transaction options:
  412.      *                   'wait' => 'WAIT' | 'NO WAIT'
  413.      *                   'rw'   => 'READ WRITE' | 'READ ONLY'
  414.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  415.      *
  416.      * @access  public
  417.      * @since   2.1.1
  418.      */
  419.     function setTransactionIsolation($isolation, $options = array())
  420.     {
  421.         $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  422.         switch ($isolation) {
  423.         case 'READ UNCOMMITTED':
  424.             $ibase_isolation = 'READ COMMITTED RECORD_VERSION';
  425.             break;
  426.         case 'READ COMMITTED':
  427.             $ibase_isolation = 'READ COMMITTED NO RECORD_VERSION';
  428.             break;
  429.         case 'REPEATABLE READ':
  430.             $ibase_isolation = 'SNAPSHOT';
  431.             break;
  432.         case 'SERIALIZABLE':
  433.             $ibase_isolation = 'SNAPSHOT TABLE STABILITY';
  434.             break;
  435.         default:
  436.             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  437.                 'isolation level is not supported: '.$isolation, __FUNCTION__);
  438.         }
  439.  
  440.         if (!empty($options['wait'])) {
  441.             switch ($options['wait']) {
  442.             case 'WAIT':
  443.             case 'NO WAIT':
  444.                 $wait = $options['wait'];
  445.                 break;
  446.             default:
  447.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  448.                     'wait option is not supported: '.$options['wait'], __FUNCTION__);
  449.             }
  450.         }
  451.  
  452.         if (!empty($options['rw'])) {
  453.             switch ($options['rw']) {
  454.             case 'READ ONLY':
  455.             case 'READ WRITE':
  456.                 $rw = $options['rw'];
  457.                 break;
  458.             default:
  459.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  460.                     'rw option is not supported: '.$options['rw'], __FUNCTION__);
  461.             }
  462.         }
  463.  
  464.         $query = "SET TRANSACTION $rw $wait ISOLATION LEVEL $ibase_isolation";
  465.         return $this->_doQuery($query, true);
  466.     }
  467.  
  468.     // }}}
  469.     // {{{ getDatabaseFile($database_name)
  470.  
  471.     /**
  472.      * Builds the string with path+dbname+extension
  473.      *
  474.      * @return string full database path+file
  475.      * @access protected
  476.      */
  477.     function _getDatabaseFile($database_name)
  478.     {
  479.         if ($database_name == '') {
  480.             return $database_name;
  481.         }
  482.         $ret = $this->options['database_path'] . $database_name;
  483.         if (!preg_match('/\.([fg]db|ib)$/i', $database_name)) {
  484.             $ret .= $this->options['database_extension'];
  485.         }
  486.         return $ret;
  487.     }
  488.  
  489.     // }}}
  490.     // {{{ _doConnect()
  491.  
  492.     /**
  493.      * Does the grunt work of connecting to the database
  494.      *
  495.      * @return mixed connection resource on success, MDB2 Error Object on failure
  496.      * @access protected
  497.      */
  498.     function _doConnect($username, $password, $database_name, $persistent = false)
  499.     {
  500.         if (!extension_loaded('interbase')) {
  501.             return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  502.                 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  503.         }
  504.  
  505.         $database_file = $this->_getDatabaseFile($database_name);
  506.         $dbhost  = $this->dsn['hostspec'] ?
  507.             ($this->dsn['hostspec'].':'.$database_file) : $database_file;
  508.  
  509.         $params = array();
  510.         $params[] = $dbhost;
  511.         $params[] = !empty($username) ? $username : null;
  512.         $params[] = !empty($password) ? $password : null;
  513.         $params[] = isset($this->dsn['charset']) ? $this->dsn['charset'] : null;
  514.         $params[] = isset($this->dsn['buffers']) ? $this->dsn['buffers'] : null;
  515.         $params[] = isset($this->dsn['dialect']) ? $this->dsn['dialect'] : null;
  516.         $params[] = isset($this->dsn['role'])    ? $this->dsn['role'] : null;
  517.  
  518.         $connect_function = $persistent ? 'ibase_pconnect' : 'ibase_connect';
  519.         $connection = @call_user_func_array($connect_function, $params);
  520.         if ($connection <= 0) {
  521.             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  522.                 'unable to establish a connection', __FUNCTION__);
  523.         }
  524.  
  525.        if (empty($this->dsn['disable_iso_date'])) {
  526.             if (function_exists('ibase_timefmt')) {
  527.                 @ibase_timefmt("%Y-%m-%d %H:%M:%S", IBASE_TIMESTAMP);
  528.                 @ibase_timefmt("%Y-%m-%d", IBASE_DATE);
  529.             } else {
  530.                 @ini_set("ibase.timestampformat", "%Y-%m-%d %H:%M:%S");
  531.                 //@ini_set("ibase.timeformat", "%H:%M:%S");
  532.                 @ini_set("ibase.dateformat", "%Y-%m-%d");
  533.             }
  534.        }
  535.  
  536.         return $connection;
  537.     }
  538.  
  539.     // }}}
  540.     // {{{ connect()
  541.  
  542.     /**
  543.      * Connect to the database
  544.      *
  545.      * @return true on success, MDB2 Error Object on failure
  546.      * @access public
  547.      */
  548.     function connect()
  549.     {
  550.         $database_file = $this->_getDatabaseFile($this->database_name);
  551.         if (is_resource($this->connection)) {
  552.             //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  553.             if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  554.                 && $this->connected_database_name == $database_file
  555.                 && $this->opened_persistent == $this->options['persistent']
  556.             ) {
  557.                 return MDB2_OK;
  558.             }
  559.             $this->disconnect(false);
  560.         }
  561.  
  562.         if (empty($this->database_name)) {
  563.             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  564.             'unable to establish a connection', __FUNCTION__);
  565.         }
  566.  
  567.         $connection = $this->_doConnect($this->dsn['username'],
  568.                                         $this->dsn['password'],
  569.                                         $this->database_name,
  570.                                         $this->options['persistent']);
  571.         if (MDB2::isError($connection)) {
  572.             return $connection;
  573.         }
  574.         $this->connection =& $connection;
  575.         $this->connected_dsn = $this->dsn;
  576.         $this->connected_database_name = $database_file;
  577.         $this->opened_persistent = $this->options['persistent'];
  578.         $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  579.         $this->supported['limit_queries'] = ($this->dbsyntax == 'firebird') ? true : 'emulated';
  580.  
  581.         return MDB2_OK;
  582.     }
  583.  
  584.     // }}}
  585.     // {{{ databaseExists()
  586.  
  587.     /**
  588.      * check if given database name is exists?
  589.      *
  590.      * @param string $name    name of the database that should be checked
  591.      *
  592.      * @return mixed true/false on success, a MDB2 error on failure
  593.      * @access public
  594.      */
  595.     function databaseExists($name)
  596.     {
  597.         $database_file = $this->_getDatabaseFile($name);
  598.         $result = file_exists($database_file);
  599.         return $result;
  600.     }
  601.  
  602.     // }}}
  603.     // {{{ disconnect()
  604.  
  605.     /**
  606.      * Log out and disconnect from the database.
  607.      *
  608.      * @param  boolean $force if the disconnect should be forced even if the
  609.      *                         connection is opened persistently
  610.      * @return mixed true on success, false if not connected and error
  611.      *                object on error
  612.      * @access public
  613.      */
  614.     function disconnect($force = true)
  615.     {
  616.         if (is_resource($this->connection)) {
  617.             if ($this->in_transaction) {
  618.                 $dsn = $this->dsn;
  619.                 $database_name = $this->database_name;
  620.                 $persistent = $this->options['persistent'];
  621.                 $this->dsn = $this->connected_dsn;
  622.                 $this->database_name = $this->connected_database_name;
  623.                 $this->options['persistent'] = $this->opened_persistent;
  624.                 $this->rollback();
  625.                 $this->dsn = $dsn;
  626.                 $this->database_name = $database_name;
  627.                 $this->options['persistent'] = $persistent;
  628.             }
  629.  
  630.             if (!$this->opened_persistent || $force) {
  631.                 $ok = @ibase_close($this->connection);
  632.                 if (!$ok) {
  633.                     return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  634.                            null, null, null, __FUNCTION__);
  635.                 }
  636.             }
  637.         } else {
  638.             return false;
  639.         }
  640.         return parent::disconnect($force);
  641.     }
  642.  
  643.     // }}}
  644.     // {{{ standaloneQuery()
  645.  
  646.     /**
  647.      * execute a query as DBA
  648.      *
  649.      * @param string $query the SQL query
  650.      * @param mixed   $types  array that contains the types of the columns in
  651.      *                         the result set
  652.      * @param boolean $is_manip  if the query is a manipulation query
  653.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  654.      * @access public
  655.      */
  656.     function standaloneQuery($query, $types = null, $is_manip = false)
  657.     {
  658.         $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  659.         $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  660.         $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
  661.         if (MDB2::isError($connection)) {
  662.             return $connection;
  663.         }
  664.  
  665.         $offset = $this->offset;
  666.         $limit = $this->limit;
  667.         $this->offset = $this->limit = 0;
  668.         $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  669.  
  670.         $result = $this->_doQuery($query, $is_manip, $connection);
  671.         if (!MDB2::isError($result)) {
  672.             $result = $this->_affectedRows($connection, $result);
  673.         }
  674.  
  675.         @ibase_close($connection);
  676.         return $result;
  677.     }
  678.  
  679.     // }}}
  680.     // {{{ _doQuery()
  681.  
  682.     /**
  683.      * Execute a query
  684.      * @param string $query  query
  685.      * @param boolean $is_manip  if the query is a manipulation query
  686.      * @param resource $connection 
  687.      * @param string $database_name 
  688.      * @return result or error object
  689.      * @access protected
  690.      */
  691.     function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  692.     {
  693.         $this->last_query = $query;
  694.         $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  695.         if ($result) {
  696.             if (MDB2::isError($result)) {
  697.                 return $result;
  698.             }
  699.             $query = $result;
  700.         }
  701.         if ($this->getOption('disable_query')) {
  702.             if ($is_manip) {
  703.                 return 0;
  704.             }
  705.             return null;
  706.         }
  707.  
  708.         if (null === $connection) {
  709.             $connection = $this->getConnection();
  710.             if (MDB2::isError($connection)) {
  711.                 return $connection;
  712.             }
  713.         }
  714.         $result = @ibase_query($connection, $query);
  715.  
  716.         if (false === $result) {
  717.             $err = $this->raiseError(null, null, null,
  718.                 'Could not execute statement', __FUNCTION__);
  719.             return $err;
  720.         }
  721.  
  722.         $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  723.         return $result;
  724.     }
  725.  
  726.     // }}}
  727.     // {{{ _affectedRows()
  728.  
  729.     /**
  730.      * Returns the number of rows affected
  731.      *
  732.      * @param resource $result 
  733.      * @param resource $connection 
  734.      * @return mixed MDB2 Error Object or the number of rows affected
  735.      * @access private
  736.      */
  737.     function _affectedRows($connection, $result = null)
  738.     {
  739.         if (null === $connection) {
  740.             $connection = $this->getConnection();
  741.             if (MDB2::isError($connection)) {
  742.                 return $connection;
  743.             }
  744.         }
  745.         return (function_exists('ibase_affected_rows') ? @ibase_affected_rows($connection) : 0);
  746.     }
  747.  
  748.     // }}}
  749.     // {{{ _modifyQuery()
  750.  
  751.     /**
  752.      * Changes a query string for various DBMS specific reasons
  753.      *
  754.      * @param string $query  query to modify
  755.      * @param boolean $is_manip  if it is a DML query
  756.      * @param integer $limit  limit the number of rows
  757.      * @param integer $offset  start reading from given offset
  758.      * @return string modified query
  759.      * @access protected
  760.      */
  761.     function _modifyQuery($query, $is_manip, $limit, $offset)
  762.     {
  763.         if ($limit > 0 && $this->supports('limit_queries') === true) {
  764.             $query = preg_replace('/^([\s(])*SELECT(?!\s*FIRST\s*\d+)/i',
  765.                 "SELECT FIRST $limit SKIP $offset", $query);
  766.         }
  767.         return $query;
  768.     }
  769.  
  770.     // }}}
  771.     // {{{ getServerVersion()
  772.  
  773.     /**
  774.      * return version information about the server
  775.      *
  776.      * @param bool   $native  determines if the raw version string should be returned
  777.      * @return mixed array/string with version information or MDB2 error object
  778.      * @access public
  779.      */
  780.     function getServerVersion($native = false)
  781.     {
  782.         $server_info = false;
  783.         if ($this->connected_server_info) {
  784.             $server_info = $this->connected_server_info;
  785.         } elseif ($this->options['server_version']) {
  786.             $server_info = $this->options['server_version'];
  787.         } else {
  788.             $username = $this->options['DBA_username'] ? $this->options['DBA_username'] : $this->dsn['username'];
  789.             $password = $this->options['DBA_password'] ? $this->options['DBA_password'] : $this->dsn['password'];
  790.             $ibserv = @ibase_service_attach($this->dsn['hostspec'], $username, $password);
  791.             $server_info = @ibase_server_info($ibserv, IBASE_SVC_SERVER_VERSION);
  792.             @ibase_service_detach($ibserv);
  793.         }
  794.         if (!$server_info) {
  795.             return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  796.                 'Requires either "server_version" or "DBA_username"/"DBA_password" option', __FUNCTION__);
  797.         }
  798.         // cache server_info
  799.         $this->connected_server_info = $server_info;
  800.         if (!$native) {
  801.             //WI-V1.5.3.4854 Firebird 1.5
  802.             //WI-T2.1.0.16780 Firebird 2.1 Beta 2
  803.             if (!preg_match('/-[VT]([\d\.]*)/', $server_info, $matches)) {
  804.                 return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  805.                     'Could not parse version information:'.$server_info, __FUNCTION__);
  806.             }
  807.             $tmp = explode('.', $matches[1], 4);
  808.             $server_info = array(
  809.                 'major' => isset($tmp[0]) ? $tmp[0] : null,
  810.                 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  811.                 'patch' => isset($tmp[2]) ? $tmp[2] : null,
  812.                 'extra' => isset($tmp[3]) ? $tmp[3] : null,
  813.                 'native' => $server_info,
  814.             );
  815.         }
  816.         return $server_info;
  817.     }
  818.  
  819.     // }}}
  820.     // {{{ prepare()
  821.  
  822.     /**
  823.      * Prepares a query for multiple execution with execute().
  824.      * With some database backends, this is emulated.
  825.      * prepare() requires a generic query as string like
  826.      * 'INSERT INTO numbers VALUES(?,?)' or
  827.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  828.      * The ? and :name and are placeholders which can be set using
  829.      * bindParam() and the query can be sent off using the execute() method.
  830.      * The allowed format for :name can be set with the 'bindname_format' option.
  831.      *
  832.      * @param string $query the query to prepare
  833.      * @param mixed   $types  array that contains the types of the placeholders
  834.      * @param mixed   $result_types  array that contains the types of the columns in
  835.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  836.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  837.      * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  838.      * @return mixed resource handle for the prepared query on success, a MDB2
  839.      *         error on failure
  840.      * @access public
  841.      * @see bindParam, execute
  842.      */
  843.     function prepare($query, $types = null, $result_types = null, $lobs = array())
  844.     {
  845.         if ($this->options['emulate_prepared']) {
  846.             return parent::prepare($query, $types, $result_types, $lobs);
  847.         }
  848.         $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  849.         $offset = $this->offset;
  850.         $limit  = $this->limit;
  851.         $this->offset = $this->limit = 0;
  852.         $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  853.         if ($result) {
  854.             if (MDB2::isError($result)) {
  855.                 return $result;
  856.             }
  857.             $query = $result;
  858.         }
  859.         $placeholder_type_guess = $placeholder_type = null;
  860.         $question = '?';
  861.         $colon = ':';
  862.         $positions = array();
  863.         $position = 0;
  864.         while ($position < strlen($query)) {
  865.             $q_position = strpos($query, $question, $position);
  866.             $c_position = strpos($query, $colon, $position);
  867.             if ($q_position && $c_position) {
  868.                 $p_position = min($q_position, $c_position);
  869.             } elseif ($q_position) {
  870.                 $p_position = $q_position;
  871.             } elseif ($c_position) {
  872.                 $p_position = $c_position;
  873.             } else {
  874.                 break;
  875.             }
  876.             if (null === $placeholder_type) {
  877.                 $placeholder_type_guess = $query[$p_position];
  878.             }
  879.  
  880.             $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  881.             if (MDB2::isError($new_pos)) {
  882.                 return $new_pos;
  883.             }
  884.             if ($new_pos != $position) {
  885.                 $position = $new_pos;
  886.                 continue; //evaluate again starting from the new position
  887.             }
  888.  
  889.             if ($query[$position] == $placeholder_type_guess) {
  890.                 if (null === $placeholder_type) {
  891.                     $placeholder_type = $query[$p_position];
  892.                     $question = $colon = $placeholder_type;
  893.                 }
  894.                 if ($placeholder_type == ':') {
  895.                     $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  896.                     $parameter = preg_replace($regexp, '\\1', $query);
  897.                     if ($parameter === '') {
  898.                         $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  899.                             'named parameter name must match "bindname_format" option', __FUNCTION__);
  900.                         return $err;
  901.                     }
  902.                     $positions[] = $parameter;
  903.                     $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  904.                 } else {
  905.                     $positions[] = count($positions);
  906.                 }
  907.                 $position = $p_position + 1;
  908.             } else {
  909.                 $position = $p_position;
  910.             }
  911.         }
  912.         $connection = $this->getConnection();
  913.         if (MDB2::isError($connection)) {
  914.             return $connection;
  915.         }
  916.         $statement = @ibase_prepare($connection, $query);
  917.         if (!$statement) {
  918.             $err = $this->raiseError(null, null, null,
  919.                 'Could not create statement', __FUNCTION__);
  920.             return $err;
  921.         }
  922.  
  923.         $class_name = 'MDB2_Statement_'.$this->phptype;
  924.         $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  925.         $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  926.         return $obj;
  927.     }
  928.  
  929.     // }}}
  930.     // {{{ getSequenceName()
  931.  
  932.     /**
  933.      * adds sequence name formatting to a sequence name
  934.      *
  935.      * @param string $sqn name of the sequence
  936.      * @return string formatted sequence name
  937.      * @access public
  938.      */
  939.     function getSequenceName($sqn)
  940.     {
  941.         return strtoupper(parent::getSequenceName($sqn));
  942.     }
  943.  
  944.     // }}}
  945.     // {{{ nextID()
  946.  
  947.     /**
  948.      * Returns the next free id of a sequence
  949.      *
  950.      * @param string $seq_name name of the sequence
  951.      * @param boolean $ondemand when true the sequence is
  952.      *                           automatic created, if it
  953.      *                           not exists
  954.      * @return mixed MDB2 Error Object or id
  955.      * @access public
  956.      */
  957.     function nextID($seq_name, $ondemand = true)
  958.     {
  959.         $sequence_name = $this->getSequenceName($seq_name);
  960.         $query = 'SELECT GEN_ID('.$sequence_name.', 1) as the_value FROM RDB$DATABASE';
  961.         $this->pushErrorHandling(PEAR_ERROR_RETURN);
  962.         $this->expectError('*');
  963.         $result = $this->queryOne($query, 'integer');
  964.         $this->popExpect();
  965.         $this->popErrorHandling();
  966.         if (MDB2::isError($result)) {
  967.             if ($ondemand) {
  968.                 $this->loadModule('Manager', null, true);
  969.                 $result = $this->manager->createSequence($seq_name);
  970.                 if (MDB2::isError($result)) {
  971.                     return $this->raiseError($result, null, null,
  972.                         'on demand sequence could not be created', __FUNCTION__);
  973.                 } else {
  974.                     return $this->nextID($seq_name, false);
  975.                 }
  976.             }
  977.         }
  978.         return $result;
  979.     }
  980.  
  981.     // }}}
  982.     // {{{ lastInsertID()
  983.  
  984.     /**
  985.      * Returns the autoincrement ID if supported or $id or fetches the current
  986.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  987.      *
  988.      * @param string $table name of the table into which a new row was inserted
  989.      * @param string $field name of the field into which a new row was inserted
  990.      * @return mixed MDB2 Error Object or id
  991.      * @access public
  992.      */
  993.     function lastInsertID($table = null, $field = null)
  994.     {
  995.         //$seq = $table.(empty($field) ? '' : '_'.$field);
  996.         return $this->currID($table);
  997.     }
  998.  
  999.     // }}}
  1000.     // {{{ currID()
  1001.  
  1002.     /**
  1003.      * Returns the current id of a sequence
  1004.      *
  1005.      * @param string $seq_name name of the sequence
  1006.      * @return mixed MDB2 Error Object or id
  1007.      * @access public
  1008.      */
  1009.     function currID($seq_name)
  1010.     {
  1011.         $sequence_name = $this->getSequenceName($seq_name);
  1012.         $query = 'SELECT GEN_ID('.$sequence_name.', 0) as the_value FROM RDB$DATABASE';
  1013.         $value = $this->queryOne($query);
  1014.         if (MDB2::isError($value)) {
  1015.             return $this->raiseError($value, null, null,
  1016.                 'Unable to select from ' . $seq_name, __FUNCTION__);
  1017.         }
  1018.         if (!is_numeric($value)) {
  1019.             return $this->raiseError(MDB2_ERROR, null, null,
  1020.                 'could not find value in sequence table', __FUNCTION__);
  1021.         }
  1022.         return $value;
  1023.     }
  1024.  
  1025.     // }}}
  1026. }
  1027.  
  1028. /**
  1029.  * MDB2 FireBird/InterBase result driver
  1030.  *
  1031.  * @package MDB2
  1032.  * @category Database
  1033.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  1034.  */
  1035. class MDB2_Result_ibase extends MDB2_Result_Common
  1036. {
  1037.     // {{{ _skipLimitOffset()
  1038.  
  1039.     /**
  1040.      * Skip the first row of a result set.
  1041.      *
  1042.      * @param resource $result 
  1043.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1044.      * @access protected
  1045.      */
  1046.     function _skipLimitOffset()
  1047.     {
  1048.         if ($this->db->supports('limit_queries') === true) {
  1049.             return true;
  1050.         }
  1051.         if ($this->limit) {
  1052.             if ($this->rownum > $this->limit) {
  1053.                 return false;
  1054.             }
  1055.         }
  1056.         if ($this->offset) {
  1057.             while ($this->offset_count < $this->offset) {
  1058.                 ++$this->offset_count;
  1059.                 if (!is_array(@ibase_fetch_row($this->result))) {
  1060.                     $this->offset_count = $this->offset;
  1061.                     return false;
  1062.                 }
  1063.             }
  1064.         }
  1065.         return true;
  1066.     }
  1067.  
  1068.     // }}}
  1069.     // {{{ fetchRow()
  1070.  
  1071.     /**
  1072.      * Fetch a row and insert the data into an existing array.
  1073.      *
  1074.      * @param int  $fetchmode how the array data should be indexed
  1075.      * @param int  $rownum    number of the row where the data can be found
  1076.      * @return int data array on success, a MDB2 error on failure
  1077.      * @access public
  1078.      */
  1079.     function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1080.     {
  1081.         if (true === $this->result) {
  1082.             //query successfully executed, but without results...
  1083.             return null;
  1084.         }
  1085.         if (!$this->_skipLimitOffset()) {
  1086.             return null;
  1087.         }
  1088.         if (null !== $rownum) {
  1089.             $seek = $this->seek($rownum);
  1090.             if (MDB2::isError($seek)) {
  1091.                 return $seek;
  1092.             }
  1093.         }
  1094.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1095.             $fetchmode = $this->db->fetchmode;
  1096.         }
  1097.         if (   $fetchmode == MDB2_FETCHMODE_ASSOC
  1098.             || $fetchmode == MDB2_FETCHMODE_OBJECT
  1099.         ) {
  1100.             $row = @ibase_fetch_assoc($this->result);
  1101.             if (is_array($row)
  1102.                 && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1103.             ) {
  1104.                 $row = array_change_key_case($row, $this->db->options['field_case']);
  1105.             }
  1106.         } else {
  1107.             $row = @ibase_fetch_row($this->result);
  1108.         }
  1109.         if (!$row) {
  1110.             if (false === $this->result) {
  1111.                 $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1112.                     'resultset has already been freed', __FUNCTION__);
  1113.                 return $err;
  1114.             }
  1115.             return null;
  1116.         }
  1117.         $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1118.         $rtrim = false;
  1119.         if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1120.             if (empty($this->types)) {
  1121.                 $mode += MDB2_PORTABILITY_RTRIM;
  1122.             } else {
  1123.                 $rtrim = true;
  1124.             }
  1125.         }
  1126.         if ($mode) {
  1127.             $this->db->_fixResultArrayValues($row, $mode);
  1128.         }
  1129.         if ($fetchmode == MDB2_FETCHMODE_ORDERED) {
  1130.             if (!empty($this->types)) {
  1131.                 $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1132.             }
  1133.         } elseif (!empty($this->types_assoc)) {
  1134.             $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1135.         }
  1136.         if (!empty($this->values)) {
  1137.             $this->_assignBindColumns($row);
  1138.         }
  1139.         if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1140.             $object_class = $this->db->options['fetch_class'];
  1141.             if ($object_class == 'stdClass') {
  1142.                 $row = (object) $row;
  1143.             } else {
  1144.                 $rowObj = new $object_class($row);
  1145.                 $row = $rowObj;
  1146.             }
  1147.         }
  1148.         ++$this->rownum;
  1149.         return $row;
  1150.     }
  1151.  
  1152.     // }}}
  1153.     // {{{ _getColumnNames()
  1154.  
  1155.     /**
  1156.      * Retrieve the names of columns returned by the DBMS in a query result.
  1157.      *
  1158.      * @return  mixed   Array variable that holds the names of columns as keys
  1159.      *                   or an MDB2 error on failure.
  1160.      *                   Some DBMS may not return any columns when the result set
  1161.      *                   does not contain any rows.
  1162.      * @access private
  1163.      */
  1164.     function _getColumnNames()
  1165.     {
  1166.         $columns = array();
  1167.         $numcols = $this->numCols();
  1168.         if (MDB2::isError($numcols)) {
  1169.             return $numcols;
  1170.         }
  1171.         for ($column = 0; $column < $numcols; $column++) {
  1172.             $column_info = @ibase_field_info($this->result, $column);
  1173.             $columns[$column_info['alias']] = $column;
  1174.         }
  1175.         if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1176.             $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1177.         }
  1178.         return $columns;
  1179.     }
  1180.  
  1181.     // }}}
  1182.     // {{{ numCols()
  1183.  
  1184.     /**
  1185.      * Count the number of columns returned by the DBMS in a query result.
  1186.      *
  1187.      * @return mixed integer value with the number of columns, a MDB2 error
  1188.      *       on failure
  1189.      * @access public
  1190.      */
  1191.     function numCols()
  1192.     {
  1193.         if (true === $this->result) {
  1194.             //query successfully executed, but without results...
  1195.             return 0;
  1196.         }
  1197.  
  1198.         if (!is_resource($this->result)) {
  1199.             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1200.                 'numCols(): not a valid ibase resource', __FUNCTION__);
  1201.         }
  1202.         $cols = @ibase_num_fields($this->result);
  1203.         if (null === $cols) {
  1204.             if (false === $this->result) {
  1205.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1206.                     'resultset has already been freed', __FUNCTION__);
  1207.             } elseif (null === $this->result) {
  1208.                 return count($this->types);
  1209.             }
  1210.             return $this->db->raiseError(null, null, null,
  1211.                 'Could not get column count', __FUNCTION__);
  1212.         }
  1213.         return $cols;
  1214.     }
  1215.  
  1216.     // }}}
  1217.     // {{{ free()
  1218.  
  1219.     /**
  1220.      * Free the internal resources associated with $result.
  1221.      *
  1222.      * @return boolean true on success, false if $result is invalid
  1223.      * @access public
  1224.      */
  1225.     function free()
  1226.     {
  1227.         if (is_resource($this->result) && $this->db->connection) {
  1228.             $free = @ibase_free_result($this->result);
  1229.             if (false === $free) {
  1230.                 return $this->db->raiseError(null, null, null,
  1231.                     'Could not free result', __FUNCTION__);
  1232.             }
  1233.         }
  1234.         $this->result = false;
  1235.         return MDB2_OK;
  1236.     }
  1237.  
  1238.     // }}}
  1239. }
  1240.  
  1241. /**
  1242.  * MDB2 FireBird/InterBase buffered result driver
  1243.  *
  1244.  * @package MDB2
  1245.  * @category Database
  1246.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  1247.  */
  1248. {
  1249.     // {{{ class vars
  1250.  
  1251.     var $buffer;
  1252.     var $buffer_rownum = - 1;
  1253.  
  1254.     // }}}
  1255.     // {{{ _fillBuffer()
  1256.  
  1257.     /**
  1258.      * Fill the row buffer
  1259.      *
  1260.      * @param int $rownum   row number upto which the buffer should be filled
  1261.      *                       if the row number is null all rows are ready into the buffer
  1262.      * @return boolean true on success, false on failure
  1263.      * @access protected
  1264.      */
  1265.     function _fillBuffer($rownum = null)
  1266.     {
  1267.         if (isset($this->buffer) && is_array($this->buffer)) {
  1268.             if (null === $rownum) {
  1269.                 if (!end($this->buffer)) {
  1270.                     return false;
  1271.                 }
  1272.             } elseif (isset($this->buffer[$rownum])) {
  1273.                 return (bool) $this->buffer[$rownum];
  1274.             }
  1275.         }
  1276.  
  1277.         if (!$this->_skipLimitOffset()) {
  1278.             return false;
  1279.         }
  1280.  
  1281.         $buffer = true;
  1282.         while (((null === $rownum) || $this->buffer_rownum < $rownum)
  1283.             && (!$this->limit || $this->buffer_rownum < $this->limit)
  1284.             && ($buffer = @ibase_fetch_row($this->result))
  1285.         ) {
  1286.             ++$this->buffer_rownum;
  1287.             $this->buffer[$this->buffer_rownum] = $buffer;
  1288.         }
  1289.  
  1290.         if (!$buffer) {
  1291.             ++$this->buffer_rownum;
  1292.             $this->buffer[$this->buffer_rownum] = false;
  1293.             return false;
  1294.         } elseif ($this->limit && $this->buffer_rownum >= $this->limit) {
  1295.             ++$this->buffer_rownum;
  1296.             $this->buffer[$this->buffer_rownum] = false;
  1297.         }
  1298.         return true;
  1299.     }
  1300.  
  1301.     // }}}
  1302.     // {{{ fetchRow()
  1303.  
  1304.     /**
  1305.      * Fetch a row and insert the data into an existing array.
  1306.      *
  1307.      * @param int       $fetchmode  how the array data should be indexed
  1308.      * @param int    $rownum    number of the row where the data can be found
  1309.      * @return int data array on success, a MDB2 error on failure
  1310.      * @access public
  1311.      */
  1312.     function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1313.     {
  1314.         if (true === $this->result || (null === $this->result)) {
  1315.             //query successfully executed, but without results...
  1316.             return null;
  1317.         }
  1318.         if (false === $this->result) {
  1319.             $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1320.                 'resultset has already been freed', __FUNCTION__);
  1321.             return $err;
  1322.         }
  1323.         if (null !== $rownum) {
  1324.             $seek = $this->seek($rownum);
  1325.             if (MDB2::isError($seek)) {
  1326.                 return $seek;
  1327.             }
  1328.         }
  1329.         $target_rownum = $this->rownum + 1;
  1330.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1331.             $fetchmode = $this->db->fetchmode;
  1332.         }
  1333.         if (!$this->_fillBuffer($target_rownum)) {
  1334.             return null;
  1335.         }
  1336.         $row = $this->buffer[$target_rownum];
  1337.         if (   $fetchmode == MDB2_FETCHMODE_ASSOC
  1338.             || $fetchmode == MDB2_FETCHMODE_OBJECT
  1339.         ) {
  1340.             $column_names = $this->getColumnNames();
  1341.             foreach ($column_names as $name => $i) {
  1342.                 $column_names[$name] = $row[$i];
  1343.             }
  1344.             $row = $column_names;
  1345.         }
  1346.         $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1347.         $rtrim = false;
  1348.         if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1349.             if (empty($this->types)) {
  1350.                 $mode += MDB2_PORTABILITY_RTRIM;
  1351.             } else {
  1352.                 $rtrim = true;
  1353.             }
  1354.         }
  1355.         if ($mode) {
  1356.             $this->db->_fixResultArrayValues($row, $mode);
  1357.         }
  1358.         if ($fetchmode == MDB2_FETCHMODE_ORDERED) {
  1359.             if (!empty($this->types)) {
  1360.                 $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1361.             }
  1362.         } elseif (!empty($this->types_assoc)) {
  1363.             $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1364.         }
  1365.         if (!empty($this->values)) {
  1366.             $this->_assignBindColumns($row);
  1367.         }
  1368.         if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1369.             $object_class = $this->db->options['fetch_class'];
  1370.             if ($object_class == 'stdClass') {
  1371.                 $row = (object) $row;
  1372.             } else {
  1373.                 $rowObj = new $object_class($row);
  1374.                 $row = $rowObj;
  1375.             }
  1376.         }
  1377.         ++$this->rownum;
  1378.         return $row;
  1379.     }
  1380.  
  1381.     // }}}
  1382.     // {{{ seek()
  1383.  
  1384.     /**
  1385.      * Seek to a specific row in a result set
  1386.      *
  1387.      * @param int    $rownum    number of the row where the data can be found
  1388.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1389.      * @access public
  1390.      */
  1391.     function seek($rownum = 0)
  1392.     {
  1393.         if (false === $this->result) {
  1394.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1395.                 'resultset has already been freed', __FUNCTION__);
  1396.         }
  1397.         $this->rownum = $rownum - 1;
  1398.         return MDB2_OK;
  1399.     }
  1400.  
  1401.     // }}}
  1402.     // {{{ valid()
  1403.  
  1404.     /**
  1405.      * Check if the end of the result set has been reached
  1406.      *
  1407.      * @return mixed true or false on sucess, a MDB2 error on failure
  1408.      * @access public
  1409.      */
  1410.     function valid()
  1411.     {
  1412.         if (false === $this->result) {
  1413.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1414.                 'resultset has already been freed', __FUNCTION__);
  1415.         }
  1416.         if (null === $this->result) {
  1417.             return true;
  1418.         }
  1419.         if ($this->_fillBuffer($this->rownum + 1)) {
  1420.             return true;
  1421.         }
  1422.         return false;
  1423.     }
  1424.  
  1425.     // }}}
  1426.     // {{{ numRows()
  1427.  
  1428.     /**
  1429.      * Returns the number of rows in a result object
  1430.      *
  1431.      * @return mixed MDB2 Error Object or the number of rows
  1432.      * @access public
  1433.      */
  1434.     function numRows()
  1435.     {
  1436.         if (false === $this->result) {
  1437.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1438.                 'resultset has already been freed', __FUNCTION__);
  1439.         }
  1440.         if (null === $this->result) {
  1441.             return 0;
  1442.         }
  1443.         $this->_fillBuffer();
  1444.         return $this->buffer_rownum;
  1445.     }
  1446.  
  1447.     // }}}
  1448.     // {{{ free()
  1449.  
  1450.     /**
  1451.      * Free the internal resources associated with $result.
  1452.      *
  1453.      * @return boolean true on success, false if $result is invalid
  1454.      * @access public
  1455.      */
  1456.     function free()
  1457.     {
  1458.         $this->buffer = null;
  1459.         $this->buffer_rownum = null;
  1460.         return parent::free();
  1461.     }
  1462.  
  1463.     // }}}
  1464. }
  1465.  
  1466. /**
  1467.  * MDB2 FireBird/InterBase statement driver
  1468.  *
  1469.  * @package MDB2
  1470.  * @category Database
  1471.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  1472.  */
  1473. class MDB2_Statement_ibase extends MDB2_Statement_Common
  1474. {
  1475.     // {{{ _execute()
  1476.  
  1477.     /**
  1478.      * Execute a prepared query statement helper method.
  1479.      *
  1480.      * @param mixed $result_class string which specifies which result class to use
  1481.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1482.      *
  1483.      * @return mixed MDB2_Result or integer (affected rows) on success,
  1484.      *                a MDB2 error on failure
  1485.      * @access private
  1486.      */
  1487.     function _execute($result_class = true, $result_wrap_class = true)
  1488.     {
  1489.         if (null === $this->statement) {
  1490.             $result = parent::_execute($result_class, $result_wrap_class);
  1491.             return $result;
  1492.         }
  1493.         $this->db->last_query = $this->query;
  1494.         $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1495.         if ($this->db->getOption('disable_query')) {
  1496.             $result = $this->is_manip ? 0 : null;
  1497.             return $result;
  1498.         }
  1499.  
  1500.         $connection = $this->db->getConnection();
  1501.         if (MDB2::isError($connection)) {
  1502.             return $connection;
  1503.         }
  1504.  
  1505.         $parameters = array(0 => $this->statement);
  1506.         foreach ($this->positions as $parameter) {
  1507.             if (!array_key_exists($parameter, $this->values)) {
  1508.                 return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1509.                     'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1510.             }
  1511.             $value = $this->values[$parameter];
  1512.             $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
  1513.             $quoted = $this->db->quote($value, $type, false);
  1514.             if (MDB2::isError($quoted)) {
  1515.                 return $quoted;
  1516.             }
  1517.             $parameters[] = $quoted;
  1518.         }
  1519.  
  1520.         $result = @call_user_func_array('ibase_execute', $parameters);
  1521.         if (false === $result) {
  1522.             $err = $this->db->raiseError(null, null, null,
  1523.                 'Could not execute statement', __FUNCTION__);
  1524.             return $err;
  1525.         }
  1526.  
  1527.         if ($this->is_manip) {
  1528.             $affected_rows = $this->db->_affectedRows($connection);
  1529.             return $affected_rows;
  1530.         }
  1531.  
  1532.         $result = $this->db->_wrapResult($result, $this->result_types,
  1533.             $result_class, $result_wrap_class, $this->limit, $this->offset);
  1534.         $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1535.         return $result;
  1536.     }
  1537.  
  1538.     // }}}
  1539.  
  1540.     // }}}
  1541.     // {{{ free()
  1542.  
  1543.     /**
  1544.      * Release resources allocated for the specified prepared query.
  1545.      *
  1546.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1547.      * @access public
  1548.      */
  1549.     function free()
  1550.     {
  1551.         if (null === $this->positions) {
  1552.             return $this->db->raiseError(MDB2_ERROR, null, null,
  1553.                 'Prepared statement has already been freed', __FUNCTION__);
  1554.         }
  1555.         $result = MDB2_OK;
  1556.  
  1557.         if ((null !== $this->statement) && !@ibase_free_query($this->statement)) {
  1558.             $result = $this->db->raiseError(null, null, null,
  1559.                 'Could not free statement', __FUNCTION__);
  1560.         }
  1561.  
  1562.         parent::free();
  1563.         return $result;
  1564.     }
  1565. }
  1566. ?>

Documentation generated on Mon, 11 Mar 2019 15:51:37 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.