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

Revision 20764, 20.3 KB checked in by nanasess, 13 years ago (diff)

#601 (コピーライトの更新)

  • Property svn:eol-style set to LF
  • Property svn:mime-type set to text/x-httpd-php; charset=UTF-8
Line 
1<?php
2// vim: set et ts=4 sw=4 fdm=marker:
3// +----------------------------------------------------------------------+
4// | PHP versions 4 and 5                                                 |
5// +----------------------------------------------------------------------+
6// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
7// | Stig. S. Bakken, Lukas Smith                                         |
8// | All rights reserved.                                                 |
9// +----------------------------------------------------------------------+
10// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
11// | API as well as database abstraction for PHP applications.            |
12// | This LICENSE is in the BSD license style.                            |
13// |                                                                      |
14// | Redistribution and use in source and binary forms, with or without   |
15// | modification, are permitted provided that the following conditions   |
16// | are met:                                                             |
17// |                                                                      |
18// | Redistributions of source code must retain the above copyright       |
19// | notice, this list of conditions and the following disclaimer.        |
20// |                                                                      |
21// | Redistributions in binary form must reproduce the above copyright    |
22// | notice, this list of conditions and the following disclaimer in the  |
23// | documentation and/or other materials provided with the distribution. |
24// |                                                                      |
25// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
26// | Lukas Smith nor the names of his contributors may be used to endorse |
27// | or promote products derived from this software without specific prior|
28// | written permission.                                                  |
29// |                                                                      |
30// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
31// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
32// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
33// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
34// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
35// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
36// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
37// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
38// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
39// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
40// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
41// | POSSIBILITY OF SUCH DAMAGE.                                          |
42// +----------------------------------------------------------------------+
43// | Author: Lukas Smith <smith@pooteeweet.org>                           |
44// +----------------------------------------------------------------------+
45//
46// $Id: mysql.php,v 1.65 2008/02/22 19:23:49 quipo Exp $
47//
48
49require_once 'MDB2/Driver/Datatype/Common.php';
50
51/**
52 * MDB2 MySQL driver
53 *
54 * @package MDB2
55 * @category Database
56 * @author  Lukas Smith <smith@pooteeweet.org>
57 */
58class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common
59{
60    // {{{ _getCharsetFieldDeclaration()
61
62    /**
63     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
64     * of a field declaration to be used in statements like CREATE TABLE.
65     *
66     * @param string $charset   name of the charset
67     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET
68     *                 of a field declaration.
69     */
70    function _getCharsetFieldDeclaration($charset)
71    {
72        return 'CHARACTER SET '.$charset;
73    }
74
75    // }}}
76    // {{{ _getCollationFieldDeclaration()
77
78    /**
79     * Obtain DBMS specific SQL code portion needed to set the COLLATION
80     * of a field declaration to be used in statements like CREATE TABLE.
81     *
82     * @param string $collation   name of the collation
83     * @return string  DBMS specific SQL code portion needed to set the COLLATION
84     *                 of a field declaration.
85     */
86    function _getCollationFieldDeclaration($collation)
87    {
88        return 'COLLATE '.$collation;
89    }
90
91    // }}}
92    // {{{ getTypeDeclaration()
93
94    /**
95     * Obtain DBMS specific SQL code portion needed to declare an text type
96     * field to be used in statements like CREATE TABLE.
97     *
98     * @param array $field  associative array with the name of the properties
99     *      of the field being declared as array indexes. Currently, the types
100     *      of supported field properties are as follows:
101     *
102     *      length
103     *          Integer value that determines the maximum length of the text
104     *          field. If this argument is missing the field should be
105     *          declared to have the longest length allowed by the DBMS.
106     *
107     *      default
108     *          Text value to be used as default for this field.
109     *
110     *      notnull
111     *          Boolean flag that indicates whether this field is constrained
112     *          to not be set to null.
113     * @return string  DBMS specific SQL code portion that should be used to
114     *      declare the specified field.
115     * @access public
116     */
117    function getTypeDeclaration($field)
118    {
119        $db =& $this->getDBInstance();
120        if (PEAR::isError($db)) {
121            return $db;
122        }
123
124        switch ($field['type']) {
125        case 'text':
126            if (empty($field['length']) && array_key_exists('default', $field)) {
127                $field['length'] = $db->varchar_max_length;
128            }
129            $length = !empty($field['length']) ? $field['length'] : false;
130            $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
131            return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)')
132                : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
133        case 'clob':
134            if (!empty($field['length'])) {
135                $length = $field['length'];
136                if ($length <= 255) {
137                    return 'TINYTEXT';
138                } elseif ($length <= 65532) {
139                    return 'TEXT';
140                } elseif ($length <= 16777215) {
141                    return 'MEDIUMTEXT';
142                }
143            }
144            return 'LONGTEXT';
145        case 'blob':
146            if (!empty($field['length'])) {
147                $length = $field['length'];
148                if ($length <= 255) {
149                    return 'TINYBLOB';
150                } elseif ($length <= 65532) {
151                    return 'BLOB';
152                } elseif ($length <= 16777215) {
153                    return 'MEDIUMBLOB';
154                }
155            }
156            return 'LONGBLOB';
157        case 'integer':
158            if (!empty($field['length'])) {
159                $length = $field['length'];
160                if ($length <= 1) {
161                    return 'TINYINT';
162                } elseif ($length == 2) {
163                    return 'SMALLINT';
164                } elseif ($length == 3) {
165                    return 'MEDIUMINT';
166                } elseif ($length == 4) {
167                    return 'INT';
168                } elseif ($length > 4) {
169                    return 'BIGINT';
170                }
171            }
172            return 'INT';
173        case 'boolean':
174            return 'TINYINT(1)';
175        case 'date':
176            return 'DATE';
177        case 'time':
178            return 'TIME';
179        case 'timestamp':
180            return 'DATETIME';
181        case 'float':
182            return 'DOUBLE';
183        case 'decimal':
184            $length = !empty($field['length']) ? $field['length'] : 18;
185            $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
186            return 'DECIMAL('.$length.','.$scale.')';
187        }
188        return '';
189    }
190
191    // }}}
192    // {{{ _getIntegerDeclaration()
193
194    /**
195     * Obtain DBMS specific SQL code portion needed to declare an integer type
196     * field to be used in statements like CREATE TABLE.
197     *
198     * @param string  $name   name the field to be declared.
199     * @param string  $field  associative array with the name of the properties
200     *                        of the field being declared as array indexes.
201     *                        Currently, the types of supported field
202     *                        properties are as follows:
203     *
204     *                       unsigned
205     *                        Boolean flag that indicates whether the field
206     *                        should be declared as unsigned integer if
207     *                        possible.
208     *
209     *                       default
210     *                        Integer value to be used as default for this
211     *                        field.
212     *
213     *                       notnull
214     *                        Boolean flag that indicates whether this field is
215     *                        constrained to not be set to null.
216     * @return string  DBMS specific SQL code portion that should be used to
217     *                 declare the specified field.
218     * @access protected
219     */
220    function _getIntegerDeclaration($name, $field)
221    {
222        $db =& $this->getDBInstance();
223        if (PEAR::isError($db)) {
224            return $db;
225        }
226
227        $default = $autoinc = '';
228        if (!empty($field['autoincrement'])) {
229            $autoinc = ' AUTO_INCREMENT PRIMARY KEY';
230        } elseif (array_key_exists('default', $field)) {
231            if ($field['default'] === '') {
232                $field['default'] = empty($field['notnull']) ? null : 0;
233            }
234            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
235        }
236
237        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
238        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
239        $name = $db->quoteIdentifier($name, true);
240        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
241    }
242
243    // }}}
244    // {{{ _getFloatDeclaration()
245
246    /**
247     * Obtain DBMS specific SQL code portion needed to declare an float type
248     * field to be used in statements like CREATE TABLE.
249     *
250     * @param string  $name   name the field to be declared.
251     * @param string  $field  associative array with the name of the properties
252     *                        of the field being declared as array indexes.
253     *                        Currently, the types of supported field
254     *                        properties are as follows:
255     *
256     *                       unsigned
257     *                        Boolean flag that indicates whether the field
258     *                        should be declared as unsigned float if
259     *                        possible.
260     *
261     *                       default
262     *                        float value to be used as default for this
263     *                        field.
264     *
265     *                       notnull
266     *                        Boolean flag that indicates whether this field is
267     *                        constrained to not be set to null.
268     * @return string  DBMS specific SQL code portion that should be used to
269     *                 declare the specified field.
270     * @access protected
271     */
272    function _getFloatDeclaration($name, $field)
273    {
274        // Since AUTO_INCREMENT can be used for integer or floating-point types,
275        // reuse the INTEGER declaration
276        // @see http://bugs.mysql.com/bug.php?id=31032
277        return $this->_getIntegerDeclaration($name, $field);
278    }
279
280    // }}}
281    // {{{ _getDecimalDeclaration()
282
283    /**
284     * Obtain DBMS specific SQL code portion needed to declare an decimal type
285     * field to be used in statements like CREATE TABLE.
286     *
287     * @param string  $name   name the field to be declared.
288     * @param string  $field  associative array with the name of the properties
289     *                        of the field being declared as array indexes.
290     *                        Currently, the types of supported field
291     *                        properties are as follows:
292     *
293     *                       unsigned
294     *                        Boolean flag that indicates whether the field
295     *                        should be declared as unsigned integer if
296     *                        possible.
297     *
298     *                       default
299     *                        Decimal value to be used as default for this
300     *                        field.
301     *
302     *                       notnull
303     *                        Boolean flag that indicates whether this field is
304     *                        constrained to not be set to null.
305     * @return string  DBMS specific SQL code portion that should be used to
306     *                 declare the specified field.
307     * @access protected
308     */
309    function _getDecimalDeclaration($name, $field)
310    {
311        $db =& $this->getDBInstance();
312        if (PEAR::isError($db)) {
313            return $db;
314        }
315
316        $default = '';
317        if (array_key_exists('default', $field)) {
318            if ($field['default'] === '') {
319                $field['default'] = empty($field['notnull']) ? null : 0;
320            }
321            $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
322        } elseif (empty($field['notnull'])) {
323            $default = ' DEFAULT NULL';
324        }
325
326        $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
327        $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
328        $name = $db->quoteIdentifier($name, true);
329        return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull;
330    }
331
332    // }}}
333    // {{{ matchPattern()
334
335    /**
336     * build a pattern matching string
337     *
338     * @access public
339     *
340     * @param array $pattern even keys are strings, odd are patterns (% and _)
341     * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
342     * @param string $field optional field name that is being matched against
343     *                  (might be required when emulating ILIKE)
344     *
345     * @return string SQL pattern
346     */
347    function matchPattern($pattern, $operator = null, $field = null)
348    {
349        $db =& $this->getDBInstance();
350        if (PEAR::isError($db)) {
351            return $db;
352        }
353
354        $match = '';
355        if (!is_null($operator)) {
356            $field = is_null($field) ? '' : $field.' ';
357            $operator = strtoupper($operator);
358            switch ($operator) {
359            // case insensitive
360            case 'ILIKE':
361                $match = $field.'LIKE ';
362                break;
363            // case sensitive
364            case 'LIKE':
365                $match = $field.'LIKE BINARY ';
366                break;
367            default:
368                return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
369                    'not a supported operator type:'. $operator, __FUNCTION__);
370            }
371        }
372        $match.= "'";
373        foreach ($pattern as $key => $value) {
374            if ($key % 2) {
375                $match.= $value;
376            } else {
377                $match.= $db->escapePattern($db->escape($value));
378            }
379        }
380        $match.= "'";
381        $match.= $this->patternEscapeString();
382        return $match;
383    }
384
385    // }}}
386    // {{{ _mapNativeDatatype()
387
388    /**
389     * Maps a native array description of a field to a MDB2 datatype and length
390     *
391     * @param array  $field native field description
392     * @return array containing the various possible types, length, sign, fixed
393     * @access public
394     */
395    function _mapNativeDatatype($field)
396    {
397        $db_type = strtolower($field['type']);
398        $db_type = strtok($db_type, '(), ');
399        if ($db_type == 'national') {
400            $db_type = strtok('(), ');
401        }
402        if (!empty($field['length'])) {
403            $length = strtok($field['length'], ', ');
404            $decimal = strtok(', ');
405        } else {
406            $length = strtok('(), ');
407            $decimal = strtok('(), ');
408        }
409        $type = array();
410        $unsigned = $fixed = null;
411        switch ($db_type) {
412        case 'tinyint':
413            $type[] = 'integer';
414            $type[] = 'boolean';
415            if (preg_match('/^(is|has)/', $field['name'])) {
416                $type = array_reverse($type);
417            }
418            $unsigned = preg_match('/ unsigned/i', $field['type']);
419            $length = 1;
420            break;
421        case 'smallint':
422            $type[] = 'integer';
423            $unsigned = preg_match('/ unsigned/i', $field['type']);
424            $length = 2;
425            break;
426        case 'mediumint':
427            $type[] = 'integer';
428            $unsigned = preg_match('/ unsigned/i', $field['type']);
429            $length = 3;
430            break;
431        case 'int':
432        case 'integer':
433            $type[] = 'integer';
434            $unsigned = preg_match('/ unsigned/i', $field['type']);
435            $length = 4;
436            break;
437        case 'bigint':
438            $type[] = 'integer';
439            $unsigned = preg_match('/ unsigned/i', $field['type']);
440            $length = 8;
441            break;
442        case 'tinytext':
443        case 'mediumtext':
444        case 'longtext':
445        case 'text':
446        case 'varchar':
447            $fixed = false;
448        case 'string':
449        case 'char':
450            $type[] = 'text';
451            if ($length == '1') {
452                $type[] = 'boolean';
453                if (preg_match('/^(is|has)/', $field['name'])) {
454                    $type = array_reverse($type);
455                }
456            } elseif (strstr($db_type, 'text')) {
457                $type[] = 'clob';
458                if ($decimal == 'binary') {
459                    $type[] = 'blob';
460                }
461                $type = array_reverse($type);
462            }
463            if ($fixed !== false) {
464                $fixed = true;
465            }
466            break;
467        case 'enum':
468            $type[] = 'text';
469            preg_match_all('/\'.+\'/U', $field['type'], $matches);
470            $length = 0;
471            $fixed = false;
472            if (is_array($matches)) {
473                foreach ($matches[0] as $value) {
474                    $length = max($length, strlen($value)-2);
475                }
476                if ($length == '1' && count($matches[0]) == 2) {
477                    $type[] = 'boolean';
478                    if (preg_match('/^(is|has)/', $field['name'])) {
479                        $type = array_reverse($type);
480                    }
481                }
482            }
483            $type[] = 'integer';
484        case 'set':
485            $fixed = false;
486            $type[] = 'text';
487            $type[] = 'integer';
488            break;
489        case 'date':
490            $type[] = 'date';
491            $length = null;
492            break;
493        case 'datetime':
494        case 'timestamp':
495            $type[] = 'timestamp';
496            $length = null;
497            break;
498        case 'time':
499            $type[] = 'time';
500            $length = null;
501            break;
502        case 'float':
503        case 'double':
504        case 'real':
505            $type[] = 'float';
506            $unsigned = preg_match('/ unsigned/i', $field['type']);
507            break;
508        case 'unknown':
509        case 'decimal':
510        case 'numeric':
511            $type[] = 'decimal';
512            $unsigned = preg_match('/ unsigned/i', $field['type']);
513            if ($decimal !== false) {
514                $length = $length.','.$decimal;
515            }
516            break;
517        case 'tinyblob':
518        case 'mediumblob':
519        case 'longblob':
520        case 'blob':
521            $type[] = 'blob';
522            $length = null;
523            break;
524        case 'binary':
525        case 'varbinary':
526            $type[] = 'blob';
527            break;
528        case 'year':
529            $type[] = 'integer';
530            $type[] = 'date';
531            $length = null;
532            break;
533        default:
534            $db =& $this->getDBInstance();
535            if (PEAR::isError($db)) {
536                return $db;
537            }
538
539            return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
540                'unknown database attribute type: '.$db_type, __FUNCTION__);
541        }
542
543        if ((int)$length <= 0) {
544            $length = null;
545        }
546
547        return array($type, $length, $unsigned, $fixed);
548    }
549
550    // }}}
551}
552
553?>
Note: See TracBrowser for help on using the repository browser.