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.147 2007/03/05 20:39:43 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.                 && $this->connected_database_name == $database_file
  349.                 && $this->opened_persistent == $this->options['persistent']
  350.             {
  351.                 return MDB2_OK;
  352.             }
  353.             $this->disconnect(false);
  354.         }
  355.  
  356.         if (!PEAR::loadExtension($this->phptype)) {
  357.             return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  358.                 'extension '.$this->phptype.' is not compiled into PHP'__FUNCTION__);
  359.         }
  360.  
  361.         if (!empty($this->database_name)) {
  362.             if ($database_file !== ':memory:'{
  363.                 if (!file_exists($database_file)) {
  364.                     if (!touch($database_file)) {
  365.                         return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  366.                             'Could not create database file'__FUNCTION__);
  367.                     }
  368.                     if (!isset($this->dsn['mode'])
  369.                         || !is_numeric($this->dsn['mode'])
  370.                     {
  371.                         $mode = 0644;
  372.                     else {
  373.                         $mode octdec($this->dsn['mode']);
  374.                     }
  375.                     if (!chmod($database_file$mode)) {
  376.                         return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  377.                             'Could not be chmodded database file'__FUNCTION__);
  378.                     }
  379.                     if (!file_exists($database_file)) {
  380.                         return $this->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  381.                             'Could not be found database file'__FUNCTION__);
  382.                     }
  383.                 }
  384.                 if (!is_file($database_file)) {
  385.                     return $this->raiseError(MDB2_ERROR_INVALIDnullnull,
  386.                             'Database is a directory name'__FUNCTION__);
  387.                 }
  388.                 if (!is_readable($database_file)) {
  389.                     return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATIONnullnull,
  390.                             'Could not read database file'__FUNCTION__);
  391.                 }
  392.             }
  393.  
  394.             $connect_function ($this->options['persistent''sqlite_popen' 'sqlite_open');
  395.             $php_errormsg '';
  396.             if (version_compare('5.1.0'PHP_VERSION'>')) {
  397.                 @ini_set('track_errors'true);
  398.                 $connection @$connect_function($database_file);
  399.                 @ini_restore('track_errors');
  400.             else {
  401.                 $connection @$connect_function($database_file0666$php_errormsg);
  402.             }
  403.             $this->_lasterror $php_errormsg;
  404.             if (!$connection{
  405.                 return $this->raiseError(MDB2_ERROR_CONNECT_FAILEDnullnull,
  406.                 'unable to establish a connection'__FUNCTION__);
  407.             }
  408.  
  409.             if (!empty($this->dsn['charset'])) {
  410.                 $result $this->setCharset($this->dsn['charset']$connection);
  411.                 if (PEAR::isError($result)) {
  412.                     return $result;
  413.                 }
  414.             }
  415.  
  416.             $this->connection $connection;
  417.             $this->connected_dsn $this->dsn;
  418.             $this->connected_database_name $database_file;
  419.             $this->opened_persistent $this->getoption('persistent');
  420.             $this->dbsyntax $this->dsn['dbsyntax'$this->dsn['dbsyntax'$this->phptype;
  421.         }
  422.         return MDB2_OK;
  423.     }
  424.  
  425.     // }}}
  426.     // {{{ disconnect()
  427.  
  428.     /**
  429.      * Log out and disconnect from the database.
  430.      *
  431.      * @param  boolean $force if the disconnect should be forced even if the
  432.      *                         connection is opened persistently
  433.      * @return mixed true on success, false if not connected and error
  434.      *                 object on error
  435.      * @access public
  436.      */
  437.     function disconnect($force = true)
  438.     {
  439.         if (is_resource($this->connection)) {
  440.             if ($this->in_transaction{
  441.                 $dsn $this->dsn;
  442.                 $database_name $this->database_name;
  443.                 $persistent $this->options['persistent'];
  444.                 $this->dsn $this->connected_dsn;
  445.                 $this->database_name $this->connected_database_name;
  446.                 $this->options['persistent'$this->opened_persistent;
  447.                 $this->rollback();
  448.                 $this->dsn $dsn;
  449.                 $this->database_name $database_name;
  450.                 $this->options['persistent'$persistent;
  451.             }
  452.  
  453.             if (!$this->opened_persistent || $force{
  454.                 @sqlite_close($this->connection);
  455.             }
  456.         }
  457.         return parent::disconnect($force);
  458.     }
  459.  
  460.     // }}}
  461.     // {{{ getConnection()
  462.  
  463.     /**
  464.      * Returns a native connection
  465.      *
  466.      * @return  mixed   a valid MDB2 connection object,
  467.      *                   or a MDB2 error object on error
  468.      * @access  public
  469.      */
  470.     function getConnection()
  471.     {
  472.         $connection = parent::getConnection();
  473.         if (PEAR::isError($connection)) {
  474.             return $connection;
  475.         }
  476.  
  477.         $fix_assoc_fields_names $this->options['portability'MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES;
  478.         if ($fix_assoc_fields_names !== $this->fix_assoc_fields_names{
  479.             @sqlite_query("PRAGMA short_column_names = $fix_assoc_fields_names;"$connection);
  480.             $this->fix_assoc_fields_names = $fix_assoc_fields_names;
  481.         }
  482.  
  483.         return $connection;
  484.     }
  485.  
  486.     // }}}
  487.     // {{{ _doQuery()
  488.  
  489.     /**
  490.      * Execute a query
  491.      * @param string $query  query
  492.      * @param boolean $is_manip  if the query is a manipulation query
  493.      * @param resource $connection 
  494.      * @param string $database_name 
  495.      * @return result or error object
  496.      * @access protected
  497.      */
  498.     function &_doQuery($query$is_manip = false$connection = null$database_name = null)
  499.     {
  500.         $this->last_query $query;
  501.         $result $this->debug($query'query'array('is_manip' => $is_manip'when' => 'pre'));
  502.         if ($result{
  503.             if (PEAR::isError($result)) {
  504.                 return $result;
  505.             }
  506.             $query $result;
  507.         }
  508.         if ($this->options['disable_query']{
  509.             $result $is_manip ? 0 : null;
  510.             return $result;
  511.         }
  512.  
  513.         if (is_null($connection)) {
  514.             $connection $this->getConnection();
  515.             if (PEAR::isError($connection)) {
  516.                 return $connection;
  517.             }
  518.         }
  519.  
  520.         $function $this->options['result_buffering']
  521.             ? 'sqlite_query' 'sqlite_unbuffered_query';
  522.         $php_errormsg '';
  523.         if (version_compare('5.1.0'PHP_VERSION'>')) {
  524.             @ini_set('track_errors'true);
  525.             do {
  526.                 $result @$function($query.';'$connection);
  527.             while (sqlite_last_error($connection== SQLITE_SCHEMA);
  528.             @ini_restore('track_errors');
  529.         else {
  530.             do {
  531.                 $result @$function($query.';'$connectionSQLITE_BOTH$php_errormsg);
  532.             while (sqlite_last_error($connection== SQLITE_SCHEMA);
  533.         }
  534.         $this->_lasterror $php_errormsg;
  535.  
  536.         if (!$result{
  537.             $err =$this->raiseError(nullnullnull,
  538.                 'Could not execute statement'__FUNCTION__);
  539.             return $err;
  540.         }
  541.  
  542.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  543.         return $result;
  544.     }
  545.  
  546.     // }}}
  547.     // {{{ _affectedRows()
  548.  
  549.     /**
  550.      * Returns the number of rows affected
  551.      *
  552.      * @param resource $result 
  553.      * @param resource $connection 
  554.      * @return mixed MDB2 Error Object or the number of rows affected
  555.      * @access private
  556.      */
  557.     function _affectedRows($connection$result = null)
  558.     {
  559.         if (is_null($connection)) {
  560.             $connection $this->getConnection();
  561.             if (PEAR::isError($connection)) {
  562.                 return $connection;
  563.             }
  564.         }
  565.         return @sqlite_changes($connection);
  566.     }
  567.  
  568.     // }}}
  569.     // {{{ _modifyQuery()
  570.  
  571.     /**
  572.      * Changes a query string for various DBMS specific reasons
  573.      *
  574.      * @param string $query  query to modify
  575.      * @param boolean $is_manip  if it is a DML query
  576.      * @param integer $limit  limit the number of rows
  577.      * @param integer $offset  start reading from given offset
  578.      * @return string modified query
  579.      * @access protected
  580.      */
  581.     function _modifyQuery($query$is_manip$limit$offset)
  582.     {
  583.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  584.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  585.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  586.                                       'DELETE FROM \1 WHERE 1=1'$query);
  587.             }
  588.         }
  589.         if ($limit > 0
  590.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  591.         {
  592.             $query rtrim($query);
  593.             if (substr($query-1== ';'{
  594.                 $query substr($query0-1);
  595.             }
  596.             if ($is_manip{
  597.                 $query.= " LIMIT $limit";
  598.             else {
  599.                 $query.= " LIMIT $offset,$limit";
  600.             }
  601.         }
  602.         return $query;
  603.     }
  604.  
  605.     // }}}
  606.     // {{{ getServerVersion()
  607.  
  608.     /**
  609.      * return version information about the server
  610.      *
  611.      * @param bool   $native  determines if the raw version string should be returned
  612.      * @return mixed array/string with version information or MDB2 error object
  613.      * @access public
  614.      */
  615.     function getServerVersion($native = false)
  616.     {
  617.         $server_info = false;
  618.         if ($this->connected_server_info{
  619.             $server_info $this->connected_server_info;
  620.         elseif ($this->options['server_version']{
  621.             $server_info $this->options['server_version'];
  622.         elseif (function_exists('sqlite_libversion')) {
  623.             $server_info @sqlite_libversion();
  624.         }
  625.         if (!$server_info{
  626.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  627.                 'Requires either the "server_version" option or the sqlite_libversion() function'__FUNCTION__);
  628.         }
  629.         // cache server_info
  630.         $this->connected_server_info $server_info;
  631.         if (!$native{
  632.             $tmp explode('.'$server_info3);
  633.             $server_info = array(
  634.                 'major' => isset($tmp[0]$tmp[0: null,
  635.                 'minor' => isset($tmp[1]$tmp[1: null,
  636.                 'patch' => isset($tmp[2]$tmp[2: null,
  637.                 'extra' => null,
  638.                 'native' => $server_info,
  639.             );
  640.         }
  641.         return $server_info;
  642.     }
  643.  
  644.     // }}}
  645.     // {{{ replace()
  646.  
  647.     /**
  648.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  649.      * query, except that if there is already a row in the table with the same
  650.      * key field values, the REPLACE query just updates its values instead of
  651.      * inserting a new row.
  652.      *
  653.      * The REPLACE type of query does not make part of the SQL standards. Since
  654.      * practically only SQLite implements it natively, this type of query is
  655.      * emulated through this method for other DBMS using standard types of
  656.      * queries inside a transaction to assure the atomicity of the operation.
  657.      *
  658.      * @access public
  659.      *
  660.      * @param string $table name of the table on which the REPLACE query will
  661.      *   be executed.
  662.      * @param array $fields associative array that describes the fields and the
  663.      *   values that will be inserted or updated in the specified table. The
  664.      *   indexes of the array are the names of all the fields of the table. The
  665.      *   values of the array are also associative arrays that describe the
  666.      *   values and other properties of the table fields.
  667.      *
  668.      *   Here follows a list of field properties that need to be specified:
  669.      *
  670.      *     value:
  671.      *           Value to be assigned to the specified field. This value may be
  672.      *           of specified in database independent type format as this
  673.      *           function can perform the necessary datatype conversions.
  674.      *
  675.      *     Default:
  676.      *           this property is required unless the Null property
  677.      *           is set to 1.
  678.      *
  679.      *     type
  680.      *           Name of the type of the field. Currently, all types Metabase
  681.      *           are supported except for clob and blob.
  682.      *
  683.      *     Default: no type conversion
  684.      *
  685.      *     null
  686.      *           Boolean property that indicates that the value for this field
  687.      *           should be set to null.
  688.      *
  689.      *           The default value for fields missing in INSERT queries may be
  690.      *           specified the definition of a table. Often, the default value
  691.      *           is already null, but since the REPLACE may be emulated using
  692.      *           an UPDATE query, make sure that all fields of the table are
  693.      *           listed in this function argument array.
  694.      *
  695.      *     Default: 0
  696.      *
  697.      *     key
  698.      *           Boolean property that indicates that this field should be
  699.      *           handled as a primary key or at least as part of the compound
  700.      *           unique index of the table that will determine the row that will
  701.      *           updated if it exists or inserted a new row otherwise.
  702.      *
  703.      *           This function will fail if no key field is specified or if the
  704.      *           value of a key field is set to null because fields that are
  705.      *           part of unique index they may not be null.
  706.      *
  707.      *     Default: 0
  708.      *
  709.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  710.      */
  711.     function replace($table$fields)
  712.     {
  713.         $count count($fields);
  714.         $query $values '';
  715.         $keys $colnum = 0;
  716.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  717.             $name key($fields);
  718.             if ($colnum > 0{
  719.                 $query .= ',';
  720.                 $values.= ',';
  721.             }
  722.             $query.= $name;
  723.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  724.                 $value 'NULL';
  725.             else {
  726.                 $type = isset($fields[$name]['type']$fields[$name]['type': null;
  727.                 $value $this->quote($fields[$name]['value']$type);
  728.             }
  729.             $values.= $value;
  730.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  731.                 if ($value === 'NULL'{
  732.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  733.                         'key value '.$name.' may not be NULL'__FUNCTION__);
  734.                 }
  735.                 $keys++;
  736.             }
  737.         }
  738.         if ($keys == 0{
  739.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  740.                 'not specified which fields are keys'__FUNCTION__);
  741.         }
  742.  
  743.         $connection $this->getConnection();
  744.         if (PEAR::isError($connection)) {
  745.             return $connection;
  746.         }
  747.  
  748.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  749.         $result =$this->_doQuery($querytrue$connection);
  750.         if (PEAR::isError($result)) {
  751.             return $result;
  752.         }
  753.         return $this->_affectedRows($connection$result);
  754.     }
  755.  
  756.     // }}}
  757.     // {{{ nextID()
  758.  
  759.     /**
  760.      * Returns the next free id of a sequence
  761.      *
  762.      * @param string $seq_name name of the sequence
  763.      * @param boolean $ondemand when true the sequence is
  764.      *                           automatic created, if it
  765.      *                           not exists
  766.      *
  767.      * @return mixed MDB2 Error Object or id
  768.      * @access public
  769.      */
  770.     function nextID($seq_name$ondemand = true)
  771.     {
  772.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  773.         $seqcol_name $this->options['seqcol_name'];
  774.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  775.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  776.         $result =$this->_doQuery($querytrue);
  777.         $this->popExpect();
  778.         if (PEAR::isError($result)) {
  779.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  780.                 $this->loadModule('Manager'nulltrue);
  781.                 $result $this->manager->createSequence($seq_name);
  782.                 if (PEAR::isError($result)) {
  783.                     return $this->raiseError($resultnullnull,
  784.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  785.                 else {
  786.                     return $this->nextID($seq_namefalse);
  787.                 }
  788.             }
  789.             return $result;
  790.         }
  791.         $value $this->lastInsertID();
  792.         if (is_numeric($value)) {
  793.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  794.             $result =$this->_doQuery($querytrue);
  795.             if (PEAR::isError($result)) {
  796.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  797.             }
  798.         }
  799.         return $value;
  800.     }
  801.  
  802.     // }}}
  803.     // {{{ lastInsertID()
  804.  
  805.     /**
  806.      * Returns the autoincrement ID if supported or $id or fetches the current
  807.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  808.      *
  809.      * @param string $table name of the table into which a new row was inserted
  810.      * @param string $field name of the field into which a new row was inserted
  811.      * @return mixed MDB2 Error Object or id
  812.      * @access public
  813.      */
  814.     function lastInsertID($table = null$field = null)
  815.     {
  816.         $connection $this->getConnection();
  817.         if (PEAR::isError($connection)) {
  818.             return $connection;
  819.         }
  820.         $value @sqlite_last_insert_rowid($connection);
  821.         if (!$value{
  822.             return $this->raiseError(nullnullnull,
  823.                 'Could not get last insert ID'__FUNCTION__);
  824.         }
  825.         return $value;
  826.     }
  827.  
  828.     // }}}
  829.     // {{{ currID()
  830.  
  831.     /**
  832.      * Returns the current id of a sequence
  833.      *
  834.      * @param string $seq_name name of the sequence
  835.      * @return mixed MDB2 Error Object or id
  836.      * @access public
  837.      */
  838.     function currID($seq_name)
  839.     {
  840.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  841.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  842.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  843.         return $this->queryOne($query'integer');
  844.     }
  845. }
  846.  
  847. /**
  848.  * MDB2 SQLite result driver
  849.  *
  850.  * @package MDB2
  851.  * @category Database
  852.  * @author  Lukas Smith <smith@pooteeweet.org>
  853.  */
  854. class MDB2_Result_sqlite extends MDB2_Result_Common
  855. {
  856.     // }}}
  857.     // {{{ fetchRow()
  858.  
  859.     /**
  860.      * Fetch a row and insert the data into an existing array.
  861.      *
  862.      * @param int       $fetchmode  how the array data should be indexed
  863.      * @param int    $rownum    number of the row where the data can be found
  864.      * @return int data array on success, a MDB2 error on failure
  865.      * @access public
  866.      */
  867.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  868.     {
  869.         if (!is_null($rownum)) {
  870.             $seek $this->seek($rownum);
  871.             if (PEAR::isError($seek)) {
  872.                 return $seek;
  873.             }
  874.         }
  875.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  876.             $fetchmode $this->db->fetchmode;
  877.         }
  878.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  879.             $row @sqlite_fetch_array($this->resultSQLITE_ASSOC);
  880.             if (is_array($row)
  881.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  882.             {
  883.                 $row array_change_key_case($row$this->db->options['field_case']);
  884.             }
  885.         else {
  886.            $row @sqlite_fetch_array($this->resultSQLITE_NUM);
  887.         }
  888.         if (!$row{
  889.             if ($this->result === false{
  890.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  891.                     'resultset has already been freed'__FUNCTION__);
  892.                 return $err;
  893.             }
  894.             $null = null;
  895.             return $null;
  896.         }
  897.         $mode $this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL;
  898.         $rtrim = false;
  899.         if ($this->db->options['portability'MDB2_PORTABILITY_RTRIM{
  900.             if (empty($this->types)) {
  901.                 $mode += MDB2_PORTABILITY_RTRIM;
  902.             else {
  903.                 $rtrim = true;
  904.             }
  905.         }
  906.         if ($mode{
  907.             $this->db->_fixResultArrayValues($row$mode);
  908.         }
  909.         if (!empty($this->types)) {
  910.             $row $this->db->datatype->convertResultRow($this->types$row$rtrim);
  911.         }
  912.         if (!empty($this->values)) {
  913.             $this->_assignBindColumns($row);
  914.         }
  915.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  916.             $object_class $this->db->options['fetch_class'];
  917.             if ($object_class == 'stdClass'{
  918.                 $row = (object) $row;
  919.             else {
  920.                 $row &new $object_class($row);
  921.             }
  922.         }
  923.         ++$this->rownum;
  924.         return $row;
  925.     }
  926.  
  927.     // }}}
  928.     // {{{ _getColumnNames()
  929.  
  930.     /**
  931.      * Retrieve the names of columns returned by the DBMS in a query result.
  932.      *
  933.      * @return  mixed   Array variable that holds the names of columns as keys
  934.      *                   or an MDB2 error on failure.
  935.      *                   Some DBMS may not return any columns when the result set
  936.      *                   does not contain any rows.
  937.      * @access private
  938.      */
  939.     function _getColumnNames()
  940.     {
  941.         $columns = array();
  942.         $numcols $this->numCols();
  943.         if (PEAR::isError($numcols)) {
  944.             return $numcols;
  945.         }
  946.         for ($column = 0; $column $numcols$column++{
  947.             $column_name @sqlite_field_name($this->result$column);
  948.             $columns[$column_name$column;
  949.         }
  950.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  951.             $columns array_change_key_case($columns$this->db->options['field_case']);
  952.         }
  953.         return $columns;
  954.     }
  955.  
  956.     // }}}
  957.     // {{{ numCols()
  958.  
  959.     /**
  960.      * Count the number of columns returned by the DBMS in a query result.
  961.      *
  962.      * @access public
  963.      * @return mixed integer value with the number of columns, a MDB2 error
  964.      *                        on failure
  965.      */
  966.     function numCols()
  967.     {
  968.         $cols @sqlite_num_fields($this->result);
  969.         if (is_null($cols)) {
  970.             if ($this->result === false{
  971.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  972.                     'resultset has already been freed'__FUNCTION__);
  973.             elseif (is_null($this->result)) {
  974.                 return count($this->types);
  975.             }
  976.             return $this->db->raiseError(nullnullnull,
  977.                 'Could not get column count'__FUNCTION__);
  978.         }
  979.         return $cols;
  980.     }
  981. }
  982.  
  983. /**
  984.  * MDB2 SQLite buffered result driver
  985.  *
  986.  * @package MDB2
  987.  * @category Database
  988.  * @author  Lukas Smith <smith@pooteeweet.org>
  989.  */
  990. {
  991.     // {{{ seek()
  992.  
  993.     /**
  994.      * Seek to a specific row in a result set
  995.      *
  996.      * @param int    $rownum    number of the row where the data can be found
  997.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  998.      * @access public
  999.      */
  1000.     function seek($rownum = 0)
  1001.     {
  1002.         if (!@sqlite_seek($this->result$rownum)) {
  1003.             if ($this->result === false{
  1004.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1005.                     'resultset has already been freed'__FUNCTION__);
  1006.             elseif (is_null($this->result)) {
  1007.                 return MDB2_OK;
  1008.             }
  1009.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  1010.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  1011.         }
  1012.         $this->rownum $rownum - 1;
  1013.         return MDB2_OK;
  1014.     }
  1015.  
  1016.     // }}}
  1017.     // {{{ valid()
  1018.  
  1019.     /**
  1020.      * Check if the end of the result set has been reached
  1021.      *
  1022.      * @return mixed true or false on sucess, a MDB2 error on failure
  1023.      * @access public
  1024.      */
  1025.     function valid()
  1026.     {
  1027.         $numrows $this->numRows();
  1028.         if (PEAR::isError($numrows)) {
  1029.             return $numrows;
  1030.         }
  1031.         return $this->rownum ($numrows - 1);
  1032.     }
  1033.  
  1034.     // }}}
  1035.     // {{{ numRows()
  1036.  
  1037.     /**
  1038.      * Returns the number of rows in a result object
  1039.      *
  1040.      * @return mixed MDB2 Error Object or the number of rows
  1041.      * @access public
  1042.      */
  1043.     function numRows()
  1044.     {
  1045.         $rows @sqlite_num_rows($this->result);
  1046.         if (is_null($rows)) {
  1047.             if ($this->result === false{
  1048.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1049.                     'resultset has already been freed'__FUNCTION__);
  1050.             elseif (is_null($this->result)) {
  1051.                 return 0;
  1052.             }
  1053.             return $this->db->raiseError(nullnullnull,
  1054.                 'Could not get row count'__FUNCTION__);
  1055.         }
  1056.         return $rows;
  1057.     }
  1058. }
  1059.  
  1060. /**
  1061.  * MDB2 SQLite statement driver
  1062.  *
  1063.  * @package MDB2
  1064.  * @category Database
  1065.  * @author  Lukas Smith <smith@pooteeweet.org>
  1066.  */
  1067. class MDB2_Statement_sqlite extends MDB2_Statement_Common
  1068. {
  1069.  
  1070. }
  1071.  
  1072. ?>

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