MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file sqlite.php

Documentation is available at sqlite.php

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

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