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-2007 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |
  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. // | Authors: Lukas Smith <smith@pooteeweet.org>                          |
  43. // |          Lorenzo Alberton <l.alberton@quipo.it>                      |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: sqlite.php,v 1.71 2007/09/23 18:46:05 quipo Exp $
  47. //
  48.  
  49. require_once 'MDB2/Driver/Manager/Common.php';
  50.  
  51. /**
  52.  * MDB2 SQLite driver for the management modules
  53.  *
  54.  * @package MDB2
  55.  * @category Database
  56.  * @author  Lukas Smith <smith@pooteeweet.org>
  57.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  58.  */
  59. class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common
  60. {
  61.     // {{{ createDatabase()
  62.  
  63.     /**
  64.      * create a new database
  65.      *
  66.      * @param string $name name of the database that should be created
  67.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  68.      * @access public
  69.      */
  70.     function createDatabase($name)
  71.     {
  72.         $db =$this->getDBInstance();
  73.         if (PEAR::isError($db)) {
  74.             return $db;
  75.         }
  76.  
  77.         $database_file $db->_getDatabaseFile($name);
  78.         if (file_exists($database_file)) {
  79.             return $db->raiseError(MDB2_ERROR_ALREADY_EXISTSnullnull,
  80.                 'database already exists'__FUNCTION__);
  81.         }
  82.         $php_errormsg '';
  83.         $handle @sqlite_open($database_file$db->dsn['mode']$php_errormsg);
  84.         if (!$handle{
  85.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  86.                 (isset($php_errormsg$php_errormsg 'could not create the database file')__FUNCTION__);
  87.         }
  88.         @sqlite_close($handle);
  89.         return MDB2_OK;
  90.     }
  91.  
  92.     // }}}
  93.     // {{{ dropDatabase()
  94.  
  95.     /**
  96.      * drop an existing database
  97.      *
  98.      * @param string $name name of the database that should be dropped
  99.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  100.      * @access public
  101.      */
  102.     function dropDatabase($name)
  103.     {
  104.         $db =$this->getDBInstance();
  105.         if (PEAR::isError($db)) {
  106.             return $db;
  107.         }
  108.  
  109.         $database_file $db->_getDatabaseFile($name);
  110.         if (!@file_exists($database_file)) {
  111.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  112.                 'database does not exist'__FUNCTION__);
  113.         }
  114.         $result @unlink($database_file);
  115.         if (!$result{
  116.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  117.                 (isset($php_errormsg$php_errormsg 'could not remove the database file')__FUNCTION__);
  118.         }
  119.         return MDB2_OK;
  120.     }
  121.  
  122.     // }}}
  123.     // {{{ _getAdvancedFKOptions()
  124.  
  125.     /**
  126.      * Return the FOREIGN KEY query section dealing with non-standard options
  127.      * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
  128.      *
  129.      * @param array $definition 
  130.      * @return string 
  131.      * @access protected
  132.      */
  133.     function _getAdvancedFKOptions($definition)
  134.     {
  135.         $query '';
  136.         if (!empty($definition['match'])) {
  137.             $query .= ' MATCH '.$definition['match'];
  138.         }
  139.         if (!empty($definition['onupdate']&& (strtoupper($definition['onupdate']!= 'NO ACTION')) {
  140.             $query .= ' ON UPDATE '.$definition['onupdate'];
  141.         }
  142.         if (!empty($definition['ondelete']&& (strtoupper($definition['ondelete']!= 'NO ACTION')) {
  143.             $query .= ' ON DELETE '.$definition['ondelete'];
  144.         }
  145.         if (!empty($definition['deferrable'])) {
  146.             $query .= ' DEFERRABLE';
  147.         else {
  148.             $query .= ' NOT DEFERRABLE';
  149.         }
  150.         if (!empty($definition['initiallydeferred'])) {
  151.             $query .= ' INITIALLY DEFERRED';
  152.         else {
  153.             $query .= ' INITIALLY IMMEDIATE';
  154.         }
  155.         return $query;
  156.     }
  157.  
  158.     // }}}
  159.     // {{{ _getCreateTableQuery()
  160.  
  161.     /**
  162.      * Create a basic SQL query for a new table creation
  163.      * @param string $name   Name of the database that should be created
  164.      * @param array $fields  Associative array that contains the definition of each field of the new table
  165.      * @param array $options  An associative array of table options
  166.      * @return mixed string (the SQL query) on success, a MDB2 error on failure
  167.      * @see createTable()
  168.      */
  169.     function _getCreateTableQuery($name$fields$options = array())
  170.     {
  171.         $db =$this->getDBInstance();
  172.         if (PEAR::isError($db)) {
  173.             return $db;
  174.         }
  175.  
  176.         if (!$name{
  177.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  178.                 'no valid table name specified'__FUNCTION__);
  179.         }
  180.         if (empty($fields)) {
  181.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  182.                 'no fields specified for table "'.$name.'"'__FUNCTION__);
  183.         }
  184.         $query_fields $this->getFieldDeclarationList($fields);
  185.         if (PEAR::isError($query_fields)) {
  186.             return $query_fields;
  187.         }
  188.         if (!empty($options['primary'])) {
  189.             $query_fields.= ', PRIMARY KEY ('.implode(', 'array_keys($options['primary'])).')';
  190.         }
  191.         if (!empty($options['foreign_keys'])) {
  192.             foreach ($options['foreign_keys'as $fkname => $fkdef{
  193.                 if (empty($fkdef)) {
  194.                     continue;
  195.                 }
  196.                 $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', 'array_keys($fkdef['fields'])).')';
  197.                 $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', 'array_keys($fkdef['references']['fields'])).')';
  198.                 $query_fields.= $this->_getAdvancedFKOptions($fkdef);
  199.             }
  200.         }
  201.  
  202.         $name $db->quoteIdentifier($nametrue);
  203.         $result 'CREATE ';
  204.         if (!empty($options['temporary'])) {
  205.             $result .= $this->_getTemporaryTableQuery();
  206.         }
  207.         $result .= " TABLE $name ($query_fields)";
  208.         return $result;
  209.     }
  210.  
  211.     // }}}
  212.     // {{{ createTable()
  213.  
  214.     /**
  215.      * create a new table
  216.      *
  217.      * @param string $name   Name of the database that should be created
  218.      * @param array $fields  Associative array that contains the definition of each field of the new table
  219.      * @param array $options  An associative array of table options
  220.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  221.      * @access public
  222.      */
  223.     function createTable($name$fields$options = array())
  224.     {
  225.         $result = parent::createTable($name$fields$options);
  226.         if (PEAR::isError($result)) {
  227.             return $result;
  228.         }
  229.         // create triggers to enforce FOREIGN KEY constraints
  230.         if (!empty($options['foreign_keys'])) {
  231.             $db =$this->getDBInstance();
  232.             if (PEAR::isError($db)) {
  233.                 return $db;
  234.             }
  235.             foreach ($options['foreign_keys'as $fkname => $fkdef{
  236.                 if (empty($fkdef)) {
  237.                     continue;
  238.                 }
  239.                 //set actions to 'RESTRICT' if not set
  240.                 $fkdef['onupdate'= empty($fkdef['onupdate']'RESTRICT' strtoupper($fkdef['onupdate']);
  241.                 $fkdef['ondelete'= empty($fkdef['ondelete']'RESTRICT' strtoupper($fkdef['ondelete']);
  242.  
  243.                 $trigger_names = array(
  244.                     'insert'    => $fkname.'_insert_trg',
  245.                     'update'    => $fkname.'_update_trg',
  246.                     'pk_update' => $fkname.'_pk_update_trg',
  247.                     'pk_delete' => $fkname.'_pk_delete_trg',
  248.                 );
  249.                 
  250.                 //create the [insert|update] triggers on the FK table
  251.                 $table_fields array_keys($fkdef['fields']);
  252.                 $referenced_fields array_keys($fkdef['references']['fields']);
  253.                 $query 'CREATE TRIGGER %s BEFORE %s ON '.$name
  254.                         .' FOR EACH ROW BEGIN'
  255.                         .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
  256.                         .' WHERE  (SELECT ';
  257.                 $aliased_fields = array();
  258.                 foreach ($referenced_fields as $field{
  259.                     $aliased_fields[$fkdef['references']['table'.'.'.$field .' AS '.$field;
  260.                 }
  261.                 $query .= implode(','$aliased_fields)
  262.                        .' FROM '.$fkdef['references']['table']
  263.                        .' WHERE ';
  264.                 $conditions = array();
  265.                 for ($i=0; $i<count($table_fields)$i++{
  266.                     $conditions[$referenced_fields[$i.' = NEW.'.$table_fields[$i];
  267.                 }
  268.                 $query .= implode(' AND '$conditions).') IS NULL; END;';
  269.                 $result $db->exec(sprintf($query$trigger_names['insert']'INSERT''insert'));
  270.                 if (PEAR::isError($result)) {
  271.                     return $result;
  272.                 }
  273.  
  274.                 $result $db->exec(sprintf($query$trigger_names['update']'UPDATE''update'));
  275.                 if (PEAR::isError($result)) {
  276.                     return $result;
  277.                 }
  278.                 
  279.                 //create the ON [UPDATE|DELETE] triggers on the primary table
  280.                 $restrict_action 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
  281.                                   .' WHERE  (SELECT ';
  282.                 $aliased_fields = array();
  283.                 foreach ($table_fields as $field{
  284.                     $aliased_fields[$name .'.'.$field .' AS '.$field;
  285.                 }
  286.                 $restrict_action .= implode(','$aliased_fields)
  287.                        .' FROM '.$name
  288.                        .' WHERE ';
  289.                 $conditions  = array();
  290.                 $new_values  = array();
  291.                 $null_values = array();
  292.                 for ($i=0; $i<count($table_fields)$i++{
  293.                     $conditions[]  $table_fields[$i.' = OLD.'.$referenced_fields[$i];
  294.                     $new_values[]  $table_fields[$i.' = NEW.'.$referenced_fields[$i];
  295.                     $null_values[$table_fields[$i.' = NULL';
  296.                 }
  297.                 $restrict_action .= implode(' AND '$conditions).') IS NOT NULL';
  298.  
  299.                 $cascade_action_update 'UPDATE '.$name.' SET '.implode(', '$new_values.' WHERE '.implode(' AND '$conditions);
  300.                 $cascade_action_delete 'DELETE FROM '.$name.' WHERE '.implode(' AND '$conditions);
  301.                 $setnull_action        'UPDATE '.$name.' SET '.implode(', '$null_values).' WHERE '.implode(' AND '$conditions);
  302.  
  303.                 if ('SET DEFAULT' == $fkdef['onupdate'|| 'SET DEFAULT' == $fkdef['ondelete']{
  304.                     $db->loadModule('Reverse'nulltrue);
  305.                     $default_values = array();
  306.                     foreach ($table_fields as $table_field{
  307.                         $field_definition $db->reverse->getTableFieldDefinition($name$field);
  308.                         if (PEAR::isError($field_definition)) {
  309.                             return $field_definition;
  310.                         }
  311.                         $default_values[$table_field .' = '$field_definition[0]['default'];
  312.                     }
  313.                     $setdefault_action 'UPDATE '.$name.' SET '.implode(', '$default_values).' WHERE '.implode(' AND '$conditions);
  314.                 }
  315.  
  316.                 $query 'CREATE TRIGGER %s'
  317.                         .' %s ON '.$fkdef['references']['table']
  318.                         .' FOR EACH ROW BEGIN ';
  319.  
  320.                 if ('CASCADE' == $fkdef['onupdate']{
  321.                     $sql_update sprintf($query$trigger_names['pk_update']'AFTER UPDATE',  'update'$cascade_action_update'; END;';
  322.                 elseif ('SET NULL' == $fkdef['onupdate']{
  323.                     $sql_update sprintf($query$trigger_names['pk_update']'BEFORE UPDATE''update'$setnull_action'; END;';
  324.                 elseif ('SET DEFAULT' == $fkdef['onupdate']{
  325.                     $sql_update sprintf($query$trigger_names['pk_update']'BEFORE UPDATE''update'$setdefault_action'; END;';
  326.                 elseif ('NO ACTION' == $fkdef['onupdate']{
  327.                     $sql_update sprintf($query.$restrict_action$trigger_names['pk_update']'AFTER UPDATE''update''; END;';
  328.                 else {
  329.                     //'RESTRICT'
  330.                     $sql_update sprintf($query.$restrict_action$trigger_names['pk_update']'BEFORE UPDATE''update''; END;';
  331.                 }
  332.                 if ('CASCADE' == $fkdef['ondelete']{
  333.                     $sql_delete sprintf($query$trigger_names['pk_delete']'AFTER DELETE',  'delete'$cascade_action_delete'; END;';
  334.                 elseif ('SET NULL' == $fkdef['ondelete']{
  335.                     $sql_delete sprintf($query$trigger_names['pk_delete']'BEFORE DELETE''delete'$setnull_action'; END;';
  336.                 elseif ('SET DEFAULT' == $fkdef['ondelete']{
  337.                     $sql_delete sprintf($query$trigger_names['pk_delete']'BEFORE DELETE''delete'$setdefault_action'; END;';
  338.                 elseif ('NO ACTION' == $fkdef['ondelete']{
  339.                     $sql_delete sprintf($query.$restrict_action$trigger_names['pk_delete']'AFTER DELETE''delete')  '; END;';
  340.                 else {
  341.                     //'RESTRICT'
  342.                     $sql_delete sprintf($query.$restrict_action$trigger_names['pk_delete']'BEFORE DELETE''delete''; END;';
  343.                 }
  344.  
  345.                 if (PEAR::isError($result)) {
  346.                     return $result;
  347.                 }
  348.                 $result $db->exec($sql_delete);
  349.                 if (PEAR::isError($result)) {
  350.                     return $result;
  351.                 }
  352.                 $result $db->exec($sql_update);
  353.                 if (PEAR::isError($result)) {
  354.                     return $result;
  355.                 }
  356.             }
  357.         }
  358.         if (PEAR::isError($result)) {
  359.             return $result;
  360.         }
  361.         return MDB2_OK;
  362.     }
  363.  
  364.     // }}}
  365.     // {{{ dropTable()
  366.  
  367.     /**
  368.      * drop an existing table
  369.      *
  370.      * @param string $name name of the table that should be dropped
  371.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  372.      * @access public
  373.      */
  374.     function dropTable($name)
  375.     {
  376.         $db =$this->getDBInstance();
  377.         if (PEAR::isError($db)) {
  378.             return $db;
  379.         }
  380.         
  381.         //delete the triggers associated to existing FK constraints
  382.         $constraints $this->listTableConstraints($name);
  383.         if (!PEAR::isError($constraints&& !empty($constraints)) {
  384.             $db->loadModule('Reverse'nulltrue);
  385.             foreach ($constraints as $constraint{
  386.                 $definition $db->reverse->getTableConstraintDefinition($name$constraint);
  387.                 if (!PEAR::isError($definition&& !empty($definition['foreign'])) {
  388.                     $result $this->_dropFKTriggers($name$constraint$definition['references']['table']);
  389.                     if (PEAR::isError($result)) {
  390.                         return $result;
  391.                     }
  392.                 }
  393.             }
  394.         }
  395.  
  396.         $name $db->quoteIdentifier($nametrue);
  397.         return $db->exec("DROP TABLE $name");
  398.     }
  399.  
  400.     // }}}
  401.     // {{{ alterTable()
  402.  
  403.     /**
  404.      * alter an existing table
  405.      *
  406.      * @param string $name         name of the table that is intended to be changed.
  407.      * @param array $changes     associative array that contains the details of each type
  408.      *                              of change that is intended to be performed. The types of
  409.      *                              changes that are currently supported are defined as follows:
  410.      *
  411.      *                              name
  412.      *
  413.      *                                 New name for the table.
  414.      *
  415.      *                             add
  416.      *
  417.      *                                 Associative array with the names of fields to be added as
  418.      *                                  indexes of the array. The value of each entry of the array
  419.      *                                  should be set to another associative array with the properties
  420.      *                                  of the fields to be added. The properties of the fields should
  421.      *                                  be the same as defined by the MDB2 parser.
  422.      *
  423.      *
  424.      *                             remove
  425.      *
  426.      *                                 Associative array with the names of fields to be removed as indexes
  427.      *                                  of the array. Currently the values assigned to each entry are ignored.
  428.      *                                  An empty array should be used for future compatibility.
  429.      *
  430.      *                             rename
  431.      *
  432.      *                                 Associative array with the names of fields to be renamed as indexes
  433.      *                                  of the array. The value of each entry of the array should be set to
  434.      *                                  another associative array with the entry named name with the new
  435.      *                                  field name and the entry named Declaration that is expected to contain
  436.      *                                  the portion of the field declaration already in DBMS specific SQL code
  437.      *                                  as it is used in the CREATE TABLE statement.
  438.      *
  439.      *                             change
  440.      *
  441.      *                                 Associative array with the names of the fields to be changed as indexes
  442.      *                                  of the array. Keep in mind that if it is intended to change either the
  443.      *                                  name of a field and any other properties, the change array entries
  444.      *                                  should have the new names of the fields as array indexes.
  445.      *
  446.      *                                 The value of each entry of the array should be set to another associative
  447.      *                                  array with the properties of the fields to that are meant to be changed as
  448.      *                                  array entries. These entries should be assigned to the new values of the
  449.      *                                  respective properties. The properties of the fields should be the same
  450.      *                                  as defined by the MDB2 parser.
  451.      *
  452.      *                             Example
  453.      *                                 array(
  454.      *                                     'name' => 'userlist',
  455.      *                                     'add' => array(
  456.      *                                         'quota' => array(
  457.      *                                             'type' => 'integer',
  458.      *                                             'unsigned' => 1
  459.      *                                         )
  460.      *                                     ),
  461.      *                                     'remove' => array(
  462.      *                                         'file_limit' => array(),
  463.      *                                         'time_limit' => array()
  464.      *                                     ),
  465.      *                                     'change' => array(
  466.      *                                         'name' => array(
  467.      *                                             'length' => '20',
  468.      *                                             'definition' => array(
  469.      *                                                 'type' => 'text',
  470.      *                                                 'length' => 20,
  471.      *                                             ),
  472.      *                                         )
  473.      *                                     ),
  474.      *                                     'rename' => array(
  475.      *                                         'sex' => array(
  476.      *                                             'name' => 'gender',
  477.      *                                             'definition' => array(
  478.      *                                                 'type' => 'text',
  479.      *                                                 'length' => 1,
  480.      *                                                 'default' => 'M',
  481.      *                                             ),
  482.      *                                         )
  483.      *                                     )
  484.      *                                 )
  485.      *
  486.      * @param boolean $check     indicates whether the function should just check if the DBMS driver
  487.      *                              can perform the requested table alterations if the value is true or
  488.      *                              actually perform them otherwise.
  489.      * @access public
  490.      *
  491.       * @return mixed MDB2_OK on success, a MDB2 error on failure
  492.      */
  493.     function alterTable($name$changes$check$options = array())
  494.     {
  495.         $db =$this->getDBInstance();
  496.         if (PEAR::isError($db)) {
  497.             return $db;
  498.         }
  499.  
  500.         foreach ($changes as $change_name => $change{
  501.             switch ($change_name{
  502.             case 'add':
  503.             case 'remove':
  504.             case 'change':
  505.             case 'name':
  506.             case 'rename':
  507.                 break;
  508.             default:
  509.                 return $db->raiseError(MDB2_ERROR_CANNOT_ALTERnullnull,
  510.                     'change type "'.$change_name.'" not yet supported'__FUNCTION__);
  511.             }
  512.         }
  513.  
  514.         if ($check{
  515.             return MDB2_OK;
  516.         }
  517.  
  518.         $db->loadModule('Reverse'nulltrue);
  519.  
  520.         // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it
  521.         $fields $db->manager->listTableFields($name);
  522.         if (PEAR::isError($fields)) {
  523.             return $fields;
  524.         }
  525.  
  526.         $fields array_flip($fields);
  527.         foreach ($fields as $field => $value{
  528.             $definition $db->reverse->getTableFieldDefinition($name$field);
  529.             if (PEAR::isError($definition)) {
  530.                 return $definition;
  531.             }
  532.             $fields[$field$definition[0];
  533.         }
  534.  
  535.         $indexes $db->manager->listTableIndexes($name);
  536.         if (PEAR::isError($indexes)) {
  537.             return $indexes;
  538.         }
  539.  
  540.         $indexes array_flip($indexes);
  541.         foreach ($indexes as $index => $value{
  542.             $definition $db->reverse->getTableIndexDefinition($name$index);
  543.             if (PEAR::isError($definition)) {
  544.                 return $definition;
  545.             }
  546.             $indexes[$index$definition;
  547.         }
  548.  
  549.         $constraints $db->manager->listTableConstraints($name);
  550.         if (PEAR::isError($constraints)) {
  551.             return $constraints;
  552.         }
  553.  
  554.         if (!array_key_exists('foreign_keys'$options)) {
  555.             $options['foreign_keys'= array();
  556.         }
  557.         $constraints array_flip($constraints);
  558.         foreach ($constraints as $constraint => $value{
  559.             if (!empty($definition['primary'])) {
  560.                 if (!array_key_exists('primary'$options)) {
  561.                     $options['primary'$definition['fields'];
  562.                     //remove from the $constraint array, it's already handled by createTable()
  563.                     unset($constraints[$constraint]);
  564.                 }
  565.             else {
  566.                 $c_definition $db->reverse->getTableConstraintDefinition($name$constraint);
  567.                 if (PEAR::isError($c_definition)) {
  568.                     return $c_definition;
  569.                 }
  570.                 if (!empty($c_definition['foreign'])) {
  571.                     if (!array_key_exists($constraint$options['foreign_keys'])) {
  572.                         $options['foreign_keys'][$constraint$c_definition;
  573.                     }
  574.                     //remove from the $constraint array, it's already handled by createTable()
  575.                     unset($constraints[$constraint]);
  576.                 else {
  577.                     $constraints[$constraint$c_definition;
  578.                 }
  579.             }
  580.         }
  581.  
  582.         $name_new $name;
  583.         $create_order $select_fields array_keys($fields);
  584.         foreach ($changes as $change_name => $change{
  585.             switch ($change_name{
  586.             case 'add':
  587.                 foreach ($change as $field_name => $field{
  588.                     $fields[$field_name$field;
  589.                     $create_order[$field_name;
  590.                 }
  591.                 break;
  592.             case 'remove':
  593.                 foreach ($change as $field_name => $field{
  594.                     unset($fields[$field_name]);
  595.                     $select_fields array_diff($select_fieldsarray($field_name));
  596.                     $create_order array_diff($create_orderarray($field_name));
  597.                 }
  598.                 break;
  599.             case 'change':
  600.                 foreach ($change as $field_name => $field{
  601.                     $fields[$field_name$field['definition'];
  602.                 }
  603.                 break;
  604.             case 'name':
  605.                 $name_new $change;
  606.                 break;
  607.             case 'rename':
  608.                 foreach ($change as $field_name => $field{
  609.                     unset($fields[$field_name]);
  610.                     $fields[$field['name']] $field['definition'];
  611.                     $create_order[array_search($field_name$create_order)$field['name'];
  612.                 }
  613.                 break;
  614.             default:
  615.                 return $db->raiseError(MDB2_ERROR_CANNOT_ALTERnullnull,
  616.                     'change type "'.$change_name.'" not yet supported'__FUNCTION__);
  617.             }
  618.         }
  619.  
  620.         $data = null;
  621.         if (!empty($select_fields)) {
  622.             $query 'SELECT '.implode(', '$select_fields).' FROM '.$db->quoteIdentifier($nametrue);
  623.             $data $db->queryAll($querynullMDB2_FETCHMODE_ORDERED);
  624.         }
  625.  
  626.         $result $this->dropTable($name);
  627.         if (PEAR::isError($result)) {
  628.             return $result;
  629.         }
  630.  
  631.         $result $this->createTable($name_new$fields$options);
  632.         if (PEAR::isError($result)) {
  633.             return $result;
  634.         }
  635.  
  636.         foreach ($indexes as $index => $definition{
  637.             $this->createIndex($name_new$index$definition);
  638.         }
  639.  
  640.         foreach ($constraints as $constraint => $definition{
  641.             $this->createConstraint($name_new$constraint$definition);
  642.         }
  643.  
  644.         if (!empty($select_fields&& !empty($data)) {
  645.             $query 'INSERT INTO '.$db->quoteIdentifier($name_newtrue);
  646.             $query.= '('.implode(', 'array_slice(array_keys($fields)0count($select_fields))).')';
  647.             $query.=' VALUES (?'.str_repeat(', ?'(count($select_fields- 1)).')';
  648.             $stmt =$db->prepare($querynullMDB2_PREPARE_MANIP);
  649.             if (PEAR::isError($stmt)) {
  650.                 return $stmt;
  651.             }
  652.             foreach ($data as $row{
  653.                 $result $stmt->execute($row);
  654.                 if (PEAR::isError($result)) {
  655.                     return $result;
  656.                 }
  657.             }
  658.         }
  659.         return MDB2_OK;
  660.     }
  661.  
  662.     // }}}
  663.     // {{{ listDatabases()
  664.  
  665.     /**
  666.      * list all databases
  667.      *
  668.      * @return mixed array of database names on success, a MDB2 error on failure
  669.      * @access public
  670.      */
  671.     function listDatabases()
  672.     {
  673.         $db =$this->getDBInstance();
  674.         if (PEAR::isError($db)) {
  675.             return $db;
  676.         }
  677.  
  678.         return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  679.             'list databases is not supported'__FUNCTION__);
  680.     }
  681.  
  682.     // }}}
  683.     // {{{ listUsers()
  684.  
  685.     /**
  686.      * list all users
  687.      *
  688.      * @return mixed array of user names on success, a MDB2 error on failure
  689.      * @access public
  690.      */
  691.     function listUsers()
  692.     {
  693.         $db =$this->getDBInstance();
  694.         if (PEAR::isError($db)) {
  695.             return $db;
  696.         }
  697.  
  698.         return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  699.             'list databases is not supported'__FUNCTION__);
  700.     }
  701.  
  702.     // }}}
  703.     // {{{ listViews()
  704.  
  705.     /**
  706.      * list all views in the current database
  707.      *
  708.      * @return mixed array of view names on success, a MDB2 error on failure
  709.      * @access public
  710.      */
  711.     function listViews()
  712.     {
  713.         $db =$this->getDBInstance();
  714.         if (PEAR::isError($db)) {
  715.             return $db;
  716.         }
  717.  
  718.         $query "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  719.         $result $db->queryCol($query);
  720.         if (PEAR::isError($result)) {
  721.             return $result;
  722.         }
  723.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  724.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  725.         }
  726.         return $result;
  727.     }
  728.  
  729.     // }}}
  730.     // {{{ listTableViews()
  731.  
  732.     /**
  733.      * list the views in the database that reference a given table
  734.      *
  735.      * @param string table for which all referenced views should be found
  736.      * @return mixed array of view names on success, a MDB2 error on failure
  737.      * @access public
  738.      */
  739.     function listTableViews($table)
  740.     {
  741.         $db =$this->getDBInstance();
  742.         if (PEAR::isError($db)) {
  743.             return $db;
  744.         }
  745.  
  746.         $query "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  747.         $views $db->queryAll($queryarray('text''text')MDB2_FETCHMODE_ASSOC);
  748.         if (PEAR::isError($views)) {
  749.             return $views;
  750.         }
  751.         $result = array();
  752.         foreach ($views as $row{
  753.             if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i"$row['sql'])) {
  754.                 if (!empty($row['name'])) {
  755.                     $result[$row['name']] = true;
  756.                 }
  757.             }
  758.         }
  759.  
  760.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  761.             $result array_change_key_case($result$db->options['field_case']);
  762.         }
  763.         return array_keys($result);
  764.     }
  765.  
  766.     // }}}
  767.     // {{{ listTables()
  768.  
  769.     /**
  770.      * list all tables in the current database
  771.      *
  772.      * @return mixed array of table names on success, a MDB2 error on failure
  773.      * @access public
  774.      */
  775.     function listTables()
  776.     {
  777.         $db =$this->getDBInstance();
  778.         if (PEAR::isError($db)) {
  779.             return $db;
  780.         }
  781.  
  782.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  783.         $table_names $db->queryCol($query);
  784.         if (PEAR::isError($table_names)) {
  785.             return $table_names;
  786.         }
  787.         $result = array();
  788.         foreach ($table_names as $table_name{
  789.             if (!$this->_fixSequenceName($table_nametrue)) {
  790.                 $result[$table_name;
  791.             }
  792.         }
  793.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  794.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  795.         }
  796.         return $result;
  797.     }
  798.  
  799.     // }}}
  800.     // {{{ listTableFields()
  801.  
  802.     /**
  803.      * list all fields in a table in the current database
  804.      *
  805.      * @param string $table name of table that should be used in method
  806.      * @return mixed array of field names on success, a MDB2 error on failure
  807.      * @access public
  808.      */
  809.     function listTableFields($table)
  810.     {
  811.         $db =$this->getDBInstance();
  812.         if (PEAR::isError($db)) {
  813.             return $db;
  814.         }
  815.  
  816.         $result $db->loadModule('Reverse'nulltrue);
  817.         if (PEAR::isError($result)) {
  818.             return $result;
  819.         }
  820.         $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  821.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  822.             $query.= 'LOWER(name)='.$db->quote(strtolower($table)'text');
  823.         else {
  824.             $query.= 'name='.$db->quote($table'text');
  825.         }
  826.         $sql $db->queryOne($query);
  827.         if (PEAR::isError($sql)) {
  828.             return $sql;
  829.         }
  830.         $columns $db->reverse->_getTableColumns($sql);
  831.         $fields = array();
  832.         foreach ($columns as $column{
  833.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  834.                 if ($db->options['field_case'== CASE_LOWER{
  835.                     $column['name'strtolower($column['name']);
  836.                 else {
  837.                     $column['name'strtoupper($column['name']);
  838.                 }
  839.             else {
  840.                 $column array_change_key_case($column$db->options['field_case']);
  841.             }
  842.             $fields[$column['name'];
  843.         }
  844.         return $fields;
  845.     }
  846.  
  847.     // }}}
  848.     // {{{ listTableTriggers()
  849.  
  850.     /**
  851.      * list all triggers in the database that reference a given table
  852.      *
  853.      * @param string table for which all referenced triggers should be found
  854.      * @return mixed array of trigger names on success, a MDB2 error on failure
  855.      * @access public
  856.      */
  857.     function listTableTriggers($table = null)
  858.     {
  859.         $db =$this->getDBInstance();
  860.         if (PEAR::isError($db)) {
  861.             return $db;
  862.         }
  863.  
  864.         $query "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";
  865.         if (!is_null($table)) {
  866.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  867.                 $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table)'text');
  868.             else {
  869.                 $query.= ' AND tbl_name='.$db->quote($table'text');
  870.             }
  871.         }
  872.         $result $db->queryCol($query);
  873.         if (PEAR::isError($result)) {
  874.             return $result;
  875.         }
  876.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  877.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  878.         }
  879.         return $result;
  880.     }
  881.  
  882.     // }}}
  883.     // {{{ createIndex()
  884.  
  885.     /**
  886.      * Get the stucture of a field into an array
  887.      *
  888.      * @param string    $table         name of the table on which the index is to be created
  889.      * @param string    $name         name of the index to be created
  890.      * @param array     $definition        associative array that defines properties of the index to be created.
  891.      *                                  Currently, only one property named FIELDS is supported. This property
  892.      *                                  is also an associative with the names of the index fields as array
  893.      *                                  indexes. Each entry of this array is set to another type of associative
  894.      *                                  array that specifies properties of the index that are specific to
  895.      *                                  each field.
  896.      *
  897.      *                                 Currently, only the sorting property is supported. It should be used
  898.      *                                  to define the sorting direction of the index. It may be set to either
  899.      *                                  ascending or descending.
  900.      *
  901.      *                                 Not all DBMS support index sorting direction configuration. The DBMS
  902.      *                                  drivers of those that do not support it ignore this property. Use the
  903.      *                                  function support() to determine whether the DBMS driver can manage indexes.
  904.  
  905.      *                                  Example
  906.      *                                     array(
  907.      *                                         'fields' => array(
  908.      *                                             'user_name' => array(
  909.      *                                                 'sorting' => 'ascending'
  910.      *                                             ),
  911.      *                                             'last_login' => array()
  912.      *                                         )
  913.      *                                     )
  914.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  915.      * @access public
  916.      */
  917.     function createIndex($table$name$definition)
  918.     {
  919.         $db =$this->getDBInstance();
  920.         if (PEAR::isError($db)) {
  921.             return $db;
  922.         }
  923.  
  924.         $table $db->quoteIdentifier($tabletrue);
  925.         $name  $db->getIndexName($name);
  926.         $query = "CREATE INDEX $name ON $table";
  927.         $fields = array();
  928.         foreach ($definition['fields'as $field_name => $field{
  929.             $field_string $field_name;
  930.             if (!empty($field['sorting'])) {
  931.                 switch ($field['sorting']{
  932.                 case 'ascending':
  933.                     $field_string.= ' ASC';
  934.                     break;
  935.                 case 'descending':
  936.                     $field_string.= ' DESC';
  937.                     break;
  938.                 }
  939.             }
  940.             $fields[$field_string;
  941.         }
  942.         $query .= ' ('.implode(', '$fields')';
  943.         return $db->exec($query);
  944.     }
  945.  
  946.     // }}}
  947.     // {{{ dropIndex()
  948.  
  949.     /**
  950.      * drop existing index
  951.      *
  952.      * @param string    $table         name of table that should be used in method
  953.      * @param string    $name         name of the index to be dropped
  954.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  955.      * @access public
  956.      */
  957.     function dropIndex($table$name)
  958.     {
  959.         $db =$this->getDBInstance();
  960.         if (PEAR::isError($db)) {
  961.             return $db;
  962.         }
  963.  
  964.         $name $db->getIndexName($name);
  965.         return $db->exec("DROP INDEX $name");
  966.     }
  967.  
  968.     // }}}
  969.     // {{{ listTableIndexes()
  970.  
  971.     /**
  972.      * list all indexes in a table
  973.      *
  974.      * @param string $table name of table that should be used in method
  975.      * @return mixed array of index names on success, a MDB2 error on failure
  976.      * @access public
  977.      */
  978.     function listTableIndexes($table)
  979.     {
  980.         $db =$this->getDBInstance();
  981.         if (PEAR::isError($db)) {
  982.             return $db;
  983.         }
  984.  
  985.         $table $db->quote($table'text');
  986.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  987.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  988.             $query.= 'LOWER(tbl_name)='.strtolower($table);
  989.         else {
  990.             $query.= "tbl_name=$table";
  991.         }
  992.         $query.= " AND sql NOT NULL ORDER BY name";
  993.         $indexes $db->queryCol($query'text');
  994.         if (PEAR::isError($indexes)) {
  995.             return $indexes;
  996.         }
  997.  
  998.         $result = array();
  999.         foreach ($indexes as $sql{
  1000.             if (preg_match("/^create index ([^ ]+) on /i"$sql$tmp)) {
  1001.                 $index $this->_fixIndexName($tmp[1]);
  1002.                 if (!empty($index)) {
  1003.                     $result[$index= true;
  1004.                 }
  1005.             }
  1006.         }
  1007.  
  1008.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1009.             $result array_change_key_case($result$db->options['field_case']);
  1010.         }
  1011.         return array_keys($result);
  1012.     }
  1013.  
  1014.     // }}}
  1015.     // {{{ createConstraint()
  1016.  
  1017.     /**
  1018.      * create a constraint on a table
  1019.      *
  1020.      * @param string $table      name of the table on which the constraint is to be created
  1021.      * @param string $name       name of the constraint to be created
  1022.      * @param array  $definition associative array that defines properties of the constraint to be created.
  1023.      *                            Currently, only one property named FIELDS is supported. This property
  1024.      *                            is also an associative with the names of the constraint fields as array
  1025.      *                            constraints. Each entry of this array is set to another type of associative
  1026.      *                            array that specifies properties of the constraint that are specific to
  1027.      *                            each field.
  1028.      *
  1029.      *                            Example
  1030.      *                               array(
  1031.      *                                   'fields' => array(
  1032.      *                                       'user_name' => array(),
  1033.      *                                       'last_login' => array()
  1034.      *                                   )
  1035.      *                               )
  1036.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1037.      * @access public
  1038.      */
  1039.     function createConstraint($table$name$definition)
  1040.     {
  1041.         $db =$this->getDBInstance();
  1042.         if (PEAR::isError($db)) {
  1043.             return $db;
  1044.         }
  1045.  
  1046.         if (!empty($definition['primary'])) {
  1047.             return $db->manager->alterTable($tablearray()falsearray('primary' => $definition['fields']));
  1048.         }
  1049.         
  1050.         if (!empty($definition['foreign'])) {
  1051.             return $db->manager->alterTable($tablearray()falsearray('foreign_keys' => array($name => $definition)));
  1052.         }
  1053.  
  1054.         $table $db->quoteIdentifier($tabletrue);
  1055.         $name  $db->getIndexName($name);
  1056.         $query = "CREATE UNIQUE INDEX $name ON $table";
  1057.         $fields = array();
  1058.         foreach ($definition['fields'as $field_name => $field{
  1059.             $field_string $field_name;
  1060.             if (!empty($field['sorting'])) {
  1061.                 switch ($field['sorting']{
  1062.                 case 'ascending':
  1063.                     $field_string.= ' ASC';
  1064.                     break;
  1065.                 case 'descending':
  1066.                     $field_string.= ' DESC';
  1067.                     break;
  1068.                 }
  1069.             }
  1070.             $fields[$field_string;
  1071.         }
  1072.         $query .= ' ('.implode(', '$fields')';
  1073.         return $db->exec($query);
  1074.     }
  1075.  
  1076.     // }}}
  1077.     // {{{ dropConstraint()
  1078.  
  1079.     /**
  1080.      * drop existing constraint
  1081.      *
  1082.      * @param string    $table        name of table that should be used in method
  1083.      * @param string    $name         name of the constraint to be dropped
  1084.      * @param string    $primary      hint if the constraint is primary
  1085.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1086.      * @access public
  1087.      */
  1088.     function dropConstraint($table$name$primary = false)
  1089.     {
  1090.         if ($primary || $name == 'PRIMARY'{
  1091.             return $this->alterTable($tablearray()falsearray('primary' => null));
  1092.         }
  1093.  
  1094.         $db =$this->getDBInstance();
  1095.         if (PEAR::isError($db)) {
  1096.             return $db;
  1097.         }
  1098.  
  1099.         //is it a FK constraint? If so, also delete the associated triggers
  1100.         $db->loadModule('Reverse'nulltrue);
  1101.         $definition $db->reverse->getTableConstraintDefinition($table$name);
  1102.         if (!PEAR::isError($definition&& !empty($definition['foreign'])) {
  1103.             //first drop the FK enforcing triggers
  1104.             $result $this->_dropFKTriggers($table$name$definition['references']['table']);
  1105.             if (PEAR::isError($result)) {
  1106.                 return $result;
  1107.             }
  1108.             //then drop the constraint itself
  1109.             return $this->alterTable($tablearray()falsearray('foreign_keys' => array($name => null)));
  1110.         }
  1111.  
  1112.         $name $db->getIndexName($name);
  1113.         return $db->exec("DROP INDEX $name");
  1114.     }
  1115.  
  1116.     // }}}
  1117.     // {{{ _dropFKTriggers()
  1118.     
  1119.     /**
  1120.      * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
  1121.      *
  1122.      * @param string $table  table name
  1123.      * @param string $fkname FOREIGN KEY constraint name
  1124.      * @param string $referenced_table  referenced table name
  1125.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1126.      * @access private
  1127.      */
  1128.     function _dropFKTriggers($table$fkname$referenced_table)
  1129.     {
  1130.         $db =$this->getDBInstance();
  1131.         if (PEAR::isError($db)) {
  1132.             return $db;
  1133.         }
  1134.  
  1135.         $triggers  $this->listTableTriggers($table);
  1136.         $triggers2 $this->listTableTriggers($referenced_table);
  1137.         if (!PEAR::isError($triggers2&& !PEAR::isError($triggers)) {
  1138.             $triggers array_merge($triggers$triggers2);
  1139.             $pattern '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
  1140.             foreach ($triggers as $trigger{
  1141.                 if (preg_match($pattern$trigger)) {
  1142.                     $result $db->exec('DROP TRIGGER '.$trigger);
  1143.                     if (PEAR::isError($result)) {
  1144.                         return $result;
  1145.                     }
  1146.                 }
  1147.             }
  1148.         }
  1149.         return MDB2_OK;
  1150.     }
  1151.  
  1152.     // }]]
  1153.     // {{{ listTableConstraints()
  1154.  
  1155.     /**
  1156.      * list all constraints in a table
  1157.      *
  1158.      * @param string $table name of table that should be used in method
  1159.      * @return mixed array of constraint names on success, a MDB2 error on failure
  1160.      * @access public
  1161.      */
  1162.     function listTableConstraints($table)
  1163.     {
  1164.         $db =$this->getDBInstance();
  1165.         if (PEAR::isError($db)) {
  1166.             return $db;
  1167.         }
  1168.  
  1169.         $table $db->quote($table'text');
  1170.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  1171.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1172.             $query.= 'LOWER(tbl_name)='.strtolower($table);
  1173.         else {
  1174.             $query.= "tbl_name=$table";
  1175.         }
  1176.         $query.= " AND sql NOT NULL ORDER BY name";
  1177.         $indexes $db->queryCol($query'text');
  1178.         if (PEAR::isError($indexes)) {
  1179.             return $indexes;
  1180.         }
  1181.  
  1182.         $result = array();
  1183.         foreach ($indexes as $sql{
  1184.             if (preg_match("/^create unique index ([^ ]+) on /i"$sql$tmp)) {
  1185.                 $index $this->_fixIndexName($tmp[1]);
  1186.                 if (!empty($index)) {
  1187.                     $result[$index= true;
  1188.                 }
  1189.             }
  1190.         }
  1191.         
  1192.         // also search in table definition for PRIMARY KEYs...
  1193.         $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  1194.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1195.             $query.= 'LOWER(name)='.strtolower($table);
  1196.         else {
  1197.             $query.= "name=$table";
  1198.         }
  1199.         $query.= " AND sql NOT NULL ORDER BY name";
  1200.         $table_def $db->queryOne($query'text');
  1201.         if (PEAR::isError($table_def)) {
  1202.             return $table_def;
  1203.         }
  1204.         if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i"$table_def$tmp)) {
  1205.             $result['primary'= true;
  1206.         }
  1207.  
  1208.         // ...and for FOREIGN KEYs
  1209.         if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx"$table_def$tmp)) {
  1210.             foreach ($tmp[1as $fk{
  1211.                 $result[$fk= true;
  1212.             }
  1213.         }
  1214.  
  1215.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1216.             $result array_change_key_case($result$db->options['field_case']);
  1217.         }
  1218.         return array_keys($result);
  1219.     }
  1220.  
  1221.     // }}}
  1222.     // {{{ createSequence()
  1223.  
  1224.     /**
  1225.      * create sequence
  1226.      *
  1227.      * @param string    $seq_name     name of the sequence to be created
  1228.      * @param string    $start         start value of the sequence; default is 1
  1229.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1230.      * @access public
  1231.      */
  1232.     function createSequence($seq_name$start = 1)
  1233.     {
  1234.         $db =$this->getDBInstance();
  1235.         if (PEAR::isError($db)) {
  1236.             return $db;
  1237.         }
  1238.  
  1239.         $sequence_name $db->quoteIdentifier($db->getSequenceName($seq_name)true);
  1240.         $seqcol_name $db->quoteIdentifier($db->options['seqcol_name']true);
  1241.         $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
  1242.         $res $db->exec($query);
  1243.         if (PEAR::isError($res)) {
  1244.             return $res;
  1245.         }
  1246.         if ($start == 1{
  1247.             return MDB2_OK;
  1248.         }
  1249.         $res $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');
  1250.         if (!PEAR::isError($res)) {
  1251.             return MDB2_OK;
  1252.         }
  1253.         // Handle error
  1254.         $result $db->exec("DROP TABLE $sequence_name");
  1255.         if (PEAR::isError($result)) {
  1256.             return $db->raiseError($resultnullnull,
  1257.                 'could not drop inconsistent sequence table'__FUNCTION__);
  1258.         }
  1259.         return $db->raiseError($resnullnull,
  1260.             'could not create sequence table'__FUNCTION__);
  1261.     }
  1262.  
  1263.     // }}}
  1264.     // {{{ dropSequence()
  1265.  
  1266.     /**
  1267.      * drop existing sequence
  1268.      *
  1269.      * @param string    $seq_name     name of the sequence to be dropped
  1270.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1271.      * @access public
  1272.      */
  1273.     function dropSequence($seq_name)
  1274.     {
  1275.         $db =$this->getDBInstance();
  1276.         if (PEAR::isError($db)) {
  1277.             return $db;
  1278.         }
  1279.  
  1280.         $sequence_name $db->quoteIdentifier($db->getSequenceName($seq_name)true);
  1281.         return $db->exec("DROP TABLE $sequence_name");
  1282.     }
  1283.  
  1284.     // }}}
  1285.     // {{{ listSequences()
  1286.  
  1287.     /**
  1288.      * list all sequences in the current database
  1289.      *
  1290.      * @return mixed array of sequence names on success, a MDB2 error on failure
  1291.      * @access public
  1292.      */
  1293.     function listSequences()
  1294.     {
  1295.         $db =$this->getDBInstance();
  1296.         if (PEAR::isError($db)) {
  1297.             return $db;
  1298.         }
  1299.  
  1300.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  1301.         $table_names $db->queryCol($query);
  1302.         if (PEAR::isError($table_names)) {
  1303.             return $table_names;
  1304.         }
  1305.         $result = array();
  1306.         foreach ($table_names as $table_name{
  1307.             if ($sqn $this->_fixSequenceName($table_nametrue)) {
  1308.                 $result[$sqn;
  1309.             }
  1310.         }
  1311.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1312.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  1313.         }
  1314.         return $result;
  1315.     }
  1316.  
  1317.     // }}}
  1318. }
  1319. ?>

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