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

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