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

Source for file mysql.php

Documentation is available at mysql.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: Lukas Smith <smith@pooteeweet.org>                           |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mysql.php,v 1.195 2007/11/10 13:27:03 quipo Exp $
  47. //
  48.  
  49. /**
  50.  * MDB2 MySQL driver
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Lukas Smith <smith@pooteeweet.org>
  55.  */
  56. class MDB2_Driver_mysql extends MDB2_Driver_Common
  57. {
  58.     // {{{ properties
  59.  
  60.     var $string_quoting = array('start' => "'"'end' => "'"'escape' => '\\''escape_pattern' => '\\');
  61.  
  62.     var $identifier_quoting = array('start' => '`''end' => '`''escape' => '`');
  63.  
  64.     var $sql_comments = array(
  65.         array('start' => '-- ''end' => "\n"'escape' => false),
  66.         array('start' => '#''end' => "\n"'escape' => false),
  67.         array('start' => '/*''end' => '*/''escape' => false),
  68.     );
  69.  
  70.     var $server_capabilities_checked = false;
  71.  
  72.     var $start_transaction = false;
  73.  
  74.     var $varchar_max_length = 255;
  75.  
  76.     // }}}
  77.     // {{{ constructor
  78.  
  79.     /**
  80.      * Constructor
  81.      */
  82.     function __construct()
  83.     {
  84.         parent::__construct();
  85.  
  86.         $this->phptype 'mysql';
  87.         $this->dbsyntax 'mysql';
  88.  
  89.         $this->supported['sequences''emulated';
  90.         $this->supported['indexes'= true;
  91.         $this->supported['affected_rows'= true;
  92.         $this->supported['transactions'= false;
  93.         $this->supported['savepoints'= false;
  94.         $this->supported['summary_functions'= true;
  95.         $this->supported['order_by_text'= true;
  96.         $this->supported['current_id''emulated';
  97.         $this->supported['limit_queries'= true;
  98.         $this->supported['LOBs'= true;
  99.         $this->supported['replace'= true;
  100.         $this->supported['sub_selects''emulated';
  101.         $this->supported['auto_increment'= true;
  102.         $this->supported['primary_key'= true;
  103.         $this->supported['result_introspection'= true;
  104.         $this->supported['prepared_statements''emulated';
  105.         $this->supported['identifier_quoting'= true;
  106.         $this->supported['pattern_escaping'= true;
  107.         $this->supported['new_link'= true;
  108.  
  109.         $this->options['default_table_type''';
  110.     }
  111.  
  112.     // }}}
  113.     // {{{ errorInfo()
  114.  
  115.     /**
  116.      * This method is used to collect information about an error
  117.      *
  118.      * @param integer $error 
  119.      * @return array 
  120.      * @access public
  121.      */
  122.     function errorInfo($error = null)
  123.     {
  124.         if ($this->connection{
  125.             $native_code @mysql_errno($this->connection);
  126.             $native_msg  @mysql_error($this->connection);
  127.         else {
  128.             $native_code @mysql_errno();
  129.             $native_msg  @mysql_error();
  130.         }
  131.         if (is_null($error)) {
  132.             static $ecode_map;
  133.             if (empty($ecode_map)) {
  134.                 $ecode_map = array(
  135.                     1000 => MDB2_ERROR_INVALID//hashchk
  136.                     1001 => MDB2_ERROR_INVALID//isamchk
  137.                     1004 => MDB2_ERROR_CANNOT_CREATE,
  138.                     1005 => MDB2_ERROR_CANNOT_CREATE,
  139.                     1006 => MDB2_ERROR_CANNOT_CREATE,
  140.                     1007 => MDB2_ERROR_ALREADY_EXISTS,
  141.                     1008 => MDB2_ERROR_CANNOT_DROP,
  142.                     1009 => MDB2_ERROR_CANNOT_DROP,
  143.                     1010 => MDB2_ERROR_CANNOT_DROP,
  144.                     1011 => MDB2_ERROR_CANNOT_DELETE,
  145.                     1022 => MDB2_ERROR_ALREADY_EXISTS,
  146.                     1029 => MDB2_ERROR_NOT_FOUND,
  147.                     1032 => MDB2_ERROR_NOT_FOUND,
  148.                     1044 => MDB2_ERROR_ACCESS_VIOLATION,
  149.                     1045 => MDB2_ERROR_ACCESS_VIOLATION,
  150.                     1046 => MDB2_ERROR_NODBSELECTED,
  151.                     1048 => MDB2_ERROR_CONSTRAINT,
  152.                     1049 => MDB2_ERROR_NOSUCHDB,
  153.                     1050 => MDB2_ERROR_ALREADY_EXISTS,
  154.                     1051 => MDB2_ERROR_NOSUCHTABLE,
  155.                     1054 => MDB2_ERROR_NOSUCHFIELD,
  156.                     1060 => MDB2_ERROR_ALREADY_EXISTS,
  157.                     1061 => MDB2_ERROR_ALREADY_EXISTS,
  158.                     1062 => MDB2_ERROR_ALREADY_EXISTS,
  159.                     1064 => MDB2_ERROR_SYNTAX,
  160.                     1067 => MDB2_ERROR_INVALID,
  161.                     1072 => MDB2_ERROR_NOT_FOUND,
  162.                     1086 => MDB2_ERROR_ALREADY_EXISTS,
  163.                     1091 => MDB2_ERROR_NOT_FOUND,
  164.                     1100 => MDB2_ERROR_NOT_LOCKED,
  165.                     1109 => MDB2_ERROR_NOT_FOUND,
  166.                     1125 => MDB2_ERROR_ALREADY_EXISTS,
  167.                     1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  168.                     1138 => MDB2_ERROR_INVALID,
  169.                     1142 => MDB2_ERROR_ACCESS_VIOLATION,
  170.                     1143 => MDB2_ERROR_ACCESS_VIOLATION,
  171.                     1146 => MDB2_ERROR_NOSUCHTABLE,
  172.                     1149 => MDB2_ERROR_SYNTAX,
  173.                     1169 => MDB2_ERROR_CONSTRAINT,
  174.                     1176 => MDB2_ERROR_NOT_FOUND,
  175.                     1177 => MDB2_ERROR_NOSUCHTABLE,
  176.                     1213 => MDB2_ERROR_DEADLOCK,
  177.                     1216 => MDB2_ERROR_CONSTRAINT,
  178.                     1217 => MDB2_ERROR_CONSTRAINT,
  179.                     1227 => MDB2_ERROR_ACCESS_VIOLATION,
  180.                     1299 => MDB2_ERROR_INVALID_DATE,
  181.                     1300 => MDB2_ERROR_INVALID,
  182.                     1304 => MDB2_ERROR_ALREADY_EXISTS,
  183.                     1305 => MDB2_ERROR_NOT_FOUND,
  184.                     1306 => MDB2_ERROR_CANNOT_DROP,
  185.                     1307 => MDB2_ERROR_CANNOT_CREATE,
  186.                     1334 => MDB2_ERROR_CANNOT_ALTER,
  187.                     1339 => MDB2_ERROR_NOT_FOUND,
  188.                     1356 => MDB2_ERROR_INVALID,
  189.                     1359 => MDB2_ERROR_ALREADY_EXISTS,
  190.                     1360 => MDB2_ERROR_NOT_FOUND,
  191.                     1363 => MDB2_ERROR_NOT_FOUND,
  192.                     1365 => MDB2_ERROR_DIVZERO,
  193.                     1451 => MDB2_ERROR_CONSTRAINT,
  194.                     1452 => MDB2_ERROR_CONSTRAINT,
  195.                     1542 => MDB2_ERROR_CANNOT_DROP,
  196.                     1546 => MDB2_ERROR_CONSTRAINT,
  197.                     1582 => MDB2_ERROR_CONSTRAINT,
  198.                 );
  199.             }
  200.             if ($this->options['portability'MDB2_PORTABILITY_ERRORS{
  201.                 $ecode_map[1022= MDB2_ERROR_CONSTRAINT;
  202.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT_NOT_NULL;
  203.                 $ecode_map[1062= MDB2_ERROR_CONSTRAINT;
  204.             else {
  205.                 // Doing this in case mode changes during runtime.
  206.                 $ecode_map[1022= MDB2_ERROR_ALREADY_EXISTS;
  207.                 $ecode_map[1048= MDB2_ERROR_CONSTRAINT;
  208.                 $ecode_map[1062= MDB2_ERROR_ALREADY_EXISTS;
  209.             }
  210.             if (isset($ecode_map[$native_code])) {
  211.                 $error $ecode_map[$native_code];
  212.             }
  213.         }
  214.         return array($error$native_code$native_msg);
  215.     }
  216.  
  217.     // }}}
  218.     // {{{ escape()
  219.  
  220.     /**
  221.      * Quotes a string so it can be safely used in a query. It will quote
  222.      * the text so it can safely be used within a query.
  223.      *
  224.      * @param   string  the input string to quote
  225.      * @param   bool    escape wildcards
  226.      *
  227.      * @return  string  quoted string
  228.      *
  229.      * @access  public
  230.      */
  231.     function escape($text$escape_wildcards = false)
  232.     {
  233.         if ($escape_wildcards{
  234.             $text $this->escapePattern($text);
  235.         }
  236.         $connection $this->getConnection();
  237.         if (PEAR::isError($connection)) {
  238.             return $connection;
  239.         }
  240.         $text @mysql_real_escape_string($text$connection);
  241.         return $text;
  242.     }
  243.  
  244.     // }}}
  245.     // {{{ beginTransaction()
  246.  
  247.     /**
  248.      * Start a transaction or set a savepoint.
  249.      *
  250.      * @param   string  name of a savepoint to set
  251.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  252.      *
  253.      * @access  public
  254.      */
  255.     function beginTransaction($savepoint = null)
  256.     {
  257.         $this->debug('Starting transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  258.         $this->_getServerCapabilities();
  259.         if (!is_null($savepoint)) {
  260.             if (!$this->supports('savepoints')) {
  261.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  262.                     'savepoints are not supported'__FUNCTION__);
  263.             }
  264.             if (!$this->in_transaction{
  265.                 return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  266.                     'savepoint cannot be released when changes are auto committed'__FUNCTION__);
  267.             }
  268.             $query 'SAVEPOINT '.$savepoint;
  269.             return $this->_doQuery($querytrue);
  270.         elseif ($this->in_transaction{
  271.             return MDB2_OK;  //nothing to do
  272.         }
  273.         if (!$this->destructor_registered && $this->opened_persistent{
  274.             $this->destructor_registered = true;
  275.             register_shutdown_function('MDB2_closeOpenTransactions');
  276.         }
  277.         $query $this->start_transaction ? 'START TRANSACTION' 'SET AUTOCOMMIT = 1';
  278.         $result =$this->_doQuery($querytrue);
  279.         if (PEAR::isError($result)) {
  280.             return $result;
  281.         }
  282.         $this->in_transaction = true;
  283.         return MDB2_OK;
  284.     }
  285.  
  286.     // }}}
  287.     // {{{ commit()
  288.  
  289.     /**
  290.      * Commit the database changes done during a transaction that is in
  291.      * progress or release a savepoint. This function may only be called when
  292.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  293.      * transaction is implicitly started after committing the pending changes.
  294.      *
  295.      * @param   string  name of a savepoint to release
  296.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  297.      *
  298.      * @access  public
  299.      */
  300.     function commit($savepoint = null)
  301.     {
  302.         $this->debug('Committing transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  303.         if (!$this->in_transaction{
  304.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  305.                 'commit/release savepoint cannot be done changes are auto committed'__FUNCTION__);
  306.         }
  307.         if (!is_null($savepoint)) {
  308.             if (!$this->supports('savepoints')) {
  309.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  310.                     'savepoints are not supported'__FUNCTION__);
  311.             }
  312.             $server_info $this->getServerVersion();
  313.             if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'5.0.3''<')) {
  314.                 return MDB2_OK;
  315.             }
  316.             $query 'RELEASE SAVEPOINT '.$savepoint;
  317.             return $this->_doQuery($querytrue);
  318.         }
  319.  
  320.         if (!$this->supports('transactions')) {
  321.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  322.                 'transactions are not supported'__FUNCTION__);
  323.         }
  324.  
  325.         $result =$this->_doQuery('COMMIT'true);
  326.         if (PEAR::isError($result)) {
  327.             return $result;
  328.         }
  329.         if (!$this->start_transaction{
  330.             $query 'SET AUTOCOMMIT = 0';
  331.             $result =$this->_doQuery($querytrue);
  332.             if (PEAR::isError($result)) {
  333.                 return $result;
  334.             }
  335.         }
  336.         $this->in_transaction = false;
  337.         return MDB2_OK;
  338.     }
  339.  
  340.     // }}}
  341.     // {{{ rollback()
  342.  
  343.     /**
  344.      * Cancel any database changes done during a transaction or since a specific
  345.      * savepoint that is in progress. This function may only be called when
  346.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  347.      * transaction is implicitly started after canceling the pending changes.
  348.      *
  349.      * @param   string  name of a savepoint to rollback to
  350.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  351.      *
  352.      * @access  public
  353.      */
  354.     function rollback($savepoint = null)
  355.     {
  356.         $this->debug('Rolling back transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  357.         if (!$this->in_transaction{
  358.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  359.                 'rollback cannot be done changes are auto committed'__FUNCTION__);
  360.         }
  361.         if (!is_null($savepoint)) {
  362.             if (!$this->supports('savepoints')) {
  363.                 return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  364.                     'savepoints are not supported'__FUNCTION__);
  365.             }
  366.             $query 'ROLLBACK TO SAVEPOINT '.$savepoint;
  367.             return $this->_doQuery($querytrue);
  368.         }
  369.  
  370.         $query 'ROLLBACK';
  371.         $result =$this->_doQuery($querytrue);
  372.         if (PEAR::isError($result)) {
  373.             return $result;
  374.         }
  375.         if (!$this->start_transaction{
  376.             $query 'SET AUTOCOMMIT = 0';
  377.             $result =$this->_doQuery($querytrue);
  378.             if (PEAR::isError($result)) {
  379.                 return $result;
  380.             }
  381.         }
  382.         $this->in_transaction = false;
  383.         return MDB2_OK;
  384.     }
  385.  
  386.     // }}}
  387.     // {{{ function setTransactionIsolation()
  388.  
  389.     /**
  390.      * Set the transacton isolation level.
  391.      *
  392.      * @param   string  standard isolation level
  393.      *                   READ UNCOMMITTED (allows dirty reads)
  394.      *                   READ COMMITTED (prevents dirty reads)
  395.      *                   REPEATABLE READ (prevents nonrepeatable reads)
  396.      *                   SERIALIZABLE (prevents phantom reads)
  397.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  398.      *
  399.      * @access  public
  400.      * @since   2.1.1
  401.      */
  402.     function setTransactionIsolation($isolation)
  403.     {
  404.         $this->debug('Setting transaction isolation level'__FUNCTION__array('is_manip' => true));
  405.         if (!$this->supports('transactions')) {
  406.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  407.                 'transactions are not supported'__FUNCTION__);
  408.         }
  409.         switch ($isolation{
  410.         case 'READ UNCOMMITTED':
  411.         case 'READ COMMITTED':
  412.         case 'REPEATABLE READ':
  413.         case 'SERIALIZABLE':
  414.             break;
  415.         default:
  416.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  417.                 'isolation level is not supported: '.$isolation__FUNCTION__);
  418.         }
  419.  
  420.         $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  421.         return $this->_doQuery($querytrue);
  422.     }
  423.  
  424.     // }}}
  425.     // {{{ connect()
  426.  
  427.     /**
  428.      * Connect to the database
  429.      *
  430.      * @return true on success, MDB2 Error Object on failure
  431.      */
  432.     function connect()
  433.     {
  434.         if (is_resource($this->connection)) {
  435.             //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  436.             if (MDB2::areEquals($this->connected_dsn$this->dsn)
  437.                 && $this->opened_persistent == $this->options['persistent']
  438.                 && $this->connected_database_name == $this->database_name
  439.             {
  440.                 return MDB2_OK;
  441.             }
  442.             $this->disconnect(false);
  443.         }
  444.  
  445.         if (!PEAR::loadExtension($this->phptype)) {
  446.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  447.                 'extension '.$this->phptype.' is not compiled into PHP'__FUNCTION__);
  448.         }
  449.  
  450.         $params = array();
  451.         if ($this->dsn['protocol'&& $this->dsn['protocol'== 'unix'{
  452.             $params[0':' $this->dsn['socket'];
  453.         else {
  454.             $params[0$this->dsn['hostspec'$this->dsn['hostspec']
  455.                          : 'localhost';
  456.             if ($this->dsn['port']{
  457.                 $params[0].= ':' $this->dsn['port'];
  458.             }
  459.         }
  460.         $params[$this->dsn['username'$this->dsn['username': null;
  461.         $params[$this->dsn['password'$this->dsn['password': null;
  462.         if (!$this->options['persistent']{
  463.             if (isset($this->dsn['new_link'])
  464.                 && ($this->dsn['new_link'== 'true' || $this->dsn['new_link'=== true)
  465.             {
  466.                 $params[= true;
  467.             else {
  468.                 $params[= false;
  469.             }
  470.         }
  471.         if (version_compare(phpversion()'4.3.0''>=')) {
  472.             $params[= isset($this->dsn['client_flags'])
  473.                 ? $this->dsn['client_flags': null;
  474.         }
  475.         $connect_function $this->options['persistent''mysql_pconnect' 'mysql_connect';
  476.  
  477.         $connection @call_user_func_array($connect_function$params);
  478.         if (!$connection{
  479.             if (($err @mysql_error()) != ''{
  480.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  481.                     $err__FUNCTION__);
  482.             else {
  483.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  484.                     'unable to establish a connection'__FUNCTION__);
  485.             }
  486.         }
  487.  
  488.         if (!empty($this->dsn['charset'])) {
  489.             $result $this->setCharset($this->dsn['charset']$connection);
  490.             if (PEAR::isError($result)) {
  491.                 return $result;
  492.             }
  493.         }
  494.  
  495.         $this->connection $connection;
  496.         $this->connected_dsn $this->dsn;
  497.         $this->connected_database_name '';
  498.         $this->opened_persistent $this->options['persistent'];
  499.         $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  500.  
  501.         if ($this->database_name{
  502.             if ($this->database_name != $this->connected_database_name{
  503.                 if (!@mysql_select_db($this->database_name$connection)) {
  504.                     $err $this->raiseError(nullnullnull,
  505.                         'Could not select the database: '.$this->database_name__FUNCTION__);
  506.                     return $err;
  507.                 }
  508.                 $this->connected_database_name $this->database_name;
  509.             }
  510.         }
  511.  
  512.         $this->supported['transactions'$this->options['use_transactions'];
  513.         if ($this->options['default_table_type']{
  514.             switch (strtoupper($this->options['default_table_type'])) {
  515.             case 'BLACKHOLE':
  516.             case 'MEMORY':
  517.             case 'ARCHIVE':
  518.             case 'CSV':
  519.             case 'HEAP':
  520.             case 'ISAM':
  521.             case 'MERGE':
  522.             case 'MRG_ISAM':
  523.             case 'ISAM':
  524.             case 'MRG_MYISAM':
  525.             case 'MYISAM':
  526.                 $this->supported['transactions'= false;
  527.                 $this->warnings[$this->options['default_table_type'.
  528.                     ' is not a supported default table type';
  529.                 break;
  530.             }
  531.         }
  532.         
  533.         $this->_getServerCapabilities();
  534.  
  535.         return MDB2_OK;
  536.     }
  537.  
  538.     // }}}
  539.     // {{{ setCharset()
  540.  
  541.     /**
  542.      * Set the charset on the current connection
  543.      *
  544.      * @param string    charset
  545.      * @param resource  connection handle
  546.      *
  547.      * @return true on success, MDB2 Error Object on failure
  548.      */
  549.     function setCharset($charset$connection = null)
  550.     {
  551.         if (is_null($connection)) {
  552.             $connection $this->getConnection();
  553.             if (PEAR::isError($connection)) {
  554.                 return $connection;
  555.             }
  556.         }
  557.         $query "SET NAMES '".mysql_real_escape_string($charset$connection)."'";
  558.         return $this->_doQuery($querytrue$connection);
  559.     }
  560.  
  561.     // }}}
  562.     // {{{ disconnect()
  563.  
  564.     /**
  565.      * Log out and disconnect from the database.
  566.      *
  567.      * @param  boolean $force if the disconnect should be forced even if the
  568.      *                         connection is opened persistently
  569.      * @return mixed true on success, false if not connected and error
  570.      *                 object on error
  571.      * @access public
  572.      */
  573.     function disconnect($force = true)
  574.     {
  575.         if (is_resource($this->connection)) {
  576.             if ($this->in_transaction{
  577.                 $dsn $this->dsn;
  578.                 $database_name $this->database_name;
  579.                 $persistent $this->options['persistent'];
  580.                 $this->dsn $this->connected_dsn;
  581.                 $this->database_name $this->connected_database_name;
  582.                 $this->options['persistent'$this->opened_persistent;
  583.                 $this->rollback();
  584.                 $this->dsn $dsn;
  585.                 $this->database_name $database_name;
  586.                 $this->options['persistent'$persistent;
  587.             }
  588.  
  589.             if (!$this->opened_persistent || $force{
  590.                 @mysql_close($this->connection);
  591.             }
  592.         }
  593.         return parent::disconnect($force);
  594.     }
  595.  
  596.     // }}}
  597.     // {{{ _doQuery()
  598.  
  599.     /**
  600.      * Execute a query
  601.      * @param string $query  query
  602.      * @param boolean $is_manip  if the query is a manipulation query
  603.      * @param resource $connection 
  604.      * @param string $database_name 
  605.      * @return result or error object
  606.      * @access protected
  607.      */
  608.     function &_doQuery($query$is_manip = false$connection = null$database_name = null)
  609.     {
  610.         $this->last_query $query;
  611.         $result $this->debug($query'query'array('is_manip' => $is_manip'when' => 'pre'));
  612.         if ($result{
  613.             if (PEAR::isError($result)) {
  614.                 return $result;
  615.             }
  616.             $query $result;
  617.         }
  618.         if ($this->options['disable_query']{
  619.             $result $is_manip ? 0 : null;
  620.             return $result;
  621.         }
  622.  
  623.         if (is_null($connection)) {
  624.             $connection $this->getConnection();
  625.             if (PEAR::isError($connection)) {
  626.                 return $connection;
  627.             }
  628.         }
  629.         if (is_null($database_name)) {
  630.             $database_name $this->database_name;
  631.         }
  632.  
  633.         if ($database_name{
  634.             if ($database_name != $this->connected_database_name{
  635.                 if (!@mysql_select_db($database_name$connection)) {
  636.                     $err $this->raiseError(nullnullnull,
  637.                         'Could not select the database: '.$database_name__FUNCTION__);
  638.                     return $err;
  639.                 }
  640.                 $this->connected_database_name $database_name;
  641.             }
  642.         }
  643.  
  644.         $function $this->options['result_buffering']
  645.             ? 'mysql_query' 'mysql_unbuffered_query';
  646.         $result @$function($query$connection);
  647.         if (!$result{
  648.             $err =$this->raiseError(nullnullnull,
  649.                 'Could not execute statement'__FUNCTION__);
  650.             return $err;
  651.         }
  652.  
  653.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  654.         return $result;
  655.     }
  656.  
  657.     // }}}
  658.     // {{{ _affectedRows()
  659.  
  660.     /**
  661.      * Returns the number of rows affected
  662.      *
  663.      * @param resource $result 
  664.      * @param resource $connection 
  665.      * @return mixed MDB2 Error Object or the number of rows affected
  666.      * @access private
  667.      */
  668.     function _affectedRows($connection$result = null)
  669.     {
  670.         if (is_null($connection)) {
  671.             $connection $this->getConnection();
  672.             if (PEAR::isError($connection)) {
  673.                 return $connection;
  674.             }
  675.         }
  676.         return @mysql_affected_rows($connection);
  677.     }
  678.  
  679.     // }}}
  680.     // {{{ _modifyQuery()
  681.  
  682.     /**
  683.      * Changes a query string for various DBMS specific reasons
  684.      *
  685.      * @param string $query  query to modify
  686.      * @param boolean $is_manip  if it is a DML query
  687.      * @param integer $limit  limit the number of rows
  688.      * @param integer $offset  start reading from given offset
  689.      * @return string modified query
  690.      * @access protected
  691.      */
  692.     function _modifyQuery($query$is_manip$limit$offset)
  693.     {
  694.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  695.             // "DELETE FROM table" gives 0 affected rows in MySQL.
  696.             // This little hack lets you know how many rows were deleted.
  697.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  698.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  699.                                       'DELETE FROM \1 WHERE 1=1'$query);
  700.             }
  701.         }
  702.         if ($limit > 0
  703.             && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i'$query)
  704.         {
  705.             $query rtrim($query);
  706.             if (substr($query-1== ';'{
  707.                 $query substr($query0-1);
  708.             }
  709.  
  710.             // LIMIT doesn't always come last in the query
  711.             // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  712.             $after '';
  713.             if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims'$query$matches)) {
  714.                 $after $matches[0];
  715.                 $query preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims'''$query);
  716.             elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i'$query$matches)) {
  717.                $after $matches[0];
  718.                $query preg_replace('/(\s+FOR\s+UPDATE\s*)$/im'''$query);
  719.             elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im'$query$matches)) {
  720.                $after $matches[0];
  721.                $query preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im'''$query);
  722.             }
  723.  
  724.             if ($is_manip{
  725.                 return $query . " LIMIT $limit" . $after;
  726.             else {
  727.                 return $query . " LIMIT $offset$limit" . $after;
  728.             }
  729.         }
  730.         return $query;
  731.     }
  732.  
  733.     // }}}
  734.     // {{{ getServerVersion()
  735.  
  736.     /**
  737.      * return version information about the server
  738.      *
  739.      * @param bool   $native  determines if the raw version string should be returned
  740.      * @return mixed array/string with version information or MDB2 error object
  741.      * @access public
  742.      */
  743.     function getServerVersion($native = false)
  744.     {
  745.         $connection $this->getConnection();
  746.         if (PEAR::isError($connection)) {
  747.             return $connection;
  748.         }
  749.         if ($this->connected_server_info{
  750.             $server_info $this->connected_server_info;
  751.         else {
  752.             $server_info @mysql_get_server_info($connection);
  753.         }
  754.         if (!$server_info{
  755.             return $this->raiseError(nullnullnull,
  756.                 'Could not get server information'__FUNCTION__);
  757.         }
  758.         // cache server_info
  759.         $this->connected_server_info $server_info;
  760.         if (!$native{
  761.             $tmp explode('.'$server_info3);
  762.             if (isset($tmp[2]&& strpos($tmp[2]'-')) {
  763.                 $tmp2 explode('-'@$tmp[2]2);
  764.             else {
  765.                 $tmp2[0= isset($tmp[2]$tmp[2: null;
  766.                 $tmp2[1= null;
  767.             }
  768.             $server_info = array(
  769.                 'major' => isset($tmp[0]$tmp[0: null,
  770.                 'minor' => isset($tmp[1]$tmp[1: null,
  771.                 'patch' => $tmp2[0],
  772.                 'extra' => $tmp2[1],
  773.                 'native' => $server_info,
  774.             );
  775.         }
  776.         return $server_info;
  777.     }
  778.  
  779.     // }}}
  780.     // {{{ _getServerCapabilities()
  781.  
  782.     /**
  783.      * Fetch some information about the server capabilities
  784.      * (transactions, subselects, prepared statements, etc).
  785.      *
  786.      * @access private
  787.      */
  788.     function _getServerCapabilities()
  789.     {
  790.         if (!$this->server_capabilities_checked{
  791.             $this->server_capabilities_checked = true;
  792.  
  793.             //set defaults
  794.             $this->supported['sub_selects''emulated';
  795.             $this->supported['prepared_statements''emulated';
  796.             $this->start_transaction = false;
  797.             $this->varchar_max_length = 255;
  798.             
  799.             $server_info $this->getServerVersion();
  800.             if (is_array($server_info)) {
  801.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.1.0''<')) {
  802.                     $this->supported['sub_selects'= true;
  803.                     $this->supported['prepared_statements'= true;
  804.                 }
  805.  
  806.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.0.14''<')
  807.                     || !version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.1.1''<')
  808.                 {
  809.                     $this->supported['savepoints'= true;
  810.                 }
  811.  
  812.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'4.0.11''<')) {
  813.                     $this->start_transaction = true;
  814.                 }
  815.  
  816.                 if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']'5.0.3''<')) {
  817.                     $this->varchar_max_length = 65532;
  818.                 }
  819.             }
  820.         }
  821.     }
  822.  
  823.     // }}}
  824.     // {{{ function _skipUserDefinedVariable($query, $position)
  825.  
  826.     /**
  827.      * Utility method, used by prepare() to avoid misinterpreting MySQL user
  828.      * defined variables (SELECT @x:=5) for placeholders.
  829.      * Check if the placeholder is a false positive, i.e. if it is an user defined
  830.      * variable instead. If so, skip it and advance the position, otherwise
  831.      * return the current position, which is valid
  832.      *
  833.      * @param string $query 
  834.      * @param integer $position current string cursor position
  835.      * @return integer $new_position
  836.      * @access protected
  837.      */
  838.     function _skipUserDefinedVariable($query$position)
  839.     {
  840.         $found strpos(strrev(substr($query0$position))'@');
  841.         if ($found === false{
  842.             return $position;
  843.         }
  844.         $pos strlen($querystrlen(substr($query$position)) $found - 1;
  845.         $substring substr($query$pos$position $pos + 2);
  846.         if (preg_match('/^@\w+\s*:=$/'$substring)) {
  847.             return $position + 1; //found an user defined variable: skip it
  848.         }
  849.         return $position;
  850.     }
  851.  
  852.     // }}}
  853.     // {{{ prepare()
  854.  
  855.     /**
  856.      * Prepares a query for multiple execution with execute().
  857.      * With some database backends, this is emulated.
  858.      * prepare() requires a generic query as string like
  859.      * 'INSERT INTO numbers VALUES(?,?)' or
  860.      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  861.      * The ? and :name and are placeholders which can be set using
  862.      * bindParam() and the query can be sent off using the execute() method.
  863.      * The allowed format for :name can be set with the 'bindname_format' option.
  864.      *
  865.      * @param string $query the query to prepare
  866.      * @param mixed   $types  array that contains the types of the placeholders
  867.      * @param mixed   $result_types  array that contains the types of the columns in
  868.      *                         the result set or MDB2_PREPARE_RESULT, if set to
  869.      *                         MDB2_PREPARE_MANIP the query is handled as a manipulation query
  870.      * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
  871.      * @return mixed resource handle for the prepared query on success, a MDB2
  872.      *         error on failure
  873.      * @access public
  874.      * @see bindParam, execute
  875.      */
  876.     function &prepare($query$types = null$result_types = null$lobs = array())
  877.     {
  878.         if ($this->options['emulate_prepared']
  879.             || $this->supported['prepared_statements'!== true
  880.         {
  881.             $obj =parent::prepare($query$types$result_types$lobs);
  882.             return $obj;
  883.         }
  884.         $is_manip ($result_types === MDB2_PREPARE_MANIP);
  885.         $offset $this->offset;
  886.         $limit $this->limit;
  887.         $this->offset $this->limit = 0;
  888.         $query $this->_modifyQuery($query$is_manip$limit$offset);
  889.         $result $this->debug($query__FUNCTION__array('is_manip' => $is_manip'when' => 'pre'));
  890.         if ($result{
  891.             if (PEAR::isError($result)) {
  892.                 return $result;
  893.             }
  894.             $query $result;
  895.         }
  896.         $placeholder_type_guess $placeholder_type = null;
  897.         $question '?';
  898.         $colon ':';
  899.         $positions = array();
  900.         $position = 0;
  901.         while ($position strlen($query)) {
  902.             $q_position strpos($query$question$position);
  903.             $c_position strpos($query$colon$position);
  904.             if ($q_position && $c_position{
  905.                 $p_position min($q_position$c_position);
  906.             elseif ($q_position{
  907.                 $p_position $q_position;
  908.             elseif ($c_position{
  909.                 $p_position $c_position;
  910.             else {
  911.                 break;
  912.             }
  913.             if (is_null($placeholder_type)) {
  914.                 $placeholder_type_guess $query[$p_position];
  915.             }
  916.             
  917.             $new_pos $this->_skipDelimitedStrings($query$position$p_position);
  918.             if (PEAR::isError($new_pos)) {
  919.                 return $new_pos;
  920.             }
  921.             if ($new_pos != $position{
  922.                 $position $new_pos;
  923.                 continue; //evaluate again starting from the new position
  924.             }
  925.             
  926.             //make sure this is not part of an user defined variable
  927.             $new_pos $this->_skipUserDefinedVariable($query$position);
  928.             if ($new_pos != $position{
  929.                 $position $new_pos;
  930.                 continue; //evaluate again starting from the new position
  931.             }
  932.  
  933.             if ($query[$position== $placeholder_type_guess{
  934.                 if (is_null($placeholder_type)) {
  935.                     $placeholder_type $query[$p_position];
  936.                     $question $colon $placeholder_type;
  937.                 }
  938.                 if ($placeholder_type == ':'{
  939.                     $regexp '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  940.                     $parameter preg_replace($regexp'\\1'$query);
  941.                     if ($parameter === ''{
  942.                         $err =$this->raiseError(MDB2_ERROR_SYNTAXnullnull,
  943.                             'named parameter name must match "bindname_format" option'__FUNCTION__);
  944.                         return $err;
  945.                     }
  946.                     $positions[$p_position$parameter;
  947.                     $query substr_replace($query'?'$positionstrlen($parameter)+1);
  948.                 else {
  949.                     $positions[$p_positioncount($positions);
  950.                 }
  951.                 $position $p_position + 1;
  952.             else {
  953.                 $position $p_position;
  954.             }
  955.         }
  956.         $connection $this->getConnection();
  957.         if (PEAR::isError($connection)) {
  958.             return $connection;
  959.         }
  960.         static $prep_statement_counter = 1;
  961.         $statement_name = sprintf($this->options['statement_format']$this->phptypesha1(microtime(+ mt_rand())) $prep_statement_counter++;
  962.         $query = "PREPARE $statement_name FROM ".$this->quote($query'text');
  963.         $statement =$this->_doQuery($querytrue$connection);
  964.         if (PEAR::isError($statement)) {
  965.             return $statement;
  966.         }
  967.  
  968.         $class_name 'MDB2_Statement_'.$this->phptype;
  969.         $obj = new $class_name($this$statement_name$positions$query$types$result_types$is_manip$limit$offset);
  970.         $this->debug($query__FUNCTION__array('is_manip' => $is_manip'when' => 'post''result' => $obj));
  971.         return $obj;
  972.     }
  973.  
  974.     // }}}
  975.     // {{{ replace()
  976.  
  977.     /**
  978.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  979.      * query, except that if there is already a row in the table with the same
  980.      * key field values, the REPLACE query just updates its values instead of
  981.      * inserting a new row.
  982.      *
  983.      * The REPLACE type of query does not make part of the SQL standards. Since
  984.      * practically only MySQL implements it natively, this type of query is
  985.      * emulated through this method for other DBMS using standard types of
  986.      * queries inside a transaction to assure the atomicity of the operation.
  987.      *
  988.      * @access public
  989.      *
  990.      * @param string $table name of the table on which the REPLACE query will
  991.      *   be executed.
  992.      * @param array $fields associative array that describes the fields and the
  993.      *   values that will be inserted or updated in the specified table. The
  994.      *   indexes of the array are the names of all the fields of the table. The
  995.      *   values of the array are also associative arrays that describe the
  996.      *   values and other properties of the table fields.
  997.      *
  998.      *   Here follows a list of field properties that need to be specified:
  999.      *
  1000.      *     value:
  1001.      *           Value to be assigned to the specified field. This value may be
  1002.      *           of specified in database independent type format as this
  1003.      *           function can perform the necessary datatype conversions.
  1004.      *
  1005.      *     Default:
  1006.      *           this property is required unless the Null property
  1007.      *           is set to 1.
  1008.      *
  1009.      *     type
  1010.      *           Name of the type of the field. Currently, all types Metabase
  1011.      *           are supported except for clob and blob.
  1012.      *
  1013.      *     Default: no type conversion
  1014.      *
  1015.      *     null
  1016.      *           Boolean property that indicates that the value for this field
  1017.      *           should be set to null.
  1018.      *
  1019.      *           The default value for fields missing in INSERT queries may be
  1020.      *           specified the definition of a table. Often, the default value
  1021.      *           is already null, but since the REPLACE may be emulated using
  1022.      *           an UPDATE query, make sure that all fields of the table are
  1023.      *           listed in this function argument array.
  1024.      *
  1025.      *     Default: 0
  1026.      *
  1027.      *     key
  1028.      *           Boolean property that indicates that this field should be
  1029.      *           handled as a primary key or at least as part of the compound
  1030.      *           unique index of the table that will determine the row that will
  1031.      *           updated if it exists or inserted a new row otherwise.
  1032.      *
  1033.      *           This function will fail if no key field is specified or if the
  1034.      *           value of a key field is set to null because fields that are
  1035.      *           part of unique index they may not be null.
  1036.      *
  1037.      *     Default: 0
  1038.      *
  1039.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1040.      */
  1041.     function replace($table$fields)
  1042.     {
  1043.         $count count($fields);
  1044.         $query $values '';
  1045.         $keys $colnum = 0;
  1046.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  1047.             $name key($fields);
  1048.             if ($colnum > 0{
  1049.                 $query .= ',';
  1050.                 $values.= ',';
  1051.             }
  1052.             $query.= $name;
  1053.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  1054.                 $value 'NULL';
  1055.             else {
  1056.                 $type = isset($fields[$name]['type']$fields[$name]['type': null;
  1057.                 $value $this->quote($fields[$name]['value']$type);
  1058.                 if (PEAR::isError($value)) {
  1059.                     return $value;
  1060.                 }
  1061.             }
  1062.             $values.= $value;
  1063.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  1064.                 if ($value === 'NULL'{
  1065.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  1066.                         'key value '.$name.' may not be NULL'__FUNCTION__);
  1067.                 }
  1068.                 $keys++;
  1069.             }
  1070.         }
  1071.         if ($keys == 0{
  1072.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  1073.                 'not specified which fields are keys'__FUNCTION__);
  1074.         }
  1075.  
  1076.         $connection $this->getConnection();
  1077.         if (PEAR::isError($connection)) {
  1078.             return $connection;
  1079.         }
  1080.  
  1081.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1082.         $result =$this->_doQuery($querytrue$connection);
  1083.         if (PEAR::isError($result)) {
  1084.             return $result;
  1085.         }
  1086.         return $this->_affectedRows($connection$result);
  1087.     }
  1088.  
  1089.     // }}}
  1090.     // {{{ nextID()
  1091.  
  1092.     /**
  1093.      * Returns the next free id of a sequence
  1094.      *
  1095.      * @param string $seq_name name of the sequence
  1096.      * @param boolean $ondemand when true the sequence is
  1097.      *                           automatic created, if it
  1098.      *                           not exists
  1099.      *
  1100.      * @return mixed MDB2 Error Object or id
  1101.      * @access public
  1102.      */
  1103.     function nextID($seq_name$ondemand = true)
  1104.     {
  1105.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  1106.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  1107.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  1108.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1109.         $result =$this->_doQuery($querytrue);
  1110.         $this->popExpect();
  1111.         if (PEAR::isError($result)) {
  1112.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  1113.                 $this->loadModule('Manager'nulltrue);
  1114.                 $result $this->manager->createSequence($seq_name);
  1115.                 if (PEAR::isError($result)) {
  1116.                     return $this->raiseError($resultnullnull,
  1117.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  1118.                 else {
  1119.                     return $this->nextID($seq_namefalse);
  1120.                 }
  1121.             }
  1122.             return $result;
  1123.         }
  1124.         $value $this->lastInsertID();
  1125.         if (is_numeric($value)) {
  1126.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1127.             $result =$this->_doQuery($querytrue);
  1128.             if (PEAR::isError($result)) {
  1129.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  1130.             }
  1131.         }
  1132.         return $value;
  1133.     }
  1134.  
  1135.     // }}}
  1136.     // {{{ lastInsertID()
  1137.  
  1138.     /**
  1139.      * Returns the autoincrement ID if supported or $id or fetches the current
  1140.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1141.      *
  1142.      * @param string $table name of the table into which a new row was inserted
  1143.      * @param string $field name of the field into which a new row was inserted
  1144.      * @return mixed MDB2 Error Object or id
  1145.      * @access public
  1146.      */
  1147.     function lastInsertID($table = null$field = null)
  1148.     {
  1149.         // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1150.         return $this->queryOne('SELECT LAST_INSERT_ID()''integer');
  1151.     }
  1152.  
  1153.     // }}}
  1154.     // {{{ currID()
  1155.  
  1156.     /**
  1157.      * Returns the current id of a sequence
  1158.      *
  1159.      * @param string $seq_name name of the sequence
  1160.      * @return mixed MDB2 Error Object or id
  1161.      * @access public
  1162.      */
  1163.     function currID($seq_name)
  1164.     {
  1165.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  1166.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  1167.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1168.         return $this->queryOne($query'integer');
  1169.     }
  1170. }
  1171.  
  1172. /**
  1173.  * MDB2 MySQL result driver
  1174.  *
  1175.  * @package MDB2
  1176.  * @category Database
  1177.  * @author  Lukas Smith <smith@pooteeweet.org>
  1178.  */
  1179. class MDB2_Result_mysql extends MDB2_Result_Common
  1180. {
  1181.     // }}}
  1182.     // {{{ fetchRow()
  1183.  
  1184.     /**
  1185.      * Fetch a row and insert the data into an existing array.
  1186.      *
  1187.      * @param int       $fetchmode  how the array data should be indexed
  1188.      * @param int    $rownum    number of the row where the data can be found
  1189.      * @return int data array on success, a MDB2 error on failure
  1190.      * @access public
  1191.      */
  1192.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  1193.     {
  1194.         if (!is_null($rownum)) {
  1195.             $seek $this->seek($rownum);
  1196.             if (PEAR::isError($seek)) {
  1197.                 return $seek;
  1198.             }
  1199.         }
  1200.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  1201.             $fetchmode $this->db->fetchmode;
  1202.         }
  1203.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  1204.             $row @mysql_fetch_assoc($this->result);
  1205.             if (is_array($row)
  1206.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  1207.             {
  1208.                 $row array_change_key_case($row$this->db->options['field_case']);
  1209.             }
  1210.         else {
  1211.            $row @mysql_fetch_row($this->result);
  1212.         }
  1213.  
  1214.         if (!$row{
  1215.             if ($this->result === false{
  1216.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1217.                     'resultset has already been freed'__FUNCTION__);
  1218.                 return $err;
  1219.             }
  1220.             $null = null;
  1221.             return $null;
  1222.         }
  1223.         $mode $this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL;
  1224.         $rtrim = false;
  1225.         if ($this->db->options['portability'MDB2_PORTABILITY_RTRIM{
  1226.             if (empty($this->types)) {
  1227.                 $mode += MDB2_PORTABILITY_RTRIM;
  1228.             else {
  1229.                 $rtrim = true;
  1230.             }
  1231.         }
  1232.         if ($mode{
  1233.             $this->db->_fixResultArrayValues($row$mode);
  1234.         }
  1235.         if (!empty($this->types)) {
  1236.             $row $this->db->datatype->convertResultRow($this->types$row$rtrim);
  1237.         }
  1238.         if (!empty($this->values)) {
  1239.             $this->_assignBindColumns($row);
  1240.         }
  1241.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  1242.             $object_class $this->db->options['fetch_class'];
  1243.             if ($object_class == 'stdClass'{
  1244.                 $row = (object) $row;
  1245.             else {
  1246.                 $row &new $object_class($row);
  1247.             }
  1248.         }
  1249.         ++$this->rownum;
  1250.         return $row;
  1251.     }
  1252.  
  1253.     // }}}
  1254.     // {{{ _getColumnNames()
  1255.  
  1256.     /**
  1257.      * Retrieve the names of columns returned by the DBMS in a query result.
  1258.      *
  1259.      * @return  mixed   Array variable that holds the names of columns as keys
  1260.      *                   or an MDB2 error on failure.
  1261.      *                   Some DBMS may not return any columns when the result set
  1262.      *                   does not contain any rows.
  1263.      * @access private
  1264.      */
  1265.     function _getColumnNames()
  1266.     {
  1267.         $columns = array();
  1268.         $numcols $this->numCols();
  1269.         if (PEAR::isError($numcols)) {
  1270.             return $numcols;
  1271.         }
  1272.         for ($column = 0; $column $numcols$column++{
  1273.             $column_name @mysql_field_name($this->result$column);
  1274.             $columns[$column_name$column;
  1275.         }
  1276.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1277.             $columns array_change_key_case($columns$this->db->options['field_case']);
  1278.         }
  1279.         return $columns;
  1280.     }
  1281.  
  1282.     // }}}
  1283.     // {{{ numCols()
  1284.  
  1285.     /**
  1286.      * Count the number of columns returned by the DBMS in a query result.
  1287.      *
  1288.      * @return mixed integer value with the number of columns, a MDB2 error
  1289.      *                        on failure
  1290.      * @access public
  1291.      */
  1292.     function numCols()
  1293.     {
  1294.         $cols @mysql_num_fields($this->result);
  1295.         if (is_null($cols)) {
  1296.             if ($this->result === false{
  1297.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1298.                     'resultset has already been freed'__FUNCTION__);
  1299.             elseif (is_null($this->result)) {
  1300.                 return count($this->types);
  1301.             }
  1302.             return $this->db->raiseError(nullnullnull,
  1303.                 'Could not get column count'__FUNCTION__);
  1304.         }
  1305.         return $cols;
  1306.     }
  1307.  
  1308.     // }}}
  1309.     // {{{ free()
  1310.  
  1311.     /**
  1312.      * Free the internal resources associated with result.
  1313.      *
  1314.      * @return boolean true on success, false if result is invalid
  1315.      * @access public
  1316.      */
  1317.     function free()
  1318.     {
  1319.         if (is_resource($this->result&& $this->db->connection{
  1320.             $free @mysql_free_result($this->result);
  1321.             if ($free === false{
  1322.                 return $this->db->raiseError(nullnullnull,
  1323.                     'Could not free result'__FUNCTION__);
  1324.             }
  1325.         }
  1326.         $this->result = false;
  1327.         return MDB2_OK;
  1328.     }
  1329. }
  1330.  
  1331. /**
  1332.  * MDB2 MySQL buffered result driver
  1333.  *
  1334.  * @package MDB2
  1335.  * @category Database
  1336.  * @author  Lukas Smith <smith@pooteeweet.org>
  1337.  */
  1338. {
  1339.     // }}}
  1340.     // {{{ seek()
  1341.  
  1342.     /**
  1343.      * Seek to a specific row in a result set
  1344.      *
  1345.      * @param int    $rownum    number of the row where the data can be found
  1346.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1347.      * @access public
  1348.      */
  1349.     function seek($rownum = 0)
  1350.     {
  1351.         if ($this->rownum != ($rownum - 1&& !@mysql_data_seek($this->result$rownum)) {
  1352.             if ($this->result === false{
  1353.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1354.                     'resultset has already been freed'__FUNCTION__);
  1355.             elseif (is_null($this->result)) {
  1356.                 return MDB2_OK;
  1357.             }
  1358.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1359.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  1360.         }
  1361.         $this->rownum $rownum - 1;
  1362.         return MDB2_OK;
  1363.     }
  1364.  
  1365.     // }}}
  1366.     // {{{ valid()
  1367.  
  1368.     /**
  1369.      * Check if the end of the result set has been reached
  1370.      *
  1371.      * @return mixed true or false on sucess, a MDB2 error on failure
  1372.      * @access public
  1373.      */
  1374.     function valid()
  1375.     {
  1376.         $numrows $this->numRows();
  1377.         if (PEAR::isError($numrows)) {
  1378.             return $numrows;
  1379.         }
  1380.         return $this->rownum ($numrows - 1);
  1381.     }
  1382.  
  1383.     // }}}
  1384.     // {{{ numRows()
  1385.  
  1386.     /**
  1387.      * Returns the number of rows in a result object
  1388.      *
  1389.      * @return mixed MDB2 Error Object or the number of rows
  1390.      * @access public
  1391.      */
  1392.     function numRows()
  1393.     {
  1394.         $rows @mysql_num_rows($this->result);
  1395.         if (false === $rows{
  1396.             if (false === $this->result{
  1397.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1398.                     'resultset has already been freed'__FUNCTION__);
  1399.             elseif (is_null($this->result)) {
  1400.                 return 0;
  1401.             }
  1402.             return $this->db->raiseError(nullnullnull,
  1403.                 'Could not get row count'__FUNCTION__);
  1404.         }
  1405.         return $rows;
  1406.     }
  1407. }
  1408.  
  1409. /**
  1410.  * MDB2 MySQL statement driver
  1411.  *
  1412.  * @package MDB2
  1413.  * @category Database
  1414.  * @author  Lukas Smith <smith@pooteeweet.org>
  1415.  */
  1416. class MDB2_Statement_mysql extends MDB2_Statement_Common
  1417. {
  1418.     // {{{ _execute()
  1419.  
  1420.     /**
  1421.      * Execute a prepared query statement helper method.
  1422.      *
  1423.      * @param mixed $result_class string which specifies which result class to use
  1424.      * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1425.      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1426.      * @access private
  1427.      */
  1428.     function &_execute($result_class = true$result_wrap_class = false)
  1429.     {
  1430.         if (is_null($this->statement)) {
  1431.             $result =parent::_execute($result_class$result_wrap_class);
  1432.             return $result;
  1433.         }
  1434.         $this->db->last_query = $this->query;
  1435.         $this->db->debug($this->query'execute'array('is_manip' => $this->is_manip'when' => 'pre''parameters' => $this->values));
  1436.         if ($this->db->getOption('disable_query')) {
  1437.             $result $this->is_manip ? 0 : null;
  1438.             return $result;
  1439.         }
  1440.  
  1441.         $connection $this->db->getConnection();
  1442.         if (PEAR::isError($connection)) {
  1443.             return $connection;
  1444.         }
  1445.  
  1446.         $query 'EXECUTE '.$this->statement;
  1447.         if (!empty($this->positions)) {
  1448.             $parameters = array();
  1449.             foreach ($this->positions as $parameter{
  1450.                 if (!array_key_exists($parameter$this->values)) {
  1451.                     return $this->db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  1452.                         'Unable to bind to missing placeholder: '.$parameter__FUNCTION__);
  1453.                 }
  1454.                 $value $this->values[$parameter];
  1455.                 $type array_key_exists($parameter$this->types$this->types[$parameter: null;
  1456.                 if (is_resource($value|| $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']{
  1457.                     if (!is_resource($value&& preg_match('/^(\w+:\/\/)(.*)$/'$value$match)) {
  1458.                         if ($match[1== 'file://'{
  1459.                             $value $match[2];
  1460.                         }
  1461.                         $value @fopen($value'r');
  1462.                         $close = true;
  1463.                     }
  1464.                     if (is_resource($value)) {
  1465.                         $data '';
  1466.                         while (!@feof($value)) {
  1467.                             $data.= @fread($value$this->db->options['lob_buffer_length']);
  1468.                         }
  1469.                         if ($close{
  1470.                             @fclose($value);
  1471.                         }
  1472.                         $value $data;
  1473.                     }
  1474.                 }
  1475.                 $quoted $this->db->quote($value$type);
  1476.                 if (PEAR::isError($quoted)) {
  1477.                     return $quoted;
  1478.                 }
  1479.                 $param_query 'SET @'.$parameter.' = '.$quoted;
  1480.                 $result $this->db->_doQuery($param_querytrue$connection);
  1481.                 if (PEAR::isError($result)) {
  1482.                     return $result;
  1483.                 }
  1484.             }
  1485.             $query.= ' USING @'.implode(', @'array_values($this->positions));
  1486.         }
  1487.  
  1488.         $result $this->db->_doQuery($query$this->is_manip$connection);
  1489.         if (PEAR::isError($result)) {
  1490.             return $result;
  1491.         }
  1492.  
  1493.         if ($this->is_manip{
  1494.             $affected_rows $this->db->_affectedRows($connection$result);
  1495.             return $affected_rows;
  1496.         }
  1497.  
  1498.         $result =$this->db->_wrapResult($result$this->result_types,
  1499.             $result_class$result_wrap_class$this->limit$this->offset);
  1500.         $this->db->debug($this->query'execute'array('is_manip' => $this->is_manip'when' => 'post''result' => $result));
  1501.         return $result;
  1502.     }
  1503.  
  1504.     // }}}
  1505.     // {{{ free()
  1506.  
  1507.     /**
  1508.      * Release resources allocated for the specified prepared query.
  1509.      *
  1510.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1511.      * @access public
  1512.      */
  1513.     function free()
  1514.     {
  1515.         if (is_null($this->positions)) {
  1516.             return $this->db->raiseError(MDB2_ERRORnullnull,
  1517.                 'Prepared statement has already been freed'__FUNCTION__);
  1518.         }
  1519.         $result = MDB2_OK;
  1520.  
  1521.         if (!is_null($this->statement)) {
  1522.             $connection $this->db->getConnection();
  1523.             if (PEAR::isError($connection)) {
  1524.                 return $connection;
  1525.             }
  1526.             $query 'DEALLOCATE PREPARE '.$this->statement;
  1527.             $result $this->db->_doQuery($querytrue$connection);
  1528.         }
  1529.  
  1530.         parent::free();
  1531.         return $result;
  1532.     }
  1533. }
  1534. ?>

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