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-2006 Manuel Lemos, Tomas V.V.Cox,                 |
  7. // | Stig. S. Bakken, Lukas Smith                                         |
  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,v 1.149 2006/04/16 11:55:14 lsmith Exp $
  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.     var $escape_quotes = "'";
  59.  
  60.     var $transaction_id = 0;
  61.  
  62.     var $query_parameters = array();
  63.     var $query_parameter_values = array();
  64.  
  65.     // }}}
  66.     // {{{ constructor
  67.  
  68.     /**
  69.      * Constructor
  70.      */
  71.     function __construct()
  72.     {
  73.         parent::__construct();
  74.  
  75.         $this->phptype  'ibase';
  76.         $this->dbsyntax 'ibase';
  77.  
  78.         $this->supported['sequences'= true;
  79.         $this->supported['indexes'= true;
  80.         $this->supported['affected_rows'function_exists('ibase_affected_rows');
  81.         $this->supported['summary_functions'= true;
  82.         $this->supported['order_by_text'= true;
  83.         $this->supported['transactions'= true;
  84.         $this->supported['current_id'= true;
  85.         $this->supported['limit_queries''emulated';
  86.         $this->supported['LOBs'= true;
  87.         $this->supported['replace'= false;
  88.         $this->supported['sub_selects'= true;
  89.         $this->supported['auto_increment'= true;
  90.         $this->supported['primary_key'= true;
  91.         $this->supported['result_introspection'= true;
  92.  
  93.         $this->options['DBA_username'= false;
  94.         $this->options['DBA_password'= false;
  95.         $this->options['database_path''';
  96.         $this->options['database_extension''.gdb';
  97.         $this->options['default_text_field_length'= 4096;
  98.         $this->options['server_version''';
  99.     }
  100.  
  101.     // }}}
  102.     // {{{ errorInfo()
  103.  
  104.     /**
  105.      * This method is used to collect information about an error
  106.      *
  107.      * @param integer $error 
  108.      * @return array 
  109.      * @access public
  110.      */
  111.     function errorInfo($error = null)
  112.     {
  113.         $native_msg @ibase_errmsg();
  114.  
  115.         if (function_exists('ibase_errcode')) {
  116.             $native_code @ibase_errcode();
  117.         else {
  118.             // memo for the interbase php module hackers: we need something similar
  119.             // to mysql_errno() to retrieve error codes instead of this ugly hack
  120.             if (preg_match('/^([^0-9\-]+)([0-9\-]+)\s+(.*)$/'$native_msg$m)) {
  121.                 $native_code = (int)$m[2];
  122.             else {
  123.                 $native_code = null;
  124.             }
  125.         }
  126.         if (is_null($error)) {
  127.             $error = MDB2_ERROR;
  128.             if ($native_code{
  129.                 // try to interpret Interbase error code (that's why we need ibase_errno()
  130.                 // in the interbase module to return the real error code)
  131.                 switch ($native_code{
  132.                 case -204:
  133.                     if (isset($m[3]&& is_int(strpos($m[3]'Table unknown'))) {
  134.                         $errno = MDB2_ERROR_NOSUCHTABLE;
  135.                     }
  136.                 break;
  137.                 default:
  138.                     static $ecode_map;
  139.                     if (empty($ecode_map)) {
  140.                         $ecode_map = array(
  141.                             -104 => MDB2_ERROR_SYNTAX,
  142.                             -150 => MDB2_ERROR_ACCESS_VIOLATION,
  143.                             -151 => MDB2_ERROR_ACCESS_VIOLATION,
  144.                             -155 => MDB2_ERROR_NOSUCHTABLE,
  145.                             -157 => MDB2_ERROR_NOSUCHFIELD,
  146.                             -158 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  147.                             -170 => MDB2_ERROR_MISMATCH,
  148.                             -171 => MDB2_ERROR_MISMATCH,
  149.                             -172 => MDB2_ERROR_INVALID,
  150.                             // -204 =>  // Covers too many errors, need to use regex on msg
  151.                             -205 => MDB2_ERROR_NOSUCHFIELD,
  152.                             -206 => MDB2_ERROR_NOSUCHFIELD,
  153.                             -208 => MDB2_ERROR_INVALID,
  154.                             -219 => MDB2_ERROR_NOSUCHTABLE,
  155.                             -297 => MDB2_ERROR_CONSTRAINT,
  156.                             -303 => MDB2_ERROR_INVALID,
  157.                             -413 => MDB2_ERROR_INVALID_NUMBER,
  158.                             -530 => MDB2_ERROR_CONSTRAINT,
  159.                             -551 => MDB2_ERROR_ACCESS_VIOLATION,
  160.                             -552 => MDB2_ERROR_ACCESS_VIOLATION,
  161.                             // -607 =>  // Covers too many errors, need to use regex on msg
  162.                             -625 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  163.                             -803 => MDB2_ERROR_CONSTRAINT,
  164.                             -804 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  165.                             -904 => MDB2_ERROR_CONNECT_FAILED,
  166.                             -922 => MDB2_ERROR_NOSUCHDB,
  167.                             -923 => MDB2_ERROR_CONNECT_FAILED,
  168.                             -924 => MDB2_ERROR_CONNECT_FAILED
  169.                         );
  170.                     }
  171.                     if (isset($ecode_map[$native_code])) {
  172.                         $error $ecode_map[$native_code];
  173.                     }
  174.                     break;
  175.                 }
  176.             else {
  177.                 static $error_regexps;
  178.                 if (!isset($error_regexps)) {
  179.                     $error_regexps = array(
  180.                         '/generator .* is not defined/'
  181.                             => MDB2_ERROR_SYNTAX,  // for compat. w ibase_errcode()
  182.                         '/table.*(not exist|not found|unknown)/i'
  183.                             => MDB2_ERROR_NOSUCHTABLE,
  184.                         '/table .* already exists/i'
  185.                             => MDB2_ERROR_ALREADY_EXISTS,
  186.                         '/unsuccessful metadata update .* failed attempt to store duplicate value/i'
  187.                             => MDB2_ERROR_ALREADY_EXISTS,
  188.                         '/unsuccessful metadata update .* not found/i'
  189.                             => MDB2_ERROR_NOT_FOUND,
  190.                         '/validation error for column .* value "\*\*\* null/i'
  191.                             => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  192.                         '/violation of [\w ]+ constraint/i'
  193.                             => MDB2_ERROR_CONSTRAINT,
  194.                         '/conversion error from string/i'
  195.                             => MDB2_ERROR_INVALID_NUMBER,
  196.                         '/no permission for/i'
  197.                             => MDB2_ERROR_ACCESS_VIOLATION,
  198.                         '/arithmetic exception, numeric overflow, or string truncation/i'
  199.                             => MDB2_ERROR_INVALID,
  200.                     );
  201.                 }
  202.                 foreach ($error_regexps as $regexp => $code{
  203.                     if (preg_match($regexp$native_msg$m)) {
  204.                         $error $code;
  205.                         break;
  206.                     }
  207.                 }
  208.             }
  209.         }
  210.         return array($error$native_code$native_msg);
  211.     }
  212.  
  213.     // }}}
  214.     // {{{ quoteIdentifier()
  215.  
  216.     /**
  217.      * Delimited identifiers are a nightmare with InterBase, so they're disabled
  218.      *
  219.      * @param string $str  identifier name to be quoted
  220.      * @param bool   $check_option  check the 'quote_identifier' option
  221.      *
  222.      * @return string  quoted identifier string
  223.      *
  224.      * @access public
  225.      */
  226.     function quoteIdentifier($str$check_option = false)
  227.     {
  228.         if ($check_option && !$this->options['quote_identifier']{
  229.             return $str;
  230.         }
  231.         return strtoupper($str);
  232.     }
  233.  
  234.     // }}}
  235.     // {{{ getConnection()
  236.  
  237.     /**
  238.      * Returns a native connection
  239.      *
  240.      * @return  mixed   a valid MDB2 connection object,
  241.      *                   or a MDB2 error object on error
  242.      * @access  public
  243.      */
  244.     function getConnection()
  245.     {
  246.         $result $this->connect();
  247.         if (PEAR::isError($result)) {
  248.             return $result;
  249.         }
  250.         if ($this->in_transaction{
  251.             return $this->transaction_id;
  252.         }
  253.         return $this->connection;
  254.     }
  255.  
  256.     // }}}
  257.     // {{{ beginTransaction()
  258.  
  259.     /**
  260.      * Start a transaction.
  261.      *
  262.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  263.      * @access public
  264.      */
  265.     function beginTransaction()
  266.     {
  267.         $this->debug('starting transaction''beginTransaction');
  268.         if ($this->in_transaction{
  269.             return MDB2_OK;  //nothing to do
  270.         }
  271.         $connection $this->getConnection();
  272.         if (PEAR::isError($connection)) {
  273.             return $connection;
  274.         }
  275.         $result @ibase_trans(IBASE_DEFAULT$connection);
  276.         if (!$result{
  277.             return $this->raiseError(MDB2_ERRORnullnull,
  278.                 'beginTransaction: could not start a transaction');
  279.         }
  280.         $this->transaction_id = $result;
  281.         $this->in_transaction = true;
  282.         return MDB2_OK;
  283.     }
  284.  
  285.     // }}}
  286.     // {{{ commit()
  287.  
  288.     /**
  289.      * Commit the database changes done during a transaction that is in
  290.      * progress.
  291.      *
  292.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  293.      * @access public
  294.      */
  295.     function commit()
  296.     {
  297.         $this->debug('commit transaction''commit');
  298.         if (!$this->in_transaction{
  299.             return $this->raiseError(MDB2_ERRORnullnull,
  300.                 'commit: transaction changes are being auto committed');
  301.         }
  302.         if (!@ibase_commit($this->transaction_id)) {
  303.             return $this->raiseError(MDB2_ERRORnullnull,
  304.                 'commit: could not commit a transaction');
  305.         }
  306.         $this->in_transaction = false;
  307.         //$this->transaction_id = 0;
  308.         return MDB2_OK;
  309.     }
  310.  
  311.     // }}}
  312.     // {{{ rollback()
  313.  
  314.     /**
  315.      * Cancel any database changes done during a transaction that is in
  316.      * progress.
  317.      *
  318.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  319.      * @access public
  320.      */
  321.     function rollback()
  322.     {
  323.         $this->debug('rolling back transaction''rollback');
  324.         if (!$this->in_transaction{
  325.             return $this->raiseError(MDB2_ERRORnullnull,
  326.                 'rollback: transactions can not be rolled back when changes are auto committed');
  327.         }
  328.         if ($this->transaction_id && !@ibase_rollback($this->transaction_id)) {
  329.             return $this->raiseError(MDB2_ERRORnullnull,
  330.                 'rollback: Could not rollback a pending transaction: '.@ibase_errmsg());
  331.         }
  332.         $this->in_transaction = false;
  333.         $this->transaction_id = 0;
  334.         return MDB2_OK;
  335.     }
  336.  
  337.     // }}}
  338.     // {{{ getDatabaseFile()
  339.  
  340.     /**
  341.      * Builds the string with path+dbname+extension
  342.      *
  343.      * @return string full database path+file
  344.      * @access protected
  345.      */
  346.     function _getDatabaseFile($database_name)
  347.     {
  348.         if ($database_name == ''{
  349.             return $database_name;
  350.         }
  351.         $ret $this->options['database_path'$database_name;
  352.         if (   strpos($database_name'.fdb'=== false
  353.             && strpos($database_name'.gdb'=== false
  354.         {
  355.             $ret .= $this->options['database_extension'];
  356.         }
  357.         return $ret;
  358.     }
  359.  
  360.     // }}}
  361.     // {{{ _doConnect()
  362.  
  363.     /**
  364.      * Does the grunt work of connecting to the database
  365.      *
  366.      * @return mixed connection resource on success, MDB2 Error Object on failure
  367.      * @access protected
  368.      */
  369.     function _doConnect($database_name$persistent = false)
  370.     {
  371.         $user    $this->dsn['username'];
  372.         $pw      $this->dsn['password'];
  373.         $dbhost  $this->dsn['hostspec'?
  374.             ($this->dsn['hostspec'].':'.$database_name$database_name;
  375.  
  376.         $params = array();
  377.         $params[$dbhost;
  378.         $params[!empty($user$user : null;
  379.         $params[!empty($pw$pw : null;
  380.         $params[= isset($this->dsn['charset']$this->dsn['charset': null;
  381.         $params[= isset($this->dsn['buffers']$this->dsn['buffers': null;
  382.         $params[= isset($this->dsn['dialect']$this->dsn['dialect': null;
  383.         $params[= isset($this->dsn['role'])    $this->dsn['role': null;
  384.  
  385.         $connect_function $persistent 'ibase_pconnect' 'ibase_connect';
  386.  
  387.         $connection @call_user_func_array($connect_function$params);
  388.         if ($connection <= 0{
  389.             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED);
  390.         }
  391.  
  392.         if (function_exists('ibase_timefmt')) {
  393.             @ibase_timefmt("%Y-%m-%d %H:%M:%S"IBASE_TIMESTAMP);
  394.             @ibase_timefmt("%Y-%m-%d"IBASE_DATE);
  395.         else {
  396.             @ini_set("ibase.timestampformat""%Y-%m-%d %H:%M:%S");
  397.             //@ini_set("ibase.timeformat", "%H:%M:%S");
  398.             @ini_set("ibase.dateformat""%Y-%m-%d");
  399.         }
  400.  
  401.         return $connection;
  402.     }
  403.  
  404.     // }}}
  405.     // {{{ connect()
  406.  
  407.     /**
  408.      * Connect to the database
  409.      *
  410.      * @return true on success, MDB2 Error Object on failure
  411.      * @access public
  412.      */
  413.     function connect()
  414.     {
  415.         $database_file $this->_getDatabaseFile($this->database_name);
  416.         if (is_resource($this->connection)) {
  417.             if (count(array_diff($this->connected_dsn$this->dsn)) == 0
  418.                 && $this->connected_database_name == $database_file
  419.                 && $this->opened_persistent == $this->options['persistent']
  420.             {
  421.                 return MDB2_OK;
  422.             }
  423.             $this->disconnect(false);
  424.         }
  425.  
  426.         if (!PEAR::loadExtension('interbase')) {
  427.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  428.                 'connect: extension '.$this->phptype.' is not compiled into PHP');
  429.         }
  430.  
  431.         if (!empty($this->database_name)) {
  432.             $connection $this->_doConnect($database_file$this->options['persistent']);
  433.             if (PEAR::isError($connection)) {
  434.                 return $connection;
  435.             }
  436.             $this->connection =$connection;
  437.             $this->connected_dsn $this->dsn;
  438.             $this->connected_database_name $database_file;
  439.             $this->opened_persistent $this->options['persistent'];
  440.             $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  441.             $this->supported['limit_queries'($this->dbsyntax == 'firebird'? true : 'emulated';
  442.         }
  443.         return MDB2_OK;
  444.     }
  445.  
  446.     // }}}
  447.     // {{{ disconnect()
  448.  
  449.     /**
  450.      * Log out and disconnect from the database.
  451.      *
  452.      * @param  boolean $force if the disconnect should be forced even if the
  453.      *                         connection is opened persistently
  454.      * @return mixed true on success, false if not connected and error
  455.      *                 object on error
  456.      * @access public
  457.      */
  458.     function disconnect($force = true)
  459.     {
  460.         if (is_resource($this->connection)) {
  461.             if ($this->in_transaction{
  462.                 $this->rollback();
  463.             }
  464.             if (!$this->opened_persistent || $force{
  465.                 @ibase_close($this->connection);
  466.             }
  467.         }
  468.         return parent::disconnect($force);
  469.     }
  470.  
  471.     // }}}
  472.     // {{{ _doQuery()
  473.  
  474.     /**
  475.      * Execute a query
  476.      * @param string $query  query
  477.      * @param boolean $is_manip  if the query is a manipulation query
  478.      * @param resource $connection 
  479.      * @param string $database_name 
  480.      * @return result or error object
  481.      * @access protected
  482.      */
  483.     function _doQuery($query$is_manip = false$connection = null$database_name = null)
  484.     {
  485.         $this->last_query $query;
  486.         $this->debug($query'query'$is_manip);
  487.         if ($this->getOption('disable_query')) {
  488.             if ($is_manip{
  489.                 return 0;
  490.             }
  491.             return null;
  492.         }
  493.  
  494.         if (is_null($connection)) {
  495.             $connection $this->getConnection();
  496.             if (PEAR::isError($connection)) {
  497.                 return $connection;
  498.             }
  499.         }
  500.         $result @ibase_query($connection$query);
  501.  
  502.         if ($result === false{
  503.             return $this->raiseError();
  504.         }
  505.  
  506.         return $result;
  507.     }
  508.  
  509.     // }}}
  510.     // {{{ _affectedRows()
  511.  
  512.     /**
  513.      * returns the number of rows affected
  514.      *
  515.      * @param resource $result 
  516.      * @param resource $connection 
  517.      * @return mixed MDB2 Error Object or the number of rows affected
  518.      * @access private
  519.      */
  520.     function _affectedRows($connection$result = null)
  521.     {
  522.         if (is_null($connection)) {
  523.             $connection $this->getConnection();
  524.             if (PEAR::isError($connection)) {
  525.                 return $connection;
  526.             }
  527.         }
  528.         return (function_exists('ibase_affected_rows'@ibase_affected_rows($connection: 0);
  529.     }
  530.  
  531.     // }}}
  532.     // {{{ _modifyQuery()
  533.  
  534.     /**
  535.      * Changes a query string for various DBMS specific reasons
  536.      *
  537.      * @param string $query  query to modify
  538.      * @param boolean $is_manip  if it is a DML query
  539.      * @param integer $limit  limit the number of rows
  540.      * @param integer $offset  start reading from given offset
  541.      * @return string modified query
  542.      * @access protected
  543.      */
  544.     function _modifyQuery($query$is_manip$limit$offset)
  545.     {
  546.         if ($limit > 0 && $this->supports('limit_queries'=== true{
  547.             $query preg_replace('/^([\s(])*SELECT(?!\s*FIRST\s*\d+)/i',
  548.                 "SELECT FIRST $limit SKIP $offset"$query);
  549.         }
  550.         return $query;
  551.     }
  552.  
  553.     // }}}
  554.     // {{{ getServerVersion()
  555.  
  556.     /**
  557.      * return version information about the server
  558.      *
  559.      * @param string     $native  determines if the raw version string should be returned
  560.      * @return mixed array/string with version information or MDB2 error object
  561.      * @access public
  562.      */
  563.     function getServerVersion($native = false)
  564.     {
  565.         $server_info = false;
  566.         if ($this->connected_server_info{
  567.             $server_info $this->connected_server_info;
  568.         elseif ($this->options['server_version']{
  569.             $server_info $this->options['server_version'];
  570.         elseif ($this->options['DBA_username']{
  571.             $ibserv @ibase_service_attach($this->dsn['hostspec']$this->options['DBA_username']$this->options['DBA_password']);
  572.             $server_info @ibase_server_info($ibservIBASE_SVC_SERVER_VERSION);
  573.             @ibase_service_detach($ibserv);
  574.         }
  575.         if (!$server_info{
  576.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  577.                 'getServerVersion: Requires either "server_version" or "DBA_username"/"DBA_password" option');
  578.         }
  579.         // cache server_info
  580.         $this->connected_server_info $server_info;
  581.         if (!$native{
  582.             //WI-V1.5.3.4854 Firebird 1.5
  583.             if (!preg_match('/-V([\d\.]*)/'$server_info$matches)) {
  584.                 return $this->raiseError(MDB2_ERRORnullnull,
  585.                     'getServerVersion: Could not parse version information:'.$server_info);
  586.             }
  587.             $tmp explode('.'$matches[1]4);
  588.             $server_info = array(
  589.                 'major' => isset($tmp[0]$tmp[0: null,
  590.                 'minor' => isset($tmp[1]$tmp[1: null,
  591.                 'patch' => isset($tmp[2]$tmp[2: null,
  592.                 'extra' => isset($tmp[3]$tmp[3: null,
  593.                 'native' => $server_info,
  594.             );
  595.         }
  596.         return $server_info;
  597.     }
  598.  
  599.     // }}}
  600.     // {{{ prepare()
  601.  
  602.     /**
  603.      * Prepares a query for multiple execution with execute().
  604.      * With some database backends, this is emulated.
  605.      * prepare() requires a generic query as string like
  606.      * 'INSERT INTO numbers VALUES(?,?)' or
  607.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  608.      * The ? and :[a-zA-Z] and  are placeholders which can be set using
  609.      * bindParam() and the query can be send off using the execute() method.
  610.      *
  611.      * @param string $query the query to prepare
  612.      * @param mixed   $types  array that contains the types of the placeholders
  613.      * @param mixed   $result_types  array that contains the types of the columns in
  614.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  615.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  616.      * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  617.      * @return mixed resource handle for the prepared query on success, a MDB2
  618.      *         error on failure
  619.      * @access public
  620.      * @see bindParam, execute
  621.      */
  622.     function &prepare($query$types = null$result_types = null)
  623.     {
  624.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  625.         $offset $this->offset;
  626.         $limit $this->limit;
  627.         $this->offset $this->limit = 0;
  628.         $this->debug($query'prepare'$is_manip);
  629.         $placeholder_type_guess $placeholder_type = null;
  630.         $question '?';
  631.         $colon ':';
  632.         $positions = array();
  633.         $position = 0;
  634.         while ($position strlen($query)) {
  635.             $q_position strpos($query$question$position);
  636.             $c_position strpos($query$colon$position);
  637.             if ($q_position && $c_position{
  638.                 $p_position min($q_position$c_position);
  639.             elseif ($q_position{
  640.                 $p_position $q_position;
  641.             elseif ($c_position{
  642.                 $p_position $c_position;
  643.             else {
  644.                 break;
  645.             }
  646.             if (is_null($placeholder_type)) {
  647.                 $placeholder_type_guess $query[$p_position];
  648.             }
  649.             if (is_int($quote strpos($query"'"$position)) && $quote $p_position{
  650.                 if (!is_int($end_quote strpos($query"'"$quote + 1))) {
  651.                     $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  652.                         'prepare: query with an unterminated text string specified');
  653.                     return $err;
  654.                 }
  655.                 switch ($this->escape_quotes{
  656.                 case '':
  657.                 case "'":
  658.                     $position $end_quote + 1;
  659.                     break;
  660.                 default:
  661.                     if ($end_quote == $quote + 1{
  662.                         $position $end_quote + 1;
  663.                     else {
  664.                         if ($query[$end_quote-1== $this->escape_quotes{
  665.                             $position $end_quote;
  666.                         else {
  667.                             $position $end_quote + 1;
  668.                         }
  669.                     }
  670.                     break;
  671.                 }
  672.             elseif ($query[$position== $placeholder_type_guess{
  673.                 if (is_null($placeholder_type)) {
  674.                     $placeholder_type $query[$p_position];
  675.                     $question $colon $placeholder_type;
  676.                 }
  677.                 if ($placeholder_type == ':'{
  678.                     $parameter preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si''\\1'$query);
  679.                     if ($parameter === ''{
  680.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  681.                             'prepare: named parameter with an empty name');
  682.                         return $err;
  683.                     }
  684.                     $positions[$parameter$p_position;
  685.                     $query substr_replace($query'?'$positionstrlen($parameter)+1);
  686.                 else {
  687.                     $positions[$p_position;
  688.                 }
  689.                 $position $p_position + 1;
  690.             else {
  691.                 $position $p_position;
  692.             }
  693.         }
  694.         $connection $this->getConnection();
  695.         if (PEAR::isError($connection)) {
  696.             return $connection;
  697.         }
  698.         $statement @ibase_prepare($connection$query);
  699.         if (!$statement{
  700.             $err =$this->raiseError(MDB2_ERRORnullnull,
  701.                 'Could not create statement');
  702.             return $err;
  703.         }
  704.  
  705.         $class_name 'MDB2_Statement_'.$this->phptype;
  706.         $obj =new $class_name($this$statement$positions$query$types$result_types$is_manip$limit$offset);
  707.         return $obj;
  708.     }
  709.  
  710.     // }}}
  711.     // {{{ getSequenceName()
  712.  
  713.     /**
  714.      * adds sequence name formatting to a sequence name
  715.      *
  716.      * @param string $sqn name of the sequence
  717.      * @return string formatted sequence name
  718.      * @access public
  719.      */
  720.     function getSequenceName($sqn)
  721.     {
  722.         return strtoupper(parent::getSequenceName($sqn));
  723.     }
  724.  
  725.     // }}}
  726.     // {{{ nextID()
  727.  
  728.     /**
  729.      * returns the next free id of a sequence
  730.      *
  731.      * @param string $seq_name name of the sequence
  732.      * @param boolean $ondemand when true the seqence is
  733.      *                           automatic created, if it
  734.      *                           not exists
  735.      * @return mixed MDB2 Error Object or id
  736.      * @access public
  737.      */
  738.     function nextID($seq_name$ondemand = true)
  739.     {
  740.         $sequence_name $this->getSequenceName($seq_name);
  741.         $query 'SELECT GEN_ID('.$sequence_name.', 1) as the_value FROM RDB$DATABASE';
  742.         $this->expectError('*');
  743.         $result $this->queryOne($query'integer');
  744.         $this->popExpect();
  745.         if (PEAR::isError($result)) {
  746.             if ($ondemand{
  747.                 $this->loadModule('Manager'nulltrue);
  748.                 // Since we are creating the sequence on demand
  749.                 // we know the first id = 1 so initialize the
  750.                 // sequence at 2
  751.                 $result $this->manager->createSequence($seq_name2);
  752.                 if (PEAR::isError($result)) {
  753.                     return $this->raiseError(MDB2_ERRORnullnull,
  754.                         'nextID: on demand sequence could not be created');
  755.                 else {
  756.                     // First ID of a newly created sequence is 1
  757.                     // return 1;
  758.                     // BUT generators are not always reset, so return the actual value
  759.                     return $this->currID($seq_name);
  760.                 }
  761.             }
  762.         }
  763.         return $result;
  764.     }
  765.  
  766.     // }}}
  767.     // {{{ currID()
  768.  
  769.     /**
  770.      * returns the current id of a sequence
  771.      *
  772.      * @param string $seq_name name of the sequence
  773.      * @return mixed MDB2 Error Object or id
  774.      * @access public
  775.      */
  776.     function currID($seq_name)
  777.     {
  778.         $sequence_name $this->getSequenceName($seq_name);
  779.         $query 'SELECT GEN_ID('.$sequence_name.', 0) as the_value FROM RDB$DATABASE';
  780.         $value @$this->queryOne($query);
  781.         if (PEAR::isError($value)) {
  782.             return $this->raiseError(MDB2_ERRORnullnull,
  783.                 'currID: Unable to select from ' $seq_name;
  784.         }
  785.         if (!is_numeric($value)) {
  786.             return $this->raiseError(MDB2_ERRORnullnull,
  787.                 'currID: could not find value in sequence table');
  788.         }
  789.         return $value;
  790.     }
  791.  
  792.     // }}}
  793. }
  794.  
  795. class MDB2_Result_ibase extends MDB2_Result_Common
  796. {
  797.     // {{{ _skipLimitOffset()
  798.  
  799.     /**
  800.      * Skip the first row of a result set.
  801.      *
  802.      * @param resource $result 
  803.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  804.      * @access protected
  805.      */
  806.     function _skipLimitOffset()
  807.     {
  808.         if ($this->db->supports('limit_queries'=== true{
  809.             return true;
  810.         }
  811.         if ($this->limit{
  812.             if ($this->rownum $this->limit{
  813.                 return false;
  814.             }
  815.         }
  816.         if ($this->offset{
  817.             while ($this->offset_count $this->offset{
  818.                 ++$this->offset_count;
  819.                 if (!is_array(@ibase_fetch_row($this->result))) {
  820.                     $this->offset_count $this->offset;
  821.                     return false;
  822.                 }
  823.             }
  824.         }
  825.         return true;
  826.     }
  827.  
  828.     // }}}
  829.     // {{{ fetchRow()
  830.  
  831.     /**
  832.      * Fetch a row and insert the data into an existing array.
  833.      *
  834.      * @param int  $fetchmode how the array data should be indexed
  835.      * @param int  $rownum    number of the row where the data can be found
  836.      * @return int data array on success, a MDB2 error on failure
  837.      * @access public
  838.      */
  839.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  840.     {
  841.         if ($this->result === true{
  842.             //query successfully executed, but without results...
  843.             $null = null;
  844.             return $null;
  845.         }
  846.         if (!$this->_skipLimitOffset()) {
  847.             $null = null;
  848.             return $null;
  849.         }
  850.         if (!is_null($rownum)) {
  851.             $seek $this->seek($rownum);
  852.             if (PEAR::isError($seek)) {
  853.                 return $seek;
  854.             }
  855.         }
  856.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  857.             $fetchmode $this->db->fetchmode;
  858.         }
  859.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  860.             $row @ibase_fetch_assoc($this->result);
  861.             if (is_array($row)
  862.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  863.             {
  864.                 $row array_change_key_case($row$this->db->options['field_case']);
  865.             }
  866.         else {
  867.             $row @ibase_fetch_row($this->result);
  868.         }
  869.         if (!$row{
  870.             if ($this->result === false{
  871.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  872.                     'fetchRow: resultset has already been freed');
  873.                 return $err;
  874.             }
  875.             $null = null;
  876.             return $null;
  877.         }
  878.         if (($mode ($this->db->options['portability'MDB2_PORTABILITY_RTRIM)
  879.             + ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL))
  880.         {
  881.             $this->db->_fixResultArrayValues($row$mode);
  882.         }
  883.         if (!empty($this->values)) {
  884.             $this->_assignBindColumns($row);
  885.         }
  886.         if (!empty($this->types)) {
  887.             $row $this->db->datatype->convertResultRow($this->types$row);
  888.         }
  889.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  890.             $object_class $this->db->options['fetch_class'];
  891.             if ($object_class == 'stdClass'{
  892.                 $row = (object) $row;
  893.             else {
  894.                 $row &new $object_class($row);
  895.             }
  896.         }
  897.         ++$this->rownum;
  898.         return $row;
  899.     }
  900.  
  901.     // }}}
  902.     // {{{ _getColumnNames()
  903.  
  904.     /**
  905.      * Retrieve the names of columns returned by the DBMS in a query result.
  906.      *
  907.      * @return mixed associative array variable
  908.      *       that holds the names of columns. The indexes of the array are
  909.      *       the column names mapped to lower case and the values are the
  910.      *       respective numbers of the columns starting from 0. Some DBMS may
  911.      *       not return any columns when the result set does not contain any
  912.      *       rows.
  913.      * @access private
  914.      */
  915.     function _getColumnNames()
  916.     {
  917.         $columns = array();
  918.         $numcols $this->numCols();
  919.         if (PEAR::isError($numcols)) {
  920.             return $numcols;
  921.         }
  922.         for ($column = 0; $column $numcols$column++{
  923.             $column_info @ibase_field_info($this->result$column);
  924.             $columns[$column_info['alias']] $column;
  925.         }
  926.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  927.             $columns array_change_key_case($columns$this->db->options['field_case']);
  928.         }
  929.         return $columns;
  930.     }
  931.  
  932.     // }}}
  933.     // {{{ numCols()
  934.  
  935.     /**
  936.      * Count the number of columns returned by the DBMS in a query result.
  937.      *
  938.      * @return mixed integer value with the number of columns, a MDB2 error
  939.      *       on failure
  940.      * @access public
  941.      */
  942.     function numCols()
  943.     {
  944.         if ($this->result === true{
  945.             //query successfully executed, but without results...
  946.             return 0;
  947.         }
  948.  
  949.         if (!is_resource($this->result)) {
  950.             return $this->db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  951.                 'numCols(): not a valid ibase resource');
  952.         }
  953.         $cols @ibase_num_fields($this->result);
  954.         if (is_null($cols)) {
  955.             if ($this->result === false{
  956.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  957.                     'numCols: resultset has already been freed');
  958.             elseif (is_null($this->result)) {
  959.                 return count($this->types);
  960.             }
  961.             return $this->db->raiseError();
  962.         }
  963.         return $cols;
  964.     }
  965.  
  966.     // }}}
  967.     // {{{ free()
  968.  
  969.     /**
  970.      * Free the internal resources associated with $result.
  971.      *
  972.      * @return boolean true on success, false if $result is invalid
  973.      * @access public
  974.      */
  975.     function free()
  976.     {
  977.         if (is_resource($this->result)) {
  978.             $free @ibase_free_result($this->result);
  979.             if (!$free{
  980.                 if (!$this->result{
  981.                     return MDB2_OK;
  982.                 }
  983.                 return $this->db->raiseError();
  984.             }
  985.         }
  986.         $this->result = false;
  987.         return MDB2_OK;
  988.     }
  989.  
  990.     // }}}
  991. }
  992.  
  993. {
  994.     // {{{ class vars
  995.  
  996.     var $buffer;
  997.     var $buffer_rownum = - 1;
  998.  
  999.     // }}}
  1000.     // {{{ _fillBuffer()
  1001.  
  1002.     /**
  1003.      * Fill the row buffer
  1004.      *
  1005.      * @param int $rownum   row number upto which the buffer should be filled
  1006.      *                       if the row number is null all rows are ready into the buffer
  1007.      * @return boolean true on success, false on failure
  1008.      * @access protected
  1009.      */
  1010.     function _fillBuffer($rownum = null)
  1011.     {
  1012.         if (isset($this->buffer&& is_array($this->buffer)) {
  1013.             if (is_null($rownum)) {
  1014.                 if (!end($this->buffer)) {
  1015.                     return false;
  1016.                 }
  1017.             elseif (isset($this->buffer[$rownum])) {
  1018.                 return (bool) $this->buffer[$rownum];
  1019.             }
  1020.         }
  1021.  
  1022.         if (!$this->_skipLimitOffset()) {
  1023.             return false;
  1024.         }
  1025.  
  1026.         $buffer = true;
  1027.         while ((is_null($rownum|| $this->buffer_rownum < $rownum)
  1028.             && (!$this->limit || $this->buffer_rownum < $this->limit)
  1029.             && ($buffer @ibase_fetch_row($this->result))
  1030.         {
  1031.             ++$this->buffer_rownum;
  1032.             $this->buffer[$this->buffer_rownum$buffer;
  1033.         }
  1034.  
  1035.         if (!$buffer{
  1036.             ++$this->buffer_rownum;
  1037.             $this->buffer[$this->buffer_rownum= false;
  1038.             return false;
  1039.         elseif ($this->limit && $this->buffer_rownum >= $this->limit{
  1040.             ++$this->buffer_rownum;
  1041.             $this->buffer[$this->buffer_rownum= false;
  1042.         }
  1043.         return true;
  1044.     }
  1045.  
  1046.     // }}}
  1047.     // {{{ fetchRow()
  1048.  
  1049.     /**
  1050.      * Fetch a row and insert the data into an existing array.
  1051.      *
  1052.      * @param int       $fetchmode  how the array data should be indexed
  1053.      * @param int    $rownum    number of the row where the data can be found
  1054.      * @return int data array on success, a MDB2 error on failure
  1055.      * @access public
  1056.      */
  1057.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  1058.     {
  1059.         if ($this->result === true || is_null($this->result)) {
  1060.             //query successfully executed, but without results...
  1061.             $null = null;
  1062.             return $null;
  1063.         }
  1064.         if ($this->result === false{
  1065.             $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1066.                 'fetchRow: resultset has already been freed');
  1067.             return $err;
  1068.         }
  1069.         if (!is_null($rownum)) {
  1070.             $seek $this->seek($rownum);
  1071.             if (PEAR::isError($seek)) {
  1072.                 return $seek;
  1073.             }
  1074.         }
  1075.         $target_rownum $this->rownum + 1;
  1076.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  1077.             $fetchmode $this->db->fetchmode;
  1078.         }
  1079.         if (!$this->_fillBuffer($target_rownum)) {
  1080.             $null = null;
  1081.             return $null;
  1082.         }
  1083.         $row $this->buffer[$target_rownum];
  1084.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  1085.             $column_names $this->getColumnNames();
  1086.             foreach ($column_names as $name => $i{
  1087.                 $column_names[$name$row[$i];
  1088.             }
  1089.             $row $column_names;
  1090.         }
  1091.         if (($mode ($this->db->options['portability'MDB2_PORTABILITY_RTRIM)
  1092.             + ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL))
  1093.         {
  1094.             $this->db->_fixResultArrayValues($row$mode);
  1095.         }
  1096.         if (!empty($this->values)) {
  1097.             $this->_assignBindColumns($row);
  1098.         }
  1099.         if (!empty($this->types)) {
  1100.             $row $this->db->datatype->convertResultRow($this->types$row);
  1101.         }
  1102.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  1103.             $object_class $this->db->options['fetch_class'];
  1104.             if ($object_class == 'stdClass'{
  1105.                 $row = (object) $row;
  1106.             else {
  1107.                 $row &new $object_class($row);
  1108.             }
  1109.         }
  1110.         ++$this->rownum;
  1111.         return $row;
  1112.     }
  1113.  
  1114.     // }}}
  1115.     // {{{ seek()
  1116.  
  1117.     /**
  1118.      * seek to a specific row in a result set
  1119.      *
  1120.      * @param int    $rownum    number of the row where the data can be found
  1121.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1122.      * @access public
  1123.      */
  1124.     function seek($rownum = 0)
  1125.     {
  1126.         if ($this->result === false{
  1127.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1128.                 'seek: resultset has already been freed');
  1129.         }
  1130.         $this->rownum $rownum - 1;
  1131.         return MDB2_OK;
  1132.     }
  1133.  
  1134.     // }}}
  1135.     // {{{ valid()
  1136.  
  1137.     /**
  1138.      * check if the end of the result set has been reached
  1139.      *
  1140.      * @return mixed true or false on sucess, a MDB2 error on failure
  1141.      * @access public
  1142.      */
  1143.     function valid()
  1144.     {
  1145.         if ($this->result === false{
  1146.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1147.                 'valid: resultset has already been freed');
  1148.         elseif (is_null($this->result)) {
  1149.             return true;
  1150.         }
  1151.         if ($this->_fillBuffer($this->rownum + 1)) {
  1152.             return true;
  1153.         }
  1154.         return false;
  1155.     }
  1156.  
  1157.     // }}}
  1158.     // {{{ numRows()
  1159.  
  1160.     /**
  1161.      * returns the number of rows in a result object
  1162.      *
  1163.      * @return mixed MDB2 Error Object or the number of rows
  1164.      * @access public
  1165.      */
  1166.     function numRows()
  1167.     {
  1168.         if ($this->result === false{
  1169.             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1170.                 'numRows: resultset has already been freed');
  1171.         elseif (is_null($this->result)) {
  1172.             return 0;
  1173.         }
  1174.         $this->_fillBuffer();
  1175.         return $this->buffer_rownum;
  1176.     }
  1177.  
  1178.     // }}}
  1179.     // {{{ free()
  1180.  
  1181.     /**
  1182.      * Free the internal resources associated with $result.
  1183.      *
  1184.      * @return boolean true on success, false if $result is invalid
  1185.      * @access public
  1186.      */
  1187.     function free()
  1188.     {
  1189.         $this->buffer = null;
  1190.         $this->buffer_rownum = null;
  1191.         $free = parent::free();
  1192.     }
  1193.  
  1194.     // }}}
  1195. }
  1196.  
  1197. class MDB2_Statement_ibase extends MDB2_Statement_Common
  1198. {
  1199.     // {{{ _execute()
  1200.  
  1201.     /**
  1202.      * Execute a prepared query statement helper method.
  1203.      *
  1204.      * @param mixed $result_class string which specifies which result class to use
  1205.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1206.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1207.      * @access private
  1208.      */
  1209.     function &_execute($result_class = true$result_wrap_class = false)
  1210.     {
  1211.         $this->db->last_query = $this->query;
  1212.         $this->db->debug($this->query'execute');
  1213.         if ($this->db->getOption('disable_query')) {
  1214.             if ($this->is_manip{
  1215.                 $return = 0;
  1216.                 return $return;
  1217.             }
  1218.             $null = null;
  1219.             return $null;
  1220.         }
  1221.  
  1222.         $connection $this->db->getConnection();
  1223.         if (PEAR::isError($connection)) {
  1224.             return $connection;
  1225.         }
  1226.  
  1227.         $parameters = array(0 => $this->statement);
  1228.         foreach ($this->positions as $parameter => $current_position{
  1229.             if (!array_key_exists($parameter$this->values)) {
  1230.                 return $this->db->raiseError();
  1231.             }
  1232.             $value $this->values[$parameter];
  1233.             $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1234.             $parameters[$this->db->quote($value$typefalse);
  1235.         }
  1236.  
  1237.         $result @call_user_func_array('ibase_execute'$parameters);
  1238.         if ($result === false{
  1239.             $err =$this->db->raiseError();
  1240.             return $err;
  1241.         }
  1242.  
  1243.         if ($this->is_manip{
  1244.             $affected_rows $this->db->_affectedRows($connection);
  1245.             return $affected_rows;
  1246.         }
  1247.  
  1248.         $result =$this->db->_wrapResult($result$this->result_types,
  1249.             $result_class$result_wrap_class$this->limit$this->offset);
  1250.         return $result;
  1251.     }
  1252.  
  1253.     // }}}
  1254.  
  1255.     // }}}
  1256.     // {{{ free()
  1257.  
  1258.     /**
  1259.      * Release resources allocated for the specified prepared query.
  1260.      *
  1261.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1262.      * @access public
  1263.      */
  1264.     function free()
  1265.     {
  1266.         if (!@ibase_free_query($this->statement)) {
  1267.             return $this->db->raiseError();
  1268.         }
  1269.         return MDB2_OK;
  1270.     }
  1271. }
  1272. ?>

Documentation generated on Mon, 11 Mar 2019 14:39:21 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.