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

Source for file mysql.php

Documentation is available at mysql.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5                                                 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith                                         |
  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: mysql.php,v 1.79 2007/11/25 13:38:29 quipo Exp $
  46. //
  47.  
  48. require_once 'MDB2/Driver/Reverse/Common.php';
  49.  
  50. /**
  51.  * MDB2 MySQL driver for the schema reverse engineering module
  52.  *
  53.  * @package MDB2
  54.  * @category Database
  55.  * @author  Lukas Smith <smith@pooteeweet.org>
  56.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  57.  */
  58. class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common
  59. {
  60.     // {{{ getTableFieldDefinition()
  61.  
  62.     /**
  63.      * Get the structure of a field into an array
  64.      *
  65.      * @param string $table_name name of table that should be used in method
  66.      * @param string $field_name name of field that should be used in method
  67.      * @return mixed data array on success, a MDB2 error on failure
  68.      * @access public
  69.      */
  70.     function getTableFieldDefinition($table_name$field_name)
  71.     {
  72.         $db =$this->getDBInstance();
  73.         if (PEAR::isError($db)) {
  74.             return $db;
  75.         }
  76.  
  77.         $result $db->loadModule('Datatype'nulltrue);
  78.         if (PEAR::isError($result)) {
  79.             return $result;
  80.         }
  81.  
  82.         list($schema$table$this->splitTableSchema($table_name);
  83.  
  84.         $table $db->quoteIdentifier($tabletrue);
  85.         $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
  86.         $columns $db->queryAll($querynullMDB2_FETCHMODE_ASSOC);
  87.         if (PEAR::isError($columns)) {
  88.             return $columns;
  89.         }
  90.         foreach ($columns as $column{
  91.             $column array_change_key_case($columnCASE_LOWER);
  92.             $column['name'$column['field'];
  93.             unset($column['field']);
  94.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  95.                 if ($db->options['field_case'== CASE_LOWER{
  96.                     $column['name'strtolower($column['name']);
  97.                 else {
  98.                     $column['name'strtoupper($column['name']);
  99.                 }
  100.             else {
  101.                 $column array_change_key_case($column$db->options['field_case']);
  102.             }
  103.             if ($field_name == $column['name']{
  104.                 $mapped_datatype $db->datatype->mapNativeDatatype($column);
  105.                 if (PEAR::isError($mapped_datatype)) {
  106.                     return $mapped_datatype;
  107.                 }
  108.                 list($types$length$unsigned$fixed$mapped_datatype;
  109.                 $notnull = false;
  110.                 if (empty($column['null']|| $column['null'!== 'YES'{
  111.                     $notnull = true;
  112.                 }
  113.                 $default = false;
  114.                 if (array_key_exists('default'$column)) {
  115.                     $default $column['default'];
  116.                     if (is_null($default&& $notnull{
  117.                         $default '';
  118.                     }
  119.                 }
  120.                 $autoincrement = false;
  121.                 if (!empty($column['extra']&& $column['extra'== 'auto_increment'{
  122.                     $autoincrement = true;
  123.                 }
  124.                 $collate = null;
  125.                 if (!empty($column['collation'])) {
  126.                     $collate $column['collation'];
  127.                     $charset preg_replace('/(.+?)(_.+)?/''$1'$collate);
  128.                 }
  129.  
  130.                 $definition[0= array(
  131.                     'notnull' => $notnull,
  132.                     'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i''\\1'$column['type'])
  133.                 );
  134.                 if (!is_null($length)) {
  135.                     $definition[0]['length'$length;
  136.                 }
  137.                 if (!is_null($unsigned)) {
  138.                     $definition[0]['unsigned'$unsigned;
  139.                 }
  140.                 if (!is_null($fixed)) {
  141.                     $definition[0]['fixed'$fixed;
  142.                 }
  143.                 if ($default !== false{
  144.                     $definition[0]['default'$default;
  145.                 }
  146.                 if ($autoincrement !== false{
  147.                     $definition[0]['autoincrement'$autoincrement;
  148.                 }
  149.                 if (!is_null($collate)) {
  150.                     $definition[0]['collate'$collate;
  151.                     $definition[0]['charset'$charset;
  152.                 }
  153.                 foreach ($types as $key => $type{
  154.                     $definition[$key$definition[0];
  155.                     if ($type == 'clob' || $type == 'blob'{
  156.                         unset($definition[$key]['default']);
  157.                     elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
  158.                         $definition[$key]['default''0000-00-00 00:00:00';
  159.                     }
  160.                     $definition[$key]['type'$type;
  161.                     $definition[$key]['mdb2type'$type;
  162.                 }
  163.                 return $definition;
  164.             }
  165.         }
  166.  
  167.         return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  168.             'it was not specified an existing table column'__FUNCTION__);
  169.     }
  170.  
  171.     // }}}
  172.     // {{{ getTableIndexDefinition()
  173.  
  174.     /**
  175.      * Get the structure of an index into an array
  176.      *
  177.      * @param string $table_name name of table that should be used in method
  178.      * @param string $index_name name of index that should be used in method
  179.      * @return mixed data array on success, a MDB2 error on failure
  180.      * @access public
  181.      */
  182.     function getTableIndexDefinition($table_name$index_name)
  183.     {
  184.         $db =$this->getDBInstance();
  185.         if (PEAR::isError($db)) {
  186.             return $db;
  187.         }
  188.  
  189.         list($schema$table$this->splitTableSchema($table_name);
  190.  
  191.         $table $db->quoteIdentifier($tabletrue);
  192.         $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
  193.         $index_name_mdb2 $db->getIndexName($index_name);
  194.         $result $db->queryRow(sprintf($query$db->quote($index_name_mdb2)));
  195.         if (!PEAR::isError($result&& !is_null($result)) {
  196.             // apply 'idxname_format' only if the query succeeded, otherwise
  197.             // fallback to the given $index_name, without transformation
  198.             $index_name $index_name_mdb2;
  199.         }
  200.         $result $db->query(sprintf($query$db->quote($index_name)));
  201.         if (PEAR::isError($result)) {
  202.             return $result;
  203.         }
  204.         $colpos = 1;
  205.         $definition = array();
  206.         while (is_array($row $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
  207.             $row array_change_key_case($rowCASE_LOWER);
  208.             $key_name $row['key_name'];
  209.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  210.                 if ($db->options['field_case'== CASE_LOWER{
  211.                     $key_name strtolower($key_name);
  212.                 else {
  213.                     $key_name strtoupper($key_name);
  214.                 }
  215.             }
  216.             if ($index_name == $key_name{
  217.                 if (!$row['non_unique']{
  218.                     return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  219.                         $index_name ' is not an existing table index'__FUNCTION__);
  220.                 }
  221.                 $column_name $row['column_name'];
  222.                 if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  223.                     if ($db->options['field_case'== CASE_LOWER{
  224.                         $column_name strtolower($column_name);
  225.                     else {
  226.                         $column_name strtoupper($column_name);
  227.                     }
  228.                 }
  229.                 $definition['fields'][$column_name= array(
  230.                     'position' => $colpos++
  231.                 );
  232.                 if (!empty($row['collation'])) {
  233.                     $definition['fields'][$column_name]['sorting'($row['collation'== 'A'
  234.                         ? 'ascending' 'descending');
  235.                 }
  236.             }
  237.         }
  238.         $result->free();
  239.         if (empty($definition['fields'])) {
  240.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  241.                 $index_name ' is not an existing table index'__FUNCTION__);
  242.         }
  243.         return $definition;
  244.     }
  245.  
  246.     // }}}
  247.     // {{{ getTableConstraintDefinition()
  248.  
  249.     /**
  250.      * Get the structure of a constraint into an array
  251.      *
  252.      * @param string $table_name      name of table that should be used in method
  253.      * @param string $constraint_name name of constraint that should be used in method
  254.      * @return mixed data array on success, a MDB2 error on failure
  255.      * @access public
  256.      */
  257.     function getTableConstraintDefinition($table_name$constraint_name)
  258.     {
  259.         $db =$this->getDBInstance();
  260.         if (PEAR::isError($db)) {
  261.             return $db;
  262.         }
  263.  
  264.         list($schema$table$this->splitTableSchema($table_name);
  265.         $constraint_name_original $constraint_name;
  266.  
  267.         $table $db->quoteIdentifier($tabletrue);
  268.         $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
  269.         if (strtolower($constraint_name!= 'primary'{
  270.             $constraint_name_mdb2 $db->getIndexName($constraint_name);
  271.             $result $db->queryRow(sprintf($query$db->quote($constraint_name_mdb2)));
  272.             if (!PEAR::isError($result&& !is_null($result)) {
  273.                 // apply 'idxname_format' only if the query succeeded, otherwise
  274.                 // fallback to the given $index_name, without transformation
  275.                 $constraint_name $constraint_name_mdb2;
  276.             }
  277.         }
  278.         $result $db->query(sprintf($query$db->quote($constraint_name)));
  279.         if (PEAR::isError($result)) {
  280.             return $result;
  281.         }
  282.         $colpos = 1;
  283.         //default values, eventually overridden
  284.         $definition = array(
  285.             'primary' => false,
  286.             'unique'  => false,
  287.             'foreign' => false,
  288.             'check'   => false,
  289.             'fields'  => array(),
  290.             'references' => array(
  291.                 'table'  => '',
  292.                 'fields' => array(),
  293.             ),
  294.             'onupdate'  => '',
  295.             'ondelete'  => '',
  296.             'match'     => '',
  297.             'deferrable'        => false,
  298.             'initiallydeferred' => false,
  299.         );
  300.         while (is_array($row $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
  301.             $row array_change_key_case($rowCASE_LOWER);
  302.             $key_name $row['key_name'];
  303.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  304.                 if ($db->options['field_case'== CASE_LOWER{
  305.                     $key_name strtolower($key_name);
  306.                 else {
  307.                     $key_name strtoupper($key_name);
  308.                 }
  309.             }
  310.             if ($constraint_name == $key_name{
  311.                 if ($row['non_unique']{
  312.                     //FOREIGN KEY?
  313.                     $query 'SHOW CREATE TABLE '$db->escape($table);
  314.                     $constraint $db->queryOne($query'text'1);
  315.                     if (!PEAR::isError($constraint&& !empty($constraint)) {
  316.                         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  317.                             if ($db->options['field_case'== CASE_LOWER{
  318.                                 $constraint strtolower($constraint);
  319.                             else {
  320.                                 $constraint strtoupper($constraint);
  321.                             }
  322.                         }
  323.                         $pattern '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
  324.                         if (!preg_match($patternstr_replace('`'''$constraint)$matches)) {
  325.                             //fallback to original constraint name
  326.                             $pattern '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
  327.                         }
  328.                         if (preg_match($patternstr_replace('`'''$constraint)$matches)) {
  329.                             $definition['foreign'= true;
  330.                             $column_names explode(','$matches[1]);
  331.                             $referenced_cols explode(','$matches[3]);
  332.                             $definition['references'= array(
  333.                                 'table'  => $matches[2],
  334.                                 'fields' => array(),
  335.                             );
  336.                             $colpos = 1;
  337.                             foreach ($column_names as $column_name{
  338.                                 $definition['fields'][trim($column_name)= array(
  339.                                     'position' => $colpos++
  340.                                 );
  341.                             }
  342.                             $colpos = 1;
  343.                             foreach ($referenced_cols as $column_name{
  344.                                 $definition['references']['fields'][trim($column_name)= array(
  345.                                     'position' => $colpos++
  346.                                 );
  347.                             }
  348.                             $definition['onupdate''NO ACTION';
  349.                             $definition['ondelete''NO ACTION';
  350.                             $definition['match']    'SIMPLE';
  351.                             return $definition;
  352.                         }
  353.                     }
  354.  
  355.                     return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  356.                         $constraint_name ' is not an existing table constraint'__FUNCTION__);
  357.                 }
  358.                 if ($row['key_name'== 'PRIMARY'{
  359.                     $definition['primary'= true;
  360.                 elseif (!$row['non_unique']{
  361.                     $definition['unique'= true;
  362.                 }
  363.                 $column_name $row['column_name'];
  364.                 if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  365.                     if ($db->options['field_case'== CASE_LOWER{
  366.                         $column_name strtolower($column_name);
  367.                     else {
  368.                         $column_name strtoupper($column_name);
  369.                     }
  370.                 }
  371.                 $definition['fields'][$column_name= array(
  372.                     'position' => $colpos++
  373.                 );
  374.                 if (!empty($row['collation'])) {
  375.                     $definition['fields'][$column_name]['sorting'($row['collation'== 'A'
  376.                         ? 'ascending' 'descending');
  377.                 }
  378.             }
  379.         }
  380.         $result->free();
  381.         if (empty($definition['fields'])) {
  382.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  383.                 $constraint_name ' is not an existing table constraint'__FUNCTION__);
  384.         }
  385.         return $definition;
  386.     }
  387.  
  388.     // }}}
  389.     // {{{ getTriggerDefinition()
  390.  
  391.     /**
  392.      * Get the structure of a trigger into an array
  393.      *
  394.      * EXPERIMENTAL
  395.      *
  396.      * WARNING: this function is experimental and may change the returned value
  397.      * at any time until labelled as non-experimental
  398.      *
  399.      * @param string    $trigger    name of trigger that should be used in method
  400.      * @return mixed data array on success, a MDB2 error on failure
  401.      * @access public
  402.      */
  403.     function getTriggerDefinition($trigger)
  404.     {
  405.         $db =$this->getDBInstance();
  406.         if (PEAR::isError($db)) {
  407.             return $db;
  408.         }
  409.  
  410.         $query 'SELECT trigger_name,
  411.                          event_object_table AS table_name,
  412.                          action_statement AS trigger_body,
  413.                          action_timing AS trigger_type,
  414.                          event_manipulation AS trigger_event
  415.                     FROM information_schema.triggers
  416.                    WHERE trigger_name = '$db->quote($trigger'text');
  417.         $types = array(
  418.             'trigger_name'    => 'text',
  419.             'table_name'      => 'text',
  420.             'trigger_body'    => 'text',
  421.             'trigger_type'    => 'text',
  422.             'trigger_event'   => 'text',
  423.         );
  424.         $def $db->queryRow($query$typesMDB2_FETCHMODE_ASSOC);
  425.         if (PEAR::isError($def)) {
  426.             return $def;
  427.         }
  428.         $def['trigger_comment''';
  429.         $def['trigger_enabled'= true;
  430.         return $def;
  431.     }
  432.  
  433.     // }}}
  434.     // {{{ tableInfo()
  435.  
  436.     /**
  437.      * Returns information about a table or a result set
  438.      *
  439.      * @param object|string $result  MDB2_result object from a query or a
  440.      *                                  string containing the name of a table.
  441.      *                                  While this also accepts a query result
  442.      *                                  resource identifier, this behavior is
  443.      *                                  deprecated.
  444.      * @param int            $mode    a valid tableInfo mode
  445.      *
  446.      * @return array  an associative array with the information requested.
  447.      *                  A MDB2_Error object on failure.
  448.      *
  449.      * @see MDB2_Driver_Common::setOption()
  450.      */
  451.     function tableInfo($result$mode = null)
  452.     {
  453.         if (is_string($result)) {
  454.            return parent::tableInfo($result$mode);
  455.         }
  456.  
  457.         $db =$this->getDBInstance();
  458.         if (PEAR::isError($db)) {
  459.             return $db;
  460.         }
  461.  
  462.         $resource = MDB2::isResultCommon($result$result->getResource($result;
  463.         if (!is_resource($resource)) {
  464.             return $db->raiseError(MDB2_ERROR_NEED_MORE_DATAnullnull,
  465.                 'Could not generate result resource'__FUNCTION__);
  466.         }
  467.  
  468.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  469.             if ($db->options['field_case'== CASE_LOWER{
  470.                 $case_func 'strtolower';
  471.             else {
  472.                 $case_func 'strtoupper';
  473.             }
  474.         else {
  475.             $case_func 'strval';
  476.         }
  477.  
  478.         $count @mysql_num_fields($resource);
  479.         $res   = array();
  480.         if ($mode{
  481.             $res['num_fields'$count;
  482.         }
  483.  
  484.         $db->loadModule('Datatype'nulltrue);
  485.         for ($i = 0; $i $count$i++{
  486.             $res[$i= array(
  487.                 'table' => $case_func(@mysql_field_table($resource$i)),
  488.                 'name'  => $case_func(@mysql_field_name($resource$i)),
  489.                 'type'  => @mysql_field_type($resource$i),
  490.                 'length'   => @mysql_field_len($resource$i),
  491.                 'flags' => @mysql_field_flags($resource$i),
  492.             );
  493.             if ($res[$i]['type'== 'string'{
  494.                 $res[$i]['type''char';
  495.             elseif ($res[$i]['type'== 'unknown'{
  496.                 $res[$i]['type''decimal';
  497.             }
  498.             $mdb2type_info $db->datatype->mapNativeDatatype($res[$i]);
  499.             if (PEAR::isError($mdb2type_info)) {
  500.                return $mdb2type_info;
  501.             }
  502.             $res[$i]['mdb2type'$mdb2type_info[0][0];
  503.             if ($mode MDB2_TABLEINFO_ORDER{
  504.                 $res['order'][$res[$i]['name']] $i;
  505.             }
  506.             if ($mode MDB2_TABLEINFO_ORDERTABLE{
  507.                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] $i;
  508.             }
  509.         }
  510.  
  511.         return $res;
  512.     }
  513. }
  514. ?>

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