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

Source for file sqlite.php

Documentation is available at sqlite.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5                                                 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith                                         |
  7. // | All rights reserved.                                                 |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  10. // | API as well as database abstraction for PHP applications.            |
  11. // | This LICENSE is in the BSD license style.                            |
  12. // |                                                                      |
  13. // | Redistribution and use in source and binary forms, with or without   |
  14. // | modification, are permitted provided that the following conditions   |
  15. // | are met:                                                             |
  16. // |                                                                      |
  17. // | Redistributions of source code must retain the above copyright       |
  18. // | notice, this list of conditions and the following disclaimer.        |
  19. // |                                                                      |
  20. // | Redistributions in binary form must reproduce the above copyright    |
  21. // | notice, this list of conditions and the following disclaimer in the  |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // |                                                                      |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission.                                                  |
  28. // |                                                                      |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  40. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  41. // +----------------------------------------------------------------------+
  42. // | Author: Lukas Smith <smith@backendmedia.com>                         |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: sqlite.php,v 1.14 2005/01/03 16:12:03 lsmith Exp $
  46. //
  47.  
  48. require_once 'MDB2/Driver/Manager/Common.php';
  49.  
  50. /**
  51.  * MDB2 SQLite driver for the management modules
  52.  *
  53.  * @package MDB2
  54.  * @category Database
  55.  * @author  Lukas Smith <smith@backendmedia.com>
  56.  */
  57. {
  58.     // {{{ createDatabase()
  59.  
  60.     /**
  61.      * create a new database
  62.      *
  63.      * @param string $name name of the database that should be created
  64.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  65.      * @access public
  66.      */
  67.     function createDatabase($name)
  68.     {
  69.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  70.         $database_file $db->_getDatabaseFile($name);
  71.         if (file_exists($database_file)) {
  72.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  73.                 'createDatabase: database already exists');
  74.         }
  75.         $php_errormsg '';
  76.         $handle @sqlite_open($database_file$db->dsn['mode']$php_errormsg);
  77.         if (!$handle{
  78.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  79.                 'createDatabase: '.(isset($php_errormsg$php_errormsg 'could not create the database file'));
  80.         }
  81.         @sqlite_close($handle);
  82.         return MDB2_OK;
  83.     }
  84.  
  85.     // }}}
  86.     // {{{ dropDatabase()
  87.  
  88.     /**
  89.      * drop an existing database
  90.      *
  91.      * @param string $name name of the database that should be dropped
  92.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  93.      * @access public
  94.      */
  95.     function dropDatabase($name)
  96.     {
  97.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  98.         $database_file $db->_getDatabaseFile($name);
  99.         if (!@file_exists($database_file)) {
  100.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  101.                 'dropDatabase: database does not exist');
  102.         }
  103.         $result @unlink($database_file);
  104.         if (!$result{
  105.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  106.                 'dropDatabase: '.(isset($php_errormsg$php_errormsg 'could not remove the database file'));
  107.         }
  108.         return MDB2_OK;
  109.     }
  110.  
  111.     // }}}
  112.     // {{{ listDatabases()
  113.  
  114.     /**
  115.      * list all databases
  116.      *
  117.      * @return mixed data array on success, a MDB2 error on failure
  118.      * @access public
  119.      */
  120.     function listDatabases()
  121.     {
  122.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  123.         return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  124.             'listDatabases: list databases is not supported');
  125.     }
  126.  
  127.     // }}}
  128.     // {{{ listUsers()
  129.  
  130.     /**
  131.      * list all users
  132.      *
  133.      * @return mixed data array on success, a MDB2 error on failure
  134.      * @access public
  135.      */
  136.     function listUsers()
  137.     {
  138.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  139.         return $db->queryCol('SELECT DISTINCT USER FROM USER');
  140.     }
  141.  
  142.     // }}}
  143.     // {{{ listTables()
  144.  
  145.     /**
  146.      * list all tables in the current database
  147.      *
  148.      * @return mixed data array on success, a MDB2 error on failure
  149.      * @access public
  150.      */
  151.     function listTables()
  152.     {
  153.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  154.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  155.         $table_names $db->queryCol($query);
  156.         if (MDB2::isError($table_names)) {
  157.             return $table_names;
  158.         }
  159.         $tables = array();
  160.         for ($i = 0$j count($table_names)$i $j; ++$i{
  161.             if (!$this->_isSequenceName($table_names[$i]))
  162.                 $tables[$table_names[$i];
  163.         }
  164.         return $tables;
  165.     }
  166.  
  167.     function _getTableColumns($query)
  168.     {
  169.         $start_pos strpos($query'(');
  170.         $end_pos strrpos($query')');
  171.         $column_def substr($query$start_pos+1$end_pos-$start_pos-1);
  172.         $column_sql split(','$column_def);
  173.         $columns = array();
  174.         $count count($column_sql);
  175.         if ($count == 0{
  176.             return $db->raiseError('unexpected empty table column definition list');
  177.         }
  178.         $regexp '/^([^ ]+) (CHAR|VARCHAR|VARCHAR2|TEXT|INT|INTEGER|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( PRIMARY)?( \(([1-9][0-9]*)(,([1-9][0-9]*))?\))?( DEFAULT (\'[^\']*\'|[^ ]+))?( NOT NULL)?$/i';
  179.         for ($i=0$j=0; $i<$count; ++$i{
  180.             if (!preg_match($regexp$column_sql[$i]$matches)) {
  181.                 return $db->raiseError('unexpected table column SQL definition');
  182.             }
  183.             $columns[$j]['name'$matches[1];
  184.             $columns[$j]['type'strtolower($matches[2]);
  185.             if (isset($matches[5]&& strlen($matches[5])) {
  186.                 $columns[$j]['length'$matches[5];
  187.             }
  188.             if (isset($matches[7]&& strlen($matches[7])) {
  189.                 $columns[$j]['decimal'$matches[7];
  190.             }
  191.             if (isset($matches[9]&& strlen($matches[9])) {
  192.                 $default $matches[9];
  193.                 if (strlen($default&& $default[0]=="'"{
  194.                     $default str_replace("''","'",substr($default1strlen($default)-2));
  195.                 }
  196.                 $columns[$j]['default'$default;
  197.             }
  198.             if (isset($matches[10]&& strlen($matches[10])) {
  199.                 $columns[$j]['notnull'= true;
  200.             }
  201.             ++$j;
  202.         }
  203.         return $columns;
  204.     }
  205.  
  206.     // }}}
  207.     // {{{ listTableFields()
  208.  
  209.     /**
  210.      * list all fields in a tables in the current database
  211.      *
  212.      * @param string $table name of table that should be used in method
  213.      * @return mixed data array on success, a MDB2 error on failure
  214.      * @access public
  215.      */
  216.     function listTableFields($table)
  217.     {
  218.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  219.         $query = "SELECT sql FROM sqlite_master WHERE type='table' AND name='$table'";
  220.         $result $db->queryCol($query);
  221.         if (MDB2::isError($result)) {
  222.             return $result;
  223.         }
  224.         $columns $result->getColumnNames();
  225.         $result->free();
  226.         if (MDB2::isError($columns)) {
  227.             return $columns;
  228.         }
  229.         return array_flip($columns);
  230.     }
  231.  
  232.     // }}}
  233.     // {{{ createIndex()
  234.  
  235.     /**
  236.      * get the stucture of a field into an array
  237.      *
  238.      * @param string    $table         name of the table on which the index is to be created
  239.      * @param string    $name         name of the index to be created
  240.      * @param array     $definition        associative array that defines properties of the index to be created.
  241.      *                                  Currently, only one property named FIELDS is supported. This property
  242.      *                                  is also an associative with the names of the index fields as array
  243.      *                                  indexes. Each entry of this array is set to another type of associative
  244.      *                                  array that specifies properties of the index that are specific to
  245.      *                                  each field.
  246.      *
  247.      *                                 Currently, only the sorting property is supported. It should be used
  248.      *                                  to define the sorting direction of the index. It may be set to either
  249.      *                                  ascending or descending.
  250.      *
  251.      *                                 Not all DBMS support index sorting direction configuration. The DBMS
  252.      *                                  drivers of those that do not support it ignore this property. Use the
  253.      *                                  function support() to determine whether the DBMS driver can manage indexes.
  254.  
  255.      *                                  Example
  256.      *                                     array(
  257.      *                                         'fields' => array(
  258.      *                                             'user_name' => array(
  259.      *                                                 'sorting' => 'ascending'
  260.      *                                             ),
  261.      *                                             'last_login' => array()
  262.      *                                         )
  263.      *                                     )
  264.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  265.      * @access public
  266.      */
  267.     function createIndex($table$name$definition)
  268.     {
  269.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  270.         $query 'CREATE '.(isset($definition['unique']'UNIQUE' '')." INDEX $name ON $table (";
  271.         $skipped_first = false;
  272.         foreach ($definition['fields'as $field_name => $field{
  273.             if ($skipped_first{
  274.                 $query .= ',';
  275.             }
  276.             $query .= $field_name;
  277.             $skipped_first = true;
  278.         }
  279.         $query .= ')';
  280.         return $db->query($query);
  281.     }
  282.  
  283.     // }}}
  284.     // {{{ dropIndex()
  285.  
  286.     /**
  287.      * drop existing index
  288.      *
  289.      * @param string    $table         name of table that should be used in method
  290.      * @param string    $name         name of the index to be dropped
  291.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  292.      * @access public
  293.      */
  294.     function dropIndex($table$name)
  295.     {
  296.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  297.         return $db->query("DROP INDEX $name");
  298.     }
  299.  
  300.     // }}}
  301.     // {{{ listTableIndexes()
  302.  
  303.     /**
  304.      * list all indexes in a table
  305.      *
  306.      * @param string    $table      name of table that should be used in method
  307.      * @return mixed data array on success, a MDB2 error on failure
  308.      * @access public
  309.      */
  310.     function listTableIndexes($table)
  311.     {
  312.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  313.         $query = "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='$table' AND sql NOT NULL ORDER BY name";
  314.         $indexes_all $db->queryCol($query);
  315.         if (MDB2::isError($indexes_all)) {
  316.             return $indexes_all;
  317.         }
  318.         $found $indexes = array();
  319.         foreach ($indexes_all as $index_name{
  320.             if ($indexes_all[$index!= 'PRIMARY' && !isset($found[$index_name])) {
  321.                 $indexes[$index_name;
  322.                 $found[$index_name= true;
  323.             }
  324.         }
  325.         return $indexes;
  326.     }
  327.  
  328.     // }}}
  329.     // {{{ createSequence()
  330.  
  331.     /**
  332.      * create sequence
  333.      *
  334.      * @param string    $seq_name     name of the sequence to be created
  335.      * @param string    $start         start value of the sequence; default is 1
  336.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  337.      * @access public
  338.      */
  339.     function createSequence($seq_name$start = 1)
  340.     {
  341.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  342.         $sequence_name $db->getSequenceName($seq_name);
  343.         $seqname_col_name $db->options['seqname_col_name'];
  344.         $query = "CREATE TABLE $sequence_name ($seqname_col_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
  345.         $res $db->query($query);
  346.         if (MDB2::isError($res)) {
  347.             return $res;
  348.         }
  349.         if ($start == 1{
  350.             return MDB2_OK;
  351.         }
  352.         $res $db->query("INSERT INTO $sequence_name ($seqname_col_name) VALUES (".($start-1).')');
  353.         if (!MDB2::isError($res)) {
  354.             return MDB2_OK;
  355.         }
  356.         // Handle error
  357.         $result $db->query("DROP TABLE $sequence_name");
  358.         if (MDB2::isError($result)) {
  359.             return $db->raiseError(MDB2_ERRORnullnull,
  360.                 'createSequence: could not drop inconsistent sequence table ('.
  361.                 $result->getMessage().' ('.$result->getUserinfo().'))');
  362.         }
  363.         return $db->raiseError(MDB2_ERRORnullnull,
  364.             'createSequence: could not create sequence table ('.
  365.             $res->getMessage().' ('.$res->getUserinfo().'))');
  366.     }
  367.  
  368.     // }}}
  369.     // {{{ dropSequence()
  370.  
  371.     /**
  372.      * drop existing sequence
  373.      *
  374.      * @param string    $seq_name     name of the sequence to be dropped
  375.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  376.      * @access public
  377.      */
  378.     function dropSequence($seq_name)
  379.     {
  380.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  381.         $sequence_name $db->getSequenceName($seq_name);
  382.         return $db->query("DROP TABLE $sequence_name");
  383.     }
  384.  
  385.     // }}}
  386.     // {{{ listSequences()
  387.  
  388.     /**
  389.      * list all sequences in the current database
  390.      *
  391.      * @return mixed data array on success, a MDB2 error on failure
  392.      * @access public
  393.      */
  394.     function listSequences()
  395.     {
  396.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  397.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  398.         $table_names $db->queryCol($query);
  399.         if (MDB2::isError($table_names)) {
  400.             return $table_names;
  401.         }
  402.         $sequences = array();
  403.         for ($i = 0$j count($table_names)$i $j; ++$i{
  404.             if ($sqn $this->_isSequenceName($table_names[$i]))
  405.                 $sequences[$sqn;
  406.         }
  407.         return $sequences;
  408.     }
  409.  
  410.     // }}}
  411. }
  412. ?>

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