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

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