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.116 2007/08/20 03:15:41 ifeghali 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.  * If you add an error code here, make sure you also add a textual
  56.  * version of it in MDB2_Schema::errorMessage().
  57.  */
  58.  
  59. define('MDB2_SCHEMA_ERROR',                                         -1);
  60. define('MDB2_SCHEMA_ERROR_PARSE',                                   -2);
  61. define('MDB2_SCHEMA_ERROR_VALIDATE',                                -3);
  62. define('MDB2_SCHEMA_ERROR_UNSUPPORTED',                             -4);    // Driver does not support this function
  63. define('MDB2_SCHEMA_ERROR_INVALID',                                 -5);    // Invalid attribute value
  64. define('MDB2_SCHEMA_ERROR_WRITER',                                  -6);
  65.  
  66. /**
  67.  * The database manager is a class that provides a set of database
  68.  * management services like installing, altering and dumping the data
  69.  * structures of databases.
  70.  *
  71.  * @package MDB2_Schema
  72.  * @category Database
  73.  * @author  Lukas Smith <smith@pooteeweet.org>
  74.  */
  75. class MDB2_Schema extends PEAR
  76. {
  77.     // {{{ properties
  78.  
  79.     var $db;
  80.  
  81.     var $warnings = array();
  82.  
  83.     var $options = array(
  84.         'fail_on_invalid_names' => true,
  85.         'dtd_file' => false,
  86.         'valid_types' => array(),
  87.         'force_defaults' => true,
  88.         'parser' => 'MDB2_Schema_Parser',
  89.         'writer' => 'MDB2_Schema_Writer',
  90.         'validate' => 'MDB2_Schema_Validate'
  91.     );
  92.  
  93.     // }}}
  94.     // {{{ apiVersion()
  95.  
  96.     /**
  97.      * Return the MDB2 API version
  98.      *
  99.      * @return string  the MDB2 API version number
  100.      * @access public
  101.      */
  102.     function apiVersion()
  103.     {
  104.         return '0.4.3';
  105.     }
  106.  
  107.     // }}}
  108.     // {{{ arrayMergeClobber()
  109.  
  110.     /**
  111.      * Clobbers two arrays together
  112.      *
  113.      * @param  array        array that should be clobbered
  114.      * @param  array        array that should be clobbered
  115.      * @return array|false array on success and false on error
  116.      *
  117.      * @access public
  118.      * @author kc@hireability.com
  119.      */
  120.     function arrayMergeClobber($a1$a2)
  121.     {
  122.         if (!is_array($a1|| !is_array($a2)) {
  123.             return false;
  124.         }
  125.         foreach ($a2 as $key => $val{
  126.             if (is_array($val&& array_key_exists($key$a1&& is_array($a1[$key])) {
  127.                 $a1[$keyMDB2_Schema::arrayMergeClobber($a1[$key]$val);
  128.             else {
  129.                 $a1[$key$val;
  130.             }
  131.         }
  132.         return $a1;
  133.     }
  134.  
  135.     // }}}
  136.     // {{{ resetWarnings()
  137.  
  138.     /**
  139.      * reset the warning array
  140.      *
  141.      * @access public
  142.      */
  143.     function resetWarnings()
  144.     {
  145.         $this->warnings = array();
  146.     }
  147.  
  148.     // }}}
  149.     // {{{ getWarnings()
  150.  
  151.     /**
  152.      * Get all warnings in reverse order
  153.      *
  154.      * This means that the last warning is the first element in the array
  155.      *
  156.      * @return array with warnings
  157.      * @access public
  158.      * @see resetWarnings()
  159.      */
  160.     function getWarnings()
  161.     {
  162.         return array_reverse($this->warnings);
  163.     }
  164.  
  165.     // }}}
  166.     // {{{ setOption()
  167.  
  168.     /**
  169.      * Sets the option for the db class
  170.      *
  171.      * @param string option name
  172.      * @param mixed value for the option
  173.      * @return bool|MDB2_ErrorMDB2_OK or error object
  174.      * @access public
  175.      */
  176.     function setOption($option$value)
  177.     {
  178.         if (isset($this->options[$option])) {
  179.             if (is_null($value)) {
  180.                 return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  181.                     'may not set an option to value null');
  182.             }
  183.             $this->options[$option$value;
  184.             return MDB2_OK;
  185.         }
  186.         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  187.             "unknown option $option");
  188.     }
  189.  
  190.     // }}}
  191.     // {{{ getOption()
  192.  
  193.     /**
  194.      * returns the value of an option
  195.      *
  196.      * @param string option name
  197.      * @return mixed the option value or error object
  198.      * @access public
  199.      */
  200.     function getOption($option)
  201.     {
  202.         if (isset($this->options[$option])) {
  203.             return $this->options[$option];
  204.         }
  205.         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED,
  206.             nullnull"unknown option $option");
  207.     }
  208.  
  209.     // }}}
  210.     // {{{ factory()
  211.  
  212.     /**
  213.      * Create a new MDB2 object for the specified database type
  214.      * type
  215.      *
  216.      * @param string|array|MDB2_Driver_Common  'data source name', see the
  217.      *              @see MDB2::parseDSN method for a description of the dsn format.
  218.      *               Can also be specified as an array of the
  219.      *               format returned by @see MDB2::parseDSN.
  220.      *               Finally you can also pass an existing db object to be used.
  221.      * @param array An associative array of option names and their values.
  222.      * @return bool|MDB2_ErrorMDB2_OK or error object
  223.      * @access public
  224.      * @see     MDB2::parseDSN
  225.      */
  226.     function &factory(&$db$options = array())
  227.     {
  228.         $obj =new MDB2_Schema();
  229.         $result $obj->connect($db$options);
  230.         if (PEAR::isError($result)) {
  231.             return $result;
  232.         }
  233.         return $obj;
  234.     }
  235.  
  236.     // }}}
  237.     // {{{ connect()
  238.  
  239.     /**
  240.      * Create a new MDB2 connection object and connect to the specified
  241.      * database
  242.      *
  243.      * @param string|array|MDB2_Driver_Common  'data source name', see the
  244.      *              @see MDB2::parseDSN method for a description of the dsn format.
  245.      *               Can also be specified as an array of the
  246.      *               format returned by @see MDB2::parseDSN.
  247.      *               Finally you can also pass an existing db object to be used.
  248.      * @param array An associative array of option names and their values.
  249.      * @return bool|MDB2_ErrorMDB2_OK or error object
  250.      * @access public
  251.      * @see    MDB2::parseDSN
  252.      */
  253.     function connect(&$db$options = array())
  254.     {
  255.         $db_options = array();
  256.         if (is_array($options)) {
  257.             foreach ($options as $option => $value{
  258.                 if (array_key_exists($option$this->options)) {
  259.                     $result $this->setOption($option$value);
  260.                     if (PEAR::isError($result)) {
  261.                         return $result;
  262.                     }
  263.                 else {
  264.                     $db_options[$option$value;
  265.                 }
  266.             }
  267.         }
  268.         $this->disconnect();
  269.         if (!MDB2::isConnection($db)) {
  270.             $db =MDB2::factory($db$db_options);
  271.         }
  272.         if (PEAR::isError($db)) {
  273.             return $db;
  274.         }
  275.  
  276.         $this->db =$db;
  277.         $this->db->loadModule('Datatype');
  278.         $this->db->loadModule('Manager');
  279.         $this->db->loadModule('Reverse');
  280.         $this->db->loadModule('Function');
  281.         if (empty($this->options['valid_types'])) {
  282.             $this->options['valid_types'$this->db->datatype->getValidTypes();
  283.         }
  284.  
  285.         return MDB2_OK;
  286.     }
  287.  
  288.     // }}}
  289.     // {{{ disconnect()
  290.  
  291.     /**
  292.      * Log out and disconnect from the database.
  293.      *
  294.      * @access public
  295.      */
  296.     function disconnect()
  297.     {
  298.         if (MDB2::isConnection($this->db)) {
  299.             $this->db->disconnect();
  300.             unset($this->db);
  301.         }
  302.     }
  303.  
  304.     // }}}
  305.     // {{{ parseDatabaseDefinition()
  306.  
  307.     /**
  308.      * Parse a database definition from a file or an array
  309.      *
  310.      * @param string|arraythe database schema array or file name
  311.      * @param bool if non readable files should be skipped
  312.      * @param array associative array that the defines the text string values
  313.      *               that are meant to be used to replace the variables that are
  314.      *               used in the schema description.
  315.      * @param bool make function fail on invalid names
  316.      * @param array database structure definition
  317.      * @access public
  318.      */
  319.     function parseDatabaseDefinition($schema$skip_unreadable = false$variables = array(),
  320.         $fail_on_invalid_names = true$structure = false)
  321.     {
  322.         $database_definition = false;
  323.         if (is_string($schema)) {
  324.             // if $schema is not readable then we just skip it
  325.             // and simply copy the $current_schema file to that file name
  326.             if (is_readable($schema)) {
  327.                 $database_definition $this->parseDatabaseDefinitionFile(
  328.                     $schema$variables$fail_on_invalid_names$structure
  329.                 );
  330.             }
  331.         elseif (is_array($schema)) {
  332.             $database_definition $schema;
  333.         }
  334.         if (!$database_definition && !$skip_unreadable{
  335.             $database_definition $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  336.                 'invalid data type of schema or unreadable data source');
  337.         }
  338.         return $database_definition;
  339.     }
  340.  
  341.     // }}}
  342.     // {{{ parseDatabaseDefinitionFile()
  343.  
  344.     /**
  345.      * Parse a database definition file by creating a schema format
  346.      * parser object and passing the file contents as parser input data stream.
  347.      *
  348.      * @param string the database schema file.
  349.      * @param array associative array that the defines the text string values
  350.      *               that are meant to be used to replace the variables that are
  351.      *               used in the schema description.
  352.      * @param bool make function fail on invalid names
  353.      * @param array database structure definition
  354.      * @access public
  355.      */
  356.     function parseDatabaseDefinitionFile($input_file$variables = array(),
  357.         $fail_on_invalid_names = true$structure = false)
  358.     {
  359.         $dtd_file $this->options['dtd_file'];
  360.         if ($dtd_file{
  361.             require_once 'XML/DTD/XmlValidator.php';
  362.             $dtd =new XML_DTD_XmlValidator;
  363.             if (!$dtd->isValid($dtd_file$input_file)) {
  364.                 return $this->raiseError(MDB2_SCHEMA_ERROR_PARSEnullnull$dtd->getMessage());
  365.             }
  366.         }
  367.  
  368.         $class_name $this->options['parser'];
  369.         $result = MDB2::loadClass($class_name$this->db->getOption('debug'));
  370.         if (PEAR::isError($result)) {
  371.             return $result;
  372.         }
  373.  
  374.         $parser =new $class_name($variables$fail_on_invalid_names$structure$this->options['valid_types']$this->options['force_defaults']);
  375.         $result $parser->setInputFile($input_file);
  376.         if (PEAR::isError($result)) {
  377.             return $result;
  378.         }
  379.  
  380.         $result $parser->parse();
  381.         if (PEAR::isError($result)) {
  382.             return $result;
  383.         }
  384.         if (PEAR::isError($parser->error)) {
  385.             return $parser->error;
  386.         }
  387.  
  388.         return $parser->database_definition;
  389.     }
  390.  
  391.     // }}}
  392.     // {{{ getDefinitionFromDatabase()
  393.  
  394.     /**
  395.      * Attempt to reverse engineer a schema structure from an existing MDB2
  396.      * This method can be used if no xml schema file exists yet.
  397.      * The resulting xml schema file may need some manual adjustments.
  398.      *
  399.      * @return array|MDB2_Errorarray with definition or error object
  400.      * @access public
  401.      */
  402.     function getDefinitionFromDatabase()
  403.     {
  404.         $database $this->db->database_name;
  405.         if (empty($database)) {
  406.             return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  407.                 'it was not specified a valid database name');
  408.         }
  409.  
  410.         $class_name $this->options['validate'];
  411.         $result = MDB2::loadClass($class_name$this->db->getOption('debug'));
  412.         if (PEAR::isError($result)) {
  413.             return $result;
  414.         }
  415.  
  416.         $val =new $class_name($this->options['fail_on_invalid_names']$this->options['valid_types']$this->options['force_defaults']);
  417.  
  418.         $database_definition = array(
  419.             'name' => $database,
  420.             'create' => true,
  421.             'overwrite' => false,
  422.             'description' => '',
  423.             'comments' => '',
  424.             'tables' => array(),
  425.             'sequences' => array(),
  426.         );
  427.  
  428.         $tables $this->db->manager->listTables();
  429.         if (PEAR::isError($tables)) {
  430.             return $tables;
  431.         }
  432.  
  433.         foreach ($tables as $table_name{
  434.             $fields $this->db->manager->listTableFields($table_name);
  435.             if (PEAR::isError($fields)) {
  436.                 return $fields;
  437.             }
  438.  
  439.             $database_definition['tables'][$table_name= array(
  440.                 'was' => '',
  441.                 'description' => '',
  442.                 'comments' => '',
  443.                 'fields' => array(),
  444.                 'indexes' => array(),
  445.                 'constraints' => array(),
  446.                 'initialization' => array()
  447.             );
  448.  
  449.             $table_definition =$database_definition['tables'][$table_name];
  450.             foreach ($fields as $field_name{
  451.                 $definition $this->db->reverse->getTableFieldDefinition($table_name$field_name);
  452.                 if (PEAR::isError($definition)) {
  453.                     return $definition;
  454.                 }
  455.  
  456.                 if (!empty($definition[0]['autoincrement'])) {
  457.                     $definition[0]['default''0';
  458.                 }
  459.                 $table_definition['fields'][$field_name$definition[0];
  460.                 $field_choices count($definition);
  461.                 if ($field_choices > 1{
  462.                     $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): ";
  463.                     $field_choice_cnt = 1;
  464.                     $table_definition['fields'][$field_name]['choices'= array();
  465.                     foreach ($definition as $field_choice{
  466.                         $table_definition['fields'][$field_name]['choices'][$field_choice;
  467.                         $warning.= 'choice #'.($field_choice_cnt).': '.serialize($field_choice);
  468.                         $field_choice_cnt++;
  469.                     }
  470.                     $this->warnings[$warning;
  471.                 }
  472.  
  473.                 /**
  474.                  * The first parameter is used to verify if there are duplicated
  475.                  * fields which we can guarantee that won't happen when reverse engineering
  476.                  */
  477.                 $result $val->validateField(array()$table_definition['fields'][$field_name]$field_name);
  478.                 if (PEAR::isError($result)) {
  479.                     return $result;
  480.                 }
  481.             }
  482.  
  483.             $keys = array();
  484.             $indexes $this->db->manager->listTableIndexes($table_name);
  485.             if (PEAR::isError($indexes)) {
  486.                 return $indexes;
  487.             }
  488.  
  489.             if (is_array($indexes)) {
  490.                 foreach ($indexes as $index_name{
  491.                     $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  492.                     $definition $this->db->reverse->getTableIndexDefinition($table_name$index_name);
  493.                     $this->db->popExpect();
  494.                     if (PEAR::isError($definition)) {
  495.                         if (PEAR::isError($definitionMDB2_ERROR_NOT_FOUND)) {
  496.                             continue;
  497.                         }
  498.                         return $definition;
  499.                     }
  500.  
  501.                     $keys[$index_name$definition;
  502.                 }
  503.             }
  504.  
  505.             $constraints $this->db->manager->listTableConstraints($table_name);
  506.             if (PEAR::isError($constraints)) {
  507.                 return $constraints;
  508.             }
  509.  
  510.             if (is_array($constraints)) {
  511.                 foreach ($constraints as $constraint_name{
  512.                     $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  513.                     $definition $this->db->reverse->getTableConstraintDefinition($table_name$constraint_name);
  514.                     $this->db->popExpect();
  515.                     if (PEAR::isError($definition)) {
  516.                         if (PEAR::isError($definitionMDB2_ERROR_NOT_FOUND)) {
  517.                             continue;
  518.                         }
  519.                         return $definition;
  520.                     }
  521.  
  522.                     $keys[$constraint_name$definition;
  523.                 }
  524.             }
  525.  
  526.             foreach ($keys as $key_name => $definition{
  527.                 if (array_key_exists('foreign'$definition)
  528.                     && $definition['foreign']
  529.                 {
  530.                     /**
  531.                      * The first parameter is used to verify if there are duplicated
  532.                      * foreign keys which we can guarantee that won't happen when reverse engineering
  533.                      */
  534.                     $result $val->validateConstraint(array()$definition$key_name);
  535.                     if (PEAR::isError($result)) {
  536.                         return $result;
  537.                     }
  538.  
  539.                     foreach ($definition['fields'as $field_name => $field{
  540.                         /**
  541.                          * The first parameter is used to verify if there are duplicated
  542.                          * referencing fields which we can guarantee that won't happen when reverse engineering
  543.                          */
  544.                         $result $val->validateConstraintField(array()$field_name);
  545.                         if (PEAR::isError($result)) {
  546.                             return $result;
  547.                         }
  548.  
  549.                         $definition['fields'][$field_name'';
  550.                     }
  551.  
  552.                     foreach ($definition['references']['fields'as $field_name => $field{
  553.                         /**
  554.                          * The first parameter is used to verify if there are duplicated
  555.                          * referenced fields which we can guarantee that won't happen when reverse engineering
  556.                          */
  557.                         $result $val->validateConstraintReferencedField(array()$field_name);
  558.                         if (PEAR::isError($result)) {
  559.                             return $result;
  560.                         }
  561.  
  562.                         $definition['references']['fields'][$field_name'';
  563.                     }
  564.  
  565.                     $table_definition['constraints'][$key_name$definition;
  566.                 else {
  567.                     /**
  568.                      * The first parameter is used to verify if there are duplicated
  569.                      * indices which we can guarantee that won't happen when reverse engineering
  570.                      */
  571.                     $result $val->validateIndex(array()$definition$key_name);
  572.                     if (PEAR::isError($result)) {
  573.                         return $result;
  574.                     }
  575.  
  576.                     foreach ($definition['fields'as $field_name => $field{
  577.                         /**
  578.                          * The first parameter is used to verify if there are duplicated
  579.                          * index fields which we can guarantee that won't happen when reverse engineering
  580.                          */
  581.                         $result $val->validateIndexField(array()$field$field_name);
  582.                         if (PEAR::isError($result)) {
  583.                             return $result;
  584.                         }
  585.  
  586.                         $definition['fields'][$field_name$field;
  587.                     }
  588.  
  589.                     $table_definition['indexes'][$key_name$definition;
  590.                 }
  591.             }
  592.  
  593.             /**
  594.              * The first parameter is used to verify if there are duplicated
  595.              * tables which we can guarantee that won't happen when reverse engineering
  596.              */
  597.             $result $val->validateTable(array()$table_definition$table_name);
  598.             if (PEAR::isError($result)) {
  599.                 return $result;
  600.             }
  601.             
  602.         }
  603.  
  604.         $sequences $this->db->manager->listSequences();
  605.         if (PEAR::isError($sequences)) {
  606.             return $sequences;
  607.         }
  608.  
  609.         if (is_array($sequences)) {
  610.             foreach ($sequences as $sequence_name{
  611.                 $definition $this->db->reverse->getSequenceDefinition($sequence_name);
  612.                 if (PEAR::isError($definition)) {
  613.                     return $definition;
  614.                 }
  615.                 if (isset($database_definition['tables'][$sequence_name])
  616.                     && isset($database_definition['tables'][$sequence_name]['indexes'])
  617.                 {
  618.                     foreach ($database_definition['tables'][$sequence_name]['indexes'as $index{
  619.                         if (isset($index['primary']&& $index['primary']
  620.                             && count($index['fields'== 1)
  621.                         {
  622.                             $definition['on'= array(
  623.                                 'table' => $sequence_name,
  624.                                 'field' => key($index['fields']),
  625.                             );
  626.                             break;
  627.                         }
  628.                     }
  629.                 }
  630.  
  631.                 /**
  632.                  * The first parameter is used to verify if there are duplicated
  633.                  * sequences which we can guarantee that won't happen when reverse engineering
  634.                  */
  635.                 $result $val->validateSequence(array()$definition$sequence_name);
  636.                 if (PEAR::isError($result)) {
  637.                     return $result;
  638.                 }
  639.  
  640.                 $database_definition['sequences'][$sequence_name$definition;
  641.             }
  642.         }
  643.  
  644.         $result $val->validateDatabase($database_definition);
  645.         if (PEAR::isError($result)) {
  646.             return $result;
  647.         }
  648.  
  649.         return $database_definition;
  650.     }
  651.  
  652.     // }}}
  653.     // {{{ createTableIndexes()
  654.  
  655.     /**
  656.      * A method to create indexes for an existing table
  657.      *
  658.      * @param string  Name of the table
  659.      * @param array   An array of indexes to be created
  660.      * @param boolean If the table/index should be overwritten if it already exists
  661.      * @return mixed  MDB2_Error if there is an error creating an index, MDB2_OK otherwise
  662.      * @access public
  663.      */
  664.     function createTableIndexes($table_name$indexes$overwrite = false)
  665.     {
  666.         if (!$this->db->supports('indexes')) {
  667.             $this->db->debug('Indexes are not supported'__FUNCTION__);
  668.             return MDB2_OK;
  669.         }
  670.  
  671.         $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  672.         foreach ($indexes as $index_name => $index{
  673.  
  674.             // Does the index already exist, and if so, should it be overwritten?
  675.             $create_index = true;
  676.             $this->db->expectError($errorcodes);
  677.             if (!empty($index['primary']|| !empty($index['unique'])) {
  678.                 $current_indexes $this->db->manager->listTableConstraints($table_name);
  679.             else {
  680.                 $current_indexes $this->db->manager->listTableIndexes($table_name);
  681.             }
  682.             $this->db->popExpect();
  683.             if (PEAR::isError($current_indexes)) {
  684.                 if (!MDB2::isError($current_indexes$errorcodes)) {
  685.                     return $current_indexes;
  686.                 }
  687.             elseif (is_array($current_indexes&& in_array($index_name$current_indexes)) {
  688.                 if (!$overwrite{
  689.                     $this->db->debug('Index already exists: '.$index_name__FUNCTION__);
  690.                     $create_index = false;
  691.                 else {
  692.                     $this->db->debug('Preparing to overwrite index: '.$index_name__FUNCTION__);
  693.  
  694.                     if (!empty($index['primary']|| !empty($index['unique'])) {
  695.                         $result $this->db->manager->dropConstraint($table_name$index_name);
  696.                     else {
  697.                         $result $this->db->manager->dropIndex($table_name$index_name);
  698.                     }
  699.  
  700.                     if (PEAR::isError($result)) {
  701.                         return $result;
  702.                     }
  703.                 }
  704.             }
  705.  
  706.             // Check if primary is being used and if it's supported
  707.             if (!empty($index['primary']&& !$this->db->supports('primary_key')) {
  708.  
  709.                 // Primary not supported so we fallback to UNIQUE and making the field NOT NULL
  710.                 $index['unique'= true;
  711.                 $changes = array();
  712.  
  713.                 foreach ($index['fields'as $field => $empty{
  714.                     $field_info $this->db->reverse->getTableFieldDefinition($table_name$field);
  715.                     if (PEAR::isError($field_info)) {
  716.                         return $field_info;
  717.                     }
  718.                     if (!$field_info[0]['notnull']{
  719.                         $changes['change'][$field$field_info[0];
  720.                         $changes['change'][$field]['notnull'= true;
  721.                     }
  722.                 }
  723.                 if (!empty($changes)) {
  724.                     $this->db->manager->alterTable($table_name$changesfalse);
  725.                 }
  726.             }
  727.  
  728.             // Should the index be created?
  729.             if ($create_index{
  730.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  731.                     $result $this->db->manager->createConstraint($table_name$index_name$index);
  732.                 else {
  733.                     $result $this->db->manager->createIndex($table_name$index_name$index);
  734.                 }
  735.                 if (PEAR::isError($result)) {
  736.                     return $result;
  737.                 }
  738.             }
  739.         }
  740.         return MDB2_OK;
  741.     }
  742.  
  743.     // }}}
  744.     // {{{ createTableConstraints()
  745.  
  746.     /**
  747.      * A method to create foreign keys for an existing table
  748.      *
  749.      * @param string  Name of the table
  750.      * @param array   An array of foreign keys to be created
  751.      * @param boolean If the foreign key should be overwritten if it already exists
  752.      * @return mixed  MDB2_Error if there is an error creating a foreign key, MDB2_OK otherwise
  753.      * @access public
  754.      */
  755.     function createTableConstraints($table_name$constraints$overwrite = false)
  756.     {
  757.         if (!$this->db->supports('indexes')) {
  758.             $this->db->debug('Indexes are not supported'__FUNCTION__);
  759.             return MDB2_OK;
  760.         }
  761.  
  762.         $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  763.         foreach ($constraints as $constraint_name => $constraint{
  764.  
  765.             // Does the foreign key already exist, and if so, should it be overwritten?
  766.             $create_constraint = true;
  767.             $this->db->expectError($errorcodes);
  768.             $current_constraints $this->db->manager->listTableConstraints($table_name);
  769.             $this->db->popExpect();
  770.             if (PEAR::isError($current_constraints)) {
  771.                 if (!MDB2::isError($current_constraints$errorcodes)) {
  772.                     return $current_constraints;
  773.                 }
  774.             elseif (is_array($current_constraints&& in_array($constraint_name$current_constraints)) {
  775.                 if (!$overwrite{
  776.                     $this->db->debug('Foreign key already exists: '.$constraint_name__FUNCTION__);
  777.                     $create_constraint = false;
  778.                 else {
  779.                     $this->db->debug('Preparing to overwrite foreign key: '.$constraint_name__FUNCTION__);
  780.                     $result $this->db->manager->dropConstraint($table_name$constraint_name);
  781.                     if (PEAR::isError($result)) {
  782.                         return $result;
  783.                     }
  784.                 }
  785.             }
  786.  
  787.             // Should the foreign key be created?
  788.             if ($create_constraint{
  789.                 $result $this->db->manager->createConstraint($table_name$constraint_name$constraint);
  790.                 if (PEAR::isError($result)) {
  791.                     return $result;
  792.                 }
  793.             }
  794.         }
  795.         return MDB2_OK;
  796.     }
  797.  
  798.     // }}}
  799.     // {{{ createTable()
  800.  
  801.     /**
  802.      * Create a table and inititialize the table if data is available
  803.      *
  804.      * @param string name of the table to be created
  805.      * @param array  multi dimensional array that contains the
  806.      *                structure and optional data of the table
  807.      * @param bool   if the table/index should be overwritten if it already exists
  808.      * @param array  an array of options to be passed to the database specific driver
  809.      *                version of MDB2_Driver_Manager_Common::createTable().
  810.      * @return bool|MDB2_ErrorMDB2_OK or error object
  811.      * @access public
  812.      */
  813.     function createTable($table_name$table$overwrite = false$options = array())
  814.     {
  815.         $create = true;
  816.         $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  817.         $this->db->expectError($errorcodes);
  818.         $tables $this->db->manager->listTables();
  819.         $this->db->popExpect();
  820.         if (PEAR::isError($tables)) {
  821.             if (!MDB2::isError($tables$errorcodes)) {
  822.                 return $tables;
  823.             }
  824.         elseif (is_array($tables&& in_array($table_name$tables)) {
  825.             if (!$overwrite{
  826.                 $create = false;
  827.                 $this->db->debug('Table already exists: '.$table_name__FUNCTION__);
  828.             else {
  829.                 $result $this->db->manager->dropTable($table_name);
  830.                 if (PEAR::isError($result)) {
  831.                     return $result;
  832.                 }
  833.                 $this->db->debug('Overwritting table: '.$table_name__FUNCTION__);
  834.             }
  835.         }
  836.  
  837.         if ($create{
  838.             $result $this->db->manager->createTable($table_name$table['fields']$options);
  839.             if (PEAR::isError($result)) {
  840.                 return $result;
  841.             }
  842.         }
  843.  
  844.         if (!empty($table['initialization']&& is_array($table['initialization'])) {
  845.             $result $this->initializeTable($table_name$table);
  846.             if (PEAR::isError($result)) {
  847.                 return $result;
  848.             }
  849.         }
  850.  
  851.         if (!empty($table['indexes']&& is_array($table['indexes'])) {
  852.             $result $this->createTableIndexes($table_name$table['indexes']$overwrite);
  853.             if (PEAR::isError($result)) {
  854.                 return $result;
  855.             }
  856.         }
  857.  
  858.         if (!empty($table['constraints']&& is_array($table['constraints'])) {
  859.             $result $this->createTableConstraints($table_name$table['constraints']$overwrite);
  860.             if (PEAR::isError($result)) {
  861.                 return $result;
  862.             }
  863.         }
  864.  
  865.         return MDB2_OK;
  866.     }
  867.  
  868.     // }}}
  869.     // {{{ initializeTable()
  870.  
  871.     /**
  872.      * Inititialize the table with data
  873.      *
  874.      * @param string name of the table
  875.      * @param array  multi dimensional array that contains the
  876.      *                structure and optional data of the table
  877.      * @return bool|MDB2_ErrorMDB2_OK or error object
  878.      * @access public
  879.      */
  880.     function initializeTable($table_name$table)
  881.     {
  882.         $query_insert 'INSERT INTO %s (%s) VALUES (%s)';
  883.         $query_insertselect 'INSERT INTO %s (%s) (SELECT %s FROM %s %s)';
  884.         $query_update 'UPDATE %s SET %s %s';
  885.         $query_delete 'DELETE FROM %s %s';
  886.  
  887.         $table_name $this->db->quoteIdentifier($table_nametrue);
  888.  
  889.         $result = MDB2_OK;
  890.  
  891.         foreach ($table['initialization'as $instruction{
  892.             $query '';
  893.             switch ($instruction['type']{
  894.             case 'insert':
  895.                 if (!isset($instruction['data']['select'])) {
  896.                     $data $this->getInstructionFields($instruction['data']$table['fields']);
  897.                     if (!empty($data)) {
  898.                         $fields implode(', 'array_keys($data));
  899.                         $values implode(', 'array_values($data));
  900.  
  901.                         $query sprintf($query_insert$table_name$fields$values);
  902.                     }
  903.                 else {
  904.                     $data $this->getInstructionFields($instruction['data']['select']$table['fields']);
  905.                     $where $this->getInstructionWhere($instruction['data']['select']$table['fields']);
  906.                     $select_table_name $this->db->quoteIdentifier($instruction['data']['select']['table']true);
  907.                     if (!empty($data)) {
  908.                         $fields implode(', 'array_keys($data));
  909.                         $values implode(', 'array_values($data));
  910.  
  911.                         $query sprintf($query_insertselect$table_name$fields$values$select_table_name$where);
  912.                     }
  913.                 }
  914.                 break;
  915.             case 'update':
  916.                 $data $this->getInstructionFields($instruction['data']$table['fields']);
  917.                 $where $this->getInstructionWhere($instruction['data']$table['fields']);
  918.                 if (!empty($data)) {
  919.                     array_walk($dataarray($this'buildFieldValue'));
  920.                     $fields_values implode(', '$data);
  921.  
  922.                     $query sprintf($query_update$table_name$fields_values$where);
  923.                 }
  924.                 break;
  925.             case 'delete':
  926.                 $where $this->getInstructionWhere($instruction['data']$table['fields']);
  927.                 $query sprintf($query_delete$table_name$where);
  928.                 break;
  929.             }
  930.             if ($query{
  931.                 $result $this->db->exec($query);
  932.                 if (PEAR::isError($result)) {
  933.                     return $result;
  934.                 }
  935.             }
  936.         }
  937.         return $result;
  938.     }
  939.  
  940.     // }}}
  941.     // {{{ buildFieldValue()
  942.  
  943.     /**
  944.      * Appends the contents of second argument + '=' to the beginning of first
  945.      * argument.
  946.      *
  947.      * Used with array_walk() in initializeTable() for UPDATEs.
  948.      *
  949.      * @param string  value of array's element
  950.      * @param string  key of array's element
  951.      *
  952.      * @return void 
  953.      *
  954.      * @access public
  955.      * @see MDB2_Schema::initializeTable()
  956.      */
  957.     function buildFieldValue(&$element$key)
  958.     {
  959.        $element $key."=$element";
  960.     }
  961.  
  962.     // }}}
  963.     // {{{ getExpression()
  964.  
  965.     /**
  966.      * Generates a string that represents a value that would be associated
  967.      * with a column in a DML instruction.
  968.      *
  969.      * @param array  multi dimensional array that represents the parsed field
  970.      *                 of a DML instruction.
  971.      * @param array  multi dimensional array that contains the
  972.      *                 definition for current table's fields.
  973.      * @param string  type of given field
  974.      *
  975.      * @return string 
  976.      *
  977.      * @access public
  978.      * @see MDB2_Schema::getInstructionFields(), MDB2_Schema::getInstructionWhere()
  979.      */
  980.     function getExpression($element$fields_definition = array()$type = null)
  981.     {
  982.         $str '';
  983.         switch ($element['type']{
  984.             case 'null':
  985.                 $str.= 'NULL';
  986.             break;
  987.             case 'value':
  988.                 $str.= $this->db->quote($element['data']$type);
  989.             break;
  990.             case 'column':
  991.                 $str.= $this->db->quoteIdentifier($element['data']true);
  992.             break;
  993.             case 'function':
  994.                 $arguments = array();
  995.                 if (!empty($element['data']['arguments'])
  996.                     && is_array($element['data']['arguments'])
  997.                 {
  998.                     foreach ($element['data']['arguments'as $v{
  999.                         $arguments[$this->getExpression($v$fields_definition);
  1000.                     }
  1001.                 }
  1002.                 if (method_exists($this->db->function$element['data']['name'])) {
  1003.                     $str.= call_user_func_array(
  1004.                         array(&$this->db->function$element['data']['name']),
  1005.                         $arguments
  1006.                     );
  1007.                 else {
  1008.                     $str.= $element['data']['name'].'(';
  1009.                     $str.= implode(', '$arguments);
  1010.                     $str.= ')';
  1011.                 }
  1012.             break;
  1013.             case 'expression':
  1014.                 $type0 $type1 = null;
  1015.                 if ($element['data']['operants'][0]['type'== 'column'
  1016.                     && array_key_exists($element['data']['operants'][0]['data']$fields_definition)
  1017.                 {
  1018.                     $type0 $fields_definition[$element['data']['operants'][0]['data']]['type'];
  1019.                 }
  1020.                 if ($element['data']['operants'][1]['type'== 'column'
  1021.                     && array_key_exists($element['data']['operants'][1]['data']$fields_definition)
  1022.                 {
  1023.                     $type1 $fields_definition[$element['data']['operants'][1]['data']]['type'];
  1024.                 }
  1025.                 $str.= '(';
  1026.                 $str.= $this->getExpression($element['data']['operants'][0]$fields_definition$type1);
  1027.                 $str.= $this->getOperator($element['data']['operator']);
  1028.                 $str.= $this->getExpression($element['data']['operants'][1]$fields_definition$type0);
  1029.                 $str.= ')';
  1030.             break;
  1031.         }
  1032.         return $str;
  1033.     }
  1034.  
  1035.     // }}}
  1036.     // {{{ getOperator()
  1037.  
  1038.     /**
  1039.      * Returns the matching SQL operator
  1040.      *
  1041.      * @param string parsed descriptive operator
  1042.      *
  1043.      * @return string matching SQL operator
  1044.      *
  1045.      * @access public
  1046.      * @static
  1047.      * @see MDB2_Schema::getExpression()
  1048.      */
  1049.     function getOperator($op)
  1050.     {
  1051.         switch ($op{
  1052.         case 'PLUS':
  1053.             return ' + ';
  1054.         case 'MINUS':
  1055.             return ' - ';
  1056.         case 'TIMES':
  1057.             return ' * ';
  1058.         case 'DIVIDED':
  1059.             return ' / ';
  1060.         case 'EQUAL':
  1061.             return ' = ';
  1062.         case 'NOT EQUAL':
  1063.             return ' != ';
  1064.         case 'LESS THAN':
  1065.             return ' < ';
  1066.         case 'GREATER THAN':
  1067.             return ' > ';
  1068.         case 'LESS THAN OR EQUAL':
  1069.             return ' <= ';
  1070.         case 'GREATER THAN OR EQUAL':
  1071.             return ' >= ';
  1072.         default:
  1073.             return ' '.$op.' ';
  1074.         }
  1075.     }
  1076.  
  1077.     // }}}
  1078.     // {{{ getInstructionFields()
  1079.  
  1080.     /**
  1081.      * Walks the parsed DML instruction array, field by field,
  1082.      * storing them and their processed values inside a new array.
  1083.      *
  1084.      * @param array  multi dimensional array that contains the parsed
  1085.      *                 DML instruction to be processed.
  1086.      * @param array  multi dimensional array that contains the
  1087.      *                 definition for current table's fields.
  1088.      *
  1089.      * @return array  array of strings in the form 'field_name' => 'value'
  1090.      *
  1091.      * @access public
  1092.      * @static
  1093.      * @see MDB2_Schema::initializeTable()
  1094.      */
  1095.     function getInstructionFields($instruction$fields_definition = array())
  1096.     {
  1097.         $fields = array();
  1098.         if (!empty($instruction['field']&& is_array($instruction['field'])) {
  1099.             foreach ($instruction['field'as $field{
  1100.                 $fields[$field['name']] $this->getExpression($field['group']$fields_definition);
  1101.             }
  1102.         }
  1103.         return $fields;
  1104.     }
  1105.  
  1106.     // }}}
  1107.     // {{{ getInstructionWhere()
  1108.  
  1109.     /**
  1110.      * Translates the parsed WHERE expression of a DML instruction
  1111.      * (array structure) to a SQL WHERE clause (string).
  1112.      *
  1113.      * @param array  multi dimensional array that contains the
  1114.      *                 structure of the current DML instruction.
  1115.      * @param array  multi dimensional array that contains the
  1116.      *                 definition for current table's fields.
  1117.      *
  1118.      * @return string SQL WHERE clause
  1119.      *
  1120.      * @access public
  1121.      * @static
  1122.      * @see MDB2_Schema::initializeTable()
  1123.      */
  1124.     function getInstructionWhere($instruction$fields_definition = array())
  1125.     {
  1126.         $where '';
  1127.         if (!empty($instruction['where'])) {
  1128.             $where 'WHERE '.$this->getExpression($instruction['where']$fields_definition);
  1129.         }
  1130.         return $where;
  1131.     }
  1132.  
  1133.     // }}}
  1134.     // {{{ createSequence()
  1135.  
  1136.     /**
  1137.      * Create a sequence
  1138.      *
  1139.      * @param string name of the sequence to be created
  1140.      * @param array  multi dimensional array that contains the
  1141.      *                structure and optional data of the table
  1142.      * @param bool  if the sequence should be overwritten if it already exists
  1143.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1144.      * @access public
  1145.      */
  1146.     function createSequence($sequence_name$sequence$overwrite = false)
  1147.     {
  1148.         if (!$this->db->supports('sequences')) {
  1149.             $this->db->debug('Sequences are not supported'__FUNCTION__);
  1150.             return MDB2_OK;
  1151.         }
  1152.  
  1153.         $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  1154.         $this->db->expectError($errorcodes);
  1155.         $sequences $this->db->manager->listSequences();
  1156.         $this->db->popExpect();
  1157.         if (PEAR::isError($sequences)) {
  1158.             if (!MDB2::isError($sequences$errorcodes)) {
  1159.                 return $sequences;
  1160.             }
  1161.         elseif (is_array($sequence&& in_array($sequence_name$sequences)) {
  1162.             if (!$overwrite{
  1163.                 $this->db->debug('Sequence already exists: '.$sequence_name__FUNCTION__);
  1164.                 return MDB2_OK;
  1165.             }
  1166.  
  1167.             $result $this->db->manager->dropSequence($sequence_name);
  1168.             if (PEAR::isError($result)) {
  1169.                 return $result;
  1170.             }
  1171.             $this->db->debug('Overwritting sequence: '.$sequence_name__FUNCTION__);
  1172.         }
  1173.  
  1174.         $start = 1;
  1175.         $field '';
  1176.         if (!empty($sequence['on'])) {
  1177.             $table $sequence['on']['table'];
  1178.             $field $sequence['on']['field'];
  1179.  
  1180.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  1181.             $this->db->expectError($errorcodes);
  1182.             $tables $this->db->manager->listTables();
  1183.             $this->db->popExpect();
  1184.             if (PEAR::isError($tables&& !MDB2::isError($tables$errorcodes)) {
  1185.                  return $tables;
  1186.             }
  1187.  
  1188.             if (!PEAR::isError($tables&& is_array($tables&& in_array($table$tables)) {
  1189.                 if ($this->db->supports('summary_functions')) {
  1190.                     $query = "SELECT MAX($field) FROM ".$this->db->quoteIdentifier($tabletrue);
  1191.                 else {
  1192.                     $query = "SELECT $field FROM ".$this->db->quoteIdentifier($tabletrue)." ORDER BY $field DESC";
  1193.                 }
  1194.                 $start $this->db->queryOne($query'integer');
  1195.                 if (PEAR::isError($start)) {
  1196.                     return $start;
  1197.                 }
  1198.                 ++$start;
  1199.             else {
  1200.                 $this->warnings['Could not sync sequence: '.$sequence_name;
  1201.             }
  1202.         elseif (!empty($sequence['start']&& is_numeric($sequence['start'])) {
  1203.             $start $sequence['start'];
  1204.             $table '';
  1205.         }
  1206.  
  1207.         $result $this->db->manager->createSequence($sequence_name$start);
  1208.         if (PEAR::isError($result)) {
  1209.             return $result;
  1210.         }
  1211.  
  1212.         return MDB2_OK;
  1213.     }
  1214.  
  1215.     // }}}
  1216.     // {{{ createDatabase()
  1217.  
  1218.     /**
  1219.      * Create a database space within which may be created database objects
  1220.      * like tables, indexes and sequences. The implementation of this function
  1221.      * is highly DBMS specific and may require special permissions to run
  1222.      * successfully. Consult the documentation or the DBMS drivers that you
  1223.      * use to be aware of eventual configuration requirements.
  1224.      *
  1225.      * @param array multi dimensional array that contains the current definition
  1226.      * @param array  an array of options to be passed to the database specific driver
  1227.      *                version of MDB2_Driver_Manager_Common::createTable().
  1228.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1229.      * @access public
  1230.      */
  1231.     function createDatabase($database_definition$options = array())
  1232.     {
  1233.         if (!isset($database_definition['name']|| !$database_definition['name']{
  1234.             return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1235.                 'no valid database name specified');
  1236.         }
  1237.         $create (isset($database_definition['create']&& $database_definition['create']);
  1238.         $overwrite (isset($database_definition['overwrite']&& $database_definition['overwrite']);
  1239.         if ($create{
  1240.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  1241.             $this->db->expectError($errorcodes);
  1242.  
  1243.             /**
  1244.              *
  1245.              * We need to clean up database name before any query to prevent
  1246.              * database driver from using a inexistent database
  1247.              *
  1248.              */
  1249.             $this->db->setDatabase("");
  1250.             $databases $this->db->manager->listDatabases();
  1251.  
  1252.             // Lower / Upper case the db name if the portability deems so.
  1253.             if ($this->db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1254.                 $func $this->db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper';
  1255.                 $db_name $func($database_definition['name']);
  1256.             }
  1257.  
  1258.             $this->db->popExpect();
  1259.             if (PEAR::isError($databases)) {
  1260.                 if (!MDB2::isError($databases$errorcodes)) {
  1261.                     return $databases;
  1262.                 }
  1263.             elseif (is_array($databases&& isset($db_name&& in_array($db_name$databases)) {
  1264.                 if (!$overwrite{
  1265.                     $this->db->debug('Database already exists: ' $database_definition['name']__FUNCTION__);
  1266.                     $create = false;
  1267.                 else {
  1268.                     $result $this->db->manager->dropDatabase($database_definition['name']);
  1269.                     if (PEAR::isError($result)) {
  1270.                         return $result;
  1271.                     }
  1272.                     $this->db->debug('Overwritting database: '.$database_definition['name']__FUNCTION__);
  1273.                 }
  1274.             }
  1275.             if ($create{
  1276.                 $this->db->expectError(MDB2_ERROR_ALREADY_EXISTS);
  1277.                 $result $this->db->manager->createDatabase($database_definition['name']);
  1278.                 $this->db->popExpect();
  1279.                 if (PEAR::isError($result&& !MDB2::isError($resultMDB2_ERROR_ALREADY_EXISTS)) {
  1280.                     return $result;
  1281.                 }
  1282.             }
  1283.         }
  1284.         $previous_database_name $this->db->setDatabase($database_definition['name']);
  1285.         if (($support_transactions $this->db->supports('transactions'))
  1286.             && PEAR::isError($result $this->db->beginNestedTransaction())
  1287.         {
  1288.             return $result;
  1289.         }
  1290.  
  1291.         $created_objects = 0;
  1292.         if (isset($database_definition['tables'])
  1293.             && is_array($database_definition['tables'])
  1294.         {
  1295.             foreach ($database_definition['tables'as $table_name => $table{
  1296.                 $result $this->createTable($table_name$table$overwrite$options);
  1297.                 if (PEAR::isError($result)) {
  1298.                     break;
  1299.                 }
  1300.                 $created_objects++;
  1301.             }
  1302.         }
  1303.         if (!PEAR::isError($result)
  1304.             && isset($database_definition['sequences'])
  1305.             && is_array($database_definition['sequences'])
  1306.         {
  1307.             foreach ($database_definition['sequences'as $sequence_name => $sequence{
  1308.                 $result $this->createSequence($sequence_name$sequencefalse$overwrite);
  1309.  
  1310.                 if (PEAR::isError($result)) {
  1311.                     break;
  1312.                 }
  1313.                 $created_objects++;
  1314.             }
  1315.         }
  1316.  
  1317.         if ($support_transactions{
  1318.             $res $this->db->completeNestedTransaction();
  1319.             if (PEAR::isError($res)) {
  1320.                 $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  1321.                     'Could not end transaction ('.
  1322.                     $res->getMessage().' ('.$res->getUserinfo().'))');
  1323.             }
  1324.         elseif (PEAR::isError($result&& $created_objects{
  1325.             $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  1326.                 'the database was only partially created ('.
  1327.                 $result->getMessage().' ('.$result->getUserinfo().'))');
  1328.         }
  1329.  
  1330.         $this->db->setDatabase($previous_database_name);
  1331.  
  1332.         if (PEAR::isError($result&& $create
  1333.             && PEAR::isError($result2 $this->db->manager->dropDatabase($database_definition['name']))
  1334.         {
  1335.             return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  1336.                 'Could not drop the created database after unsuccessful creation attempt ('.
  1337.                 $result2->getMessage().' ('.$result2->getUserinfo().'))');
  1338.         }
  1339.  
  1340.         return $result;
  1341.     }
  1342.  
  1343.     // }}}
  1344.     // {{{ compareDefinitions()
  1345.  
  1346.     /**
  1347.      * Compare a previous definition with the currently parsed definition
  1348.      *
  1349.      * @param array multi dimensional array that contains the current definition
  1350.      * @param array multi dimensional array that contains the previous definition
  1351.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1352.      * @access public
  1353.      */
  1354.     function compareDefinitions($current_definition$previous_definition)
  1355.     {
  1356.         $changes = array();
  1357.  
  1358.         if (!empty($current_definition['tables']&& is_array($current_definition['tables'])) {
  1359.             $changes['tables'$defined_tables = array();
  1360.             foreach ($current_definition['tables'as $table_name => $table{
  1361.                 $previous_tables = array();
  1362.                 if (!empty($previous_definition&& is_array($previous_definition)) {
  1363.                     $previous_tables $previous_definition['tables'];
  1364.                 }
  1365.                 $change $this->compareTableDefinitions($table_name$table$previous_tables$defined_tables);
  1366.                 if (PEAR::isError($change)) {
  1367.                     return $change;
  1368.                 }
  1369.                 if (!empty($change)) {
  1370.                     $changes['tables'MDB2_Schema::arrayMergeClobber($changes['tables']$change);
  1371.                 }
  1372.             }
  1373.             if (!empty($previous_definition['tables']&& is_array($previous_definition['tables'])) {
  1374.                 foreach ($previous_definition['tables'as $table_name => $table{
  1375.                     if (empty($defined_tables[$table_name])) {
  1376.                         $changes['remove'][$table_name= true;
  1377.                     }
  1378.                 }
  1379.             }
  1380.         }
  1381.         if (!empty($current_definition['sequences']&& is_array($current_definition['sequences'])) {
  1382.             $changes['sequences'$defined_sequences = array();
  1383.             foreach ($current_definition['sequences'as $sequence_name => $sequence{
  1384.                 $previous_sequences = array();
  1385.                 if (!empty($previous_definition&& is_array($previous_definition)) {
  1386.                     $previous_sequences $previous_definition['sequences'];
  1387.                 }
  1388.                 $change $this->compareSequenceDefinitions(
  1389.                     $sequence_name,
  1390.                     $sequence,
  1391.                     $previous_sequences,
  1392.                     $defined_sequences
  1393.                 );
  1394.                 if (PEAR::isError($change)) {
  1395.                     return $change;
  1396.                 }
  1397.                 if (!empty($change)) {
  1398.                     $changes['sequences'MDB2_Schema::arrayMergeClobber($changes['sequences']$change);
  1399.                 }
  1400.             }
  1401.             if (!empty($previous_definition['sequences']&& is_array($previous_definition['sequences'])) {
  1402.                 foreach ($previous_definition['sequences'as $sequence_name => $sequence{
  1403.                     if (empty($defined_sequences[$sequence_name])) {
  1404.                         $changes['remove'][$sequence_name= true;
  1405.                     }
  1406.                 }
  1407.             }
  1408.         }
  1409.         return $changes;
  1410.     }
  1411.  
  1412.     // }}}
  1413.     // {{{ compareTableFieldsDefinitions()
  1414.  
  1415.     /**
  1416.      * Compare a previous definition with the currently parsed definition
  1417.      *
  1418.      * @param string name of the table
  1419.      * @param array multi dimensional array that contains the current definition
  1420.      * @param array multi dimensional array that contains the previous definition
  1421.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1422.      * @access public
  1423.      */
  1424.     function compareTableFieldsDefinitions($table_name$current_definition,
  1425.         $previous_definition)
  1426.     {
  1427.         $changes $defined_fields = array();
  1428.  
  1429.         if (is_array($current_definition)) {
  1430.             foreach ($current_definition as $field_name => $field{
  1431.                 $was_field_name $field['was'];
  1432.                 if (!empty($previous_definition[$field_name])
  1433.                     && (
  1434.                         (isset($previous_definition[$field_name]['was'])
  1435.                          && $previous_definition[$field_name]['was'== $was_field_name)
  1436.                         || !isset($previous_definition[$was_field_name])
  1437.                        )
  1438.                 {
  1439.                     $was_field_name $field_name;
  1440.                 }
  1441.                 if (!empty($previous_definition[$was_field_name])) {
  1442.                     if ($was_field_name != $field_name{
  1443.                         $changes['rename'][$was_field_name= array('name' => $field_name'definition' => $field);
  1444.                     }
  1445.                     if (!empty($defined_fields[$was_field_name])) {
  1446.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1447.                             'the field "'.$was_field_name.
  1448.                             '" was specified for more than one field of table');
  1449.                     }
  1450.                     $defined_fields[$was_field_name= true;
  1451.                     $change $this->db->compareDefinition($field$previous_definition[$was_field_name]);
  1452.                     if (PEAR::isError($change)) {
  1453.                         return $change;
  1454.                     }
  1455.                     if (!empty($change)) {
  1456.                         $change['definition'$field;
  1457.                         $changes['change'][$field_name$change;
  1458.                     }
  1459.                 else {
  1460.                     if ($field_name != $was_field_name{
  1461.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1462.                             'it was specified a previous field name ("'.
  1463.                             $was_field_name.'") for field "'.$field_name.'" of table "'.
  1464.                             $table_name.'" that does not exist');
  1465.                     }
  1466.                     $changes['add'][$field_name$field;
  1467.                 }
  1468.             }
  1469.         }
  1470.         if (isset($previous_definition&& is_array($previous_definition)) {
  1471.             foreach ($previous_definition as $field_previous_name => $field_previous{
  1472.                 if (empty($defined_fields[$field_previous_name])) {
  1473.                     $changes['remove'][$field_previous_name= true;
  1474.                 }
  1475.             }
  1476.         }
  1477.         return $changes;
  1478.     }
  1479.  
  1480.     // }}}
  1481.     // {{{ compareTableIndexesDefinitions()
  1482.  
  1483.     /**
  1484.      * Compare a previous definition with the currently parsed definition
  1485.      *
  1486.      * @param string name of the table
  1487.      * @param array multi dimensional array that contains the current definition
  1488.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1489.      * @access public
  1490.      */
  1491.     function compareTableIndexesDefinitions($table_name$current_definition,
  1492.         $previous_definition)
  1493.     {
  1494.         $changes $defined_indexes = array();
  1495.  
  1496.         if (is_array($current_definition)) {
  1497.             foreach ($current_definition as $index_name => $index{
  1498.                 $was_index_name $index['was'];
  1499.                 if (!empty($previous_definition[$index_name])
  1500.                     && isset($previous_definition[$index_name]['was'])
  1501.                     && $previous_definition[$index_name]['was'== $was_index_name
  1502.                 {
  1503.                     $was_index_name $index_name;
  1504.                 }
  1505.                 if (!empty($previous_definition[$was_index_name])) {
  1506.                     $change = array();
  1507.                     if ($was_index_name != $index_name{
  1508.                         $change['name'$was_index_name;
  1509.                     }
  1510.                     if (!empty($defined_indexes[$was_index_name])) {
  1511.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1512.                             'the index "'.$was_index_name.'" was specified for'.
  1513.                             ' more than one index of table "'.$table_name.'"');
  1514.                     }
  1515.                     $defined_indexes[$was_index_name= true;
  1516.  
  1517.                     $previous_unique array_key_exists('unique'$previous_definition[$was_index_name])
  1518.                         ? $previous_definition[$was_index_name]['unique': false;
  1519.                     $unique array_key_exists('unique'$index$index['unique': false;
  1520.                     if ($previous_unique != $unique{
  1521.                         $change['unique'$unique;
  1522.                     }
  1523.                     $previous_primary array_key_exists('primary'$previous_definition[$was_index_name])
  1524.                         ? $previous_definition[$was_index_name]['primary': false;
  1525.                     $primary array_key_exists('primary'$index$index['primary': false;
  1526.                     if ($previous_primary != $primary{
  1527.                         $change['primary'$primary;
  1528.                     }
  1529.                     $defined_fields = array();
  1530.                     $previous_fields $previous_definition[$was_index_name]['fields'];
  1531.                     if (!empty($index['fields']&& is_array($index['fields'])) {
  1532.                         foreach ($index['fields'as $field_name => $field{
  1533.                             if (!empty($previous_fields[$field_name])) {
  1534.                                 $defined_fields[$field_name= true;
  1535.                                 $previous_sorting array_key_exists('sorting'$previous_fields[$field_name])
  1536.                                     ? $previous_fields[$field_name]['sorting''';
  1537.                                 $sorting array_key_exists('sorting'$field$field['sorting''';
  1538.                                 if ($previous_sorting != $sorting{
  1539.                                     $change['change'= true;
  1540.                                 }
  1541.                             else {
  1542.                                 $change['change'= true;
  1543.                             }
  1544.                         }
  1545.                     }
  1546.                     if (isset($previous_fields&& is_array($previous_fields)) {
  1547.                         foreach ($previous_fields as $field_name => $field{
  1548.                             if (empty($defined_fields[$field_name])) {
  1549.                                 $change['change'= true;
  1550.                             }
  1551.                         }
  1552.                     }
  1553.                     if (!empty($change)) {
  1554.                         $changes['change'][$index_name$current_definition[$index_name];
  1555.                     }
  1556.                 else {
  1557.                     if ($index_name != $was_index_name{
  1558.                         return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1559.                             'it was specified a previous index name ("'.$was_index_name.
  1560.                             ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist');
  1561.                     }
  1562.                     $changes['add'][$index_name$current_definition[$index_name];
  1563.                 }
  1564.             }
  1565.         }
  1566.         foreach ($previous_definition as $index_previous_name => $index_previous{
  1567.             if (empty($defined_indexes[$index_previous_name])) {
  1568.                 $changes['remove'][$index_previous_name$index_previous;
  1569.             }
  1570.         }
  1571.         return $changes;
  1572.     }
  1573.  
  1574.     // }}}
  1575.     // {{{ compareTableDefinitions()
  1576.  
  1577.     /**
  1578.      * Compare a previous definition with the currently parsed definition
  1579.      *
  1580.      * @param string name of the table
  1581.      * @param array multi dimensional array that contains the current definition
  1582.      * @param array multi dimensional array that contains the previous definition
  1583.      * @param array table names in the schema
  1584.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1585.      * @access public
  1586.      */
  1587.     function compareTableDefinitions($table_name$current_definition,
  1588.         $previous_definition&$defined_tables)
  1589.     {
  1590.         $changes = array();
  1591.  
  1592.         if (is_array($current_definition)) {
  1593.             $was_table_name $table_name;
  1594.             if (!empty($current_definition['was'])) {
  1595.                 $was_table_name $current_definition['was'];
  1596.             }
  1597.             if (!empty($previous_definition[$was_table_name])) {
  1598.                 $changes['change'][$was_table_name= array();
  1599.                 if ($was_table_name != $table_name{
  1600.                     $changes['change'][$was_table_name= array('name' => $table_name);
  1601.                 }
  1602.                 if (!empty($defined_tables[$was_table_name])) {
  1603.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1604.                         'the table "'.$was_table_name.
  1605.                         '" was specified for more than one table of the database');
  1606.                 }
  1607.                 $defined_tables[$was_table_name= true;
  1608.                 if (!empty($current_definition['fields']&& is_array($current_definition['fields'])) {
  1609.                     $previous_fields = array();
  1610.                     if (isset($previous_definition[$was_table_name]['fields'])
  1611.                         && is_array($previous_definition[$was_table_name]['fields'])
  1612.                     {
  1613.                         $previous_fields $previous_definition[$was_table_name]['fields'];
  1614.                     }
  1615.                     $change $this->compareTableFieldsDefinitions(
  1616.                         $table_name,
  1617.                         $current_definition['fields'],
  1618.                         $previous_fields
  1619.                     );
  1620.                     if (PEAR::isError($change)) {
  1621.                         return $change;
  1622.                     }
  1623.                     if (!empty($change)) {
  1624.                         $changes['change'][$was_table_name=
  1625.                             MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name]$change);
  1626.                     }
  1627.                 }
  1628.                 if (!empty($current_definition['indexes']&& is_array($current_definition['indexes'])) {
  1629.                     $previous_indexes = array();
  1630.                     if (isset($previous_definition[$was_table_name]['indexes'])
  1631.                         && is_array($previous_definition[$was_table_name]['indexes'])
  1632.                     {
  1633.                         $previous_indexes $previous_definition[$was_table_name]['indexes'];
  1634.                     }
  1635.                     $change $this->compareTableIndexesDefinitions(
  1636.                         $table_name,
  1637.                         $current_definition['indexes'],
  1638.                         $previous_indexes
  1639.                     );
  1640.                     if (PEAR::isError($change)) {
  1641.                         return $change;
  1642.                     }
  1643.                     if (!empty($change)) {
  1644.                         $changes['change'][$was_table_name]['indexes'$change;
  1645.                     }
  1646.                 }
  1647.                 if (empty($changes['change'][$was_table_name])) {
  1648.                     unset($changes['change'][$was_table_name]);
  1649.                 }
  1650.                 if (empty($changes['change'])) {
  1651.                     unset($changes['change']);
  1652.                 }
  1653.             else {
  1654.                 if ($table_name != $was_table_name{
  1655.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1656.                         'it was specified a previous table name ("'.$was_table_name.
  1657.                         '") for table "'.$table_name.'" that does not exist');
  1658.                 }
  1659.                 $changes['add'][$table_name= true;
  1660.             }
  1661.         }
  1662.  
  1663.         return $changes;
  1664.     }
  1665.  
  1666.     // }}}
  1667.     // {{{ compareSequenceDefinitions()
  1668.  
  1669.     /**
  1670.      * Compare a previous definition with the currently parsed definition
  1671.      *
  1672.      * @param string name of the sequence
  1673.      * @param array multi dimensional array that contains the current definition
  1674.      * @param array multi dimensional array that contains the previous definition
  1675.      * @param array sequence names in the schema
  1676.      * @return array|MDB2_Errorarray of changes on success, or a error object
  1677.      * @access public
  1678.      */
  1679.     function compareSequenceDefinitions($sequence_name$current_definition,
  1680.         $previous_definition&$defined_sequences)
  1681.     {
  1682.         $changes = array();
  1683.  
  1684.         if (is_array($current_definition)) {
  1685.             $was_sequence_name $sequence_name;
  1686.             if (!empty($previous_definition[$sequence_name])
  1687.                 && isset($previous_definition[$sequence_name]['was'])
  1688.                 && $previous_definition[$sequence_name]['was'== $was_sequence_name
  1689.             {
  1690.                 $was_sequence_name $sequence_name;
  1691.             elseif (!empty($current_definition['was'])) {
  1692.                 $was_sequence_name $current_definition['was'];
  1693.             }
  1694.             if (!empty($previous_definition[$was_sequence_name])) {
  1695.                 if ($was_sequence_name != $sequence_name{
  1696.                     $changes['change'][$was_sequence_name]['name'$sequence_name;
  1697.                 }
  1698.                 if (!empty($defined_sequences[$was_sequence_name])) {
  1699.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1700.                         'the sequence "'.$was_sequence_name.'" was specified as base'.
  1701.                         ' of more than of sequence of the database');
  1702.                 }
  1703.                 $defined_sequences[$was_sequence_name= true;
  1704.                 $change = array();
  1705.                 if (!empty($current_definition['start'])
  1706.                     && isset($previous_definition[$was_sequence_name]['start'])
  1707.                     && $current_definition['start'!= $previous_definition[$was_sequence_name]['start']
  1708.                 {
  1709.                     $change['start'$previous_definition[$sequence_name]['start'];
  1710.                 }
  1711.                 if (isset($current_definition['on']['table'])
  1712.                     && isset($previous_definition[$was_sequence_name]['on']['table'])
  1713.                     && $current_definition['on']['table'!= $previous_definition[$was_sequence_name]['on']['table']
  1714.                     && isset($current_definition['on']['field'])
  1715.                     && isset($previous_definition[$was_sequence_name]['on']['field'])
  1716.                     && $current_definition['on']['field'!= $previous_definition[$was_sequence_name]['on']['field']
  1717.                 {
  1718.                     $change['on'$current_definition['on'];
  1719.                 }
  1720.                 if (!empty($change)) {
  1721.                     $changes['change'][$was_sequence_name][$sequence_name$change;
  1722.                 }
  1723.             else {
  1724.                 if ($sequence_name != $was_sequence_name{
  1725.                     return $this->raiseError(MDB2_SCHEMA_ERROR_INVALIDnullnull,
  1726.                         'it was specified a previous sequence name ("'.$was_sequence_name.
  1727.                         '") for sequence "'.$sequence_name.'" that does not exist');
  1728.                 }
  1729.                 $changes['add'][$sequence_name= true;
  1730.             }
  1731.         }
  1732.         return $changes;
  1733.     }
  1734.     // }}}
  1735.     // {{{ verifyAlterDatabase()
  1736.  
  1737.     /**
  1738.      * Verify that the changes requested are supported
  1739.      *
  1740.      * @param array associative array that contains the definition of the changes
  1741.      *               that are meant to be applied to the database structure.
  1742.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1743.      * @access public
  1744.      */
  1745.     function verifyAlterDatabase($changes)
  1746.     {
  1747.         if (!empty($changes['tables']['change']&& is_array($changes['tables']['change'])) {
  1748.             foreach ($changes['tables']['change'as $table_name => $table{
  1749.                 if (!empty($table['indexes']&& is_array($table['indexes'])) {
  1750.                     if (!$this->db->supports('indexes')) {
  1751.                         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1752.                             'indexes are not supported');
  1753.                     }
  1754.                     $table_changes count($table['indexes']);
  1755.                     if (!empty($table['indexes']['add'])) {
  1756.                         $table_changes--;
  1757.                     }
  1758.                     if (!empty($table['indexes']['remove'])) {
  1759.                         $table_changes--;
  1760.                     }
  1761.                     if (!empty($table['indexes']['change'])) {
  1762.                         $table_changes--;
  1763.                     }
  1764.                     if ($table_changes{
  1765.                         return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1766.                             'index alteration not yet supported: '.implode(', 'array_keys($table['indexes'])));
  1767.                     }
  1768.                 }
  1769.                 unset($table['indexes']);
  1770.                 $result $this->db->manager->alterTable($table_name$tabletrue);
  1771.                 if (PEAR::isError($result)) {
  1772.                     return $result;
  1773.                 }
  1774.             }
  1775.         }
  1776.         if (!empty($changes['sequences']&& is_array($changes['sequences'])) {
  1777.             if (!$this->db->supports('sequences')) {
  1778.                 return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1779.                     'sequences are not supported');
  1780.             }
  1781.             $sequence_changes count($changes['sequences']);
  1782.             if (!empty($changes['sequences']['add'])) {
  1783.                 $sequence_changes--;
  1784.             }
  1785.             if (!empty($changes['sequences']['remove'])) {
  1786.                 $sequence_changes--;
  1787.             }
  1788.             if (!empty($changes['sequences']['change'])) {
  1789.                 $sequence_changes--;
  1790.             }
  1791.             if ($sequence_changes{
  1792.                 return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTEDnullnull,
  1793.                     'sequence alteration not yet supported: '.implode(', 'array_keys($changes['sequences'])));
  1794.             }
  1795.         }
  1796.         return MDB2_OK;
  1797.     }
  1798.  
  1799.     // }}}
  1800.     // {{{ alterDatabaseIndexes()
  1801.  
  1802.     /**
  1803.      * Execute the necessary actions to implement the requested changes
  1804.      * in the indexes inside a database structure.
  1805.      *
  1806.      * @param string name of the table
  1807.      * @param array associative array that contains the definition of the changes
  1808.      *               that are meant to be applied to the database structure.
  1809.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1810.      * @access public
  1811.      */
  1812.     function alterDatabaseIndexes($table_name$changes)
  1813.     {
  1814.         $alterations = 0;
  1815.         if (empty($changes)) {
  1816.             return $alterations;
  1817.         }
  1818.  
  1819.         if (!empty($changes['remove']&& is_array($changes['remove'])) {
  1820.             foreach ($changes['remove'as $index_name => $index{
  1821.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  1822.                     $result $this->db->manager->dropConstraint($table_name$index_name!empty($index['primary']));
  1823.                 else {
  1824.                     $result $this->db->manager->dropIndex($table_name$index_name);
  1825.                 }
  1826.                 if (PEAR::isError($result)) {
  1827.                     return $result;
  1828.                 }
  1829.                 $alterations++;
  1830.             }
  1831.         }
  1832.         if (!empty($changes['change']&& is_array($changes['change'])) {
  1833.             foreach ($changes['change'as $index_name => $index{
  1834.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  1835.                     $result $this->db->manager->dropConstraint($table_name$index_name!empty($index['primary']));
  1836.                     if (PEAR::isError($result)) {
  1837.                         return $result;
  1838.                     }
  1839.                     $result $this->db->manager->createConstraint($table_name$index_name$index);
  1840.                 else {
  1841.                     $result $this->db->manager->dropIndex($table_name$index_name);
  1842.                     if (PEAR::isError($result)) {
  1843.                         return $result;
  1844.                     }
  1845.                     $result $this->db->manager->createIndex($table_name$index_name$index);
  1846.                 }
  1847.                 if (PEAR::isError($result)) {
  1848.                     return $result;
  1849.                 }
  1850.                 $alterations++;
  1851.             }
  1852.         }
  1853.         if (!empty($changes['add']&& is_array($changes['add'])) {
  1854.             foreach ($changes['add'as $index_name => $index{
  1855.                 if (!empty($index['primary']|| !empty($index['unique'])) {
  1856.                     $result $this->db->manager->createConstraint($table_name$index_name$index);
  1857.                 else {
  1858.                     $result $this->db->manager->createIndex($table_name$index_name$index);
  1859.                 }
  1860.                 if (PEAR::isError($result)) {
  1861.                     return $result;
  1862.                 }
  1863.                 $alterations++;
  1864.             }
  1865.         }
  1866.  
  1867.         return $alterations;
  1868.     }
  1869.  
  1870.     // }}}
  1871.     // {{{ alterDatabaseTables()
  1872.  
  1873.     /**
  1874.      * Execute the necessary actions to implement the requested changes
  1875.      * in the tables inside a database structure.
  1876.      *
  1877.      * @param array multi dimensional array that contains the current definition
  1878.      * @param array multi dimensional array that contains the previous definition
  1879.      * @param array associative array that contains the definition of the changes
  1880.      *               that are meant to be applied to the database structure.
  1881.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1882.      * @access public
  1883.      */
  1884.     function alterDatabaseTables($current_definition$previous_definition$changes)
  1885.     {
  1886.         /* FIXME: tables marked to be added are initialized by createTable(), others don't */
  1887.         $alterations = 0;
  1888.         if (empty($changes)) {
  1889.             return $alterations;
  1890.         }
  1891.  
  1892.         if (!empty($changes['add']&& is_array($changes['add'])) {
  1893.             foreach ($changes['add'as $table_name => $table{
  1894.                 $result $this->createTable($table_name$current_definition[$table_name]);
  1895.                 if (PEAR::isError($result)) {
  1896.                     return $result;
  1897.                 }
  1898.                 $alterations++;
  1899.             }
  1900.         }
  1901.  
  1902.         if (!empty($changes['remove']&& is_array($changes['remove'])) {
  1903.             foreach ($changes['remove'as $table_name => $table{
  1904.                 $result $this->db->manager->dropTable($table_name);
  1905.                 if (PEAR::isError($result)) {
  1906.                     return $result;
  1907.                 }
  1908.                 $alterations++;
  1909.             }
  1910.         }
  1911.  
  1912.         if (!empty($changes['change']&& is_array($changes['change'])) {
  1913.             foreach ($changes['change'as $table_name => $table{
  1914.                 $indexes = array();
  1915.                 if (!empty($table['indexes'])) {
  1916.                     $indexes $table['indexes'];
  1917.                     unset($table['indexes']);
  1918.                 }
  1919.                 if (!empty($indexes['remove'])) {
  1920.                     $result $this->alterDatabaseIndexes($table_namearray('remove' => $indexes['remove']));
  1921.                     if (PEAR::isError($result)) {
  1922.                         return $result;
  1923.                     }
  1924.                     unset($indexes['remove']);
  1925.                     $alterations += $result;
  1926.                 }
  1927.                 $result $this->db->manager->alterTable($table_name$tablefalse);
  1928.                 if (PEAR::isError($result)) {
  1929.                     return $result;
  1930.                 }
  1931.                 $alterations++;
  1932.                 if (!empty($indexes)) {
  1933.                     $result $this->alterDatabaseIndexes($table_name$indexes);
  1934.                     if (PEAR::isError($result)) {
  1935.                         return $result;
  1936.                     }
  1937.                     $alterations += $result;
  1938.                 }
  1939.             }
  1940.         }
  1941.  
  1942.         return $alterations;
  1943.     }
  1944.  
  1945.     // }}}
  1946.     // {{{ alterDatabaseSequences()
  1947.  
  1948.     /**
  1949.      * Execute the necessary actions to implement the requested changes
  1950.      * in the sequences inside a database structure.
  1951.      *
  1952.      * @param array multi dimensional array that contains the current definition
  1953.      * @param array multi dimensional array that contains the previous definition
  1954.      * @param array associative array that contains the definition of the changes
  1955.      *               that are meant to be applied to the database structure.
  1956.      * @return bool|MDB2_ErrorMDB2_OK or error object
  1957.      * @access public
  1958.      */
  1959.     function alterDatabaseSequences($current_definition$previous_definition$changes)
  1960.     {
  1961.         $alterations = 0;
  1962.         if (empty($changes)) {
  1963.             return $alterations;
  1964.         }
  1965.  
  1966.         if (!empty($changes['add']&& is_array($changes['add'])) {
  1967.             foreach ($changes['add'as $sequence_name => $sequence{
  1968.                 $result $this->createSequence($sequence_name$current_definition[$sequence_name]);
  1969.                 if (PEAR::isError($result)) {
  1970.                     return $result;
  1971.                 }
  1972.                 $alterations++;
  1973.             }
  1974.         }
  1975.  
  1976.         if (!empty($changes['remove']&& is_array($changes['remove'])) {
  1977.             foreach ($changes['remove'as $sequence_name => $sequence{
  1978.                 $result $this->db->manager->dropSequence($sequence_name);
  1979.                 if (PEAR::isError($result)) {
  1980.                     return $result;
  1981.                 }
  1982.                 $alterations++;
  1983.             }
  1984.         }
  1985.  
  1986.         if (!empty($changes['change']&& is_array($changes['change'])) {
  1987.             foreach ($changes['change'as $sequence_name => $sequence{
  1988.                 $result $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']);
  1989.                 if (PEAR::isError($result)) {
  1990.                     return $result;
  1991.                 }
  1992.                 $result $this->createSequence($sequence_name$sequence);
  1993.                 if (PEAR::isError($result)) {
  1994.                     return $result;
  1995.                 }
  1996.                 $alterations++;
  1997.             }
  1998.         }
  1999.  
  2000.         return $alterations;
  2001.     }
  2002.  
  2003.     // }}}
  2004.     // {{{ alterDatabase()
  2005.  
  2006.     /**
  2007.      * Execute the necessary actions to implement the requested changes
  2008.      * in a database structure.
  2009.      *
  2010.      * @param array multi dimensional array that contains the current definition
  2011.      * @param array multi dimensional array that contains the previous definition
  2012.      * @param array associative array that contains the definition of the changes
  2013.      *               that are meant to be applied to the database structure.
  2014.      * @return bool|MDB2_ErrorMDB2_OK or error object
  2015.      * @access public
  2016.      */
  2017.     function alterDatabase($current_definition$previous_definition$changes)
  2018.     {
  2019.         $alterations = 0;
  2020.         if (empty($changes)) {
  2021.             return $alterations;
  2022.         }
  2023.  
  2024.         $result $this->verifyAlterDatabase($changes);
  2025.         if (PEAR::isError($result)) {
  2026.             return $result;
  2027.         }
  2028.  
  2029.         if (!empty($current_definition['name'])) {
  2030.             $previous_database_name $this->db->setDatabase($current_definition['name']);
  2031.         }
  2032.  
  2033.         if (($support_transactions $this->db->supports('transactions'))
  2034.             && PEAR::isError($result $this->db->beginNestedTransaction())
  2035.         {
  2036.             return $result;
  2037.         }
  2038.  
  2039.         if (!empty($changes['tables']&& !empty($current_definition['tables'])) {
  2040.             $current_tables = isset($current_definition['tables']$current_definition['tables': array();
  2041.             $previous_tables = isset($previous_definition['tables']$previous_definition['tables': array();
  2042.             $result $this->alterDatabaseTables($current_tables$previous_tables$changes['tables']);
  2043.             if (is_numeric($result)) {
  2044.                 $alterations += $result;
  2045.             }
  2046.         }
  2047.  
  2048.         if (!PEAR::isError($result&& !empty($changes['sequences'])) {
  2049.             $current_sequences = isset($current_definition['sequences']$current_definition['sequences': array();
  2050.             $previous_sequences = isset($previous_definition['sequences']$previous_definition['sequences': array();
  2051.             $result $this->alterDatabaseSequences($current_sequences$previous_sequences$changes['sequences']);
  2052.             if (is_numeric($result)) {
  2053.                 $alterations += $result;
  2054.             }
  2055.         }
  2056.  
  2057.         if ($support_transactions{
  2058.             $res $this->db->completeNestedTransaction();
  2059.             if (PEAR::isError($res)) {
  2060.                 $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  2061.                     'Could not end transaction ('.
  2062.                     $res->getMessage().' ('.$res->getUserinfo().'))');
  2063.             }
  2064.         elseif (PEAR::isError($result&& $alterations{
  2065.             $result $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  2066.                 'the requested database alterations were only partially implemented ('.
  2067.                 $result->getMessage().' ('.$result->getUserinfo().'))');
  2068.         }
  2069.  
  2070.         if (isset($previous_database_name)) {
  2071.             $this->db->setDatabase($previous_database_name);
  2072.         }
  2073.         return $result;
  2074.     }
  2075.  
  2076.     // }}}
  2077.     // {{{ dumpDatabaseChanges()
  2078.  
  2079.     /**
  2080.      * Dump the changes between two database definitions.
  2081.      *
  2082.      * @param array associative array that specifies the list of database
  2083.      *               definitions changes as returned by the _compareDefinitions
  2084.      *               manager class function.
  2085.      * @return bool|MDB2_ErrorMDB2_OK or error object
  2086.      * @access public
  2087.      */
  2088.     function dumpDatabaseChanges($changes)
  2089.     {
  2090.         if (!empty($changes['tables'])) {
  2091.             if (!empty($changes['tables']['add']&& is_array($changes['tables']['add'])) {
  2092.                 foreach ($changes['tables']['add'as $table_name => $table{
  2093.                     $this->db->debug("$table_name:"__FUNCTION__);
  2094.                     $this->db->debug("\tAdded table '$table_name'"__FUNCTION__);
  2095.                 }
  2096.             }
  2097.             if (!empty($changes['tables']['remove']&& is_array($changes['tables']['remove'])) {
  2098.                 foreach ($changes['tables']['remove'as $table_name => $table{
  2099.                     $this->db->debug("$table_name:"__FUNCTION__);
  2100.                     $this->db->debug("\tRemoved table '$table_name'"__FUNCTION__);
  2101.                 }
  2102.             }
  2103.             if (!empty($changes['tables']['change']&& is_array($changes['tables']['change'])) {
  2104.                 foreach ($changes['tables']['change'as $table_name => $table{
  2105.                     if (array_key_exists('name'$table)) {
  2106.                         $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'"__FUNCTION__);
  2107.                     }
  2108.                     if (!empty($table['add']&& is_array($table['add'])) {
  2109.                         foreach ($table['add'as $field_name => $field{
  2110.                             $this->db->debug("\tAdded field '".$field_name."'"__FUNCTION__);
  2111.                         }
  2112.                     }
  2113.                     if (!empty($table['remove']&& is_array($table['remove'])) {
  2114.                         foreach ($table['remove'as $field_name => $field{
  2115.                             $this->db->debug("\tRemoved field '".$field_name."'"__FUNCTION__);
  2116.                         }
  2117.                     }
  2118.                     if (!empty($table['rename']&& is_array($table['rename'])) {
  2119.                         foreach ($table['rename'as $field_name => $field{
  2120.                             $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'"__FUNCTION__);
  2121.                         }
  2122.                     }
  2123.                     if (!empty($table['change']&& is_array($table['change'])) {
  2124.                         foreach ($table['change'as $field_name => $field{
  2125.                             $field $field['definition'];
  2126.                             if (array_key_exists('type'$field)) {
  2127.                                 $this->db->debug(
  2128.                                     "\tChanged field '$field_name' type to '".$field['type']."'"__FUNCTION__);
  2129.                             }
  2130.                             if (array_key_exists('unsigned'$field)) {
  2131.                                 $this->db->debug(
  2132.                                     "\tChanged field '$field_name' type to '".
  2133.                                     (!empty($field['unsigned']&& $field['unsigned''' 'not ')."unsigned'",
  2134.                                     __FUNCTION__);
  2135.                             }
  2136.                             if (array_key_exists('length'$field)) {
  2137.                                 $this->db->debug(
  2138.                                     "\tChanged field '$field_name' length to '".
  2139.                                     (!empty($field['length']$field['length']'no length')."'"__FUNCTION__);
  2140.                             }
  2141.                             if (array_key_exists('default'$field)) {
  2142.                                 $this->db->debug(
  2143.                                     "\tChanged field '$field_name' default to ".
  2144.                                     (isset($field['default']"'".$field['default']."'" 'NULL')__FUNCTION__);
  2145.                             }
  2146.                             if (array_key_exists('notnull'$field)) {
  2147.                                 $this->db->debug(
  2148.                                    "\tChanged field '$field_name' notnull to ".
  2149.                                     (!empty($field['notnull']&& $field['notnull''true' 'false'),
  2150.                                     __FUNCTION__
  2151.                                 );
  2152.                             }
  2153.                         }
  2154.                     }
  2155.                     if (!empty($table['indexes']&& is_array($table['indexes'])) {
  2156.                         if (!empty($table['indexes']['add']&& is_array($table['indexes']['add'])) {
  2157.                             foreach ($table['indexes']['add'as $index_name => $index{
  2158.                                 $this->db->debug("\tAdded index '".$index_name.
  2159.                                     "' of table '$table_name'"__FUNCTION__);
  2160.                             }
  2161.                         }
  2162.                         if (!empty($table['indexes']['remove']&& is_array($table['indexes']['remove'])) {
  2163.                             foreach ($table['indexes']['remove'as $index_name => $index{
  2164.                                 $this->db->debug("\tRemoved index '".$index_name.
  2165.                                     "' of table '$table_name'"__FUNCTION__);
  2166.                             }
  2167.                         }
  2168.                         if (!empty($table['indexes']['change']&& is_array($table['indexes']['change'])) {
  2169.                             foreach ($table['indexes']['change'as $index_name => $index{
  2170.                                 if (array_key_exists('name'$index)) {
  2171.                                     $this->db->debug(
  2172.                                         "\tRenamed index '".$index_name."' to '".$index['name'].
  2173.                                         "' on table '$table_name'"__FUNCTION__);
  2174.                                 }
  2175.                                 if (array_key_exists('unique'$index)) {
  2176.                                     $this->db->debug(
  2177.                                         "\tChanged index '".$index_name."' unique to '".
  2178.                                         !empty($index['unique'])."' on table '$table_name'"__FUNCTION__);
  2179.                                 }
  2180.                                 if (array_key_exists('primary'$index)) {
  2181.                                     $this->db->debug(
  2182.                                         "\tChanged index '".$index_name."' primary to '".
  2183.                                         !empty($index['primary'])."' on table '$table_name'"__FUNCTION__);
  2184.                                 }
  2185.                                 if (array_key_exists('change'$index)) {
  2186.                                     $this->db->debug("\tChanged index '".$index_name.
  2187.                                         "' on table '$table_name'"__FUNCTION__);
  2188.                                 }
  2189.                             }
  2190.                         }
  2191.                     }
  2192.                 }
  2193.             }
  2194.         }
  2195.         if (!empty($changes['sequences'])) {
  2196.             if (!empty($changes['sequences']['add']&& is_array($changes['sequences']['add'])) {
  2197.                 foreach ($changes['sequences']['add'as $sequence_name => $sequence{
  2198.                     $this->db->debug("$sequence_name:"__FUNCTION__);
  2199.                     $this->db->debug("\tAdded sequence '$sequence_name'"__FUNCTION__);
  2200.                 }
  2201.             }
  2202.             if (!empty($changes['sequences']['remove']&& is_array($changes['sequences']['remove'])) {
  2203.                 foreach ($changes['sequences']['remove'as $sequence_name => $sequence{
  2204.                     $this->db->debug("$sequence_name:"__FUNCTION__);
  2205.                     $this->db->debug("\tAdded sequence '$sequence_name'"__FUNCTION__);
  2206.                 }
  2207.             }
  2208.             if (!empty($changes['sequences']['change']&& is_array($changes['sequences']['change'])) {
  2209.                 foreach ($changes['sequences']['change'as $sequence_name => $sequence{
  2210.                     if (array_key_exists('name'$sequence)) {
  2211.                         $this->db->debug(
  2212.                             "\tRenamed sequence '$sequence_name' to '".
  2213.                             $sequence['name']."'"__FUNCTION__);
  2214.                     }
  2215.                     if (!empty($sequence['change']&& is_array($sequence['change'])) {
  2216.                         foreach ($sequence['change'as $sequence_name => $sequence{
  2217.                             if (array_key_exists('start'$sequence)) {
  2218.                                 $this->db->debug(
  2219.                                     "\tChanged sequence '$sequence_name' start to '".
  2220.                                     $sequence['start']."'"__FUNCTION__);
  2221.                             }
  2222.                         }
  2223.                     }
  2224.                 }
  2225.             }
  2226.         }
  2227.         return MDB2_OK;
  2228.     }
  2229.  
  2230.     // }}}
  2231.     // {{{ dumpDatabase()
  2232.  
  2233.     /**
  2234.      * Dump a previously parsed database structure in the Metabase schema
  2235.      * XML based format suitable for the Metabase parser. This function
  2236.      * may optionally dump the database definition with initialization
  2237.      * commands that specify the data that is currently present in the tables.
  2238.      *
  2239.      * @param array multi dimensional array that contains the current definition
  2240.      * @param array associative array that takes pairs of tag
  2241.      *  names and values that define dump options.
  2242.      *                  <pre>array (
  2243.      *                      'output_mode'    =>    String
  2244.      *                          'file' :   dump into a file
  2245.      *                          default:   dump using a function
  2246.      *                      'output'        =>    String
  2247.      *                          depending on the 'Output_Mode'
  2248.      *                                   name of the file
  2249.      *                                   name of the function
  2250.      *                      'end_of_line'        =>    String
  2251.      *                          end of line delimiter that should be used
  2252.      *                          default: "\n"
  2253.      *                  );</pre>
  2254.      * @param int that determines what data to dump
  2255.      *               + MDB2_SCHEMA_DUMP_ALL       : the entire db
  2256.      *               + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
  2257.      *               + MDB2_SCHEMA_DUMP_CONTENT   : only the content of the db
  2258.      * @return bool|MDB2_ErrorMDB2_OK or error object
  2259.      * @access public
  2260.      */
  2261.     function dumpDatabase($database_definition$arguments$dump = MDB2_SCHEMA_DUMP_ALL)
  2262.     {
  2263.         $class_name $this->options['writer'];
  2264.         $result = MDB2::loadClass($class_name$this->db->getOption('debug'));
  2265.         if (PEAR::isError($result)) {
  2266.             return $result;
  2267.         }
  2268.  
  2269.         // get initialization data
  2270.         if (isset($database_definition['tables']&& is_array($database_definition['tables'])
  2271.             && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT
  2272.         {
  2273.             foreach ($database_definition['tables'as $table_name => $table{
  2274.                 $fields = array();
  2275.                 $fieldsq = array();
  2276.                 foreach ($table['fields'as $field_name => $field{
  2277.                     $fields[$field_name$field['type'];
  2278.                     $fieldsq[$this->db->quoteIdentifier($field_nametrue);
  2279.                 }
  2280.                 $query 'SELECT '.implode(', '$fieldsq).' FROM ';
  2281.                 $query.= $this->db->quoteIdentifier($table_nametrue);
  2282.                 $data $this->db->queryAll($query$fieldsMDB2_FETCHMODE_ASSOC);
  2283.                 if (PEAR::isError($data)) {
  2284.                     return $data;
  2285.                 }
  2286.                 if (!empty($data)) {
  2287.                     $initialization = array();
  2288.                     $lob_buffer_length $this->db->getOption('lob_buffer_length');
  2289.                     foreach ($data as $row{
  2290.                         $rows = array();
  2291.                         foreach($row as $key => $lob{
  2292.                             if (is_resource($lob)) {
  2293.                                 $value '';
  2294.                                 while (!feof($lob)) {
  2295.                                     $value.= fread($lob$lob_buffer_length);
  2296.                                 }
  2297.                                 $row[$key$value;
  2298.                             }
  2299.                             $rows[= array('name' => $key'group' => array('type' => 'value''data' => $row[$key]));
  2300.                         }
  2301.                         $initialization[= array('type' => 'insert''data' => array('field' => $rows));
  2302.                     }
  2303.                     $database_definition['tables'][$table_name]['initialization'$initialization;
  2304.                 }
  2305.             }
  2306.         }
  2307.  
  2308.         $writer =new $class_name($this->options['valid_types']);
  2309.         return $writer->dumpDatabase($database_definition$arguments$dump);
  2310.     }
  2311.  
  2312.     // }}}
  2313.     // {{{ writeInitialization()
  2314.  
  2315.     /**
  2316.      * Write initialization and sequences
  2317.      *
  2318.      * @param string|array data file or data array
  2319.      * @param string|array structure file or array
  2320.      * @param array associative array that is passed to the argument
  2321.      *  of the same name to the parseDatabaseDefinitionFile function. (there third
  2322.      *  param)
  2323.      * @return bool|MDB2_ErrorMDB2_OK or error object
  2324.      * @access public
  2325.      */
  2326.     function writeInitialization($data$structure = false$variables = array())
  2327.     {
  2328.         if ($structure{
  2329.             $structure $this->parseDatabaseDefinition($structurefalse$variables);
  2330.             if (PEAR::isError($structure)) {
  2331.                 return $structure;
  2332.             }
  2333.         }
  2334.  
  2335.         $data $this->parseDatabaseDefinition($datafalse$variablesfalse$structure);
  2336.         if (PEAR::isError($data)) {
  2337.             return $data;
  2338.         }
  2339.  
  2340.         $previous_database_name = null;
  2341.         if (!empty($data['name'])) {
  2342.             $previous_database_name $this->db->setDatabase($data['name']);
  2343.         elseif(!empty($structure['name'])) {
  2344.             $previous_database_name $this->db->setDatabase($structure['name']);
  2345.         }
  2346.  
  2347.         if (!empty($data['tables']&& is_array($data['tables'])) {
  2348.             foreach ($data['tables'as $table_name => $table{
  2349.                 if (empty($table['initialization'])) {
  2350.                     continue;
  2351.                 }
  2352.                 $result $this->initializeTable($table_name$table);
  2353.                 if (PEAR::isError($result)) {
  2354.                     return $result;
  2355.                 }
  2356.             }
  2357.         }
  2358.  
  2359.         if (!empty($structure['sequences']&& is_array($structure['sequences'])) {
  2360.             foreach ($structure['sequences'as $sequence_name => $sequence{
  2361.                 if (isset($data['sequences'][$sequence_name])
  2362.                     || !isset($sequence['on']['table'])
  2363.                     || !isset($data['tables'][$sequence['on']['table']])
  2364.                 {
  2365.                     continue;
  2366.                 }
  2367.                 $result $this->createSequence($sequence_name$sequencetrue);
  2368.                 if (PEAR::isError($result)) {
  2369.                     return $result;
  2370.                 }
  2371.             }
  2372.         }
  2373.         if (!empty($data['sequences']&& is_array($data['sequences'])) {
  2374.             foreach ($data['sequences'as $sequence_name => $sequence{
  2375.                 $result $this->createSequence($sequence_name$sequencetrue);
  2376.                 if (PEAR::isError($result)) {
  2377.                     return $result;
  2378.                 }
  2379.             }
  2380.         }
  2381.  
  2382.         if (isset($previous_database_name)) {
  2383.             $this->db->setDatabase($previous_database_name);
  2384.         }
  2385.  
  2386.         return MDB2_OK;
  2387.     }
  2388.  
  2389.     // }}}
  2390.     // {{{ updateDatabase()
  2391.  
  2392.     /**
  2393.      * Compare the correspondent files of two versions of a database schema
  2394.      * definition: the previously installed and the one that defines the schema
  2395.      * that is meant to update the database.
  2396.      * If the specified previous definition file does not exist, this function
  2397.      * will create the database from the definition specified in the current
  2398.      * schema file.
  2399.      * If both files exist, the function assumes that the database was previously
  2400.      * installed based on the previous schema file and will update it by just
  2401.      * applying the changes.
  2402.      * If this function succeeds, the contents of the current schema file are
  2403.      * copied to replace the previous schema file contents. Any subsequent schema
  2404.      * changes should only be done on the file specified by the $current_schema_file
  2405.      * to let this function make a consistent evaluation of the exact changes that
  2406.      * need to be applied.
  2407.      *
  2408.      * @param string|arrayfilename or array of the updated database schema definition.
  2409.      * @param string|arrayfilename or array of the previously installed database schema definition.
  2410.      * @param array associative array that is passed to the argument of the same
  2411.      *               name to the parseDatabaseDefinitionFile function. (there third param)
  2412.      * @param bool determines if the disable_query option should be set to true
  2413.      *               for the alterDatabase() or createDatabase() call
  2414.      * @return bool|MDB2_ErrorMDB2_OK or error object
  2415.      * @access public
  2416.      */
  2417.     function updateDatabase($current_schema$previous_schema = false
  2418.         $variables = array()$disable_query = false$overwrite_old_schema_file = false)
  2419.     {
  2420.         $current_definition $this->parseDatabaseDefinition(
  2421.             $current_schemafalse$variables$this->options['fail_on_invalid_names']
  2422.         );
  2423.         if (PEAR::isError($current_definition)) {
  2424.             return $current_definition;
  2425.         }
  2426.  
  2427.         $previous_definition = false;
  2428.         if ($previous_schema{
  2429.             $previous_definition $this->parseDatabaseDefinition(
  2430.                 $previous_schematrue$variables$this->options['fail_on_invalid_names']
  2431.             );
  2432.             if (PEAR::isError($previous_definition)) {
  2433.                 return $previous_definition;
  2434.             }
  2435.         }
  2436.  
  2437.         if ($previous_definition{
  2438.             $errorcodes = array(MDB2_ERROR_UNSUPPORTEDMDB2_ERROR_NOT_CAPABLE);
  2439.             $this->db->expectError($errorcodes);
  2440.             $databases $this->db->manager->listDatabases();
  2441.             $this->db->popExpect();
  2442.             if (PEAR::isError($databases)) {
  2443.                 if (!MDB2::isError($databases$errorcodes)) {
  2444.                     return $databases;
  2445.                 }
  2446.             elseif (!is_array($databases||
  2447.                 !in_array($current_definition['name']$databases)
  2448.             {
  2449.                 return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  2450.                     'database to update does not exist: '.$current_definition['name']);
  2451.             }
  2452.  
  2453.             $changes $this->compareDefinitions($current_definition$previous_definition);
  2454.             if (PEAR::isError($changes)) {
  2455.                 return $changes;
  2456.             }
  2457.  
  2458.             if (is_array($changes)) {
  2459.                 $this->db->setOption('disable_query'$disable_query);
  2460.                 $result $this->alterDatabase($current_definition$previous_definition$changes);
  2461.                 $this->db->setOption('disable_query'false);
  2462.                 if (PEAR::isError($result)) {
  2463.                     return $result;
  2464.                 }
  2465.                 $copy = true;
  2466.                 if ($this->db->options['debug']{
  2467.                     $result $this->dumpDatabaseChanges($changes);
  2468.                     if (PEAR::isError($result)) {
  2469.                         return $result;
  2470.                     }
  2471.                 }
  2472.             }
  2473.         else {
  2474.             $this->db->setOption('disable_query'$disable_query);
  2475.             $result $this->createDatabase($current_definition);
  2476.             $this->db->setOption('disable_query'false);
  2477.             if (PEAR::isError($result)) {
  2478.                 return $result;
  2479.             }
  2480.         }
  2481.  
  2482.         if ($overwrite_old_schema_file
  2483.             && !$disable_query
  2484.             && is_string($previous_schema&& is_string($current_schema)
  2485.             && !copy($current_schema$previous_schema)
  2486.         {
  2487.             return $this->raiseError(MDB2_SCHEMA_ERRORnullnull,
  2488.                 'Could not copy the new database definition file to the current file');
  2489.         }
  2490.  
  2491.         return MDB2_OK;
  2492.     }
  2493.     // }}}
  2494.     // {{{ errorMessage()
  2495.  
  2496.     /**
  2497.      * Return a textual error message for a MDB2 error code
  2498.      *
  2499.      * @param   int|arrayinteger error code,
  2500.      *                      <code>null</code> to get the current error code-message map,
  2501.      *                     or an array with a new error code-message map
  2502.      * @return  string  error message, or false if the error code was not recognized
  2503.      * @access public
  2504.      */
  2505.     function errorMessage($value = null)
  2506.     {
  2507.         static $errorMessages;
  2508.         if (is_array($value)) {
  2509.             $errorMessages $value;
  2510.             return MDB2_OK;
  2511.         elseif (!isset($errorMessages)) {
  2512.             $errorMessages = array(
  2513.                 MDB2_SCHEMA_ERROR              => 'unknown error',
  2514.                 MDB2_SCHEMA_ERROR_PARSE        => 'schema parse error',
  2515.                 MDB2_SCHEMA_ERROR_VALIDATE     => 'schema validation error',
  2516.                 MDB2_SCHEMA_ERROR_INVALID      => 'invalid',
  2517.                 MDB2_SCHEMA_ERROR_UNSUPPORTED  => 'not supported',
  2518.                 MDB2_SCHEMA_ERROR_WRITER       => 'schema writer error',
  2519.             );
  2520.         }
  2521.  
  2522.         if (is_null($value)) {
  2523.             return $errorMessages;
  2524.         }
  2525.  
  2526.         if (PEAR::isError($value)) {
  2527.             $value $value->getCode();
  2528.         }
  2529.  
  2530.         return !empty($errorMessages[$value]?
  2531.            $errorMessages[$value$errorMessages[MDB2_SCHEMA_ERROR];
  2532.     }
  2533.  
  2534.     // }}}
  2535.     // {{{ raiseError()
  2536.  
  2537.     /**
  2538.      * This method is used to communicate an error and invoke error
  2539.      * callbacks etc.  Basically a wrapper for PEAR::raiseError
  2540.      * without the message string.
  2541.      *
  2542.      * @param int|PEAR_Error integer error code or and PEAR_Error instance
  2543.      * @param int      error mode, see PEAR_Error docs
  2544.      *
  2545.      *                  error level (E_USER_NOTICE etc).  If error mode is
  2546.      *                  PEAR_ERROR_CALLBACK, this is the callback function,
  2547.      *                  either as a function name, or as an array of an
  2548.      *                  object and method name.  For other error modes this
  2549.      *                  parameter is ignored.
  2550.      * @param array    Options, depending on the mode, @see PEAR::setErrorHandling
  2551.      * @param string   Extra debug information.  Defaults to the last
  2552.      *                  query and native error code.
  2553.      * @return object  PEAR error object
  2554.      * @access  public
  2555.      * @see PEAR_Error
  2556.      */
  2557.     function &raiseError($code = null$mode = null$options = null$userinfo = null)
  2558.     {
  2559.         $err =PEAR::raiseError(null$code$mode$options$userinfo'MDB2_Schema_Error'true);
  2560.         return $err;
  2561.     }
  2562.  
  2563.     // }}}
  2564.     // {{{ isError()
  2565.  
  2566.     /**
  2567.      * Tell whether a value is an MDB2_Schema error.
  2568.      *
  2569.      * @param   mixed the value to test
  2570.      * @param   int   if $data is an error object, return true only if $code is
  2571.                       a string and $db->getMessage() == $code or
  2572.      *                 $code is an integer and $db->getCode() == $code
  2573.      * @return  bool  true if parameter is an error
  2574.      * @access  public
  2575.      */
  2576.     function isError($data$code = null)
  2577.     {
  2578.         if (is_a($data'MDB2_Schema_Error')) {
  2579.             if (is_null($code)) {
  2580.                 return true;
  2581.             elseif (is_string($code)) {
  2582.                 return $data->getMessage(=== $code;
  2583.             else {
  2584.                 $code = (array)$code;
  2585.                 return in_array($data->getCode()$code);
  2586.             }
  2587.         }
  2588.         return false;
  2589.     }
  2590.  
  2591.     // }}}
  2592. }
  2593.  
  2594. /**
  2595.  * MDB2_Schema_Error implements a class for reporting portable database error
  2596.  * messages.
  2597.  *
  2598.  * @package MDB2_Schema
  2599.  * @category Database
  2600.  * @author  Stig Bakken <ssb@fast.no>
  2601.  */
  2602. class MDB2_Schema_Error extends PEAR_Error
  2603. {
  2604.     /**
  2605.      * MDB2_Schema_Error constructor.
  2606.      *
  2607.      * @param mixed     error code, or string with error message.
  2608.      * @param int       what 'error mode' to operate in
  2609.      * @param int       what error level to use for $mode & PEAR_ERROR_TRIGGER
  2610.      * @param mixed     additional debug info, such as the last query
  2611.      * @access  public
  2612.      */
  2613.     function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR$mode = PEAR_ERROR_RETURN,
  2614.               $level = E_USER_NOTICE$debuginfo = null)
  2615.     {
  2616.         $this->PEAR_Error('MDB2_Schema Error: ' MDB2_Schema::errorMessage($code)$code,
  2617.             $mode$level$debuginfo);
  2618.     }
  2619. }
  2620. ?>

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