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

Source for file sqlite.php

Documentation is available at sqlite.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP Version 4                                                        |
  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.5 2004/04/07 21:15:31 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.     // }}}
  59.     // {{{ constructor
  60.  
  61.     /**
  62.      * Constructor
  63.      */
  64.     function MDB2_Driver_Manager_sqlite($db_index)
  65.     {
  66.         $this->MDB2_Driver_Manager_Common($db_index);
  67.     }
  68.  
  69.     // }}}
  70.     // {{{ createDatabase()
  71.  
  72.     /**
  73.      * create a new database
  74.      *
  75.      * @param string $name name of the database that should be created
  76.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  77.      * @access public
  78.      */
  79.     function createDatabase($name)
  80.     {
  81.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  82.         $database_file $db->_getDatabaseFile($name);
  83.         if (file_exists($database_file)) {
  84.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  85.                 'createDatabase: database already exists');
  86.         }
  87.         $php_errormsg '';
  88.         $handle @sqlite_open($database_file$db->dsn['mode']$php_errormsg);
  89.         if (!$handle{
  90.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  91.                 'createDatabase: '.(isset($php_errormsg$php_errormsg 'could not create the database file'));
  92.         }
  93.         @sqlite_close($handle);
  94.         return MDB2_OK;
  95.     }
  96.  
  97.     // }}}
  98.     // {{{ dropDatabase()
  99.  
  100.     /**
  101.      * drop an existing database
  102.      *
  103.      * @param string $name name of the database that should be dropped
  104.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  105.      * @access public
  106.      */
  107.     function dropDatabase($name)
  108.     {
  109.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  110.         $database_file $db->_getDatabaseFile($name);
  111.         if (!@file_exists($database_file)) {
  112.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  113.                 'dropDatabase: database does not exist');
  114.         }
  115.         $success @unlink($database_file);
  116.         if (!$success{
  117.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  118.                 'dropDatabase: '.(isset($php_errormsg$php_errormsg 'could not remove the database file'));
  119.         }
  120.         return MDB2_OK;
  121.     }
  122.  
  123.     // }}}
  124.     // {{{ createTable()
  125.  
  126.     /**
  127.      * create a new table
  128.      *
  129.      * @param string $name     Name of the database that should be created
  130.      * @param array $fields Associative array that contains the definition of each field of the new table
  131.      *                         The indexes of the array entries are the names of the fields of the table an
  132.      *                         the array entry values are associative arrays like those that are meant to be
  133.      *                          passed with the field definitions to get[Type]Declaration() functions.
  134.      *
  135.      *                         Example
  136.      *                         array(
  137.      *
  138.      *                             'id' => array(
  139.      *                                 'type' => 'integer',
  140.      *                                 'unsigned' => 1
  141.      *                                 'notnull' => 1
  142.      *                                 'default' => 0
  143.      *                             ),
  144.      *                             'name' => array(
  145.      *                                 'type' => 'text',
  146.      *                                 'length' => 12
  147.      *                             ),
  148.      *                             'password' => array(
  149.      *                                 'type' => 'text',
  150.      *                                 'length' => 12
  151.      *                             )
  152.      *                         );
  153.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  154.      * @access public
  155.      */
  156.     function createTable($name$fields)
  157.     {
  158.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  159.         if (!isset($name|| !strcmp($name'')) {
  160.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  161.                 'createTable: no valid table name specified');
  162.         }
  163.         if (count($fields== 0{
  164.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  165.                 'createTable: no fields specified for table "'.$name.'"');
  166.         }
  167.         if (MDB2::isError($query_fields $this->getFieldDeclarationList($fields))) {
  168.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  169.                 'createTable: unkown error');
  170.         }
  171.         $query = "CREATE TABLE $name ($query_fields)";
  172.         return $db->query($query);
  173.     }
  174.  
  175.     // }}}
  176.     // {{{ listDatabases()
  177.  
  178.     /**
  179.      * list all databases
  180.      *
  181.      * @return mixed data array on success, a MDB2 error on failure
  182.      * @access public
  183.      */
  184.     function listDatabases()
  185.     {
  186.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  187.         return $db->queryCol('SHOW DATABASES');
  188.     }
  189.  
  190.     // }}}
  191.     // {{{ listUsers()
  192.  
  193.     /**
  194.      * list all users
  195.      *
  196.      * @return mixed data array on success, a MDB2 error on failure
  197.      * @access public
  198.      */
  199.     function listUsers()
  200.     {
  201.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  202.         return $db->queryCol('SELECT DISTINCT USER FROM USER');
  203.     }
  204.  
  205.     // }}}
  206.     // {{{ listTables()
  207.  
  208.     /**
  209.      * list all tables in the current database
  210.      *
  211.      * @return mixed data array on success, a MDB2 error on failure
  212.      * @access public
  213.      */
  214.     function listTables()
  215.     {
  216.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  217.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  218.         $table_names $db->queryCol($query);
  219.         if (MDB2::isError($table_names)) {
  220.             return $table_names;
  221.         }
  222.         for ($i = 0$j count($table_names)$tables = array()$i $j; ++$i)
  223.         {
  224.             if (!$this->_isSequenceName($table_names[$i]))
  225.                 $tables[$table_names[$i];
  226.         }
  227.         return $tables;
  228.     }
  229.  
  230.     function _getTableColumnNames($sql)
  231.     {
  232.         if (MDB2::isError($columns $this->_getTableColumns($sql))) {
  233.             return $columns;
  234.         }
  235.         $count count($columns);
  236.         if ($count == 0{
  237.             return $db->raiseError('table did not return any columns');
  238.         }
  239.         $column_names=array();
  240.         for ($i=0;$i<$count;++$i{
  241.             $column_names[$columns[$i]['name'];
  242.         }
  243.         return $column_names;
  244.     }
  245.  
  246.     function _getTableColumns($sql)
  247.     {
  248.         $start_pos strpos($sql,"(");
  249.         $end_pos strrpos($sql,")");
  250.         $column_def substr($sql$start_pos+1$end_pos-$start_pos-1);
  251.         $column_sql split(","$column_def);
  252.         $columns = array();
  253.         $count count($column_sql);
  254.         if ($count == 0{
  255.             return $db->raiseError('unexpected empty table column definition list');
  256.         }
  257.         $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';
  258.         for ($i=0$j=0; $i<$count; ++$i{
  259.             if (!preg_match($regexp$column_sql[$i]$matches)) {
  260.                 return $db->raiseError('unexpected table column SQL definition');
  261.             }
  262.             $columns[$j]['name'$matches[1];
  263.             $columns[$j]['type'strtolower($matches[2]);
  264.             if (isset($matches[5]&& strlen($matches[5])) {
  265.                 $columns[$j]['length'$matches[5];
  266.             }
  267.             if (isset($matches[7]&& strlen($matches[7])) {
  268.                 $columns[$j]['decimal'$matches[7];
  269.             }
  270.             if (isset($matches[9]&& strlen($matches[9])) {
  271.                 $default $matches[9];
  272.                 if (strlen($default&& $default[0]=="'"{
  273.                     $default str_replace("''","'",substr($default1strlen($default)-2));
  274.                 }
  275.                 $columns[$j]['default'$default;
  276.             }
  277.             if (isset($matches[10]&& strlen($matches[10])) {
  278.                 $columns[$j]['notnull'= true;
  279.             }
  280.             ++$j;
  281.         }
  282.         return $columns;
  283.     }
  284.  
  285.     // }}}
  286.     // {{{ listTableFields()
  287.  
  288.     /**
  289.      * list all fields in a tables in the current database
  290.      *
  291.      * @param string $table name of table that should be used in method
  292.      * @return mixed data array on success, a MDB2 error on failure
  293.      * @access public
  294.      */
  295.     function listTableFields($table)
  296.     {
  297.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  298.         $query = "SELECT sql FROM sqlite_master WHERE type='table' AND name='$table'";
  299.         $sql $db->queryCol($query);
  300.         if (MDB2::isError($sql)) {
  301.             return $sql;
  302.         }
  303.         if (MDB2::isError($fields $this->_getTableColumnNames($sql))) {
  304.             return $fields;
  305.         }
  306.         if (!is_array($fields)) {
  307.             return array();
  308.         }
  309.         return $fields;
  310.     }
  311.  
  312.     // }}}
  313.     // {{{ createIndex()
  314.  
  315.     /**
  316.      * get the stucture of a field into an array
  317.      *
  318.      * @param string    $table         name of the table on which the index is to be created
  319.      * @param string    $name         name of the index to be created
  320.      * @param array     $definition        associative array that defines properties of the index to be created.
  321.      *                                  Currently, only one property named FIELDS is supported. This property
  322.      *                                  is also an associative with the names of the index fields as array
  323.      *                                  indexes. Each entry of this array is set to another type of associative
  324.      *                                  array that specifies properties of the index that are specific to
  325.      *                                  each field.
  326.      *
  327.      *                                 Currently, only the sorting property is supported. It should be used
  328.      *                                  to define the sorting direction of the index. It may be set to either
  329.      *                                  ascending or descending.
  330.      *
  331.      *                                 Not all DBMS support index sorting direction configuration. The DBMS
  332.      *                                  drivers of those that do not support it ignore this property. Use the
  333.      *                                  function support() to determine whether the DBMS driver can manage indexes.
  334.  
  335.      *                                  Example
  336.      *                                     array(
  337.      *                                         'fields' => array(
  338.      *                                             'user_name' => array(
  339.      *                                                 'sorting' => 'ascending'
  340.      *                                             ),
  341.      *                                             'last_login' => array()
  342.      *                                         )
  343.      *                                     )
  344.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  345.      * @access public
  346.      */
  347.     function createIndex($table$name$definition)
  348.     {
  349.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  350.         $query 'CREATE '.(isset($definition['unique']'UNIQUE' '')." INDEX $name ON $table (";
  351.         for ($field = 0reset($definition['fields']);
  352.             $field count($definition['fields']);
  353.             $field++next($definition['fields']))
  354.         {
  355.             if ($field > 0{
  356.                 $query .= ',';
  357.             }
  358.             $query .= key($definition['fields']);
  359.         }
  360.         $query .= ')';
  361.         return $db->query($query);
  362.     }
  363.  
  364.     // }}}
  365.     // {{{ dropIndex()
  366.  
  367.     /**
  368.      * drop existing index
  369.      *
  370.      * @param string    $table         name of table that should be used in method
  371.      * @param string    $name         name of the index to be dropped
  372.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  373.      * @access public
  374.      */
  375.     function dropIndex($table$name)
  376.     {
  377.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  378.         return $db->query("DROP INDEX $name");
  379.     }
  380.  
  381.     // }}}
  382.     // {{{ listTableIndexes()
  383.  
  384.     /**
  385.      * list all indexes in a table
  386.      *
  387.      * @param string    $table      name of table that should be used in method
  388.      * @return mixed data array on success, a MDB2 error on failure
  389.      * @access public
  390.      */
  391.     function listTableIndexes($table)
  392.     {
  393.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  394.         $query = "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='$table' AND sql NOT NULL ORDER BY name";
  395.         $indexes_all $db->queryCol($query);
  396.         if (MDB2::isError($indexes_all)) {
  397.             return $indexes_all;
  398.         }
  399.         for ($found $indexes = array()$index = 0$indexes_all_cnt count($indexes_all);
  400.             $index $indexes_all_cnt;
  401.             $index++)
  402.         {
  403.             if (!isset($found[$indexes_all[$index]]))
  404.             {
  405.                 $indexes[$indexes_all[$index];
  406.                 $found[$indexes_all[$index]] = true;
  407.             }
  408.         }
  409.         return $indexes;
  410.     }
  411.  
  412.     // }}}
  413.     // {{{ createSequence()
  414.  
  415.     /**
  416.      * create sequence
  417.      *
  418.      * @param string    $seq_name     name of the sequence to be created
  419.      * @param string    $start         start value of the sequence; default is 1
  420.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  421.      * @access public
  422.      */
  423.     function createSequence($seq_name$start = 1)
  424.     {
  425.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  426.         $sequence_name $db->getSequenceName($seq_name);
  427.         $seqname_col_name $db->options['seqname_col_name'];
  428.         $query = "CREATE TABLE $sequence_name ($seqname_col_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
  429.         $res $db->query($query);
  430.         if (MDB2::isError($res)) {
  431.             return $res;
  432.         }
  433.         if ($start == 1{
  434.             return MDB2_OK;
  435.         }
  436.         $res $db->query("INSERT INTO $sequence_name VALUES (".($start-1).')');
  437.         if (!MDB2::isError($res)) {
  438.             return MDB2_OK;
  439.         }
  440.         // Handle error
  441.         $result $db->query("DROP TABLE $sequence_name");
  442.         if (MDB2::isError($result)) {
  443.             return $db->raiseError(MDB2_ERRORnullnull,
  444.                 'createSequence: could not drop inconsistent sequence table ('.
  445.                 $result->getMessage().' ('.$result->getUserinfo().'))');
  446.         }
  447.         return $db->raiseError(MDB2_ERRORnullnull,
  448.             'createSequence: could not create sequence table ('.
  449.             $res->getMessage().' ('.$res->getUserinfo().'))');
  450.     }
  451.  
  452.     // }}}
  453.     // {{{ dropSequence()
  454.  
  455.     /**
  456.      * drop existing sequence
  457.      *
  458.      * @param string    $seq_name     name of the sequence to be dropped
  459.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  460.      * @access public
  461.      */
  462.     function dropSequence($seq_name)
  463.     {
  464.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  465.         $sequence_name $db->getSequenceName($seq_name);
  466.         return $db->query("DROP TABLE $sequence_name");
  467.     }
  468.  
  469.     // }}}
  470.     // {{{ listSequences()
  471.  
  472.     /**
  473.      * list all sequences in the current database
  474.      *
  475.      * @return mixed data array on success, a MDB2 error on failure
  476.      * @access public
  477.      */
  478.     function listSequences()
  479.     {
  480.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  481.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  482.         $table_names $db->queryCol($query);
  483.         if (MDB2::isError($table_names)) {
  484.             return $table_names;
  485.         }
  486.         for ($i = 0$j count($table_names)$sequences = array()$i $j; ++$i)
  487.         {
  488.             if ($sqn $this->_isSequenceName($table_names[$i]))
  489.                 $sequences[$sqn;
  490.         }
  491.         return $sequences;
  492.     }
  493.  
  494.     // }}}
  495. }
  496. ?>

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