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

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