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

Source for file Schema.php

Documentation is available at Schema.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5                                                 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith                                         |
  7. // | All rights reserved.                                                 |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  10. // | API as well as database abstraction for PHP applications.            |
  11. // | This LICENSE is in the BSD license style.                            |
  12. // |                                                                      |
  13. // | Redistribution and use in source and binary forms, with or without   |
  14. // | modification, are permitted provided that the following conditions   |
  15. // | are met:                                                             |
  16. // |                                                                      |
  17. // | Redistributions of source code must retain the above copyright       |
  18. // | notice, this list of conditions and the following disclaimer.        |
  19. // |                                                                      |
  20. // | Redistributions in binary form must reproduce the above copyright    |
  21. // | notice, this list of conditions and the following disclaimer in the  |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // |                                                                      |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission.                                                  |
  28. // |                                                                      |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  40. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  41. // +----------------------------------------------------------------------+
  42. // | Author: Lukas Smith <smith@pooteeweet.org>                           |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: Schema.php,v 1.79 2006/07/22 08:37:56 lsmith Exp $
  46. //
  47.  
  48. require_once 'MDB2.php';
  49.  
  50. define('MDB2_SCHEMA_DUMP_ALL',          0);
  51. define('MDB2_SCHEMA_DUMP_STRUCTURE',    1);
  52. define('MDB2_SCHEMA_DUMP_CONTENT',      2);
  53.  
  54. /**
  55.  * The method mapErrorCode in each MDB2_Schema_dbtype implementation maps
  56.  * native error codes to one of these.
  57.  *
  58.  * If you add an error code here, make sure you also add a textual
  59.  * version of it in MDB2_Schema::errorMessage().
  60.  */
  61.  
  62. define('MDB2_SCHEMA_ERROR',              -1);
  63. define('MDB2_SCHEMA_ERROR_PARSE',        -2);
  64. define('MDB2_SCHEMA_ERROR_NOT_CAPABLE',  -3);
  65. define('MDB2_SCHEMA_ERROR_UNSUPPORTED',  -4);    // Driver does not support this function
  66. define('MDB2_SCHEMA_ERROR_INVALID',      -5);    // Invalid attribute value
  67. define('MDB2_SCHEMA_ERROR_NODBSELECTED'-6);
  68.  
  69. /**
  70.  * The database manager is a class that provides a set of database
  71.  * management services like installing, altering and dumping the data
  72.  * structures of databases.
  73.  *
  74.  * @package MDB2_Schema
  75.  * @category Database
  76.  * @author  Lukas Smith <smith@pooteeweet.org>
  77.  */
  78. class MDB2_Schema extends PEAR
  79. {
  80.     // {{{ properties
  81.  
  82.     var $db;
  83.  
  84.     var $warnings = array();
  85.  
  86.     var $options = array(
  87.         'fail_on_invalid_names' => true,
  88.         'dtd_file' => false,
  89.         'valid_types' => array(),
  90.         'force_defaults' => true,
  91.         'parser' => 'MDB2_Schema_Parser',
  92.         'writer' => 'MDB2_Schema_Writer',
  93.     );
  94.  
  95.     // }}}
  96.     // {{{ apiVersion()
  97.  
  98.     /**
  99.      * Return the MDB2 API version
  100.      *
  101.      * @return string  the MDB2 API version number
  102.      * @access public
  103.      */
  104.     function apiVersion()
  105.     {
  106.         return '0.4.3';
  107.     }
  108.  
  109.     /**
  110.      * Clobbers two arrays together.
  111.      *
  112.      * @param  array        array that should be clobbered
  113.      * @param  array        array that should be clobbered
  114.      * @return array|false array on success and false on error
  115.      *
  116.      * @access public
  117.      * @author kc@hireability.com
  118.      */
  119.     function arrayMergeClobber($a1$a2)
  120.     {
  121.         if (!is_array($a1|| !is_array($a2)) {
  122.             return false;
  123.         }
  124.         foreach ($a2 as $key => $val{
  125.             if (is_array($val&& array_key_exists($key$a1&& is_array($a1[$key])) {
  126.                 $a1[$keyMDB2_Schema::arrayMergeClobber($a1[$key]$val);
  127.             else {
  128.                 $a1[$key$val;
  129.             }
  130.         }
  131.         return $a1;
  132.     }
  133.  
  134.     // }}}
  135.     // {{{ resetWarnings()
  136.  
  137.     /**
  138.      * reset the warning array
  139.      *
  140.      * @access public
  141.      */
  142.     function resetWarnings()
  143.     {
  144.         $this->warnings = array();
  145.     }
  146.  
  147.     // }}}
  148.     // {{{ getWarnings()
  149.  
  150.     /**
  151.      * Get all warnings in reverse order.
  152.      *
  153.      * This means that the last warning is the first element in the array
  154.      *
  155.      * @return array with warnings
  156.      * @access public
  157.      * @see resetWarnings()
  158.      */
  159.     function getWarnings()
  160.     {
  161.         return array_reverse($this->warnings);
  162.     }
  163.  
  164.     // }}}
  165.     // {{{ setOption()
  166.  
  167.     /**
  168.      * set the option for the db class
  169.      *
  170.      * @param string option name
  171.      * @param mixed value for the option
  172.      * @return bool|MDB2_ErrorMDB2_OK or error object
  173.      * @access public
  174.      */
  175.     function setOption($option$value)
  176.     {
  177.         if (isset($this->options[$option])) {
  178.             if (is_null($value)) {
  179.                 return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  180.                     'may not set an option to value null');
  181.             }
  182.             $this->options[$option$value;
  183.             return MDB2_OK;
  184.         }
  185.         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  186.             "unknown option $option");
  187.     }
  188.  
  189.     // }}}
  190.     // {{{ getOption()
  191.  
  192.     /**
  193.      * returns the value of an option
  194.      *
  195.      * @param string option name
  196.      * @return mixed the option value or error object
  197.      * @access public
  198.      */
  199.     function getOption($option)
  200.     {
  201.         if (isset($this->options[$option])) {
  202.             return $this->options[$option];
  203.         }
  204.         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED,
  205.             nullnull"unknown option $option");
  206.     }
  207.  
  208.     // }}}
  209.     // {{{ factory()
  210.  
  211.     /**
  212.      * Create a new MDB2 object for the specified database type
  213.      * type
  214.      *
  215.      * @param string|array|MDB2_Driver_Common  'data source name', see the
  216.      *              @see MDB2::parseDSN method for a description of the dsn format.
  217.      *               Can also be specified as an array of the
  218.      *               format returned by @see MDB2::parseDSN.
  219.      *               Finally you can also pass an existing db object to be used.
  220.      * @param array An associative array of option names and their values.
  221.      * @return bool|MDB2_ErrorMDB2_OK or error object
  222.      * @access public
  223.      * @see     MDB2::parseDSN
  224.      */
  225.     function &factory(&$db$options = array())
  226.     {
  227.         $obj =new MDB2_Schema();
  228.         $err $obj->connect($db$options);
  229.         if (PEAR::isError($err)) {
  230.             return $err;
  231.         }
  232.         return $obj;
  233.     }
  234.  
  235.     // }}}
  236.     // {{{ connect()
  237.  
  238.     /**
  239.      * Create a new MDB2 connection object and connect to the specified
  240.      * database
  241.      *
  242.      * @param string|array|MDB2_Driver_Common  'data source name', see the
  243.      *              @see MDB2::parseDSN method for a description of the dsn format.
  244.      *               Can also be specified as an array of the
  245.      *               format returned by @see MDB2::parseDSN.
  246.      *               Finally you can also pass an existing db object to be used.
  247.      * @param array An associative array of option names and their values.
  248.      * @return bool|MDB2_ErrorMDB2_OK or error object
  249.      * @access public
  250.      * @see    MDB2::parseDSN
  251.      */
  252.     function connect(&$db$options = array())
  253.     {
  254.         $db_options = array();
  255.         if (is_array($options)) {
  256.             foreach ($options as $option => $value{
  257.                 if (array_key_exists($option$this->options)) {
  258.                     $err $this->setOption($option$value);
  259.                     if (PEAR::isError($err)) {
  260.                         return $err;
  261.                     }
  262.                 else {
  263.                     $db_options[$option$value;
  264.                 }
  265.             }
  266.         }
  267.         $this->disconnect();
  268.         if (!MDB2::isConnection($db)) {
  269.             $db =MDB2::factory($db$db_options);
  270.         }
  271.         if (PEAR::isError($db)) {
  272.             return $db;
  273.         }
  274.  
  275.         $this->db =$db;
  276.         $this->db->loadModule('Datatype');
  277.         $this->db->loadModule('Manager');
  278.         $this->db->loadModule('Reverse');
  279.         $this->db->loadModule('Function');
  280.         if (empty($this->options['valid_types'])) {
  281.             $this->options['valid_types'$this->db->datatype->getValidTypes();
  282.         }
  283.  
  284.         return MDB2_OK;
  285.     }
  286.  
  287.     // }}}
  288.     // {{{ disconnect()
  289.  
  290.     /**
  291.      * Log out and disconnect from the database.
  292.      *
  293.      * @access public
  294.      */
  295.     function disconnect()
  296.     {
  297.         if (MDB2::isConnection($this->db)) {
  298.             $this->db->disconnect();
  299.             unset($this->db);
  300.         }
  301.     }
  302.  
  303.     // }}}
  304.     // {{{ parseDatabaseDefinition()
  305.  
  306.     /**
  307.      * Parse a database definition from a file or an array
  308.      *
  309.      * @param string|arraythe database schema array or file name
  310.      * @param bool if non readable files should be skipped
  311.      * @param array associative array that the defines the text string values
  312.      *               that are meant to be used to replace the variables that are
  313.      *               used in the schema description.
  314.      * @param bool make function fail on invalid names
  315.      * @param array database structure definition
  316.      * @access public
  317.      */
  318.     function parseDatabaseDefinition($schema$skip_unreadable = false$variables = array(),
  319.         $fail_on_invalid_names = true$structure = false)
  320.     {
  321.         $database_definition = false;
  322.         if (is_string($schema)) {
  323.             // if $schema is not readable then we just skip it
  324.             // and simply copy the $current_schema file to that file name
  325.             if (is_readable($schema)) {
  326.                 $database_definition $this->parseDatabaseDefinitionFile(
  327.                     $schema$variables$fail_on_invalid_names$structure
  328.                 );
  329.             }
  330.         elseif (is_array($schema)) {
  331.             $database_definition $schema;
  332.         }
  333.         if (!$database_definition && !$skip_unreadable{
  334.             $database_definition $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  335.                 'invalid data type of schema or unreadable data source');
  336.         }
  337.         return $database_definition;
  338.     }
  339.  
  340.     // }}}
  341.     // {{{ parseDatabaseDefinitionFile()
  342.  
  343.     /**
  344.      * Parse a database definition file by creating a schema format
  345.      * parser object and passing the file contents as parser input data stream.
  346.      *
  347.      * @param string the database schema file.
  348.      * @param array associative array that the defines the text string values
  349.      *               that are meant to be used to replace the variables that are
  350.      *               used in the schema description.
  351.      * @param bool make function fail on invalid names
  352.      * @param array database structure definition
  353.      * @access public
  354.      */
  355.     function parseDatabaseDefinitionFile($input_file$variables = array(),
  356.         $fail_on_invalid_names = true$structure = false)
  357.     {
  358.         $dtd_file $this->options['dtd_file'];
  359.         if ($dtd_file{
  360.             require_once 'XML/DTD/XmlValidator.php';
  361.             $dtd =new XML_DTD_XmlValidator;
  362.             if (!$dtd->isValid($dtd_file$input_file)) {
  363.                 return $this->raiseError(MDB2_SCHEMA_ERROR_PARSEnullnull$dtd->getMessage());
  364.             }
  365.         }
  366.  
  367.         $class_name $this->options['parser'];
  368.         $result = MDB2::loadClass($class_name$this->db->getOption('debug'));
  369.         if (PEAR::isError($result)) {
  370.             return $result;
  371.         }
  372.  
  373.         $parser =new $class_name($variables$fail_on_invalid_names$structure$this->options['valid_types']$this->options['force_defaults']);
  374.         $result $parser->setInputFile($input_file);
  375.         if (PEAR::isError($result)) {
  376.             return $result;
  377.         }
  378.  
  379.         $result $parser->parse();
  380.         if (PEAR::isError($result)) {
  381.             return $result;
  382.         }
  383.         if (PEAR::isError($parser->error)) {
  384.             return $parser->error;
  385.         }
  386.  
  387.         return $parser->database_definition;
  388.     }
  389.  
  390.     // }}}
  391.     // {{{ getDefinitionFromDatabase()
  392.  
  393.     /**
  394.      * Attempt to reverse engineer a schema structure from an existing MDB2
  395.      * This method can be used if no xml schema file exists yet.
  396.      * The resulting xml schema file may need some manual adjustments.
  397.      *
  398.      * @return array|MDB2_Errorarray with definition or error object
  399.      * @access public
  400.      */
  401.     function getDefinitionFromDatabase()
  402.     {
  403.         $database $this->db->database_name;
  404.         if (empty($database)) {
  405.             return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  406.                 'it was not specified a valid database name');
  407.         }
  408.  
  409.         $database_definition = array(
  410.             'name' => $database,
  411.             'create' => true,
  412.             'overwrite' => false,
  413.             'tables' => array(),
  414.             'sequences' => array(),
  415.         );
  416.  
  417.         $tables $this->db->manager->listTables();
  418.         if (PEAR::isError($tables)) {
  419.             return $tables;
  420.         }
  421.  
  422.         foreach ($tables as $table_name{
  423.             $fields $this->db->manager->listTableFields($table_name);
  424.             if (PEAR::isError($fields)) {
  425.                 return $fields;
  426.             }
  427.  
  428.             $database_definition['tables'][$table_name= array('fields' => array());
  429.             $table_definition =$database_definition['tables'][$table_name];
  430.             foreach ($fields as $field_name{
  431.                 $definition $this->db->reverse->getTableFieldDefinition($table_name$field_name);
  432.                 if (PEAR::isError($definition)) {
  433.                     return $definition;
  434.                 }
  435.  
  436.                 if (!empty($definition[0]['autoincrement'])) {
  437.                     $definition[0]['default'= 0;
  438.                 }
  439.                 $table_definition['fields'][$field_name$definition[0];
  440.                 $field_choices count($definition);
  441.                 if ($field_choices > 1{
  442.                     $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): ";
  443.                     $field_choice_cnt = 1;
  444.                     $table_definition['fields'][$field_name]['choices'= array();
  445.                     foreach ($definition as $field_choice{
  446.                         $table_definition['fields'][$field_name]['choices'][$field_choice;
  447.                         $warning .= 'choice #'.($field_choice_cnt).': '.serialize($field_choice);
  448.                         $field_choice_cnt++;
  449.                     }
  450.                     $this->warnings[$warning;
  451.                 }
  452.             }
  453.             $index_definitions = array();
  454.             $indexes $this->db->manager->listTableIndexes($table_name);
  455.             if (PEAR::isError($indexes)) {
  456.                 return $indexes;
  457.             }
  458.  
  459.             if (is_array($indexes&& empty($table_definition['indexes'])) {
  460.                 foreach ($indexes as $index_name{
  461.                     $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  462.                     $definition $this->db->reverse->getTableIndexDefinition($table_name$index_name);
  463.                     $this->db->popExpect();
  464.                     if (PEAR::isError($definition)) {
  465.                         if (PEAR::isError($definitionMDB2_ERROR_NOT_FOUND)) {
  466.                             continue;
  467.                         }
  468.                         return $definition;
  469.                     }
  470.                    $index_definitions[$index_name$definition;
  471.                 }
  472.             }
  473.  
  474.             $constraints $this->db->manager->listTableConstraints($table_name);
  475.             if (PEAR::isError($constraints)) {
  476.                 return $constraints;
  477.             }
  478.  
  479.             if (is_array($constraints&& empty($table_definition['indexes'])) {
  480.                 foreach ($constraints as $index_name{
  481.                     $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  482.                     $definition $this->db->reverse->getTableConstraintDefinition($table_name$index_name);
  483.                     $this->db->popExpect();
  484.                     if (PEAR::isError($definition)) {
  485.                         if (PEAR::isError($definitionMDB2_ERROR_NOT_FOUND)) {
  486.                             continue;
  487.                         }
  488.                         return $definition;
  489.                     }
  490.                     $index_definitions[$index_name$definition;
  491.                 }
  492.             }
  493.             if (!empty($index_definitions)) {
  494.                 $table_definition['indexes'$index_definitions;
  495.             }
  496.         }
  497.  
  498.         $sequences $this->db->manager->listSequences();
  499.         if (PEAR::isError($sequences)) {
  500.             return $sequences;
  501.         }
  502.  
  503.         if (is_array($sequences)) {
  504.             foreach ($sequences as $sequence_name{
  505.                 $definition $this->db->reverse->getSequenceDefinition($sequence_name);
  506.                 if (PEAR::isError($definition)) {
  507.                     return $definition;
  508.                 }
  509.                 if (isset($database_definition['tables'][$sequence_name])
  510.                     && isset($database_definition['tables'][$sequence_name]['indexes'])
  511.                 {
  512.                     foreach ($database_definition['tables'][$sequence_name]['indexes'as $index{
  513.                         if (isset($index['primary']&& $index['primary']
  514.                             && count($index['fields'== 1)
  515.                         {
  516.                             $definition['on'= array(
  517.                                 'table' => $sequence_name,
  518.                                 'field' => key($index['fields']),
  519.                             );
  520.                             break;
  521.                         }
  522.                     }
  523.                 }
  524.                 $database_definition['sequences'][$sequence_name$definition;
  525.             }
  526.         }
  527.         return $database_definition;
  528.     }
  529.  
  530.     // }}}
  531.     // {{{ createTableIndexes()
  532.  
  533.     /**
  534.      * Create indexes on a table
  535.      *
  536.      * @param string  name of the table
  537.      * @param array   indexes to be created
  538.      * @param bool  if the table/index should be overwritten if it already exists
  539.      * @return bool|MDB2_ErrorMDB2_OK or error object
  540.      * @access public
  541.      */
  542.     function createTableIndexes($table_name$indexes$overwrite = false)
  543.     {
  544.         if (!$this->db->supports('indexes')) {
  545.             $this->db->debug('Indexes are not supported'__FUNCTION__);
  546.             return MDB2_OK;
  547.         }
  548.  
  549.         $supports_primary_key $this->db->supports('primary_key');
  550.         foreach ($indexes as $index_name => $index{
  551.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  552.             $this->db->expectError($errorcodes);
  553.             if (!empty($index['primary']|| !empty($index['unique'])) {
  554.                 $indexes $this->db->manager->listTableConstraints($table_name);
  555.             else {
  556.                 $indexes $this->db->manager->listTableIndexes($table_name);
  557.             }
  558.             $this->db->popExpect();
  559.             if (PEAR::isError($indexes)) {
  560.                 if (!MDB2::isError($indexes$errorcodes)) {
  561.                     return $indexes;
  562.                 }
  563.             elseif (is_array($indexes&& in_array($index_name$indexes)) {
  564.                 if (!$overwrite{
  565.                     $this->db->debug('Index already exists: '.$index_name__FUNCTION__);
  566.                     return MDB2_OK;
  567.                 }
  568.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  569.                     $result $this->db->manager->dropConstraint($table_name$index_name);
  570.                 else {
  571.                     $result $this->db->manager->dropIndex($table_name$index_name);
  572.                 }
  573.                 if (PEAR::isError($result)) {
  574.                     return $result;
  575.                 }
  576.                 $this->db->debug('Overwritting index: '.$index_name__FUNCTION__);
  577.             }
  578.  
  579.             // check if primary is being used and if it's supported
  580.             if (!empty($index['primary']&& !$supports_primary_key{
  581.                 /**
  582.                  * Primary not supported so we fallback to UNIQUE
  583.                  * and making the field NOT NULL
  584.                  */
  585.                 unset($index['primary']);
  586.                 $index['unique'= true;
  587.  
  588.                 $changes = array();
  589.  
  590.                 foreach ($index['fields'as $field => $empty{
  591.                     $field_info $this->db->reverse->getTableFieldDefinition($table_name$field);
  592.                     if (PEAR::isError($field_info)) {
  593.                         return $field_info;
  594.                     }
  595.  
  596.                     if (!$field_info[0]['notnull']{
  597.                         $changes['change'][$field$field_info[0];
  598.                         $changes['change'][$field]['notnull'= true;
  599.                     }
  600.                 }
  601.                 if (!empty($changes)) {
  602.                     $this->db->manager->alterTable($table_name$changesfalse);
  603.                 }
  604.             }
  605.  
  606.             if (!empty($index['primary']|| !empty($index['unique'])) {
  607.                 $result $this->db->manager->createConstraint($table_name$index_name$index);
  608.             else {
  609.                 $result $this->db->manager->createIndex($table_name$index_name$index);
  610.             }
  611.             if (PEAR::isError($result)) {
  612.                 return $result;
  613.             }
  614.         }
  615.         return MDB2_OK;
  616.     }
  617.  
  618.     // }}}
  619.     // {{{ createTable()
  620.  
  621.     /**
  622.      * Create a table and inititialize the table if data is available
  623.      *
  624.      * @param string name of the table to be created
  625.      * @param array  multi dimensional array that contains the
  626.      *                structure and optional data of the table
  627.      * @param bool   if the table/index should be overwritten if it already exists
  628.      * @return bool|MDB2_ErrorMDB2_OK or error object
  629.      * @access public
  630.      */
  631.     function createTable($table_name$table$overwrite = false)
  632.     {
  633.         $create = true;
  634.         $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  635.         $this->db->expectError($errorcodes);
  636.         $tables $this->db->manager->listTables();
  637.         $this->db->popExpect();
  638.         if (PEAR::isError($tables)) {
  639.             if (!MDB2::isError($tables$errorcodes)) {
  640.                 return $tables;
  641.             }
  642.         elseif (is_array($tables&& in_array($table_name$tables)) {
  643.             if (!$overwrite{
  644.                 $create = false;
  645.                 $this->db->debug('Table already exists: '.$table_name__FUNCTION__);
  646.             else {
  647.                 $result $this->db->manager->dropTable($table_name);
  648.                 if (PEAR::isError($result)) {
  649.                     return $result;
  650.                 }
  651.                 $this->db->debug('Overwritting table: '.$table_name__FUNCTION__);
  652.             }
  653.         }
  654.  
  655.         if ($create{
  656.             $result $this->db->manager->createTable($table_name$table['fields']);
  657.             if (PEAR::isError($result)) {
  658.                 return $result;
  659.             }
  660.         }
  661.  
  662.         if (!empty($table['initialization']&& is_array($table['initialization'])) {
  663.             $result $this->initializeTable($table_name$table);
  664.             if (PEAR::isError($result)) {
  665.                 return $result;
  666.             }
  667.         }
  668.  
  669.         if (!empty($table['indexes']&& is_array($table['indexes'])) {
  670.             $result $this->createTableIndexes($table_name$table['indexes']$overwrite);
  671.             if (PEAR::isError($result)) {
  672.                 return $result;
  673.             }
  674.         }
  675.  
  676.         return MDB2_OK;
  677.     }
  678.  
  679.     // }}}
  680.     // {{{ initializeTable()
  681.  
  682.     /**
  683.      * Inititialize the table with data
  684.      *
  685.      * @param string name of the table
  686.      * @param array  multi dimensional array that contains the
  687.      *                structure and optional data of the table
  688.      * @return bool|MDB2_ErrorMDB2_OK or error object
  689.      * @access public
  690.      */
  691.     function initializeTable($table_name$table)
  692.     {
  693.         foreach ($table['fields'as $field_name => $field{
  694.             $placeholders[$field_name':'.$field_name;
  695.             $types[$field_name$field['type'];
  696.         }
  697.         $fields implode(','array_keys($table['fields']));
  698.         $placeholders implode(','$placeholders);
  699.         $query = "INSERT INTO $table_name ($fields) VALUES ($placeholders)";
  700.         $stmt $this->db->prepare($query$typesnulltrue);
  701.         if (PEAR::isError($stmt)) {
  702.             return $stmt;
  703.         }
  704.  
  705.         foreach ($table['initialization'as $instruction{
  706.             switch ($instruction['type']{
  707.             case 'insert':
  708.                 if (!empty($instruction['fields']&& is_array($instruction['fields'])) {
  709.                     $result $stmt->execute($instruction['fields']);
  710.                     if (PEAR::isError($result)) {
  711.                         return $result;
  712.                     }
  713.                 }
  714.                 break;
  715.             }
  716.         }
  717.         return $stmt->free();
  718.     }
  719.  
  720.     // }}}
  721.     // {{{ createSequence()
  722.  
  723.     /**
  724.      * Create a sequence
  725.      *
  726.      * @param string name of the sequence to be created
  727.      * @param array  multi dimensional array that contains the
  728.      *                structure and optional data of the table
  729.      * @param bool  if the sequence should be overwritten if it already exists
  730.      * @return bool|MDB2_ErrorMDB2_OK or error object
  731.      * @access public
  732.      */
  733.     function createSequence($sequence_name$sequence$overwrite = false)
  734.     {
  735.         if (!$this->db->supports('sequences')) {
  736.             $this->db->debug('Sequences are not supported'__FUNCTION__);
  737.             return MDB2_OK;
  738.         }
  739.  
  740.         $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  741.         $this->db->expectError($errorcodes);
  742.         $sequences $this->db->manager->listSequences();
  743.         $this->db->popExpect();
  744.         if (PEAR::isError($sequences)) {
  745.             if (!MDB2::isError($sequences$errorcodes)) {
  746.                 return $sequences;
  747.             }
  748.         elseif (is_array($sequence&& in_array($sequence_name$sequences)) {
  749.             if (!$overwrite{
  750.                 $this->db->debug('Sequence already exists: '.$sequence_name__FUNCTION__);
  751.                 return MDB2_OK;
  752.             }
  753.  
  754.             $result $this->db->manager->dropSequence($sequence_name);
  755.             if (PEAR::isError($result)) {
  756.                 return $result;
  757.             }
  758.             $this->db->debug('Overwritting sequence: '.$sequence_name__FUNCTION__);
  759.         }
  760.  
  761.         $start = 1;
  762.         $field '';
  763.         if (!empty($sequence['on'])) {
  764.             $table $sequence['on']['table'];
  765.             $field $sequence['on']['field'];
  766.  
  767.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  768.             $this->db->expectError($errorcodes);
  769.             $tables $this->db->manager->listTables();
  770.             $this->db->popExpect();
  771.             if (PEAR::isError($tables&& !MDB2::isError($tables$errorcodes)) {
  772.                  return $tables;
  773.             }
  774.  
  775.             if (!PEAR::isError($tables&&
  776.                 is_array($tables&& in_array($table$tables)
  777.             {
  778.                 if ($this->db->supports('summary_functions')) {
  779.                     $query = "SELECT MAX($field) FROM $table";
  780.                 else {
  781.                     $query = "SELECT $field FROM $table ORDER BY $field DESC";
  782.                 }
  783.                 $start $this->db->queryOne($query'integer');
  784.                 if (PEAR::isError($start)) {
  785.                     return $start;
  786.                 }
  787.                 ++$start;
  788.             else {
  789.                 $this->warnings['Could not sync sequence: '.$sequence_name;
  790.             }
  791.         elseif (!empty($sequence['start']&& is_numeric($sequence['start'])) {
  792.             $start $sequence['start'];
  793.             $table '';
  794.         }
  795.  
  796.         $result $this->db->manager->createSequence($sequence_name$start);
  797.         if (PEAR::isError($result)) {
  798.             return $result;
  799.         }
  800.  
  801.         return MDB2_OK;
  802.     }
  803.  
  804.     // }}}
  805.     // {{{ createDatabase()
  806.  
  807.     /**
  808.      * Create a database space within which may be created database objects
  809.      * like tables, indexes and sequences. The implementation of this function
  810.      * is highly DBMS specific and may require special permissions to run
  811.      * successfully. Consult the documentation or the DBMS drivers that you
  812.      * use to be aware of eventual configuration requirements.
  813.      *
  814.      * @param array multi dimensional array that contains the current definition
  815.      * @return bool|MDB2_ErrorMDB2_OK or error object
  816.      * @access public
  817.      */
  818.     function createDatabase($database_definition)
  819.     {
  820.         if (!isset($database_definition['name']|| !$database_definition['name']{
  821.             return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  822.                 'no valid database name specified');
  823.         }
  824.         $create (isset($database_definition['create']&& $database_definition['create']);
  825.         $overwrite (isset($database_definition['overwrite']&& $database_definition['overwrite']);
  826.         if ($create{
  827.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  828.             $this->db->expectError($errorcodes);
  829.             $databases $this->db->manager->listDatabases();
  830.  
  831.             // Lower / Upper case the db name if the portability deems so.
  832.             if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  833.                 $func $this->db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper';
  834.                 $db_name $func($database_definition['name']);
  835.             }
  836.  
  837.             $this->db->popExpect();
  838.             if (PEAR::isError($databases)) {
  839.                 if (!MDB2::isError($databases$errorcodes)) {
  840.                     return $databases;
  841.                 }
  842.             elseif (is_array($databases&& in_array($db_name$databases)) {
  843.                 if (!$overwrite{
  844.                     $this->db->debug('Database already exists: ' $database_definition['name']__FUNCTION__);
  845.                     $create = false;
  846.                 else {
  847.                     $result $this->db->manager->dropDatabase($database_definition['name']);
  848.                     if (PEAR::isError($result)) {
  849.                         return $result;
  850.                     }
  851.                     $this->db->debug('Overwritting database: '.$database_definition['name']__FUNCTION__);
  852.                 }
  853.             }
  854.             if ($create{
  855.                 $this->db->expectError(MDB2_ERROR_ALREADY_EXISTS);
  856.                 $result $this->db->manager->createDatabase($database_definition['name']);
  857.                 $this->db->popExpect();
  858.                 if (PEAR::isError($result&& !MDB2::isError($resultMDB2_ERROR_ALREADY_EXISTS)) {
  859.                     return $result;
  860.                 }
  861.             }
  862.         }
  863.         $previous_database_name $this->db->setDatabase($database_definition['name']);
  864.         if (($support_transactions $this->db->supports('transactions'))
  865.             && PEAR::isError($result $this->db->beginNestedTransaction())
  866.         {
  867.             return $result;
  868.         }
  869.  
  870.         $created_objects = 0;
  871.         if (isset($database_definition['tables'])
  872.             && is_array($database_definition['tables'])
  873.         {
  874.             foreach ($database_definition['tables'as $table_name => $table{
  875.                 $result $this->createTable($table_name$table$overwrite);
  876.                 if (PEAR::isError($result)) {
  877.                     break;
  878.                 }
  879.                 $created_objects++;
  880.             }
  881.         }
  882.         if (!PEAR::isError($result)
  883.             && isset($database_definition['sequences'])
  884.             && is_array($database_definition['sequences'])
  885.         {
  886.             foreach ($database_definition['sequences'as $sequence_name => $sequence{
  887.                 $result $this->createSequence($sequence_name$sequencefalse$overwrite);
  888.  
  889.                 if (PEAR::isError($result)) {
  890.                     break;
  891.                 }
  892.                 $created_objects++;
  893.             }
  894.         }
  895.  
  896.         if ($support_transactions{
  897.             $res $this->db->completeNestedTransaction();
  898.             if (PEAR::isError($res)) {
  899.                 $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  900.                     'Could not end transaction ('.
  901.                     $res->getMessage().' ('.$res->getUserinfo().'))');
  902.             }
  903.         elseif (PEAR::isError($result&& $created_objects{
  904.             $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  905.                 'the database was only partially created ('.
  906.                 $result->getMessage().' ('.$result->getUserinfo().'))');
  907.         }
  908.  
  909.         $this->db->setDatabase($previous_database_name);
  910.  
  911.         if (PEAR::isError($result&& $create
  912.             && PEAR::isError($result2 $this->db->manager->dropDatabase($database_definition['name']))
  913.         {
  914.             return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  915.                 'Could not drop the created database after unsuccessful creation attempt ('.
  916.                 $result2->getMessage().' ('.$result2->getUserinfo().'))');
  917.         }
  918.  
  919.         return $result;
  920.     }
  921.  
  922.     // }}}
  923.     // {{{ compareDefinitions()
  924.  
  925.     /**
  926.      * Compare a previous definition with the currently parsed definition
  927.      *
  928.      * @param array multi dimensional array that contains the current definition
  929.      * @param array multi dimensional array that contains the previous definition
  930.      * @return array|MDB2_Errorarray of changes on success, or a error object
  931.      * @access public
  932.      */
  933.     function compareDefinitions($current_definition$previous_definition)
  934.     {
  935.         $changes = array();
  936.  
  937.         if (!empty($current_definition['tables']&& is_array($current_definition['tables'])) {
  938.             $changes['tables'$defined_tables = array();
  939.             foreach ($current_definition['tables'as $table_name => $table{
  940.                 $previous_tables = array();
  941.                 if (!empty($previous_definition&& is_array($previous_definition)) {
  942.                     $previous_tables $previous_definition['tables'];
  943.                 }
  944.                 $change $this->compareTableDefinitions($table_name$table$previous_tables$defined_tables);
  945.                 if (PEAR::isError($change)) {
  946.                     return $change;
  947.                 }
  948.                 if (!empty($change)) {
  949.                     $changes['tables'MDB2_Schema::arrayMergeClobber($changes['tables']$change);
  950.                 }
  951.             }
  952.             if (!empty($previous_definition['tables']&& is_array($previous_definition['tables'])) {
  953.                 foreach ($previous_definition['tables'as $table_name => $table{
  954.                     if (empty($defined_tables[$table_name])) {
  955.                         $changes['remove'][$table_name= true;
  956.                     }
  957.                 }
  958.             }
  959.         }
  960.         if (!empty($current_definition['sequences']&& is_array($current_definition['sequences'])) {
  961.             $changes['sequences'$defined_sequences = array();
  962.             foreach ($current_definition['sequences'as $sequence_name => $sequence{
  963.                 $previous_sequences = array();
  964.                 if (!empty($previous_definition&& is_array($previous_definition)) {
  965.                     $previous_sequences $previous_definition['sequences'];
  966.                 }
  967.                 $change $this->compareSequenceDefinitions(
  968.                     $sequence_name,
  969.                     $sequence,
  970.                     $previous_sequences,
  971.                     $defined_sequences
  972.                 );
  973.                 if (PEAR::isError($change)) {
  974.                     return $change;
  975.                 }
  976.                 if (!empty($change)) {
  977.                     $changes['sequences'MDB2_Schema::arrayMergeClobber($changes['sequences']$change);
  978.                 }
  979.             }
  980.             if (!empty($previous_definition['sequences']&& is_array($previous_definition['sequences'])) {
  981.                 foreach ($previous_definition['sequences'as $sequence_name => $sequence{
  982.                     if (empty($defined_sequences[$sequence_name])) {
  983.                         $changes['remove'][$sequence_name= true;
  984.                     }
  985.                 }
  986.             }
  987.         }
  988.         return $changes;
  989.     }
  990.  
  991.     // }}}
  992.     // {{{ compareTableFieldsDefinitions()
  993.  
  994.     /**
  995.      * Compare a previous definition with the currently parsed definition
  996.      *
  997.      * @param string name of the table
  998.      * @param array multi dimensional array that contains the current definition
  999.      * @param array multi dimensional array that contains the previous definition
  1000.      * @param array 
  1001.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1002.      * @access public
  1003.      */
  1004.     function compareTableFieldsDefinitions($table_name$current_definition,
  1005.         $previous_definition&$defined_fields)
  1006.     {
  1007.         $changes = array();
  1008.  
  1009.         if (is_array($current_definition)) {
  1010.             foreach ($current_definition as $field_name => $field{
  1011.                 $was_field_name $field['was'];
  1012.                 if (!empty($previous_definition[$field_name])
  1013.                     && isset($previous_definition[$field_name]['was'])
  1014.                     && $previous_definition[$field_name]['was'== $was_field_name
  1015.                 {
  1016.                     $was_field_name $field_name;
  1017.                 }
  1018.                 if (!empty($previous_definition[$was_field_name])) {
  1019.                     if ($was_field_name != $field_name{
  1020.                         $changes['rename'][$was_field_name= array('name' => $field_name'definition' => $field);
  1021.                     }
  1022.                     if (!empty($defined_fields[$was_field_name])) {
  1023.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1024.                             'the field "'.$was_field_name.
  1025.                             '" was specified as base of more than one field of table');
  1026.                     }
  1027.                     $defined_fields[$was_field_name= true;
  1028.                     $change $this->db->compareDefinition($field$previous_definition[$was_field_name]);
  1029.                     if (PEAR::isError($change)) {
  1030.                         return $change;
  1031.                     }
  1032.                     if (!empty($change)) {
  1033.                         $change['definition'$field;
  1034.                         $changes['change'][$field_name$change;
  1035.                     }
  1036.                 else {
  1037.                     if ($field_name != $was_field_name{
  1038.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1039.                             'it was specified a previous field name ("'.
  1040.                             $was_field_name.'") for field "'.$field_name.'" of table "'.
  1041.                             $table_name.'" that does not exist');
  1042.                     }
  1043.                     $changes['add'][$field_name$field;
  1044.                 }
  1045.             }
  1046.         }
  1047.         if (isset($previous_definition&& is_array($previous_definition)) {
  1048.             foreach ($previous_definition as $field_previous_name => $field_previous{
  1049.                 if (empty($defined_fields[$field_previous_name])) {
  1050.                     $changes['remove'][$field_previous_name= true;
  1051.                 }
  1052.             }
  1053.         }
  1054.         return $changes;
  1055.     }
  1056.  
  1057.     // }}}
  1058.     // {{{ compareTableIndexesDefinitions()
  1059.  
  1060.     /**
  1061.      * Compare a previous definition with the currently parsed definition
  1062.      *
  1063.      * @param string name of the table
  1064.      * @param array multi dimensional array that contains the current definition
  1065.      * @param array multi dimensional array that contains the previous definition
  1066.      * @param array 
  1067.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1068.      * @access public
  1069.      */
  1070.     function compareTableIndexesDefinitions($table_name$current_definition,
  1071.         $previous_definition&$defined_indexes)
  1072.     {
  1073.         $changes = array();
  1074.  
  1075.         if (is_array($current_definition)) {
  1076.             foreach ($current_definition as $index_name => $index{
  1077.                 $was_index_name $index['was'];
  1078.                 if (!empty($previous_definition[$index_name])
  1079.                     && isset($previous_definition[$index_name]['was'])
  1080.                     && $previous_definition[$index_name]['was'== $was_index_name
  1081.                 {
  1082.                     $was_index_name $index_name;
  1083.                 }
  1084.                 if (!empty($previous_definition[$was_index_name])) {
  1085.                     $change = array();
  1086.                     if ($was_index_name != $index_name{
  1087.                         $change['name'$was_index_name;
  1088.                     }
  1089.                     if (!empty($defined_indexes[$was_index_name])) {
  1090.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1091.                             'the index "'.$was_index_name.'" was specified as base of'.
  1092.                             ' more than one index of table "'.$table_name.'"');
  1093.                     }
  1094.                     $defined_indexes[$was_index_name= true;
  1095.  
  1096.                     $previous_unique array_key_exists('unique'$previous_definition[$was_index_name])
  1097.                         ? $previous_definition[$was_index_name]['unique': false;
  1098.                     $unique array_key_exists('unique'$index$index['unique': false;
  1099.                     if ($previous_unique != $unique{
  1100.                         $change['unique'$unique;
  1101.                     }
  1102.                     $previous_primary array_key_exists('primary'$previous_definition[$was_index_name])
  1103.                         ? $previous_definition[$was_index_name]['primary': false;
  1104.                     $primary array_key_exists('primary'$index$index['primary': false;
  1105.                     if ($previous_primary != $primary{
  1106.                         $change['primary'$primary;
  1107.                     }
  1108.                     $defined_fields = array();
  1109.                     $previous_fields $previous_definition[$was_index_name]['fields'];
  1110.                     if (!empty($index['fields']&& is_array($index['fields'])) {
  1111.                         foreach ($index['fields'as $field_name => $field{
  1112.                             if (!empty($previous_fields[$field_name])) {
  1113.                                 $defined_fields[$field_name= true;
  1114.                                 $previous_sorting array_key_exists('sorting'$previous_fields[$field_name])
  1115.                                     ? $previous_fields[$field_name]['sorting''';
  1116.                                 $sorting array_key_exists('sorting'$field$field['sorting''';
  1117.                                 if ($previous_sorting != $sorting{
  1118.                                     $change['change'= true;
  1119.                                 }
  1120.                             else {
  1121.                                 $change['change'= true;
  1122.                             }
  1123.                         }
  1124.                     }
  1125.                     if (isset($previous_fields&& is_array($previous_fields)) {
  1126.                         foreach ($previous_fields as $field_name => $field{
  1127.                             if (empty($defined_fields[$field_name])) {
  1128.                                 $change['change'= true;
  1129.                             }
  1130.                         }
  1131.                     }
  1132.                     if (!empty($change)) {
  1133.                         $changes['change'][$index_name$current_definition[$index_name];
  1134.                     }
  1135.                 else {
  1136.                     if ($index_name != $was_index_name{
  1137.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1138.                             'it was specified a previous index name ("'.$was_index_name.
  1139.                             ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist');
  1140.                     }
  1141.                     $changes['add'][$index_name$current_definition[$index_name];
  1142.                 }
  1143.             }
  1144.         }
  1145.         foreach ($previous_definition as $index_previous_name => $index_previous{
  1146.             if (empty($defined_indexes[$index_previous_name])) {
  1147.                 $changes['remove'][$index_previous_name= true;
  1148.             }
  1149.         }
  1150.         return $changes;
  1151.     }
  1152.  
  1153.     // }}}
  1154.     // {{{ compareTableDefinitions()
  1155.  
  1156.     /**
  1157.      * Compare a previous definition with the currently parsed definition
  1158.      *
  1159.      * @param string name of the table
  1160.      * @param array multi dimensional array that contains the current definition
  1161.      * @param array multi dimensional array that contains the previous definition
  1162.      * @param array 
  1163.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1164.      * @access public
  1165.      */
  1166.     function compareTableDefinitions($table_name$current_definition,
  1167.         $previous_definition&$defined_tables)
  1168.     {
  1169.         $changes = array();
  1170.  
  1171.         if (is_array($current_definition)) {
  1172.             $was_table_name $table_name;
  1173.             if (!empty($current_definition['was'])) {
  1174.                 $was_table_name $current_definition['was'];
  1175.             }
  1176.             if (!empty($previous_definition[$was_table_name])) {
  1177.                 $changes['change'][$was_table_name= array();
  1178.                 if ($was_table_name != $table_name{
  1179.                     $changes['change'][$was_table_name= array('name' => $table_name);
  1180.                 }
  1181.                 if (!empty($defined_tables[$was_table_name])) {
  1182.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1183.                         'the table "'.$was_table_name.
  1184.                         '" was specified as base of more than of table of the database');
  1185.                 }
  1186.                 $defined_tables[$was_table_name= true;
  1187.                 if (!empty($current_definition['fields']&& is_array($current_definition['fields'])) {
  1188.                     $previous_fields = array();
  1189.                     if (isset($previous_definition[$was_table_name]['fields'])
  1190.                         && is_array($previous_definition[$was_table_name]['fields'])
  1191.                     {
  1192.                         $previous_fields $previous_definition[$was_table_name]['fields'];
  1193.                     }
  1194.                     $defined_fields = array();
  1195.                     $change $this->compareTableFieldsDefinitions(
  1196.                         $table_name,
  1197.                         $current_definition['fields'],
  1198.                         $previous_fields,
  1199.                         $defined_fields
  1200.                     );
  1201.                     if (PEAR::isError($change)) {
  1202.                         return $change;
  1203.                     }
  1204.                     if (!empty($change)) {
  1205.                         $changes['change'][$was_table_name=
  1206.                             MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name]$change);
  1207.                     }
  1208.                 }
  1209.                 if (!empty($current_definition['indexes']&& is_array($current_definition['indexes'])) {
  1210.                     $previous_indexes = array();
  1211.                     if (isset($previous_definition[$was_table_name]['indexes'])
  1212.                         && is_array($previous_definition[$was_table_name]['indexes'])
  1213.                     {
  1214.                         $previous_indexes $previous_definition[$was_table_name]['indexes'];
  1215.                     }
  1216.                     $defined_indexes = array();
  1217.                     $change $this->compareTableIndexesDefinitions(
  1218.                         $table_name,
  1219.                         $current_definition['indexes'],
  1220.                         $previous_indexes,
  1221.                         $defined_indexes
  1222.                     );
  1223.                     if (PEAR::isError($change)) {
  1224.                         return $change;
  1225.                     }
  1226.                     if (!empty($change)) {
  1227.                         $changes['change'][$was_table_name]['indexes'$change;
  1228.                     }
  1229.                 }
  1230.                 if (empty($changes['change'][$was_table_name])) {
  1231.                     unset($changes['change'][$was_table_name]);
  1232.                 }
  1233.                 if (empty($changes['change'])) {
  1234.                     unset($changes['change']);
  1235.                 }
  1236.             else {
  1237.                 if ($table_name != $was_table_name{
  1238.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1239.                         'it was specified a previous table name ("'.$was_table_name.
  1240.                         '") for table "'.$table_name.'" that does not exist');
  1241.                 }
  1242.                 $changes['add'][$table_name= true;
  1243.             }
  1244.         }
  1245.  
  1246.         return $changes;
  1247.     }
  1248.  
  1249.     // }}}
  1250.     // {{{ compareSequenceDefinitions()
  1251.  
  1252.     /**
  1253.      * Compare a previous definition with the currently parsed definition
  1254.      *
  1255.      * @param string name of the sequence
  1256.      * @param array multi dimensional array that contains the current definition
  1257.      * @param array multi dimensional array that contains the previous definition
  1258.      * @param array 
  1259.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1260.      * @access public
  1261.      */
  1262.     function compareSequenceDefinitions($sequence_name$current_definition,
  1263.         $previous_definition&$defined_sequences)
  1264.     {
  1265.         $changes = array();
  1266.  
  1267.         if (is_array($current_definition)) {
  1268.             $was_sequence_name $sequence_name;
  1269.             if (!empty($previous_definition[$sequence_name])
  1270.                 && isset($previous_definition[$sequence_name]['was'])
  1271.                 && $previous_definition[$sequence_name]['was'== $was_sequence_name
  1272.             {
  1273.                 $was_sequence_name $sequence_name;
  1274.             elseif (!empty($current_definition['was'])) {
  1275.                 $was_sequence_name $current_definition['was'];
  1276.             }
  1277.             if (!empty($previous_definition[$was_sequence_name])) {
  1278.                 if ($was_sequence_name != $sequence_name{
  1279.                     $changes['change'][$was_sequence_name]['name'$sequence_name;
  1280.                 }
  1281.                 if (!empty($defined_sequences[$was_sequence_name])) {
  1282.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1283.                         'the sequence "'.$was_sequence_name.'" was specified as base'.
  1284.                         ' of more than of sequence of the database');
  1285.                 }
  1286.                 $defined_sequences[$was_sequence_name= true;
  1287.                 $change = array();
  1288.                 if (!empty($current_definition['start'])
  1289.                     && isset($previous_definition[$was_sequence_name]['start'])
  1290.                     && $current_definition['start'!= $previous_definition[$was_sequence_name]['start']
  1291.                 {
  1292.                     $change['start'$previous_definition[$sequence_name]['start'];
  1293.                 }
  1294.                 if (isset($current_definition['on']['table'])
  1295.                     && isset($previous_definition[$was_sequence_name]['on']['table'])
  1296.                     && $current_definition['on']['table'!= $previous_definition[$was_sequence_name]['on']['table']
  1297.                     && isset($current_definition['on']['field'])
  1298.                     && isset($previous_definition[$was_sequence_name]['on']['field'])
  1299.                     && $current_definition['on']['field'!= $previous_definition[$was_sequence_name]['on']['field']
  1300.                 {
  1301.                     $change['on'$current_definition['on'];
  1302.                 }
  1303.                 if (!empty($change)) {
  1304.                     $changes['change'][$was_sequence_name][$sequence_name$change;
  1305.                 }
  1306.             else {
  1307.                 if ($sequence_name != $was_sequence_name{
  1308.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1309.                         'it was specified a previous sequence name ("'.$was_sequence_name.
  1310.                         '") for sequence "'.$sequence_name.'" that does not exist');
  1311.                 }
  1312.                 $changes['add'][$sequence_name= true;
  1313.             }
  1314.         }
  1315.         return $changes;
  1316.     }
  1317.     // }}}
  1318.     // {{{ verifyAlterDatabase()
  1319.  
  1320.     /**
  1321.      * Verify that the changes requested are supported
  1322.      *
  1323.      * @param array associative array that contains the definition of the changes
  1324.      *               that are meant to be applied to the database structure.
  1325.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1326.      * @access public
  1327.      */
  1328.     function verifyAlterDatabase($changes)
  1329.     {
  1330.         if (!empty($changes['tables']['change']&& is_array($changes['tables']['change'])) {
  1331.             foreach ($changes['tables']['change'as $table_name => $table{
  1332.                 if (!empty($table['indexes']&& is_array($table['indexes'])) {
  1333.                     if (!$this->db->supports('indexes')) {
  1334.                         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1335.                             'indexes are not supported');
  1336.                     }
  1337.                     $table_changes count($table['indexes']);
  1338.                     if (!empty($table['indexes']['add'])) {
  1339.                         $table_changes--;
  1340.                     }
  1341.                     if (!empty($table['indexes']['remove'])) {
  1342.                         $table_changes--;
  1343.                     }
  1344.                     if (!empty($table['indexes']['change'])) {
  1345.                         $table_changes--;
  1346.                     }
  1347.                     if ($table_changes{
  1348.                         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1349.                             'index alteration not yet supported: '.implode(', 'array_keys($table['indexes'])));
  1350.                     }
  1351.                 }
  1352.                 unset($table['indexes']);
  1353.                 $result $this->db->manager->alterTable($table_name$tabletrue);
  1354.                 if (PEAR::isError($result)) {
  1355.                     return $result;
  1356.                 }
  1357.             }
  1358.         }
  1359.         if (!empty($changes['sequences']&& is_array($changes['sequences'])) {
  1360.             if (!$this->db->supports('sequences')) {
  1361.                 return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1362.                     'sequences are not supported');
  1363.             }
  1364.             $sequence_changes count($changes['sequences']);
  1365.             if (!empty($changes['sequences']['add'])) {
  1366.                 $sequence_changes--;
  1367.             }
  1368.             if (!empty($changes['sequences']['remove'])) {
  1369.                 $sequence_changes--;
  1370.             }
  1371.             if (!empty($changes['sequences']['change'])) {
  1372.                 $sequence_changes--;
  1373.             }
  1374.             if ($sequence_changes{
  1375.                 return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1376.                     'sequence alteration not yet supported: '.implode(', 'array_keys($changes['sequences'])));
  1377.             }
  1378.         }
  1379.         return MDB2_OK;
  1380.     }
  1381.  
  1382.     // }}}
  1383.     // {{{ alterDatabaseIndexes()
  1384.  
  1385.     /**
  1386.      * Execute the necessary actions to implement the requested changes
  1387.      * in the indexes inside a database structure.
  1388.      *
  1389.      * @param string name of the table
  1390.      * @param array associative array that contains the definition of the changes
  1391.      *               that are meant to be applied to the database structure.
  1392.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1393.      * @access public
  1394.      */
  1395.     function alterDatabaseIndexes($table_name$changes)
  1396.     {
  1397.         $alterations = 0;
  1398.         if (empty($changes)) {
  1399.             return $alterations;
  1400.         }
  1401.  
  1402.         if (!empty($changes['remove']&& is_array($changes['remove'])) {
  1403.             foreach ($changes['remove'as $index_name => $index{
  1404.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  1405.                     $result $this->db->manager->dropConstraint($table_name$index_name!empty($index['primary']));
  1406.                 else {
  1407.                     $result $this->db->manager->dropIndex($table_name$index_name);
  1408.                 }
  1409.                 if (PEAR::isError($result)) {
  1410.                     return $result;
  1411.                 }
  1412.                 $alterations++;
  1413.             }
  1414.         }
  1415.         if (!empty($changes['change']&& is_array($changes['change'])) {
  1416.             foreach ($changes['change'as $index_name => $index{
  1417.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  1418.                     $result $this->db->manager->dropConstraint($table_name$index_name!empty($index['primary']));
  1419.                     if (PEAR::isError($result)) {
  1420.                         return $result;
  1421.                     }
  1422.                     $result $this->db->manager->createConstraint($table_name$index_name$index);
  1423.                 else {
  1424.                     $result $this->db->manager->dropIndex($table_name$index_name);
  1425.                     if (PEAR::isError($result)) {
  1426.                         return $result;
  1427.                     }
  1428.                     $result $this->db->manager->createIndex($table_name$index_name$index);
  1429.                 }
  1430.                 if (PEAR::isError($result)) {
  1431.                     return $result;
  1432.                 }
  1433.                 $alterations++;
  1434.             }
  1435.         }
  1436.         if (!empty($changes['add']&& is_array($changes['add'])) {
  1437.             foreach ($changes['add'as $index_name => $index{
  1438.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  1439.                     $result $this->db->manager->createConstraint($table_name$index_name$index);
  1440.                 else {
  1441.                     $result $this->db->manager->createIndex($table_name$index_name$index);
  1442.                 }
  1443.                 if (PEAR::isError($result)) {
  1444.                     return $result;
  1445.                 }
  1446.                 $alterations++;
  1447.             }
  1448.         }
  1449.  
  1450.         return $alterations;
  1451.     }
  1452.  
  1453.     // }}}
  1454.     // {{{ alterDatabaseTables()
  1455.  
  1456.     /**
  1457.      * Execute the necessary actions to implement the requested changes
  1458.      * in the tables inside a database structure.
  1459.      *
  1460.      * @param array multi dimensional array that contains the current definition
  1461.      * @param array multi dimensional array that contains the previous definition
  1462.      * @param array associative array that contains the definition of the changes
  1463.      *               that are meant to be applied to the database structure.
  1464.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1465.      * @access public
  1466.      */
  1467.     function alterDatabaseTables($current_definition$previous_definition$changes)
  1468.     {
  1469.         $alterations = 0;
  1470.         if (empty($changes)) {
  1471.             return $alterations;
  1472.         }
  1473.  
  1474.         if (!empty($changes['remove']&& is_array($changes['remove'])) {
  1475.             foreach ($changes['remove'as $table_name => $table{
  1476.                 $result $this->db->manager->dropTable($table_name);
  1477.                 if (PEAR::isError($result)) {
  1478.                     return $result;
  1479.                 }
  1480.                 $alterations++;
  1481.             }
  1482.         }
  1483.  
  1484.         if (!empty($changes['add']&& is_array($changes['add'])) {
  1485.             foreach ($changes['add'as $table_name => $table{
  1486.                 $result $this->createTable($table_name$current_definition[$table_name]);
  1487.                 if (PEAR::isError($result)) {
  1488.                     return $result;
  1489.                 }
  1490.                 $alterations++;
  1491.             }
  1492.         }
  1493.  
  1494.         if (!empty($changes['change']&& is_array($changes['change'])) {
  1495.             foreach ($changes['change'as $table_name => $table{
  1496.                 $indexes = array();
  1497.                 if (!empty($table['indexes'])) {
  1498.                     $indexes $table['indexes'];
  1499.                     unset($table['indexes']);
  1500.                 }
  1501.                 if (!empty($indexes['remove'])) {
  1502.                     $result $this->alterDatabaseIndexes($table_namearray('remove' => $indexes['remove']));
  1503.                     if (PEAR::isError($result)) {
  1504.                         return $result;
  1505.                     }
  1506.                     unset($indexes['remove']);
  1507.                     $alterations += $result;
  1508.                 }
  1509.                 $result $this->db->manager->alterTable($table_name$tablefalse);
  1510.                 if (PEAR::isError($result)) {
  1511.                     return $result;
  1512.                 }
  1513.                 $alterations++;
  1514.                 if (!empty($indexes)) {
  1515.                     $result $this->alterDatabaseIndexes($table_name$indexes);
  1516.                     if (PEAR::isError($result)) {
  1517.                         return $result;
  1518.                     }
  1519.                     $alterations += $result;
  1520.                 }
  1521.             }
  1522.         }
  1523.  
  1524.         return $alterations;
  1525.     }
  1526.  
  1527.     // }}}
  1528.     // {{{ alterDatabaseSequences()
  1529.  
  1530.     /**
  1531.      * Execute the necessary actions to implement the requested changes
  1532.      * in the sequences inside a database structure.
  1533.      *
  1534.      * @param array multi dimensional array that contains the current definition
  1535.      * @param array multi dimensional array that contains the previous definition
  1536.      * @param array associative array that contains the definition of the changes
  1537.      *               that are meant to be applied to the database structure.
  1538.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1539.      * @access public
  1540.      */
  1541.     function alterDatabaseSequences($current_definition$previous_definition$changes)
  1542.     {
  1543.         $alterations = 0;
  1544.         if (empty($changes)) {
  1545.             return $alterations;
  1546.         }
  1547.  
  1548.         if (!empty($changes['add']&& is_array($changes['add'])) {
  1549.             foreach ($changes['add'as $sequence_name => $sequence{
  1550.                 $result $this->createSequence($sequence_name$current_definition[$sequence_name]);
  1551.                 if (PEAR::isError($result)) {
  1552.                     return $result;
  1553.                 }
  1554.                 $alterations++;
  1555.             }
  1556.         }
  1557.  
  1558.         if (!empty($changes['remove']&& is_array($changes['remove'])) {
  1559.             foreach ($changes['remove'as $sequence_name => $sequence{
  1560.                 $result $this->db->manager->dropSequence($sequence_name);
  1561.                 if (PEAR::isError($result)) {
  1562.                     return $result;
  1563.                 }
  1564.                 $alterations++;
  1565.             }
  1566.         }
  1567.  
  1568.         if (!empty($changes['change']&& is_array($changes['change'])) {
  1569.             foreach ($changes['change'as $sequence_name => $sequence{
  1570.                 $result $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']);
  1571.                 if (PEAR::isError($result)) {
  1572.                     return $result;
  1573.                 }
  1574.                 $result $this->createSequence($sequence_name$sequence);
  1575.                 if (PEAR::isError($result)) {
  1576.                     return $result;
  1577.                 }
  1578.                 $alterations++;
  1579.             }
  1580.         }
  1581.  
  1582.         return $alterations;
  1583.     }
  1584.  
  1585.     // }}}
  1586.     // {{{ alterDatabase()
  1587.  
  1588.     /**
  1589.      * Execute the necessary actions to implement the requested changes
  1590.      * in a database structure.
  1591.      *
  1592.      * @param array multi dimensional array that contains the current definition
  1593.      * @param array multi dimensional array that contains the previous definition
  1594.      * @param array associative array that contains the definition of the changes
  1595.      *               that are meant to be applied to the database structure.
  1596.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1597.      * @access public
  1598.      */
  1599.     function alterDatabase($current_definition$previous_definition$changes)
  1600.     {
  1601.         $alterations = 0;
  1602.         if (empty($changes)) {
  1603.             return $alterations;
  1604.         }
  1605.  
  1606.         $result $this->verifyAlterDatabase($changes);
  1607.         if (PEAR::isError($result)) {
  1608.             return $result;
  1609.         }
  1610.  
  1611.         if (!empty($current_definition['name'])) {
  1612.             $previous_database_name $this->db->setDatabase($current_definition['name']);
  1613.         }
  1614.  
  1615.         if (($support_transactions $this->db->supports('transactions'))
  1616.             && PEAR::isError($result $this->db->beginNestedTransaction())
  1617.         {
  1618.             return $result;
  1619.         }
  1620.  
  1621.         if (!empty($changes['tables']&& !empty($current_definition['tables'])) {
  1622.             $current_tables = isset($current_definition['tables']$current_definition['tables': array();
  1623.             $previous_tables = isset($previous_definition['tables']$previous_definition['tables': array();
  1624.             $result $this->alterDatabaseTables($current_tables$previous_tables$changes['tables']);
  1625.             if (is_numeric($result)) {
  1626.                 $alterations += $result;
  1627.             }
  1628.         }
  1629.  
  1630.         if (!PEAR::isError($result&& !empty($changes['sequences'])) {
  1631.             $current_sequences = isset($current_definition['sequences']$current_definition['sequences': array();
  1632.             $previous_sequences = isset($previous_definition['sequences']$previous_definition['sequences': array();
  1633.             $result $this->alterDatabaseSequences($current_sequences$previous_sequences$changes['sequences']);
  1634.             if (is_numeric($result)) {
  1635.                 $alterations += $result;
  1636.             }
  1637.         }
  1638.  
  1639.         if ($support_transactions{
  1640.             $res $this->db->completeNestedTransaction();
  1641.             if (PEAR::isError($res)) {
  1642.                 $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  1643.                     'Could not end transaction ('.
  1644.                     $res->getMessage().' ('.$res->getUserinfo().'))');
  1645.             }
  1646.         elseif (PEAR::isError($result&& $created_objects{
  1647.             $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  1648.                 'the requested database alterations were only partially implemented ('.
  1649.                 $result->getMessage().' ('.$result->getUserinfo().'))');
  1650.         }
  1651.  
  1652.         if (isset($previous_database_name)) {
  1653.             $this->db->setDatabase($previous_database_name);
  1654.         }
  1655.         return $result;
  1656.     }
  1657.  
  1658.     // }}}
  1659.     // {{{ dumpDatabaseChanges()
  1660.  
  1661.     /**
  1662.      * Dump the changes between two database definitions.
  1663.      *
  1664.      * @param array associative array that specifies the list of database
  1665.      *               definitions changes as returned by the _compareDefinitions
  1666.      *               manager class function.
  1667.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1668.      * @access public
  1669.      */
  1670.     function dumpDatabaseChanges($changes)
  1671.     {
  1672.         if (!empty($changes['tables'])) {
  1673.             if (!empty($changes['tables']['add']&& is_array($changes['tables']['add'])) {
  1674.                 foreach ($changes['tables']['add'as $table_name => $table{
  1675.                     $this->db->debug("$table_name:"__FUNCTION__);
  1676.                     $this->db->debug("\tAdded table '$table_name'"__FUNCTION__);
  1677.                 }
  1678.             }
  1679.             if (!empty($changes['tables']['remove']&& is_array($changes['tables']['remove'])) {
  1680.                 foreach ($changes['tables']['remove'as $table_name => $table{
  1681.                     $this->db->debug("$table_name:"__FUNCTION__);
  1682.                     $this->db->debug("\tRemoved table '$table_name'"__FUNCTION__);
  1683.                 }
  1684.             }
  1685.             if (!empty($changes['tables']['change']&& is_array($changes['tables']['change'])) {
  1686.                 foreach ($changes['tables']['change'as $table_name => $table{
  1687.                     if (array_key_exists('name'$table)) {
  1688.                         $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'"__FUNCTION__);
  1689.                     }
  1690.                     if (!empty($table['add']&& is_array($table['add'])) {
  1691.                         foreach ($table['add'as $field_name => $field{
  1692.                             $this->db->debug("\tAdded field '".$field_name."'"__FUNCTION__);
  1693.                         }
  1694.                     }
  1695.                     if (!empty($table['remove']&& is_array($table['remove'])) {
  1696.                         foreach ($table['remove'as $field_name => $field{
  1697.                             $this->db->debug("\tRemoved field '".$field_name."'"__FUNCTION__);
  1698.                         }
  1699.                     }
  1700.                     if (!empty($table['rename']&& is_array($table['rename'])) {
  1701.                         foreach ($table['rename'as $field_name => $field{
  1702.                             $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'"__FUNCTION__);
  1703.                         }
  1704.                     }
  1705.                     if (!empty($table['change']&& is_array($table['change'])) {
  1706.                         foreach ($table['change'as $field_name => $field{
  1707.                             $field $field['definition'];
  1708.                             if (array_key_exists('type'$field)) {
  1709.                                 $this->db->debug(
  1710.                                     "\tChanged field '$field_name' type to '".$field['type']."'"__FUNCTION__);
  1711.                             }
  1712.                             if (array_key_exists('unsigned'$field)) {
  1713.                                 $this->db->debug(
  1714.                                     "\tChanged field '$field_name' type to '".
  1715.                                     (!empty($field['unsigned']&& $field['unsigned''' 'not ')."unsigned'",
  1716.                                     __FUNCTION__);
  1717.                             }
  1718.                             if (array_key_exists('length'$field)) {
  1719.                                 $this->db->debug(
  1720.                                     "\tChanged field '$field_name' length to '".
  1721.                                     (!empty($field['length']$field['length']'no length')."'"__FUNCTION__);
  1722.                             }
  1723.                             if (array_key_exists('default'$field)) {
  1724.                                 $this->db->debug(
  1725.                                     "\tChanged field '$field_name' default to ".
  1726.                                     (isset($field['default']"'".$field['default']."'" 'NULL')__FUNCTION__);
  1727.                             }
  1728.                             if (array_key_exists('notnull'$field)) {
  1729.                                 $this->db->debug(
  1730.                                    "\tChanged field '$field_name' notnull to ".
  1731.                                     (!empty($field['notnull']&& $field['notnull''true' 'false'),
  1732.                                     __FUNCTION__
  1733.                                 );
  1734.                             }
  1735.                         }
  1736.                     }
  1737.                     if (!empty($table['indexes']&& is_array($table['indexes'])) {
  1738.                         if (!empty($table['indexes']['add']&& is_array($table['indexes']['add'])) {
  1739.                             foreach ($table['indexes']['add'as $index_name => $index{
  1740.                                 $this->db->debug("\tAdded index '".$index_name.
  1741.                                     "' of table '$table_name'"__FUNCTION__);
  1742.                             }
  1743.                         }
  1744.                         if (!empty($table['indexes']['remove']&& is_array($table['indexes']['remove'])) {
  1745.                             foreach ($table['indexes']['remove'as $index_name => $index{
  1746.                                 $this->db->debug("\tRemoved index '".$index_name.
  1747.                                     "' of table '$table_name'"__FUNCTION__);
  1748.                             }
  1749.                         }
  1750.                         if (!empty($table['indexes']['change']&& is_array($table['indexes']['change'])) {
  1751.                             foreach ($table['indexes']['change'as $index_name => $index{
  1752.                                 if (array_key_exists('name'$index)) {
  1753.                                     $this->db->debug(
  1754.                                         "\tRenamed index '".$index_name."' to '".$index['name'].
  1755.                                         "' on table '$table_name'"__FUNCTION__);
  1756.                                 }
  1757.                                 if (array_key_exists('unique'$index)) {
  1758.                                     $this->db->debug(
  1759.                                         "\tChanged index '".$index_name."' unique to '".
  1760.                                         !empty($index['unique'])."' on table '$table_name'"__FUNCTION__);
  1761.                                 }
  1762.                                 if (array_key_exists('primary'$index)) {
  1763.                                     $this->db->debug(
  1764.                                         "\tChanged index '".$index_name."' primary to '".
  1765.                                         !empty($index['primary'])."' on table '$table_name'"__FUNCTION__);
  1766.                                 }
  1767.                                 if (array_key_exists('change'$index)) {
  1768.                                     $this->db->debug("\tChanged index '".$index_name.
  1769.                                         "' on table '$table_name'"__FUNCTION__);
  1770.                                 }
  1771.                             }
  1772.                         }
  1773.                     }
  1774.                 }
  1775.             }
  1776.         }
  1777.         if (!empty($changes['sequences'])) {
  1778.             if (!empty($changes['sequences']['add']&& is_array($changes['sequences']['add'])) {
  1779.                 foreach ($changes['sequences']['add'as $sequence_name => $sequence{
  1780.                     $this->db->debug("$sequence_name:"__FUNCTION__);
  1781.                     $this->db->debug("\tAdded sequence '$sequence_name'"__FUNCTION__);
  1782.                 }
  1783.             }
  1784.             if (!empty($changes['sequences']['remove']&& is_array($changes['sequences']['remove'])) {
  1785.                 foreach ($changes['sequences']['remove'as $sequence_name => $sequence{
  1786.                     $this->db->debug("$sequence_name:"__FUNCTION__);
  1787.                     $this->db->debug("\tAdded sequence '$sequence_name'"__FUNCTION__);
  1788.                 }
  1789.             }
  1790.             if (!empty($changes['sequences']['change']&& is_array($changes['sequences']['change'])) {
  1791.                 foreach ($changes['sequences']['change'as $sequence_name => $sequence{
  1792.                     if (array_key_exists('name'$sequence)) {
  1793.                         $this->db->debug(
  1794.                             "\tRenamed sequence '$sequence_name' to '".
  1795.                             $sequence['name']."'"__FUNCTION__);
  1796.                     }
  1797.                     if (!empty($sequence['change']&& is_array($sequence['change'])) {
  1798.                         foreach ($sequence['change'as $sequence_name => $sequence{
  1799.                             if (array_key_exists('start'$sequence)) {
  1800.                                 $this->db->debug(
  1801.                                     "\tChanged sequence '$sequence_name' start to '".
  1802.                                     $sequence['start']."'"__FUNCTION__);
  1803.                             }
  1804.                         }
  1805.                     }
  1806.                 }
  1807.             }
  1808.         }
  1809.         return MDB2_OK;
  1810.     }
  1811.  
  1812.     // }}}
  1813.     // {{{ dumpDatabase()
  1814.  
  1815.     /**
  1816.      * Dump a previously parsed database structure in the Metabase schema
  1817.      * XML based format suitable for the Metabase parser. This function
  1818.      * may optionally dump the database definition with initialization
  1819.      * commands that specify the data that is currently present in the tables.
  1820.      *
  1821.      * @param array multi dimensional array that contains the current definition
  1822.      * @param array associative array that takes pairs of tag
  1823.      *  names and values that define dump options.
  1824.      *                  <pre>array (
  1825.      *                      'output_mode'    =>    String
  1826.      *                          'file' :   dump into a file
  1827.      *                          default:   dump using a function
  1828.      *                      'output'        =>    String
  1829.      *                          depending on the 'Output_Mode'
  1830.      *                                   name of the file
  1831.      *                                   name of the function
  1832.      *                      'end_of_line'        =>    String
  1833.      *                          end of line delimiter that should be used
  1834.      *                          default: "\n"
  1835.      *                  );</pre>
  1836.      * @param int that determines what data to dump
  1837.      *               + MDB2_SCHEMA_DUMP_ALL       : the entire db
  1838.      *               + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
  1839.      *               + MDB2_SCHEMA_DUMP_CONTENT   : only the content of the db
  1840.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1841.      * @access public
  1842.      */
  1843.     function dumpDatabase($database_definition$arguments$dump = MDB2_SCHEMA_DUMP_ALL)
  1844.     {
  1845.         $class_name $this->options['writer'];
  1846.         $result = MDB2::loadClass($class_name$this->db->getOption('debug'));
  1847.         if (PEAR::isError($result)) {
  1848.             return $result;
  1849.         }
  1850.  
  1851.         // get initialization data
  1852.         if (isset($database_definition['tables']&& is_array($database_definition['tables'])
  1853.             && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT
  1854.         {
  1855.             foreach ($database_definition['tables'as $table_name => $table{
  1856.                 $fields = array();
  1857.                 $types = array();
  1858.                 foreach ($table['fields'as $field_name => $field{
  1859.                     $fields[$field_name$field['type'];
  1860.                 }
  1861.                 $query 'SELECT '.implode(', 'array_keys($fields)).' FROM '.$table_name;
  1862.                 $data $this->db->queryAll($query$typesMDB2_FETCHMODE_ASSOC);
  1863.                 if (PEAR::isError($data)) {
  1864.                     return $data;
  1865.                 }
  1866.                 if (!empty($data)) {
  1867.                     $initialization = array();
  1868.                     $lob_buffer_length $this->db->getOption('lob_buffer_length');
  1869.                     foreach ($data as $row{
  1870.                         foreach($row as $key => $lob{
  1871.                             if (is_resource($lob)) {
  1872.                                 $value '';
  1873.                                 while (!feof($lob)) {
  1874.                                     $value.= fread($lob$lob_buffer_length);
  1875.                                 }
  1876.                                 $row[$key$value;
  1877.                             }
  1878.                         }
  1879.                         $initialization[= array('type' => 'insert''fields' => $row);
  1880.                     }
  1881.                     $database_definition['tables'][$table_name]['initialization'$initialization;
  1882.                 }
  1883.             }
  1884.         }
  1885.  
  1886.         $writer =new $class_name($this->options['valid_types']);
  1887.         return $writer->dumpDatabase($database_definition$arguments$dump);
  1888.     }
  1889.  
  1890.     // }}}
  1891.     // {{{ writeInitialization()
  1892.  
  1893.     /**
  1894.      * Write initialization and sequences
  1895.      *
  1896.      * @param string|array data file or data array
  1897.      * @param string|array structure file or array
  1898.      * @param array associative array that is passed to the argument
  1899.      *  of the same name to the parseDatabaseDefinitionFile function. (there third
  1900.      *  param)
  1901.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1902.      * @access public
  1903.      */
  1904.     function writeInitialization($data$structure = false$variables = array())
  1905.     {
  1906.         if ($structure{
  1907.             $structure $this->parseDatabaseDefinition($structurefalse$variables);
  1908.             if (PEAR::isError($structure)) {
  1909.                 return $structure;
  1910.             }
  1911.         }
  1912.  
  1913.         $data $this->parseDatabaseDefinition($datafalse$variablesfalse$structure);
  1914.         if (PEAR::isError($data)) {
  1915.             return $data;
  1916.         }
  1917.  
  1918.         $previous_database_name = null;
  1919.         if (!empty($data['name'])) {
  1920.             $previous_database_name $this->db->setDatabase($data['name']);
  1921.         elseif(!empty($structure['name'])) {
  1922.             $previous_database_name $this->db->setDatabase($structure['name']);
  1923.         }
  1924.  
  1925.         if (!empty($data['tables']&& is_array($data['tables'])) {
  1926.             foreach ($data['tables'as $table_name => $table{
  1927.                 if (empty($table['initialization'])) {
  1928.                     continue;
  1929.                 }
  1930.                 $result $this->initializeTable($table_name$table);
  1931.                 if (PEAR::isError($result)) {
  1932.                     return $result;
  1933.                 }
  1934.             }
  1935.         }
  1936.  
  1937.         if (!empty($structure['sequences']&& is_array($structure['sequences'])) {
  1938.             foreach ($structure['sequences'as $sequence_name => $sequence{
  1939.                 if (isset($data['sequences'][$sequence_name])
  1940.                     || !isset($sequence['on']['table'])
  1941.                     || !isset($data['tables'][$sequence['on']['table']])
  1942.                 {
  1943.                     continue;
  1944.                 }
  1945.                 $result $this->createSequence($sequence_name$sequencetrue);
  1946.                 if (PEAR::isError($result)) {
  1947.                     return $result;
  1948.                 }
  1949.             }
  1950.         }
  1951.         if (!empty($data['sequences']&& is_array($data['sequences'])) {
  1952.             foreach ($data['sequences'as $sequence_name => $sequence{
  1953.                 $result $this->createSequence($sequence_name$sequencetrue);
  1954.                 if (PEAR::isError($result)) {
  1955.                     return $result;
  1956.                 }
  1957.             }
  1958.         }
  1959.  
  1960.         if (isset($previous_database_name)) {
  1961.             $this->db->setDatabase($previous_database_name);
  1962.         }
  1963.  
  1964.         return MDB2_OK;
  1965.     }
  1966.  
  1967.     // }}}
  1968.     // {{{ updateDatabase()
  1969.  
  1970.     /**
  1971.      * Compare the correspondent files of two versions of a database schema
  1972.      * definition: the previously installed and the one that defines the schema
  1973.      * that is meant to update the database.
  1974.      * If the specified previous definition file does not exist, this function
  1975.      * will create the database from the definition specified in the current
  1976.      * schema file.
  1977.      * If both files exist, the function assumes that the database was previously
  1978.      * installed based on the previous schema file and will update it by just
  1979.      * applying the changes.
  1980.      * If this function succeeds, the contents of the current schema file are
  1981.      * copied to replace the previous schema file contents. Any subsequent schema
  1982.      * changes should only be done on the file specified by the $current_schema_file
  1983.      * to let this function make a consistent evaluation of the exact changes that
  1984.      * need to be applied.
  1985.      *
  1986.      * @param string|arrayfilename or array of the updated database schema definition.
  1987.      * @param string|arrayfilename or array of the previously installed database schema definition.
  1988.      * @param array associative array that is passed to the argument of the same
  1989.      *               name to the parseDatabaseDefinitionFile function. (there third param)
  1990.      * @param bool determines if the disable_query option should be set to true
  1991.      *               for the alterDatabase() or createDatabase() call
  1992.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1993.      * @access public
  1994.      */
  1995.     function updateDatabase($current_schema$previous_schema = false
  1996.         $variables = array()$disable_query = false)
  1997.     {
  1998.         $current_definition $this->parseDatabaseDefinition(
  1999.             $current_schemafalse$variables$this->options['fail_on_invalid_names']
  2000.         );
  2001.         if (PEAR::isError($current_definition)) {
  2002.             return $current_definition;
  2003.         }
  2004.  
  2005.         $previous_definition = false;
  2006.         if ($previous_schema{
  2007.             $previous_definition $this->parseDatabaseDefinition(
  2008.                 $previous_schematrue$variables$this->options['fail_on_invalid_names']
  2009.             );
  2010.             if (PEAR::isError($previous_definition)) {
  2011.                 return $previous_definition;
  2012.             }
  2013.         }
  2014.  
  2015.         if ($previous_definition{
  2016.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  2017.             $this->db->expectError($errorcodes);
  2018.             $databases $this->db->manager->listDatabases();
  2019.             $this->db->popExpect();
  2020.             if (PEAR::isError($databases)) {
  2021.                 if (!MDB2::isError($databases$errorcodes)) {
  2022.                     return $databases;
  2023.                 }
  2024.             elseif (!is_array($databases||
  2025.                 !in_array($current_definition['name']$databases)
  2026.             {
  2027.                 return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  2028.                     'database to update does not exist: '.$current_definition['name']);
  2029.             }
  2030.  
  2031.             $changes $this->compareDefinitions($current_definition$previous_definition);
  2032.             if (PEAR::isError($changes)) {
  2033.                 return $changes;
  2034.             }
  2035.  
  2036.             if (is_array($changes)) {
  2037.                 $this->db->setOption('disable_query'$disable_query);
  2038.                 $result $this->alterDatabase($current_definition$previous_definition$changes);
  2039.                 $this->db->setOption('disable_query'false);
  2040.                 if (PEAR::isError($result)) {
  2041.                     return $result;
  2042.                 }
  2043.                 $copy = true;
  2044.                 if ($this->db->options['debug']{
  2045.                     $result $this->dumpDatabaseChanges($changes);
  2046.                     if (PEAR::isError($result)) {
  2047.                         return $result;
  2048.                     }
  2049.                 }
  2050.             }
  2051.         else {
  2052.             $this->db->setOption('disable_query'$disable_query);
  2053.             $result $this->createDatabase($current_definition);
  2054.             $this->db->setOption('disable_query'false);
  2055.             if (PEAR::isError($result)) {
  2056.                 return $result;
  2057.             }
  2058.         }
  2059.  
  2060.         if (!$disable_query
  2061.             && is_string($previous_schema&& is_string($current_schema)
  2062.             && !copy($current_schema$previous_schema)
  2063.         {
  2064.             return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  2065.                 'Could not copy the new database definition file to the current file');
  2066.         }
  2067.  
  2068.         return MDB2_OK;
  2069.     }
  2070.     // }}}
  2071.     // {{{ errorMessage()
  2072.  
  2073.     /**
  2074.      * Return a textual error message for a MDB2 error code
  2075.      *
  2076.      * @param   int|arrayinteger error code,
  2077.      *                      <code>null</code> to get the current error code-message map,
  2078.      *                     or an array with a new error code-message map
  2079.      * @return  string  error message, or false if the error code was not recognized
  2080.      * @access public
  2081.      */
  2082.     function errorMessage($value = null)
  2083.     {
  2084.         static $errorMessages;
  2085.         if (is_array($value)) {
  2086.             $errorMessages $value;
  2087.             return MDB2_OK;
  2088.         elseif (!isset($errorMessages)) {
  2089.             $errorMessages = array(
  2090.                 MDB2_SCHEMA_ERROR              => 'unknown error',
  2091.                 MDB2_SCHEMA_ERROR_PARSE        => 'schema parse error',
  2092.                 MDB2_SCHEMA_ERROR_INVALID      => 'invalid',
  2093.                 MDB2_SCHEMA_ERROR_UNSUPPORTED  => 'not supported',
  2094.                 MDB2_SCHEMA_ERROR_NOT_CAPABLE  => 'not capable',
  2095.                 MDB2_SCHEMA_ERROR_NODBSELECTED => 'no database selected',
  2096.             );
  2097.         }
  2098.  
  2099.         if (is_null($value)) {
  2100.             return $errorMessages;
  2101.         }
  2102.  
  2103.         if (PEAR::isError($value)) {
  2104.             $value $value->getCode();
  2105.         }
  2106.  
  2107.         return !empty($errorMessages[$value]?
  2108.            $errorMessages[$value$errorMessages[MDB2_SCHEMA_ERROR];
  2109.     }
  2110.  
  2111.     // }}}
  2112.     // {{{ raiseError()
  2113.  
  2114.     /**
  2115.      * This method is used to communicate an error and invoke error
  2116.      * callbacks etc.  Basically a wrapper for PEAR::raiseError
  2117.      * without the message string.
  2118.      *
  2119.      * @param int|PEAR_Error integer error code or and PEAR_Error instance
  2120.      * @param int      error mode, see PEAR_Error docs
  2121.      *
  2122.      *                  error level (E_USER_NOTICE etc).  If error mode is
  2123.      *                  PEAR_ERROR_CALLBACK, this is the callback function,
  2124.      *                  either as a function name, or as an array of an
  2125.      *                  object and method name.  For other error modes this
  2126.      *                  parameter is ignored.
  2127.      * @param array    Options, depending on the mode, @see PEAR::setErrorHandling
  2128.      * @param string   Extra debug information.  Defaults to the last
  2129.      *                  query and native error code.
  2130.      * @return object  PEAR error object
  2131.      * @access  public
  2132.      * @see PEAR_Error
  2133.      */
  2134.     function &raiseError($code = null$mode = null$options = null$userinfo = null)
  2135.     {
  2136.         $err =PEAR::raiseError(null$code$mode$options$userinfo'MDB2_Schema_Error'true);
  2137.         return $err;
  2138.     }
  2139.  
  2140.     // }}}
  2141.     // {{{ isError()
  2142.  
  2143.     /**
  2144.      * Tell whether a value is an MDB2_Schema error.
  2145.      *
  2146.      * @param   mixed the value to test
  2147.      * @param   int   if $data is an error object, return true only if $code is
  2148.                       a string and $db->getMessage() == $code or
  2149.      *                 $code is an integer and $db->getCode() == $code
  2150.      * @return  bool  true if parameter is an error
  2151.      * @access  public
  2152.      */
  2153.     function isError($data$code = null)
  2154.     {
  2155.         if (is_a($data'MDB2_Schema_Error')) {
  2156.             if (is_null($code)) {
  2157.                 return true;
  2158.             elseif (is_string($code)) {
  2159.                 return $data->getMessage(=== $code;
  2160.             else {
  2161.                 $code = (array)$code;
  2162.                 return in_array($data->getCode()$code);
  2163.             }
  2164.         }
  2165.         return false;
  2166.     }
  2167.  
  2168.     // }}}
  2169. }
  2170.  
  2171. /**
  2172.  * MDB2_Schema_Error implements a class for reporting portable database error
  2173.  * messages.
  2174.  *
  2175.  * @package MDB2_Schema
  2176.  * @category Database
  2177.  * @author  Stig Bakken <ssb@fast.no>
  2178.  */
  2179. class MDB2_Schema_Error extends PEAR_Error
  2180. {
  2181.     /**
  2182.      * MDB2_Schema_Error constructor.
  2183.      *
  2184.      * @param mixed     error code, or string with error message.
  2185.      * @param int       what 'error mode' to operate in
  2186.      * @param int       what error level to use for $mode & PEAR_ERROR_TRIGGER
  2187.      * @param mixed     additional debug info, such as the last query
  2188.      * @access  public
  2189.      */
  2190.     function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR$mode = PEAR_ERROR_RETURN,
  2191.               $level = E_USER_NOTICE$debuginfo = null)
  2192.     {
  2193.         $this->PEAR_Error('MDB2_Schema Error: ' MDB2_Schema::errorMessage($code)$code,
  2194.             $mode$level$debuginfo);
  2195.     }
  2196. }
  2197. ?>

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