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

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