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

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