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

Source for file sqlite.php

Documentation is available at sqlite.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-2007 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: sqlite.php,v 1.152 2007/11/27 07:44:41 quipo Exp $
  47. //
  48.  
  49. /**
  50.  * MDB2 SQLite driver
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Lukas Smith <smith@pooteeweet.org>
  55.  */
  56. class MDB2_Driver_sqlite extends MDB2_Driver_Common
  57. {
  58.     // {{{ properties
  59.     var $string_quoting = array('start' => "'"'end' => "'"'escape' => "'"'escape_pattern' => false);
  60.  
  61.     var $identifier_quoting = array('start' => '"''end' => '"''escape' => '"');
  62.  
  63.     var $_lasterror '';
  64.  
  65.     var $fix_assoc_fields_names = false;
  66.  
  67.     // }}}
  68.     // {{{ constructor
  69.  
  70.     /**
  71.      * Constructor
  72.      */
  73.     function __construct()
  74.     {
  75.         parent::__construct();
  76.  
  77.         $this->phptype 'sqlite';
  78.         $this->dbsyntax 'sqlite';
  79.  
  80.         $this->supported['sequences''emulated';
  81.         $this->supported['indexes'= true;
  82.         $this->supported['affected_rows'= true;
  83.         $this->supported['summary_functions'= true;
  84.         $this->supported['order_by_text'= true;
  85.         $this->supported['current_id''emulated';
  86.         $this->supported['limit_queries'= true;
  87.         $this->supported['LOBs'= true;
  88.         $this->supported['replace'= true;
  89.         $this->supported['transactions'= true;
  90.         $this->supported['savepoints'= false;
  91.         $this->supported['sub_selects'= true;
  92.         $this->supported['auto_increment'= true;
  93.         $this->supported['primary_key'= false; // requires alter table implementation
  94.         $this->supported['result_introspection'= false; // not implemented
  95.         $this->supported['prepared_statements''emulated';
  96.         $this->supported['identifier_quoting'= true;
  97.         $this->supported['pattern_escaping'= false;
  98.         $this->supported['new_link'= false;
  99.  
  100.         $this->options['base_transaction_name''___php_MDB2_sqlite_auto_commit_off';
  101.         $this->options['fixed_float'= 0;
  102.         $this->options['database_path''';
  103.         $this->options['database_extension''';
  104.         $this->options['server_version''';
  105.     }
  106.  
  107.     // }}}
  108.     // {{{ errorInfo()
  109.  
  110.     /**
  111.      * This method is used to collect information about an error
  112.      *
  113.      * @param integer $error 
  114.      * @return array 
  115.      * @access public
  116.      */
  117.     function errorInfo($error = null)
  118.     {
  119.         $native_code = null;
  120.         if ($this->connection{
  121.             $native_code @sqlite_last_error($this->connection);
  122.         }
  123.         $native_msg $this->_lasterror
  124.             ? html_entity_decode($this->_lasterror@sqlite_error_string($native_code);
  125.             
  126.         // PHP 5.2+ prepends the function name to $php_errormsg, so we need
  127.         // this hack to work around it, per bug #9599.
  128.         $native_msg preg_replace('/^sqlite[a-z_]+\(\): /'''$native_msg);
  129.  
  130.         if (is_null($error)) {
  131.             static $error_regexps;
  132.             if (empty($error_regexps)) {
  133.                 $error_regexps = array(
  134.                     '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
  135.                     '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
  136.                     '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
  137.                     '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
  138.                     '/is not unique/' => MDB2_ERROR_CONSTRAINT,
  139.                     '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
  140.                     '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
  141.                     '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  142.                     '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
  143.                     '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
  144.                     '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
  145.                     '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
  146.                     '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  147.                  );
  148.             }
  149.             foreach ($error_regexps as $regexp => $code{
  150.                 if (preg_match($regexp$native_msg)) {
  151.                     $error $code;
  152.                     break;
  153.                 }
  154.             }
  155.         }
  156.         return array($error$native_code$native_msg);
  157.     }
  158.  
  159.     // }}}
  160.     // {{{ escape()
  161.  
  162.     /**
  163.      * Quotes a string so it can be safely used in a query. It will quote
  164.      * the text so it can safely be used within a query.
  165.      *
  166.      * @param   string  the input string to quote
  167.      * @param   bool    escape wildcards
  168.      *
  169.      * @return  string  quoted string
  170.      *
  171.      * @access  public
  172.      */
  173.     function escape($text$escape_wildcards = false)
  174.     {
  175.         $text @sqlite_escape_string($text);
  176.         return $text;
  177.     }
  178.  
  179.     // }}}
  180.     // {{{ beginTransaction()
  181.  
  182.     /**
  183.      * Start a transaction or set a savepoint.
  184.      *
  185.      * @param   string  name of a savepoint to set
  186.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  187.      *
  188.      * @access  public
  189.      */
  190.     function beginTransaction($savepoint = null)
  191.     {
  192.         $this->debug('Starting transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  193.         if (!is_null($savepoint)) {
  194.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  195.                 'savepoints are not supported'__FUNCTION__);
  196.         elseif ($this->in_transaction{
  197.             return MDB2_OK;  //nothing to do
  198.         }
  199.         if (!$this->destructor_registered && $this->opened_persistent{
  200.             $this->destructor_registered = true;
  201.             register_shutdown_function('MDB2_closeOpenTransactions');
  202.         }
  203.         $query 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
  204.         $result =$this->_doQuery($querytrue);
  205.         if (PEAR::isError($result)) {
  206.             return $result;
  207.         }
  208.         $this->in_transaction = true;
  209.         return MDB2_OK;
  210.     }
  211.  
  212.     // }}}
  213.     // {{{ commit()
  214.  
  215.     /**
  216.      * Commit the database changes done during a transaction that is in
  217.      * progress or release a savepoint. This function may only be called when
  218.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  219.      * transaction is implicitly started after committing the pending changes.
  220.      *
  221.      * @param   string  name of a savepoint to release
  222.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  223.      *
  224.      * @access  public
  225.      */
  226.     function commit($savepoint = null)
  227.     {
  228.         $this->debug('Committing transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  229.         if (!$this->in_transaction{
  230.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  231.                 'commit/release savepoint cannot be done changes are auto committed'__FUNCTION__);
  232.         }
  233.         if (!is_null($savepoint)) {
  234.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  235.                 'savepoints are not supported'__FUNCTION__);
  236.         }
  237.  
  238.         $query 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
  239.         $result =$this->_doQuery($querytrue);
  240.         if (PEAR::isError($result)) {
  241.             return $result;
  242.         }
  243.         $this->in_transaction = false;
  244.         return MDB2_OK;
  245.     }
  246.  
  247.     // }}}
  248.     // {{{
  249.  
  250.     /**
  251.      * Cancel any database changes done during a transaction or since a specific
  252.      * savepoint that is in progress. This function may only be called when
  253.      * auto-committing is disabled, otherwise it will fail. Therefore, a new
  254.      * transaction is implicitly started after canceling the pending changes.
  255.      *
  256.      * @param   string  name of a savepoint to rollback to
  257.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  258.      *
  259.      * @access  public
  260.      */
  261.     function rollback($savepoint = null)
  262.     {
  263.         $this->debug('Rolling back transaction/savepoint'__FUNCTION__array('is_manip' => true'savepoint' => $savepoint));
  264.         if (!$this->in_transaction{
  265.             return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  266.                 'rollback cannot be done changes are auto committed'__FUNCTION__);
  267.         }
  268.         if (!is_null($savepoint)) {
  269.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  270.                 'savepoints are not supported'__FUNCTION__);
  271.         }
  272.  
  273.         $query 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
  274.         $result =$this->_doQuery($querytrue);
  275.         if (PEAR::isError($result)) {
  276.             return $result;
  277.         }
  278.         $this->in_transaction = false;
  279.         return MDB2_OK;
  280.     }
  281.  
  282.     // }}}
  283.     // {{{ function setTransactionIsolation()
  284.  
  285.     /**
  286.      * Set the transacton isolation level.
  287.      *
  288.      * @param   string  standard isolation level
  289.      *                   READ UNCOMMITTED (allows dirty reads)
  290.      *                   READ COMMITTED (prevents dirty reads)
  291.      *                   REPEATABLE READ (prevents nonrepeatable reads)
  292.      *                   SERIALIZABLE (prevents phantom reads)
  293.      * @return  mixed   MDB2_OK on success, a MDB2 error on failure
  294.      *
  295.      * @access  public
  296.      * @since   2.1.1
  297.      */
  298.     function setTransactionIsolation($isolation)
  299.     {
  300.         $this->debug('Setting transaction isolation level'__FUNCTION__array('is_manip' => true));
  301.         switch ($isolation{
  302.         case 'READ UNCOMMITTED':
  303.             $isolation = 0;
  304.             break;
  305.         case 'READ COMMITTED':
  306.         case 'REPEATABLE READ':
  307.         case 'SERIALIZABLE':
  308.             $isolation = 1;
  309.             break;
  310.         default:
  311.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  312.                 'isolation level is not supported: '.$isolation__FUNCTION__);
  313.         }
  314.  
  315.         $query = "PRAGMA read_uncommitted=$isolation";
  316.         return $this->_doQuery($querytrue);
  317.     }
  318.  
  319.     // }}}
  320.     // {{{ getDatabaseFile()
  321.  
  322.     /**
  323.      * Builds the string with path+dbname+extension
  324.      *
  325.      * @return string full database path+file
  326.      * @access protected
  327.      */
  328.     function _getDatabaseFile($database_name)
  329.     {
  330.         if ($database_name === '' || $database_name === ':memory:'{
  331.             return $database_name;
  332.         }
  333.         return $this->options['database_path'].$database_name.$this->options['database_extension'];
  334.     }
  335.  
  336.     // }}}
  337.     // {{{ connect()
  338.  
  339.     /**
  340.      * Connect to the database
  341.      *
  342.      * @return true on success, MDB2 Error Object on failure
  343.      ***/
  344.     function connect()
  345.     {
  346.         $database_file $this->_getDatabaseFile($this->database_name);
  347.         if (is_resource($this->connection)) {
  348.             //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  349.             if (MDB2::areEquals($this->connected_dsn$this->dsn)
  350.                 && $this->connected_database_name == $database_file
  351.                 && $this->opened_persistent == $this->options['persistent']
  352.             {
  353.                 return MDB2_OK;
  354.             }
  355.             $this->disconnect(false);
  356.         }
  357.  
  358.         if (!PEAR::loadExtension($this->phptype)) {
  359.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  360.                 'extension '.$this->phptype.' is not compiled into PHP'__FUNCTION__);
  361.         }
  362.  
  363.         if (!empty($this->database_name)) {
  364.             if ($database_file !== ':memory:'{
  365.                 if (!file_exists($database_file)) {
  366.                     if (!touch($database_file)) {
  367.                         return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  368.                             'Could not create database file'__FUNCTION__);
  369.                     }
  370.                     if (!isset($this->dsn['mode'])
  371.                         || !is_numeric($this->dsn['mode'])
  372.                     {
  373.                         $mode = 0644;
  374.                     else {
  375.                         $mode octdec($this->dsn['mode']);
  376.                     }
  377.                     if (!chmod($database_file$mode)) {
  378.                         return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  379.                             'Could not be chmodded database file'__FUNCTION__);
  380.                     }
  381.                     if (!file_exists($database_file)) {
  382.                         return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  383.                             'Could not be found database file'__FUNCTION__);
  384.                     }
  385.                 }
  386.                 if (!is_file($database_file)) {
  387.                     return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  388.                             'Database is a directory name'__FUNCTION__);
  389.                 }
  390.                 if (!is_readable($database_file)) {
  391.                     return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATIONnullnull,
  392.                             'Could not read database file'__FUNCTION__);
  393.                 }
  394.             }
  395.  
  396.             $connect_function ($this->options['persistent''sqlite_popen' 'sqlite_open');
  397.             $php_errormsg '';
  398.             if (version_compare('5.1.0'PHP_VERSION'>')) {
  399.                 @ini_set('track_errors'true);
  400.                 $connection @$connect_function($database_file);
  401.                 @ini_restore('track_errors');
  402.             else {
  403.                 $connection @$connect_function($database_file0666$php_errormsg);
  404.             }
  405.             $this->_lasterror $php_errormsg;
  406.             if (!$connection{
  407.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  408.                 'unable to establish a connection'__FUNCTION__);
  409.             }
  410.  
  411.             if (!empty($this->dsn['charset'])) {
  412.                 $result $this->setCharset($this->dsn['charset']$connection);
  413.                 if (PEAR::isError($result)) {
  414.                     return $result;
  415.                 }
  416.             }
  417.  
  418.             $this->connection $connection;
  419.             $this->connected_dsn $this->dsn;
  420.             $this->connected_database_name $database_file;
  421.             $this->opened_persistent $this->getoption('persistent');
  422.             $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  423.         }
  424.         return MDB2_OK;
  425.     }
  426.  
  427.     // }}}
  428.     // {{{ disconnect()
  429.  
  430.     /**
  431.      * Log out and disconnect from the database.
  432.      *
  433.      * @param  boolean $force if the disconnect should be forced even if the
  434.      *                         connection is opened persistently
  435.      * @return mixed true on success, false if not connected and error
  436.      *                 object on error
  437.      * @access public
  438.      */
  439.     function disconnect($force = true)
  440.     {
  441.         if (is_resource($this->connection)) {
  442.             if ($this->in_transaction{
  443.                 $dsn $this->dsn;
  444.                 $database_name $this->database_name;
  445.                 $persistent $this->options['persistent'];
  446.                 $this->dsn $this->connected_dsn;
  447.                 $this->database_name $this->connected_database_name;
  448.                 $this->options['persistent'$this->opened_persistent;
  449.                 $this->rollback();
  450.                 $this->dsn $dsn;
  451.                 $this->database_name $database_name;
  452.                 $this->options['persistent'$persistent;
  453.             }
  454.  
  455.             if (!$this->opened_persistent || $force{
  456.                 @sqlite_close($this->connection);
  457.             }
  458.         }
  459.         return parent::disconnect($force);
  460.     }
  461.  
  462.     // }}}
  463.     // {{{ getConnection()
  464.  
  465.     /**
  466.      * Returns a native connection
  467.      *
  468.      * @return  mixed   a valid MDB2 connection object,
  469.      *                   or a MDB2 error object on error
  470.      * @access  public
  471.      */
  472.     function getConnection()
  473.     {
  474.         $connection = parent::getConnection();
  475.         if (PEAR::isError($connection)) {
  476.             return $connection;
  477.         }
  478.  
  479.         $fix_assoc_fields_names $this->options['portability'MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES;
  480.         if ($fix_assoc_fields_names !== $this->fix_assoc_fields_names{
  481.             @sqlite_query("PRAGMA short_column_names = $fix_assoc_fields_names;"$connection);
  482.             $this->fix_assoc_fields_names = $fix_assoc_fields_names;
  483.         }
  484.  
  485.         return $connection;
  486.     }
  487.  
  488.     // }}}
  489.     // {{{ _doQuery()
  490.  
  491.     /**
  492.      * Execute a query
  493.      * @param string $query  query
  494.      * @param boolean $is_manip  if the query is a manipulation query
  495.      * @param resource $connection 
  496.      * @param string $database_name 
  497.      * @return result or error object
  498.      * @access protected
  499.      */
  500.     function &_doQuery($query$is_manip = false$connection = null$database_name = null)
  501.     {
  502.         $this->last_query $query;
  503.         $result $this->debug($query'query'array('is_manip' => $is_manip'when' => 'pre'));
  504.         if ($result{
  505.             if (PEAR::isError($result)) {
  506.                 return $result;
  507.             }
  508.             $query $result;
  509.         }
  510.         if ($this->options['disable_query']{
  511.             $result $is_manip ? 0 : null;
  512.             return $result;
  513.         }
  514.  
  515.         if (is_null($connection)) {
  516.             $connection $this->getConnection();
  517.             if (PEAR::isError($connection)) {
  518.                 return $connection;
  519.             }
  520.         }
  521.  
  522.         $function $this->options['result_buffering']
  523.             ? 'sqlite_query' 'sqlite_unbuffered_query';
  524.         $php_errormsg '';
  525.         if (version_compare('5.1.0'PHP_VERSION'>')) {
  526.             @ini_set('track_errors'true);
  527.             do {
  528.                 $result @$function($query.';'$connection);
  529.             while (sqlite_last_error($connection== SQLITE_SCHEMA);
  530.             @ini_restore('track_errors');
  531.         else {
  532.             do {
  533.                 $result @$function($query.';'$connectionSQLITE_BOTH$php_errormsg);
  534.             while (sqlite_last_error($connection== SQLITE_SCHEMA);
  535.         }
  536.         $this->_lasterror $php_errormsg;
  537.  
  538.         if (!$result{
  539.             $err =$this->raiseError(nullnullnull,
  540.                 'Could not execute statement'__FUNCTION__);
  541.             return $err;
  542.         }
  543.  
  544.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  545.         return $result;
  546.     }
  547.  
  548.     // }}}
  549.     // {{{ _affectedRows()
  550.  
  551.     /**
  552.      * Returns the number of rows affected
  553.      *
  554.      * @param resource $result 
  555.      * @param resource $connection 
  556.      * @return mixed MDB2 Error Object or the number of rows affected
  557.      * @access private
  558.      */
  559.     function _affectedRows($connection$result = null)
  560.     {
  561.         if (is_null($connection)) {
  562.             $connection $this->getConnection();
  563.             if (PEAR::isError($connection)) {
  564.                 return $connection;
  565.             }
  566.         }
  567.         return @sqlite_changes($connection);
  568.     }
  569.  
  570.     // }}}
  571.     // {{{ _modifyQuery()
  572.  
  573.     /**
  574.      * Changes a query string for various DBMS specific reasons
  575.      *
  576.      * @param string $query  query to modify
  577.      * @param boolean $is_manip  if it is a DML query
  578.      * @param integer $limit  limit the number of rows
  579.      * @param integer $offset  start reading from given offset
  580.      * @return string modified query
  581.      * @access protected
  582.      */
  583.     function _modifyQuery($query$is_manip$limit$offset)
  584.     {
  585.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  586.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  587.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  588.                                       'DELETE FROM \1 WHERE 1=1'$query);
  589.             }
  590.         }
  591.         if ($limit > 0
  592.             && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i'$query)
  593.         {
  594.             $query rtrim($query);
  595.             if (substr($query-1== ';'{
  596.                 $query substr($query0-1);
  597.             }
  598.             if ($is_manip{
  599.                 $query.= " LIMIT $limit";
  600.             else {
  601.                 $query.= " LIMIT $offset,$limit";
  602.             }
  603.         }
  604.         return $query;
  605.     }
  606.  
  607.     // }}}
  608.     // {{{ getServerVersion()
  609.  
  610.     /**
  611.      * return version information about the server
  612.      *
  613.      * @param bool   $native  determines if the raw version string should be returned
  614.      * @return mixed array/string with version information or MDB2 error object
  615.      * @access public
  616.      */
  617.     function getServerVersion($native = false)
  618.     {
  619.         $server_info = false;
  620.         if ($this->connected_server_info{
  621.             $server_info $this->connected_server_info;
  622.         elseif ($this->options['server_version']{
  623.             $server_info $this->options['server_version'];
  624.         elseif (function_exists('sqlite_libversion')) {
  625.             $server_info @sqlite_libversion();
  626.         }
  627.         if (!$server_info{
  628.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  629.                 'Requires either the "server_version" option or the sqlite_libversion() function'__FUNCTION__);
  630.         }
  631.         // cache server_info
  632.         $this->connected_server_info $server_info;
  633.         if (!$native{
  634.             $tmp explode('.'$server_info3);
  635.             $server_info = array(
  636.                 'major' => isset($tmp[0]$tmp[0: null,
  637.                 'minor' => isset($tmp[1]$tmp[1: null,
  638.                 'patch' => isset($tmp[2]$tmp[2: null,
  639.                 'extra' => null,
  640.                 'native' => $server_info,
  641.             );
  642.         }
  643.         return $server_info;
  644.     }
  645.  
  646.     // }}}
  647.     // {{{ replace()
  648.  
  649.     /**
  650.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  651.      * query, except that if there is already a row in the table with the same
  652.      * key field values, the REPLACE query just updates its values instead of
  653.      * inserting a new row.
  654.      *
  655.      * The REPLACE type of query does not make part of the SQL standards. Since
  656.      * practically only SQLite implements it natively, this type of query is
  657.      * emulated through this method for other DBMS using standard types of
  658.      * queries inside a transaction to assure the atomicity of the operation.
  659.      *
  660.      * @access public
  661.      *
  662.      * @param string $table name of the table on which the REPLACE query will
  663.      *   be executed.
  664.      * @param array $fields associative array that describes the fields and the
  665.      *   values that will be inserted or updated in the specified table. The
  666.      *   indexes of the array are the names of all the fields of the table. The
  667.      *   values of the array are also associative arrays that describe the
  668.      *   values and other properties of the table fields.
  669.      *
  670.      *   Here follows a list of field properties that need to be specified:
  671.      *
  672.      *     value:
  673.      *           Value to be assigned to the specified field. This value may be
  674.      *           of specified in database independent type format as this
  675.      *           function can perform the necessary datatype conversions.
  676.      *
  677.      *     Default:
  678.      *           this property is required unless the Null property
  679.      *           is set to 1.
  680.      *
  681.      *     type
  682.      *           Name of the type of the field. Currently, all types Metabase
  683.      *           are supported except for clob and blob.
  684.      *
  685.      *     Default: no type conversion
  686.      *
  687.      *     null
  688.      *           Boolean property that indicates that the value for this field
  689.      *           should be set to null.
  690.      *
  691.      *           The default value for fields missing in INSERT queries may be
  692.      *           specified the definition of a table. Often, the default value
  693.      *           is already null, but since the REPLACE may be emulated using
  694.      *           an UPDATE query, make sure that all fields of the table are
  695.      *           listed in this function argument array.
  696.      *
  697.      *     Default: 0
  698.      *
  699.      *     key
  700.      *           Boolean property that indicates that this field should be
  701.      *           handled as a primary key or at least as part of the compound
  702.      *           unique index of the table that will determine the row that will
  703.      *           updated if it exists or inserted a new row otherwise.
  704.      *
  705.      *           This function will fail if no key field is specified or if the
  706.      *           value of a key field is set to null because fields that are
  707.      *           part of unique index they may not be null.
  708.      *
  709.      *     Default: 0
  710.      *
  711.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  712.      */
  713.     function replace($table$fields)
  714.     {
  715.         $count count($fields);
  716.         $query $values '';
  717.         $keys $colnum = 0;
  718.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  719.             $name key($fields);
  720.             if ($colnum > 0{
  721.                 $query .= ',';
  722.                 $values.= ',';
  723.             }
  724.             $query.= $name;
  725.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  726.                 $value 'NULL';
  727.             else {
  728.                 $type = isset($fields[$name]['type']$fields[$name]['type': null;
  729.                 $value $this->quote($fields[$name]['value']$type);
  730.                 if (PEAR::isError($value)) {
  731.                     return $value;
  732.                 }
  733.             }
  734.             $values.= $value;
  735.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  736.                 if ($value === 'NULL'{
  737.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  738.                         'key value '.$name.' may not be NULL'__FUNCTION__);
  739.                 }
  740.                 $keys++;
  741.             }
  742.         }
  743.         if ($keys == 0{
  744.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  745.                 'not specified which fields are keys'__FUNCTION__);
  746.         }
  747.  
  748.         $connection $this->getConnection();
  749.         if (PEAR::isError($connection)) {
  750.             return $connection;
  751.         }
  752.  
  753.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  754.         $result =$this->_doQuery($querytrue$connection);
  755.         if (PEAR::isError($result)) {
  756.             return $result;
  757.         }
  758.         return $this->_affectedRows($connection$result);
  759.     }
  760.  
  761.     // }}}
  762.     // {{{ nextID()
  763.  
  764.     /**
  765.      * Returns the next free id of a sequence
  766.      *
  767.      * @param string $seq_name name of the sequence
  768.      * @param boolean $ondemand when true the sequence is
  769.      *                           automatic created, if it
  770.      *                           not exists
  771.      *
  772.      * @return mixed MDB2 Error Object or id
  773.      * @access public
  774.      */
  775.     function nextID($seq_name$ondemand = true)
  776.     {
  777.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  778.         $seqcol_name $this->options['seqcol_name'];
  779.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  780.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  781.         $result =$this->_doQuery($querytrue);
  782.         $this->popExpect();
  783.         if (PEAR::isError($result)) {
  784.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  785.                 $this->loadModule('Manager'nulltrue);
  786.                 $result $this->manager->createSequence($seq_name);
  787.                 if (PEAR::isError($result)) {
  788.                     return $this->raiseError($resultnullnull,
  789.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  790.                 else {
  791.                     return $this->nextID($seq_namefalse);
  792.                 }
  793.             }
  794.             return $result;
  795.         }
  796.         $value $this->lastInsertID();
  797.         if (is_numeric($value)) {
  798.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  799.             $result =$this->_doQuery($querytrue);
  800.             if (PEAR::isError($result)) {
  801.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  802.             }
  803.         }
  804.         return $value;
  805.     }
  806.  
  807.     // }}}
  808.     // {{{ lastInsertID()
  809.  
  810.     /**
  811.      * Returns the autoincrement ID if supported or $id or fetches the current
  812.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  813.      *
  814.      * @param string $table name of the table into which a new row was inserted
  815.      * @param string $field name of the field into which a new row was inserted
  816.      * @return mixed MDB2 Error Object or id
  817.      * @access public
  818.      */
  819.     function lastInsertID($table = null$field = null)
  820.     {
  821.         $connection $this->getConnection();
  822.         if (PEAR::isError($connection)) {
  823.             return $connection;
  824.         }
  825.         $value @sqlite_last_insert_rowid($connection);
  826.         if (!$value{
  827.             return $this->raiseError(nullnullnull,
  828.                 'Could not get last insert ID'__FUNCTION__);
  829.         }
  830.         return $value;
  831.     }
  832.  
  833.     // }}}
  834.     // {{{ currID()
  835.  
  836.     /**
  837.      * Returns the current id of a sequence
  838.      *
  839.      * @param string $seq_name name of the sequence
  840.      * @return mixed MDB2 Error Object or id
  841.      * @access public
  842.      */
  843.     function currID($seq_name)
  844.     {
  845.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  846.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  847.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  848.         return $this->queryOne($query'integer');
  849.     }
  850. }
  851.  
  852. /**
  853.  * MDB2 SQLite result driver
  854.  *
  855.  * @package MDB2
  856.  * @category Database
  857.  * @author  Lukas Smith <smith@pooteeweet.org>
  858.  */
  859. class MDB2_Result_sqlite extends MDB2_Result_Common
  860. {
  861.     // }}}
  862.     // {{{ fetchRow()
  863.  
  864.     /**
  865.      * Fetch a row and insert the data into an existing array.
  866.      *
  867.      * @param int       $fetchmode  how the array data should be indexed
  868.      * @param int    $rownum    number of the row where the data can be found
  869.      * @return int data array on success, a MDB2 error on failure
  870.      * @access public
  871.      */
  872.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  873.     {
  874.         if (!is_null($rownum)) {
  875.             $seek $this->seek($rownum);
  876.             if (PEAR::isError($seek)) {
  877.                 return $seek;
  878.             }
  879.         }
  880.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  881.             $fetchmode $this->db->fetchmode;
  882.         }
  883.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  884.             $row @sqlite_fetch_array($this->resultSQLITE_ASSOC);
  885.             if (is_array($row)
  886.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  887.             {
  888.                 $row array_change_key_case($row$this->db->options['field_case']);
  889.             }
  890.         else {
  891.            $row @sqlite_fetch_array($this->resultSQLITE_NUM);
  892.         }
  893.         if (!$row{
  894.             if ($this->result === false{
  895.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  896.                     'resultset has already been freed'__FUNCTION__);
  897.                 return $err;
  898.             }
  899.             $null = null;
  900.             return $null;
  901.         }
  902.         $mode $this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL;
  903.         $rtrim = false;
  904.         if ($this->db->options['portability'MDB2_PORTABILITY_RTRIM{
  905.             if (empty($this->types)) {
  906.                 $mode += MDB2_PORTABILITY_RTRIM;
  907.             else {
  908.                 $rtrim = true;
  909.             }
  910.         }
  911.         if ($mode{
  912.             $this->db->_fixResultArrayValues($row$mode);
  913.         }
  914.         if (!empty($this->types)) {
  915.             $row $this->db->datatype->convertResultRow($this->types$row$rtrim);
  916.         }
  917.         if (!empty($this->values)) {
  918.             $this->_assignBindColumns($row);
  919.         }
  920.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  921.             $object_class $this->db->options['fetch_class'];
  922.             if ($object_class == 'stdClass'{
  923.                 $row = (object) $row;
  924.             else {
  925.                 $row &new $object_class($row);
  926.             }
  927.         }
  928.         ++$this->rownum;
  929.         return $row;
  930.     }
  931.  
  932.     // }}}
  933.     // {{{ _getColumnNames()
  934.  
  935.     /**
  936.      * Retrieve the names of columns returned by the DBMS in a query result.
  937.      *
  938.      * @return  mixed   Array variable that holds the names of columns as keys
  939.      *                   or an MDB2 error on failure.
  940.      *                   Some DBMS may not return any columns when the result set
  941.      *                   does not contain any rows.
  942.      * @access private
  943.      */
  944.     function _getColumnNames()
  945.     {
  946.         $columns = array();
  947.         $numcols $this->numCols();
  948.         if (PEAR::isError($numcols)) {
  949.             return $numcols;
  950.         }
  951.         for ($column = 0; $column $numcols$column++{
  952.             $column_name @sqlite_field_name($this->result$column);
  953.             $columns[$column_name$column;
  954.         }
  955.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  956.             $columns array_change_key_case($columns$this->db->options['field_case']);
  957.         }
  958.         return $columns;
  959.     }
  960.  
  961.     // }}}
  962.     // {{{ numCols()
  963.  
  964.     /**
  965.      * Count the number of columns returned by the DBMS in a query result.
  966.      *
  967.      * @access public
  968.      * @return mixed integer value with the number of columns, a MDB2 error
  969.      *                        on failure
  970.      */
  971.     function numCols()
  972.     {
  973.         $cols @sqlite_num_fields($this->result);
  974.         if (is_null($cols)) {
  975.             if ($this->result === false{
  976.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  977.                     'resultset has already been freed'__FUNCTION__);
  978.             elseif (is_null($this->result)) {
  979.                 return count($this->types);
  980.             }
  981.             return $this->db->raiseError(nullnullnull,
  982.                 'Could not get column count'__FUNCTION__);
  983.         }
  984.         return $cols;
  985.     }
  986. }
  987.  
  988. /**
  989.  * MDB2 SQLite buffered result driver
  990.  *
  991.  * @package MDB2
  992.  * @category Database
  993.  * @author  Lukas Smith <smith@pooteeweet.org>
  994.  */
  995. {
  996.     // {{{ seek()
  997.  
  998.     /**
  999.      * Seek to a specific row in a result set
  1000.      *
  1001.      * @param int    $rownum    number of the row where the data can be found
  1002.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1003.      * @access public
  1004.      */
  1005.     function seek($rownum = 0)
  1006.     {
  1007.         if (!@sqlite_seek($this->result$rownum)) {
  1008.             if ($this->result === false{
  1009.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1010.                     'resultset has already been freed'__FUNCTION__);
  1011.             elseif (is_null($this->result)) {
  1012.                 return MDB2_OK;
  1013.             }
  1014.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1015.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  1016.         }
  1017.         $this->rownum $rownum - 1;
  1018.         return MDB2_OK;
  1019.     }
  1020.  
  1021.     // }}}
  1022.     // {{{ valid()
  1023.  
  1024.     /**
  1025.      * Check if the end of the result set has been reached
  1026.      *
  1027.      * @return mixed true or false on sucess, a MDB2 error on failure
  1028.      * @access public
  1029.      */
  1030.     function valid()
  1031.     {
  1032.         $numrows $this->numRows();
  1033.         if (PEAR::isError($numrows)) {
  1034.             return $numrows;
  1035.         }
  1036.         return $this->rownum ($numrows - 1);
  1037.     }
  1038.  
  1039.     // }}}
  1040.     // {{{ numRows()
  1041.  
  1042.     /**
  1043.      * Returns the number of rows in a result object
  1044.      *
  1045.      * @return mixed MDB2 Error Object or the number of rows
  1046.      * @access public
  1047.      */
  1048.     function numRows()
  1049.     {
  1050.         $rows @sqlite_num_rows($this->result);
  1051.         if (is_null($rows)) {
  1052.             if ($this->result === false{
  1053.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1054.                     'resultset has already been freed'__FUNCTION__);
  1055.             elseif (is_null($this->result)) {
  1056.                 return 0;
  1057.             }
  1058.             return $this->db->raiseError(nullnullnull,
  1059.                 'Could not get row count'__FUNCTION__);
  1060.         }
  1061.         return $rows;
  1062.     }
  1063. }
  1064.  
  1065. /**
  1066.  * MDB2 SQLite statement driver
  1067.  *
  1068.  * @package MDB2
  1069.  * @category Database
  1070.  * @author  Lukas Smith <smith@pooteeweet.org>
  1071.  */
  1072. class MDB2_Statement_sqlite extends MDB2_Statement_Common
  1073. {
  1074.  
  1075. }
  1076.  
  1077. ?>

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