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

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