thomascube
2006-04-04 f3704e18d89e4065cede8509256d7fbf483b7fe6
commit | author | age
c9462d 1 <?php
S 2 // +----------------------------------------------------------------------+
3 // | PHP versions 4 and 5                                                 |
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) 1998-2004 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
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  */
57 class MDB2_Driver_Reverse_mysqli extends MDB2_Driver_Reverse_Common
58 {
59     /**
60      * Array for converting MYSQLI_*_FLAG constants to text values
61      * @var    array
62      * @access public
63      * @since  Property available since Release 1.6.5
64      */
65     var $flags = array(
66         MYSQLI_NOT_NULL_FLAG        => 'not_null',
67         MYSQLI_PRI_KEY_FLAG         => 'primary_key',
68         MYSQLI_UNIQUE_KEY_FLAG      => 'unique_key',
69         MYSQLI_MULTIPLE_KEY_FLAG    => 'multiple_key',
70         MYSQLI_BLOB_FLAG            => 'blob',
71         MYSQLI_UNSIGNED_FLAG        => 'unsigned',
72         MYSQLI_ZEROFILL_FLAG        => 'zerofill',
73         MYSQLI_AUTO_INCREMENT_FLAG  => 'auto_increment',
74         MYSQLI_TIMESTAMP_FLAG       => 'timestamp',
75         MYSQLI_SET_FLAG             => 'set',
76         // MYSQLI_NUM_FLAG             => 'numeric',  // unnecessary
77         // MYSQLI_PART_KEY_FLAG        => 'multiple_key',  // duplicatvie
78         MYSQLI_GROUP_FLAG           => 'group_by'
79     );
80
81     /**
82      * Array for converting MYSQLI_TYPE_* constants to text values
83      * @var    array
84      * @access public
85      * @since  Property available since Release 1.6.5
86      */
87     var $types = array(
88         MYSQLI_TYPE_DECIMAL     => 'decimal',
89         MYSQLI_TYPE_TINY        => 'tinyint',
90         MYSQLI_TYPE_SHORT       => 'int',
91         MYSQLI_TYPE_LONG        => 'int',
92         MYSQLI_TYPE_FLOAT       => 'float',
93         MYSQLI_TYPE_DOUBLE      => 'double',
94         // MYSQLI_TYPE_NULL        => 'DEFAULT NULL',  // let flags handle it
95         MYSQLI_TYPE_TIMESTAMP   => 'timestamp',
96         MYSQLI_TYPE_LONGLONG    => 'bigint',
97         MYSQLI_TYPE_INT24       => 'mediumint',
98         MYSQLI_TYPE_DATE        => 'date',
99         MYSQLI_TYPE_TIME        => 'time',
100         MYSQLI_TYPE_DATETIME    => 'datetime',
101         MYSQLI_TYPE_YEAR        => 'year',
102         MYSQLI_TYPE_NEWDATE     => 'date',
103         MYSQLI_TYPE_ENUM        => 'enum',
104         MYSQLI_TYPE_SET         => 'set',
105         MYSQLI_TYPE_TINY_BLOB   => 'tinyblob',
106         MYSQLI_TYPE_MEDIUM_BLOB => 'mediumblob',
107         MYSQLI_TYPE_LONG_BLOB   => 'longblob',
108         MYSQLI_TYPE_BLOB        => 'blob',
109         MYSQLI_TYPE_VAR_STRING  => 'varchar',
110         MYSQLI_TYPE_STRING      => 'char',
111         MYSQLI_TYPE_GEOMETRY    => 'geometry',
112     );
113
114     // {{{ getTableFieldDefinition()
115
116     /**
117      * get the stucture of a field into an array
118      *
119      * @param string    $table         name of table that should be used in method
120      * @param string    $field_name     name of field that should be used in method
121      * @return mixed data array on success, a MDB2 error on failure
122      * @access public
123      */
124     function getTableFieldDefinition($table, $field_name)
125     {
126         $db =& $this->getDBInstance();
127         if (PEAR::isError($db)) {
128             return $db;
129         }
130
131         $result = $db->loadModule('Datatype');
132         if (PEAR::isError($result)) {
133             return $result;
134         }
135         $columns = $db->queryAll("SHOW COLUMNS FROM $table", null, MDB2_FETCHMODE_ASSOC);
136         if (PEAR::isError($columns)) {
137             return $columns;
138         }
139         foreach ($columns as $column) {
140             if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
141                 if ($db->options['field_case'] == CASE_LOWER) {
142                     $column['field'] = strtolower($column['field']);
143                 } else {
144                     $column['field'] = strtoupper($column['field']);
145                 }
146             } else {
147                 $column = array_change_key_case($column, $db->options['field_case']);
148             }
149             if ($field_name == $column['field']) {
150                 list($types, $length) = $db->datatype->mapNativeDatatype($column);
151                 $notnull = false;
152                 if (array_key_exists('null', $column) && $column['null'] != 'YES') {
153                     $notnull = true;
154                 }
155                 $default = false;
156                 if (array_key_exists('default', $column)) {
157                     $default = $column['default'];
158                     if (is_null($default) && $notnull) {
159                         $default = '';
160                     }
161                 }
162                 $autoincrement = false;
163                 if (array_key_exists('extra', $column) && $column['extra'] == 'auto_increment') {
164                     $autoincrement = true;
165                 }
166                 $definition = array();
167                 foreach ($types as $key => $type) {
168                     $definition[$key] = array(
169                         'type' => $type,
170                         'notnull' => $notnull,
171                     );
172                     if ($length > 0) {
173                         $definition[$key]['length'] = $length;
174                     }
175                     if ($default !== false) {
176                         $definition[$key]['default'] = $default;
177                     }
178                     if ($autoincrement !== false) {
179                         $definition[$key]['autoincrement'] = $autoincrement;
180                     }
181                 }
182                 return $definition;
183             }
184         }
185
186         return $db->raiseError(MDB2_ERROR, null, null,
187             'getTableFieldDefinition: it was not specified an existing table column');
188     }
189
190     // }}}
191     // {{{ getTableIndexDefinition()
192
193     /**
194      * get the stucture of an index into an array
195      *
196      * @param string    $table      name of table that should be used in method
197      * @param string    $index_name name of index that should be used in method
198      * @return mixed data array on success, a MDB2 error on failure
199      * @access public
200      */
201     function getTableIndexDefinition($table, $index_name)
202     {
203         $db =& $this->getDBInstance();
204         if (PEAR::isError($db)) {
205             return $db;
206         }
207
208         $result = $db->query("SHOW INDEX FROM $table");
209         if (PEAR::isError($result)) {
210             return $result;
211         }
212         $definition = array();
213         while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
214             if (!($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
215                 || $db->options['field_case'] != CASE_LOWER
216             ) {
217                 $row = array_change_key_case($row, CASE_LOWER);
218             }
219             $key_name = $row['key_name'];
220             if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
221                 if ($db->options['field_case'] == CASE_LOWER) {
222                     $key_name = strtolower($key_name);
223                 } else {
224                     $key_name = strtoupper($key_name);
225                 }
226             }
227             if ($index_name == $key_name) {
228                 if ($row['key_name'] == 'PRIMARY') {
229                     $definition['primary'] = true;
230                 } elseif (!$row['non_unique']) {
231                     $definition['unique'] = true;
232                 }
233                 $column_name = $row['column_name'];
234                 if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
235                     if ($db->options['field_case'] == CASE_LOWER) {
236                         $column_name = strtolower($column_name);
237                     } else {
238                         $column_name = strtoupper($column_name);
239                     }
240                 }
241                 $definition['fields'][$column_name] = array();
242                 if (array_key_exists('collation', $row)) {
243                     $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
244                         ? 'ascending' : 'descending');
245                 }
246             }
247         }
248         $result->free();
249         if (!array_key_exists('fields', $definition)) {
250             return $db->raiseError(MDB2_ERROR, null, null,
251                 'getTableIndexDefinition: it was not specified an existing table index');
252         }
253         return $definition;
254     }
255
256     // }}}
257     // {{{ tableInfo()
258
259     /**
260      * Returns information about a table or a result set
261      *
262      * @param object|string  $result  MDB2_result object from a query or a
263      *                                 string containing the name of a table.
264      *                                 While this also accepts a query result
265      *                                 resource identifier, this behavior is
266      *                                 deprecated.
267      * @param int            $mode    a valid tableInfo mode
268      *
269      * @return array  an associative array with the information requested.
270      *                 A MDB2_Error object on failure.
271      *
272      * @see MDB2_Driver_Common::setOption()
273      */
274     function tableInfo($result, $mode = null)
275     {
276         $db =& $this->getDBInstance();
277         if (PEAR::isError($db)) {
278             return $db;
279         }
280
281         if (is_string($result)) {
282             /*
283              * Probably received a table name.
284              * Create a result resource identifier.
285              */
286             $id = $db->_doQuery("SELECT * FROM $result LIMIT 0");
287             if (PEAR::isError($id)) {
288                 return $id;
289             }
290             $got_string = true;
291         } elseif (MDB2::isResultCommon($result)) {
292             /*
293              * Probably received a result object.
294              * Extract the result resource identifier.
295              */
296             $id = $result->getResource();
297             $got_string = false;
298         } else {
299             /*
300              * Probably received a result resource identifier.
301              * Copy it.
302              * Deprecated.  Here for compatibility only.
303              */
304             $id = $result;
305             $got_string = false;
306         }
307
308         if (!is_a($id, 'mysqli_result')) {
309             return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA);
310         }
311
312         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
313             if ($db->options['field_case'] == CASE_LOWER) {
314                 $case_func = 'strtolower';
315             } else {
316                 $case_func = 'strtoupper';
317             }
318         } else {
319             $case_func = 'strval';
320         }
321
322         $count = @mysqli_num_fields($id);
323         $res   = array();
324
325         if ($mode) {
326             $res['num_fields'] = $count;
327         }
328
329         for ($i = 0; $i < $count; $i++) {
330             $tmp = @mysqli_fetch_field($id);
331
332             $flags = '';
333             foreach ($this->flags as $const => $means) {
334                 if ($tmp->flags & $const) {
335                     $flags.= $means . ' ';
336                 }
337             }
338             if ($tmp->def) {
339                 $flags.= 'default_' . rawurlencode($tmp->def);
340             }
341             $flags = trim($flags);
342
343             $res[$i] = array(
344                 'table' => $case_func($tmp->table),
345                 'name'  => $case_func($tmp->name),
346                 'type'  => isset($this->types[$tmp->type])
347                                     ? $this->types[$tmp->type]
348                                     : 'unknown',
349                 'len'   => $tmp->max_length,
350                 'flags' => $flags,
351             );
352
353             if ($mode & MDB2_TABLEINFO_ORDER) {
354                 $res['order'][$res[$i]['name']] = $i;
355             }
356             if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
357                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
358             }
359         }
360
361         // free the result only if we were called on a table
362         if ($got_string) {
363             @mysqli_free_result($id);
364         }
365         return $res;
366     }
367 }
368 ?>