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.134 2006/07/22 08:01:57 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.             if ($is__manip{
  498.                 return 0;
  499.             }
  500.             return null;
  501.         }
  502.  
  503.         if (is_null($connection)) {
  504.             $connection $this->getConnection();
  505.             if (PEAR::isError($connection)) {
  506.                 return $connection;
  507.             }
  508.         }
  509.  
  510.         $function $this->options['result_buffering']
  511.             ? 'sqlite_query' 'sqlite_unbuffered_query';
  512.         $php_errormsg '';
  513.         @ini_set('track_errors'true);
  514.         $result @$function($query.';'$connection);
  515.         @ini_restore('track_errors');
  516.         $this->_lasterror $php_errormsg;
  517.  
  518.         if (!$result{
  519.             $err =$this->raiseError(nullnullnull,
  520.                 'Could not execute statement'__FUNCTION__);
  521.             return $err;
  522.         }
  523.  
  524.         $this->debug($query'query'array('is_manip' => $is_manip'when' => 'post''result' => $result));
  525.         return $result;
  526.     }
  527.  
  528.     // }}}
  529.     // {{{ _affectedRows()
  530.  
  531.     /**
  532.      * Returns the number of rows affected
  533.      *
  534.      * @param resource $result 
  535.      * @param resource $connection 
  536.      * @return mixed MDB2 Error Object or the number of rows affected
  537.      * @access private
  538.      */
  539.     function _affectedRows($connection$result = null)
  540.     {
  541.         if (is_null($connection)) {
  542.             $connection $this->getConnection();
  543.             if (PEAR::isError($connection)) {
  544.                 return $connection;
  545.             }
  546.         }
  547.         return @sqlite_changes($connection);
  548.     }
  549.  
  550.     // }}}
  551.     // {{{ _modifyQuery()
  552.  
  553.     /**
  554.      * Changes a query string for various DBMS specific reasons
  555.      *
  556.      * @param string $query  query to modify
  557.      * @param boolean $is_manip  if it is a DML query
  558.      * @param integer $limit  limit the number of rows
  559.      * @param integer $offset  start reading from given offset
  560.      * @return string modified query
  561.      * @access protected
  562.      */
  563.     function _modifyQuery($query$is_manip$limit$offset)
  564.     {
  565.         if ($this->options['portability'MDB2_PORTABILITY_DELETE_COUNT{
  566.             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i'$query)) {
  567.                 $query preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  568.                                       'DELETE FROM \1 WHERE 1=1'$query);
  569.             }
  570.         }
  571.         if ($limit > 0
  572.             && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i'$query)
  573.         {
  574.             $query rtrim($query);
  575.             if (substr($query-1== ';'{
  576.                 $query substr($query0-1);
  577.             }
  578.             if ($is_manip{
  579.                 $query.= " LIMIT $limit";
  580.             else {
  581.                 $query.= " LIMIT $offset,$limit";
  582.             }
  583.         }
  584.         return $query;
  585.     }
  586.  
  587.     // }}}
  588.     // {{{ getServerVersion()
  589.  
  590.     /**
  591.      * return version information about the server
  592.      *
  593.      * @param string     $native  determines if the raw version string should be returned
  594.      * @return mixed array/string with version information or MDB2 error object
  595.      * @access public
  596.      */
  597.     function getServerVersion($native = false)
  598.     {
  599.         $server_info = false;
  600.         if ($this->connected_server_info{
  601.             $server_info $this->connected_server_info;
  602.         elseif ($this->options['server_version']{
  603.             $server_info $this->options['server_version'];
  604.         elseif (function_exists('sqlite_libversion')) {
  605.             $server_info @sqlite_libversion();
  606.         }
  607.         if (!$server_info{
  608.             return $this->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  609.                 'Requires either the "server_version" option or the sqlite_libversion() function'__FUNCTION__);
  610.         }
  611.         // cache server_info
  612.         $this->connected_server_info $server_info;
  613.         if (!$native{
  614.             $tmp explode('.'$server_info3);
  615.             $server_info = array(
  616.                 'major' => isset($tmp[0]$tmp[0: null,
  617.                 'minor' => isset($tmp[1]$tmp[1: null,
  618.                 'patch' => isset($tmp[2]$tmp[2: null,
  619.                 'extra' => null,
  620.                 'native' => $server_info,
  621.             );
  622.         }
  623.         return $server_info;
  624.     }
  625.  
  626.     // }}}
  627.     // {{{ replace()
  628.  
  629.     /**
  630.      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  631.      * query, except that if there is already a row in the table with the same
  632.      * key field values, the REPLACE query just updates its values instead of
  633.      * inserting a new row.
  634.      *
  635.      * The REPLACE type of query does not make part of the SQL standards. Since
  636.      * practically only SQLite implements it natively, this type of query is
  637.      * emulated through this method for other DBMS using standard types of
  638.      * queries inside a transaction to assure the atomicity of the operation.
  639.      *
  640.      * @access public
  641.      *
  642.      * @param string $table name of the table on which the REPLACE query will
  643.      *   be executed.
  644.      * @param array $fields associative array that describes the fields and the
  645.      *   values that will be inserted or updated in the specified table. The
  646.      *   indexes of the array are the names of all the fields of the table. The
  647.      *   values of the array are also associative arrays that describe the
  648.      *   values and other properties of the table fields.
  649.      *
  650.      *   Here follows a list of field properties that need to be specified:
  651.      *
  652.      *     value:
  653.      *           Value to be assigned to the specified field. This value may be
  654.      *           of specified in database independent type format as this
  655.      *           function can perform the necessary datatype conversions.
  656.      *
  657.      *     Default:
  658.      *           this property is required unless the Null property
  659.      *           is set to 1.
  660.      *
  661.      *     type
  662.      *           Name of the type of the field. Currently, all types Metabase
  663.      *           are supported except for clob and blob.
  664.      *
  665.      *     Default: no type conversion
  666.      *
  667.      *     null
  668.      *           Boolean property that indicates that the value for this field
  669.      *           should be set to null.
  670.      *
  671.      *           The default value for fields missing in INSERT queries may be
  672.      *           specified the definition of a table. Often, the default value
  673.      *           is already null, but since the REPLACE may be emulated using
  674.      *           an UPDATE query, make sure that all fields of the table are
  675.      *           listed in this function argument array.
  676.      *
  677.      *     Default: 0
  678.      *
  679.      *     key
  680.      *           Boolean property that indicates that this field should be
  681.      *           handled as a primary key or at least as part of the compound
  682.      *           unique index of the table that will determine the row that will
  683.      *           updated if it exists or inserted a new row otherwise.
  684.      *
  685.      *           This function will fail if no key field is specified or if the
  686.      *           value of a key field is set to null because fields that are
  687.      *           part of unique index they may not be null.
  688.      *
  689.      *     Default: 0
  690.      *
  691.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  692.      */
  693.     function replace($table$fields)
  694.     {
  695.         $count count($fields);
  696.         $query $values '';
  697.         $keys $colnum = 0;
  698.         for (reset($fields)$colnum $countnext($fields)$colnum++{
  699.             $name key($fields);
  700.             if ($colnum > 0{
  701.                 $query .= ',';
  702.                 $values.= ',';
  703.             }
  704.             $query.= $name;
  705.             if (isset($fields[$name]['null']&& $fields[$name]['null']{
  706.                 $value 'NULL';
  707.             else {
  708.                 $type = isset($fields[$name]['type']$fields[$name]['type': null;
  709.                 $value $this->quote($fields[$name]['value']$type);
  710.             }
  711.             $values.= $value;
  712.             if (isset($fields[$name]['key']&& $fields[$name]['key']{
  713.                 if ($value === 'NULL'{
  714.                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  715.                         'key value '.$name.' may not be NULL'__FUNCTION__);
  716.                 }
  717.                 $keys++;
  718.             }
  719.         }
  720.         if ($keys == 0{
  721.             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACEnullnull,
  722.                 'not specified which fields are keys'__FUNCTION__);
  723.         }
  724.  
  725.         $connection $this->getConnection();
  726.         if (PEAR::isError($connection)) {
  727.             return $connection;
  728.         }
  729.  
  730.         $query = "REPLACE INTO $table ($query) VALUES ($values)";
  731.         $result =$this->_doQuery($querytrue$connection);
  732.         if (PEAR::isError($result)) {
  733.             return $result;
  734.         }
  735.         return $this->_affectedRows($connection$result);
  736.     }
  737.  
  738.     // }}}
  739.     // {{{ nextID()
  740.  
  741.     /**
  742.      * Returns the next free id of a sequence
  743.      *
  744.      * @param string $seq_name name of the sequence
  745.      * @param boolean $ondemand when true the sequence is
  746.      *                           automatic created, if it
  747.      *                           not exists
  748.      *
  749.      * @return mixed MDB2 Error Object or id
  750.      * @access public
  751.      */
  752.     function nextID($seq_name$ondemand = true)
  753.     {
  754.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  755.         $seqcol_name $this->options['seqcol_name'];
  756.         $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  757.         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  758.         $result =$this->_doQuery($querytrue);
  759.         $this->popExpect();
  760.         if (PEAR::isError($result)) {
  761.             if ($ondemand && $result->getCode(== MDB2_ERROR_NOSUCHTABLE{
  762.                 $this->loadModule('Manager'nulltrue);
  763.                 // Since we are creating the sequence on demand
  764.                 // we know the first id = 1 so initialize the
  765.                 // sequence at 2
  766.                 $result $this->manager->createSequence($seq_name2);
  767.                 if (PEAR::isError($result)) {
  768.                     return $this->raiseError($resultnullnull,
  769.                         'on demand sequence '.$seq_name.' could not be created'__FUNCTION__);
  770.                 else {
  771.                     // First ID of a newly created sequence is 1
  772.                     return 1;
  773.                 }
  774.             }
  775.             return $result;
  776.         }
  777.         $value $this->lastInsertID();
  778.         if (is_numeric($value)) {
  779.             $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  780.             $result =$this->_doQuery($querytrue);
  781.             if (PEAR::isError($result)) {
  782.                 $this->warnings['nextID: could not delete previous sequence table values from '.$seq_name;
  783.             }
  784.         }
  785.         return $value;
  786.     }
  787.  
  788.     // }}}
  789.     // {{{ lastInsertID()
  790.  
  791.     /**
  792.      * Returns the autoincrement ID if supported or $id or fetches the current
  793.      * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  794.      *
  795.      * @param string $table name of the table into which a new row was inserted
  796.      * @param string $field name of the field into which a new row was inserted
  797.      * @return mixed MDB2 Error Object or id
  798.      * @access public
  799.      */
  800.     function lastInsertID($table = null$field = null)
  801.     {
  802.         $connection $this->getConnection();
  803.         if (PEAR::isError($connection)) {
  804.             return $connection;
  805.         }
  806.         $value @sqlite_last_insert_rowid($connection);
  807.         if (!$value{
  808.             return $this->raiseError(nullnullnull,
  809.                 'Could not get last insert ID'__FUNCTION__);
  810.         }
  811.         return $value;
  812.     }
  813.  
  814.     // }}}
  815.     // {{{ currID()
  816.  
  817.     /**
  818.      * Returns the current id of a sequence
  819.      *
  820.      * @param string $seq_name name of the sequence
  821.      * @return mixed MDB2 Error Object or id
  822.      * @access public
  823.      */
  824.     function currID($seq_name)
  825.     {
  826.         $sequence_name $this->quoteIdentifier($this->getSequenceName($seq_name)true);
  827.         $seqcol_name $this->quoteIdentifier($this->options['seqcol_name']true);
  828.         $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  829.         return $this->queryOne($query'integer');
  830.     }
  831. }
  832.  
  833. /**
  834.  * MDB2 SQLite result driver
  835.  *
  836.  * @package MDB2
  837.  * @category Database
  838.  * @author  Lukas Smith <smith@pooteeweet.org>
  839.  */
  840. class MDB2_Result_sqlite extends MDB2_Result_Common
  841. {
  842.     // }}}
  843.     // {{{ fetchRow()
  844.  
  845.     /**
  846.      * Fetch a row and insert the data into an existing array.
  847.      *
  848.      * @param int       $fetchmode  how the array data should be indexed
  849.      * @param int    $rownum    number of the row where the data can be found
  850.      * @return int data array on success, a MDB2 error on failure
  851.      * @access public
  852.      */
  853.     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT$rownum = null)
  854.     {
  855.         if (!is_null($rownum)) {
  856.             $seek $this->seek($rownum);
  857.             if (PEAR::isError($seek)) {
  858.                 return $seek;
  859.             }
  860.         }
  861.         if ($fetchmode == MDB2_FETCHMODE_DEFAULT{
  862.             $fetchmode $this->db->fetchmode;
  863.         }
  864.         if ($fetchmode MDB2_FETCHMODE_ASSOC{
  865.             $row @sqlite_fetch_array($this->resultSQLITE_ASSOC);
  866.             if (is_array($row)
  867.                 && $this->db->options['portability'MDB2_PORTABILITY_FIX_CASE
  868.             {
  869.                 $row array_change_key_case($row$this->db->options['field_case']);
  870.             }
  871.         else {
  872.            $row @sqlite_fetch_array($this->resultSQLITE_NUM);
  873.         }
  874.         if (!$row{
  875.             if ($this->result === false{
  876.                 $err =$this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  877.                     'resultset has already been freed'__FUNCTION__);
  878.                 return $err;
  879.             }
  880.             $null = null;
  881.             return $null;
  882.         }
  883.         if (($mode ($this->db->options['portability'MDB2_PORTABILITY_RTRIM)
  884.             + ($this->db->options['portability'MDB2_PORTABILITY_EMPTY_TO_NULL))
  885.         {
  886.             $this->db->_fixResultArrayValues($row$mode);
  887.         }
  888.         if (!empty($this->values)) {
  889.             $this->_assignBindColumns($row);
  890.         }
  891.         if (!empty($this->types)) {
  892.             $row $this->db->datatype->convertResultRow($this->types$row);
  893.         }
  894.         if ($fetchmode === MDB2_FETCHMODE_OBJECT{
  895.             $object_class $this->db->options['fetch_class'];
  896.             if ($object_class == 'stdClass'{
  897.                 $row = (object) $row;
  898.             else {
  899.                 $row &new $object_class($row);
  900.             }
  901.         }
  902.         ++$this->rownum;
  903.         return $row;
  904.     }
  905.  
  906.     // }}}
  907.     // {{{ _getColumnNames()
  908.  
  909.     /**
  910.      * Retrieve the names of columns returned by the DBMS in a query result.
  911.      *
  912.      * @return  mixed   Array variable that holds the names of columns as keys
  913.      *                   or an MDB2 error on failure.
  914.      *                   Some DBMS may not return any columns when the result set
  915.      *                   does not contain any rows.
  916.      * @access private
  917.      */
  918.     function _getColumnNames()
  919.     {
  920.         $columns = array();
  921.         $numcols $this->numCols();
  922.         if (PEAR::isError($numcols)) {
  923.             return $numcols;
  924.         }
  925.         for ($column = 0; $column $numcols$column++{
  926.             $column_name @sqlite_field_name($this->result$column);
  927.             $columns[$column_name$column;
  928.         }
  929.         if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  930.             $columns array_change_key_case($columns$this->db->options['field_case']);
  931.         }
  932.         return $columns;
  933.     }
  934.  
  935.     // }}}
  936.     // {{{ numCols()
  937.  
  938.     /**
  939.      * Count the number of columns returned by the DBMS in a query result.
  940.      *
  941.      * @access public
  942.      * @return mixed integer value with the number of columns, a MDB2 error
  943.      *                        on failure
  944.      */
  945.     function numCols()
  946.     {
  947.         $cols @sqlite_num_fields($this->result);
  948.         if (is_null($cols)) {
  949.             if ($this->result === false{
  950.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  951.                     'resultset has already been freed'__FUNCTION__);
  952.             elseif (is_null($this->result)) {
  953.                 return count($this->types);
  954.             }
  955.             return $this->db->raiseError(nullnullnull,
  956.                 'Could not get column count'__FUNCTION__);
  957.         }
  958.         return $cols;
  959.     }
  960. }
  961.  
  962. /**
  963.  * MDB2 SQLite buffered result driver
  964.  *
  965.  * @package MDB2
  966.  * @category Database
  967.  * @author  Lukas Smith <smith@pooteeweet.org>
  968.  */
  969. {
  970.     // {{{ seek()
  971.  
  972.     /**
  973.      * Seek to a specific row in a result set
  974.      *
  975.      * @param int    $rownum    number of the row where the data can be found
  976.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  977.      * @access public
  978.      */
  979.     function seek($rownum = 0)
  980.     {
  981.         if (!@sqlite_seek($this->result$rownum)) {
  982.             if ($this->result === false{
  983.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  984.                     'resultset has already been freed'__FUNCTION__);
  985.             elseif (is_null($this->result)) {
  986.                 return MDB2_OK;
  987.             }
  988.             return $this->db->raiseError(MDB2_ERROR_INVALIDnullnull,
  989.                 'tried to seek to an invalid row number ('.$rownum.')'__FUNCTION__);
  990.         }
  991.         $this->rownum $rownum - 1;
  992.         return MDB2_OK;
  993.     }
  994.  
  995.     // }}}
  996.     // {{{ valid()
  997.  
  998.     /**
  999.      * Check if the end of the result set has been reached
  1000.      *
  1001.      * @return mixed true or false on sucess, a MDB2 error on failure
  1002.      * @access public
  1003.      */
  1004.     function valid()
  1005.     {
  1006.         $numrows $this->numRows();
  1007.         if (PEAR::isError($numrows)) {
  1008.             return $numrows;
  1009.         }
  1010.         return $this->rownum ($numrows - 1);
  1011.     }
  1012.  
  1013.     // }}}
  1014.     // {{{ numRows()
  1015.  
  1016.     /**
  1017.      * Returns the number of rows in a result object
  1018.      *
  1019.      * @return mixed MDB2 Error Object or the number of rows
  1020.      * @access public
  1021.      */
  1022.     function numRows()
  1023.     {
  1024.         $rows @sqlite_num_rows($this->result);
  1025.         if (is_null($rows)) {
  1026.             if ($this->result === false{
  1027.                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  1028.                     'resultset has already been freed'__FUNCTION__);
  1029.             elseif (is_null($this->result)) {
  1030.                 return 0;
  1031.             }
  1032.             return $this->db->raiseError(nullnullnull,
  1033.                 'Could not get row count'__FUNCTION__);
  1034.         }
  1035.         return $rows;
  1036.     }
  1037. }
  1038.  
  1039. /**
  1040.  * MDB2 SQLite statement driver
  1041.  *
  1042.  * @package MDB2
  1043.  * @category Database
  1044.  * @author  Lukas Smith <smith@pooteeweet.org>
  1045.  */
  1046. class MDB2_Statement_sqlite extends MDB2_Statement_Common
  1047. {
  1048.  
  1049. }
  1050.  
  1051. ?>

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