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

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