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

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