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

Source for file sqlite.php

Documentation is available at sqlite.php

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

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