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

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