source: branches/version-2_5-dev/data/module/MDB2/Driver/Reverse/mysql.php @ 20116

Revision 20116, 22.1 KB checked in by nanasess, 13 years ago (diff)
  • svn properties を再設定
  • 再設定用のスクリプト追加
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
  • Property svn:mime-type set to text/x-httpd-php; charset=UTF-8
Line 
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$
46//
47
48require_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 */
58class 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', null, true);
78        if (PEAR::isError($result)) {
79            return $result;
80        }
81
82        list($schema, $table) = $this->splitTableSchema($table_name);
83
84        $table = $db->quoteIdentifier($table, true);
85        $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
86        $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
87        if (PEAR::isError($columns)) {
88            return $columns;
89        }
90        foreach ($columns as $column) {
91            $column = array_change_key_case($column, CASE_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_FOUND, null, null,
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($table, true);
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($row, CASE_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_FOUND, null, null,
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_FOUND, null, null,
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($table, true);
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($row, CASE_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                    return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
314                }
315                if ($row['key_name'] == 'PRIMARY') {
316                    $definition['primary'] = true;
317                } elseif (!$row['non_unique']) {
318                    $definition['unique'] = true;
319                }
320                $column_name = $row['column_name'];
321                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
322                    if ($db->options['field_case'] == CASE_LOWER) {
323                        $column_name = strtolower($column_name);
324                    } else {
325                        $column_name = strtoupper($column_name);
326                    }
327                }
328                $definition['fields'][$column_name] = array(
329                    'position' => $colpos++
330                );
331                if (!empty($row['collation'])) {
332                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
333                        ? 'ascending' : 'descending');
334                }
335            }
336        }
337        $result->free();
338        if (empty($definition['fields'])) {
339            return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
340        }
341        return $definition;
342    }
343
344    // }}}
345    // {{{ _getTableFKConstraintDefinition()
346   
347    /**
348     * Get the FK definition from the CREATE TABLE statement
349     *
350     * @param string $table           table name
351     * @param string $constraint_name constraint name
352     * @param array  $definition      default values for constraint definition
353     *
354     * @return array|PEAR_Error
355     * @access private
356     */
357    function _getTableFKConstraintDefinition($table, $constraint_name, $definition)
358    {
359        $db =& $this->getDBInstance();
360        if (PEAR::isError($db)) {
361            return $db;
362        }
363        $query = 'SHOW CREATE TABLE '. $db->escape($table);
364        $constraint = $db->queryOne($query, 'text', 1);
365        if (!PEAR::isError($constraint) && !empty($constraint)) {
366            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
367                if ($db->options['field_case'] == CASE_LOWER) {
368                    $constraint = strtolower($constraint);
369                } else {
370                    $constraint = strtoupper($constraint);
371                }
372            }
373            $constraint_name_original = $constraint_name;
374            $constraint_name = $db->getIndexName($constraint_name);
375            $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
376            if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
377                //fallback to original constraint name
378                $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
379            }
380            if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
381                $definition['foreign'] = true;
382                $column_names = explode(',', $matches[1]);
383                $referenced_cols = explode(',', $matches[3]);
384                $definition['references'] = array(
385                    'table'  => $matches[2],
386                    'fields' => array(),
387                );
388                $colpos = 1;
389                foreach ($column_names as $column_name) {
390                    $definition['fields'][trim($column_name)] = array(
391                        'position' => $colpos++
392                    );
393                }
394                $colpos = 1;
395                foreach ($referenced_cols as $column_name) {
396                    $definition['references']['fields'][trim($column_name)] = array(
397                        'position' => $colpos++
398                    );
399                }
400                $definition['onupdate'] = 'NO ACTION';
401                $definition['ondelete'] = 'NO ACTION';
402                $definition['match']    = 'SIMPLE';
403                return $definition;
404            }
405        }
406        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
407                $constraint_name . ' is not an existing table constraint', __FUNCTION__);
408    }
409
410    // }}}
411    // {{{ getTriggerDefinition()
412
413    /**
414     * Get the structure of a trigger into an array
415     *
416     * EXPERIMENTAL
417     *
418     * WARNING: this function is experimental and may change the returned value
419     * at any time until labelled as non-experimental
420     *
421     * @param string    $trigger    name of trigger that should be used in method
422     * @return mixed data array on success, a MDB2 error on failure
423     * @access public
424     */
425    function getTriggerDefinition($trigger)
426    {
427        $db =& $this->getDBInstance();
428        if (PEAR::isError($db)) {
429            return $db;
430        }
431
432        $query = 'SELECT trigger_name,
433                         event_object_table AS table_name,
434                         action_statement AS trigger_body,
435                         action_timing AS trigger_type,
436                         event_manipulation AS trigger_event
437                    FROM information_schema.triggers
438                   WHERE trigger_name = '. $db->quote($trigger, 'text');
439        $types = array(
440            'trigger_name'    => 'text',
441            'table_name'      => 'text',
442            'trigger_body'    => 'text',
443            'trigger_type'    => 'text',
444            'trigger_event'   => 'text',
445        );
446        $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
447        if (PEAR::isError($def)) {
448            return $def;
449        }
450        $def['trigger_comment'] = '';
451        $def['trigger_enabled'] = true;
452        return $def;
453    }
454
455    // }}}
456    // {{{ tableInfo()
457
458    /**
459     * Returns information about a table or a result set
460     *
461     * @param object|string  $result  MDB2_result object from a query or a
462     *                                 string containing the name of a table.
463     *                                 While this also accepts a query result
464     *                                 resource identifier, this behavior is
465     *                                 deprecated.
466     * @param int            $mode    a valid tableInfo mode
467     *
468     * @return array  an associative array with the information requested.
469     *                 A MDB2_Error object on failure.
470     *
471     * @see MDB2_Driver_Common::setOption()
472     */
473    function tableInfo($result, $mode = null)
474    {
475        if (is_string($result)) {
476           return parent::tableInfo($result, $mode);
477        }
478
479        $db =& $this->getDBInstance();
480        if (PEAR::isError($db)) {
481            return $db;
482        }
483
484        $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
485        if (!is_resource($resource)) {
486            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
487                'Could not generate result resource', __FUNCTION__);
488        }
489
490        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
491            if ($db->options['field_case'] == CASE_LOWER) {
492                $case_func = 'strtolower';
493            } else {
494                $case_func = 'strtoupper';
495            }
496        } else {
497            $case_func = 'strval';
498        }
499
500        $count = @mysql_num_fields($resource);
501        $res   = array();
502        if ($mode) {
503            $res['num_fields'] = $count;
504        }
505
506        $db->loadModule('Datatype', null, true);
507        for ($i = 0; $i < $count; $i++) {
508            $res[$i] = array(
509                'table' => $case_func(@mysql_field_table($resource, $i)),
510                'name'  => $case_func(@mysql_field_name($resource, $i)),
511                'type'  => @mysql_field_type($resource, $i),
512                'length'   => @mysql_field_len($resource, $i),
513                'flags' => @mysql_field_flags($resource, $i),
514            );
515            if ($res[$i]['type'] == 'string') {
516                $res[$i]['type'] = 'char';
517            } elseif ($res[$i]['type'] == 'unknown') {
518                $res[$i]['type'] = 'decimal';
519            }
520            $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
521            if (PEAR::isError($mdb2type_info)) {
522               return $mdb2type_info;
523            }
524            $res[$i]['mdb2type'] = $mdb2type_info[0][0];
525            if ($mode & MDB2_TABLEINFO_ORDER) {
526                $res['order'][$res[$i]['name']] = $i;
527            }
528            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
529                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
530            }
531        }
532
533        return $res;
534    }
535}
536?>
Note: See TracBrowser for help on using the repository browser.