source: github/program/lib/MDB2/Driver/Reverse/mysqli.php @ 95ebbc98

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 95ebbc98 was 95ebbc98, checked in by till <till@…>, 5 years ago
  • putting latest MDB2 into SVN
  • adding MDB2 drivers for mssql, mysql, mysqli, pgsql, sqlite
  • Property mode set to 100644
File size: 24.8 KB
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: mysqli.php,v 1.69 2007/11/25 13:38:29 quipo Exp $
46//
47
48require_once 'MDB2/Driver/Reverse/Common.php';
49
50/**
51 * MDB2 MySQLi 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_mysqli extends MDB2_Driver_Reverse_Common
59{
60    /**
61     * Array for converting MYSQLI_*_FLAG constants to text values
62     * @var    array
63     * @access public
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     */
86    var $types = array(
87        MYSQLI_TYPE_DECIMAL     => 'decimal',
88        246                     => '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 structure of a field into an array
118     *
119     * @param string $table_name 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_name, $field_name)
125    {
126        $db =& $this->getDBInstance();
127        if (PEAR::isError($db)) {
128            return $db;
129        }
130
131        $result = $db->loadModule('Datatype', null, true);
132        if (PEAR::isError($result)) {
133            return $result;
134        }
135
136        list($schema, $table) = $this->splitTableSchema($table_name);
137
138        $table = $db->quoteIdentifier($table, true);
139        $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
140        $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
141        if (PEAR::isError($columns)) {
142            return $columns;
143        }
144        foreach ($columns as $column) {
145            $column = array_change_key_case($column, CASE_LOWER);
146            $column['name'] = $column['field'];
147            unset($column['field']);
148            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
149                if ($db->options['field_case'] == CASE_LOWER) {
150                    $column['name'] = strtolower($column['name']);
151                } else {
152                    $column['name'] = strtoupper($column['name']);
153                }
154            } else {
155                $column = array_change_key_case($column, $db->options['field_case']);
156            }
157            if ($field_name == $column['name']) {
158                $mapped_datatype = $db->datatype->mapNativeDatatype($column);
159                if (PEAR::isError($mapped_datatype)) {
160                    return $mapped_datatype;
161                }
162                list($types, $length, $unsigned, $fixed) = $mapped_datatype;
163                $notnull = false;
164                if (empty($column['null']) || $column['null'] !== 'YES') {
165                    $notnull = true;
166                }
167                $default = false;
168                if (array_key_exists('default', $column)) {
169                    $default = $column['default'];
170                    if (is_null($default) && $notnull) {
171                        $default = '';
172                    }
173                }
174                $autoincrement = false;
175                if (!empty($column['extra']) && $column['extra'] == 'auto_increment') {
176                    $autoincrement = true;
177                }
178                $collate = null;
179                if (!empty($column['collation'])) {
180                    $collate = $column['collation'];
181                    $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);
182                }
183
184                $definition[0] = array(
185                    'notnull' => $notnull,
186                    'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
187                );
188                if (!is_null($length)) {
189                    $definition[0]['length'] = $length;
190                }
191                if (!is_null($unsigned)) {
192                    $definition[0]['unsigned'] = $unsigned;
193                }
194                if (!is_null($fixed)) {
195                    $definition[0]['fixed'] = $fixed;
196                }
197                if ($default !== false) {
198                    $definition[0]['default'] = $default;
199                }
200                if ($autoincrement !== false) {
201                    $definition[0]['autoincrement'] = $autoincrement;
202                }
203                if (!is_null($collate)) {
204                    $definition[0]['collate'] = $collate;
205                    $definition[0]['charset'] = $charset;
206                }
207                foreach ($types as $key => $type) {
208                    $definition[$key] = $definition[0];
209                    if ($type == 'clob' || $type == 'blob') {
210                        unset($definition[$key]['default']);
211                    } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
212                        $definition[$key]['default'] = '0000-00-00 00:00:00';
213                    }
214                    $definition[$key]['type'] = $type;
215                    $definition[$key]['mdb2type'] = $type;
216                }
217                return $definition;
218            }
219        }
220
221        return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
222            'it was not specified an existing table column', __FUNCTION__);
223    }
224
225    // }}}
226    // {{{ getTableIndexDefinition()
227
228    /**
229     * Get the structure of an index into an array
230     *
231     * @param string $table_name name of table that should be used in method
232     * @param string $index_name name of index that should be used in method
233     * @return mixed data array on success, a MDB2 error on failure
234     * @access public
235     */
236    function getTableIndexDefinition($table_name, $index_name)
237    {
238        $db =& $this->getDBInstance();
239        if (PEAR::isError($db)) {
240            return $db;
241        }
242
243        list($schema, $table) = $this->splitTableSchema($table_name);
244
245        $table = $db->quoteIdentifier($table, true);
246        $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
247        $index_name_mdb2 = $db->getIndexName($index_name);
248        $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));
249        if (!PEAR::isError($result) && !is_null($result)) {
250            // apply 'idxname_format' only if the query succeeded, otherwise
251            // fallback to the given $index_name, without transformation
252            $index_name = $index_name_mdb2;
253        }
254        $result = $db->query(sprintf($query, $db->quote($index_name)));
255        if (PEAR::isError($result)) {
256            return $result;
257        }
258        $colpos = 1;
259        $definition = array();
260        while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
261            $row = array_change_key_case($row, CASE_LOWER);
262            $key_name = $row['key_name'];
263            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
264                if ($db->options['field_case'] == CASE_LOWER) {
265                    $key_name = strtolower($key_name);
266                } else {
267                    $key_name = strtoupper($key_name);
268                }
269            }
270            if ($index_name == $key_name) {
271                if (!$row['non_unique']) {
272                    return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
273                        $index_name . ' is not an existing table index', __FUNCTION__);
274                }
275                $column_name = $row['column_name'];
276                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
277                    if ($db->options['field_case'] == CASE_LOWER) {
278                        $column_name = strtolower($column_name);
279                    } else {
280                        $column_name = strtoupper($column_name);
281                    }
282                }
283                $definition['fields'][$column_name] = array(
284                    'position' => $colpos++
285                );
286                if (!empty($row['collation'])) {
287                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
288                        ? 'ascending' : 'descending');
289                }
290            }
291        }
292        $result->free();
293        if (empty($definition['fields'])) {
294            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
295                $index_name . ' is not an existing table index', __FUNCTION__);
296        }
297        return $definition;
298    }
299
300    // }}}
301    // {{{ getTableConstraintDefinition()
302
303    /**
304     * Get the structure of a constraint into an array
305     *
306     * @param string $table_name      name of table that should be used in method
307     * @param string $constraint_name name of constraint that should be used in method
308     * @return mixed data array on success, a MDB2 error on failure
309     * @access public
310     */
311    function getTableConstraintDefinition($table_name, $constraint_name)
312    {
313        $db =& $this->getDBInstance();
314        if (PEAR::isError($db)) {
315            return $db;
316        }
317
318        list($schema, $table) = $this->splitTableSchema($table_name);
319        $constraint_name_original = $constraint_name;
320
321        $table = $db->quoteIdentifier($table, true);
322        $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
323        if (strtolower($constraint_name) != 'primary') {
324            $constraint_name_mdb2 = $db->getIndexName($constraint_name);
325            $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));
326            if (!PEAR::isError($result) && !is_null($result)) {
327                // apply 'idxname_format' only if the query succeeded, otherwise
328                // fallback to the given $index_name, without transformation
329                $constraint_name = $constraint_name_mdb2;
330            }
331        }
332        $result = $db->query(sprintf($query, $db->quote($constraint_name)));
333        if (PEAR::isError($result)) {
334            return $result;
335        }
336        $colpos = 1;
337        //default values, eventually overridden
338        $definition = array(
339            'primary' => false,
340            'unique'  => false,
341            'foreign' => false,
342            'check'   => false,
343            'fields'  => array(),
344            'references' => array(
345                'table'  => '',
346                'fields' => array(),
347            ),
348            'onupdate'  => '',
349            'ondelete'  => '',
350            'match'     => '',
351            'deferrable'        => false,
352            'initiallydeferred' => false,
353        );
354        while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
355            $row = array_change_key_case($row, CASE_LOWER);
356            $key_name = $row['key_name'];
357            if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
358                if ($db->options['field_case'] == CASE_LOWER) {
359                    $key_name = strtolower($key_name);
360                } else {
361                    $key_name = strtoupper($key_name);
362                }
363            }
364            if ($constraint_name == $key_name) {
365                if ($row['non_unique']) {
366                    //FOREIGN KEY?
367                    $query = 'SHOW CREATE TABLE '. $db->escape($table);
368                    $constraint = $db->queryOne($query, 'text', 1);
369                    if (!PEAR::isError($constraint) && !empty($constraint)) {
370                        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
371                            if ($db->options['field_case'] == CASE_LOWER) {
372                                $constraint = strtolower($constraint);
373                            } else {
374                                $constraint = strtoupper($constraint);
375                            }
376                        }
377                        $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
378                        if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
379                            //fallback to original constraint name
380                            $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
381                        }
382                        if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
383                            $definition['foreign'] = true;
384                            $column_names = explode(',', $matches[1]);
385                            $referenced_cols = explode(',', $matches[3]);
386                            $definition['references'] = array(
387                                'table'  => $matches[2],
388                                'fields' => array(),
389                            );
390                            $colpos = 1;
391                            foreach ($column_names as $column_name) {
392                                $definition['fields'][trim($column_name)] = array(
393                                    'position' => $colpos++
394                                );
395                            }
396                            $colpos = 1;
397                            foreach ($referenced_cols as $column_name) {
398                                $definition['references']['fields'][trim($column_name)] = array(
399                                    'position' => $colpos++
400                                );
401                            }
402                            $definition['onupdate'] = 'NO ACTION';
403                            $definition['ondelete'] = 'NO ACTION';
404                            $definition['match']    = 'SIMPLE';
405                            return $definition;
406                        }
407                    }
408
409                    return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
410                        $constraint_name . ' is not an existing table constraint', __FUNCTION__);
411                }
412                if ($row['key_name'] == 'PRIMARY') {
413                    $definition['primary'] = true;
414                } elseif (!$row['non_unique']) {
415                    $definition['unique'] = true;
416                }
417                $column_name = $row['column_name'];
418                if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
419                    if ($db->options['field_case'] == CASE_LOWER) {
420                        $column_name = strtolower($column_name);
421                    } else {
422                        $column_name = strtoupper($column_name);
423                    }
424                }
425                $definition['fields'][$column_name] = array(
426                    'position' => $colpos++
427                );
428                if (!empty($row['collation'])) {
429                    $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
430                        ? 'ascending' : 'descending');
431                }
432            }
433        }
434        $result->free();
435        if (empty($definition['fields'])) {
436            return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
437                $constraint_name . ' is not an existing table constraint', __FUNCTION__);
438        }
439        return $definition;
440    }
441
442    // }}}
443    // {{{ getTriggerDefinition()
444
445    /**
446     * Get the structure of a trigger into an array
447     *
448     * EXPERIMENTAL
449     *
450     * WARNING: this function is experimental and may change the returned value
451     * at any time until labelled as non-experimental
452     *
453     * @param string    $trigger    name of trigger that should be used in method
454     * @return mixed data array on success, a MDB2 error on failure
455     * @access public
456     */
457    function getTriggerDefinition($trigger)
458    {
459        $db =& $this->getDBInstance();
460        if (PEAR::isError($db)) {
461            return $db;
462        }
463
464        $query = 'SELECT trigger_name,
465                         event_object_table AS table_name,
466                         action_statement AS trigger_body,
467                         action_timing AS trigger_type,
468                         event_manipulation AS trigger_event
469                    FROM information_schema.triggers
470                   WHERE trigger_name = '. $db->quote($trigger, 'text');
471        $types = array(
472            'trigger_name'    => 'text',
473            'table_name'      => 'text',
474            'trigger_body'    => 'text',
475            'trigger_type'    => 'text',
476            'trigger_event'   => 'text',
477        );
478        $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
479        if (PEAR::isError($def)) {
480            return $def;
481        }
482        $def['trigger_comment'] = '';
483        $def['trigger_enabled'] = true;
484        return $def;
485    }
486
487    // }}}
488    // {{{ tableInfo()
489
490    /**
491     * Returns information about a table or a result set
492     *
493     * @param object|string  $result  MDB2_result object from a query or a
494     *                                 string containing the name of a table.
495     *                                 While this also accepts a query result
496     *                                 resource identifier, this behavior is
497     *                                 deprecated.
498     * @param int            $mode    a valid tableInfo mode
499     *
500     * @return array  an associative array with the information requested.
501     *                 A MDB2_Error object on failure.
502     *
503     * @see MDB2_Driver_Common::setOption()
504     */
505    function tableInfo($result, $mode = null)
506    {
507        if (is_string($result)) {
508           return parent::tableInfo($result, $mode);
509        }
510
511        $db =& $this->getDBInstance();
512        if (PEAR::isError($db)) {
513            return $db;
514        }
515
516        $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
517        if (!is_object($resource)) {
518            return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
519                'Could not generate result resource', __FUNCTION__);
520        }
521
522        if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
523            if ($db->options['field_case'] == CASE_LOWER) {
524                $case_func = 'strtolower';
525            } else {
526                $case_func = 'strtoupper';
527            }
528        } else {
529            $case_func = 'strval';
530        }
531
532        $count = @mysqli_num_fields($resource);
533        $res = array();
534        if ($mode) {
535            $res['num_fields'] = $count;
536        }
537
538        $db->loadModule('Datatype', null, true);
539        for ($i = 0; $i < $count; $i++) {
540            $tmp = @mysqli_fetch_field($resource);
541
542            $flags = '';
543            foreach ($this->flags as $const => $means) {
544                if ($tmp->flags & $const) {
545                    $flags.= $means . ' ';
546                }
547            }
548            if ($tmp->def) {
549                $flags.= 'default_' . rawurlencode($tmp->def);
550            }
551            $flags = trim($flags);
552
553            $res[$i] = array(
554                'table'  => $case_func($tmp->table),
555                'name'   => $case_func($tmp->name),
556                'type'   => isset($this->types[$tmp->type])
557                    ? $this->types[$tmp->type] : 'unknown',
558                // http://bugs.php.net/?id=36579
559                'length' => $tmp->length,
560                'flags'  => $flags,
561            );
562            $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
563            if (PEAR::isError($mdb2type_info)) {
564               return $mdb2type_info;
565            }
566            $res[$i]['mdb2type'] = $mdb2type_info[0][0];
567            if ($mode & MDB2_TABLEINFO_ORDER) {
568                $res['order'][$res[$i]['name']] = $i;
569            }
570            if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
571                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
572            }
573        }
574
575        return $res;
576    }
577}
578?>
Note: See TracBrowser for help on using the repository browser.