Coverage for Doctrine_DataDict_Mysql

Back to coverage report

1 <?php
2 /*
3  *  $Id: Mysql.php 3927 2008-03-04 23:10:53Z jwage $
4  *
5  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16  *
17  * This software consists of voluntary contributions made by many individuals
18  * and is licensed under the LGPL. For more information, see
19  * <http://www.phpdoctrine.org>.
20  */
21 Doctrine::autoload('Doctrine_DataDict');
22 /**
23  * @package     Doctrine
24  * @subpackage  DataDict
25  * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
26  * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
27  * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
28  * @version     $Revision: 3927 $
29  * @link        www.phpdoctrine.org
30  * @since       1.0
31  */
32 class Doctrine_DataDict_Mysql extends Doctrine_DataDict
33 {
34     protected $keywords = array(
35                           'ADD', 'ALL', 'ALTER',
36                           'ANALYZE', 'AND', 'AS',
37                           'ASC', 'ASENSITIVE', 'BEFORE',
38                           'BETWEEN', 'BIGINT', 'BINARY',
39                           'BLOB', 'BOTH', 'BY', 'BIT',
40                           'CALL', 'CASCADE', 'CASE',
41                           'CHANGE', 'CHAR', 'CHARACTER',
42                           'CHECK', 'COLLATE', 'COLUMN',
43                           'CONDITION', 'CONNECTION', 'CONSTRAINT',
44                           'CONTINUE', 'CONVERT', 'CREATE',
45                           'CROSS', 'CURRENT_DATE', 'CURRENT_TIME',
46                           'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR',
47                           'DATABASE', 'DATABASES', 'DAY_HOUR',
48                           'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND',
49                           'DEC', 'DECIMAL', 'DECLARE',
50                           'DEFAULT', 'DELAYED', 'DELETE',
51                           'DESC', 'DESCRIBE', 'DETERMINISTIC',
52                           'DISTINCT', 'DISTINCTROW', 'DIV',
53                           'DOUBLE', 'DROP', 'DUAL',
54                           'EACH', 'ELSE', 'ELSEIF',
55                           'ENCLOSED', 'ESCAPED', 'EXISTS',
56                           'EXIT', 'EXPLAIN', 'FALSE',
57                           'FETCH', 'FLOAT', 'FLOAT4',
58                           'FLOAT8', 'FOR', 'FORCE',
59                           'FOREIGN', 'FROM', 'FULLTEXT',
60                           'GRANT', 'GROUP', 'HAVING',
61                           'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE',
62                           'HOUR_SECOND', 'IF', 'IGNORE',
63                           'IN', 'INDEX', 'INFILE',
64                           'INNER', 'INOUT', 'INSENSITIVE',
65                           'INSERT', 'INT', 'INT1',
66                           'INT2', 'INT3', 'INT4',
67                           'INT8', 'INTEGER', 'INTERVAL',
68                           'INTO', 'IS', 'ITERATE',
69                           'JOIN', 'KEY', 'KEYS',
70                           'KILL', 'LEADING', 'LEAVE',
71                           'LEFT', 'LIKE', 'LIMIT',
72                           'LINES', 'LOAD', 'LOCALTIME',
73                           'LOCALTIMESTAMP', 'LOCK', 'LONG',
74                           'LONGBLOB', 'LONGTEXT', 'LOOP',
75                           'LOW_PRIORITY', 'MATCH', 'MEDIUMBLOB',
76                           'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT',
77                           'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD',
78                           'MODIFIES', 'NATURAL', 'NOT',
79                           'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC',
80                           'ON', 'OPTIMIZE', 'OPTION',
81                           'OPTIONALLY', 'OR', 'ORDER',
82                           'OUT', 'OUTER', 'OUTFILE',
83                           'PRECISION', 'PRIMARY', 'PROCEDURE',
84                           'PURGE', 'RAID0', 'READ',
85                           'READS', 'REAL', 'REFERENCES',
86                           'REGEXP', 'RELEASE', 'RENAME',
87                           'REPEAT', 'REPLACE', 'REQUIRE',
88                           'RESTRICT', 'RETURN', 'REVOKE',
89                           'RIGHT', 'RLIKE', 'SCHEMA',
90                           'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT',
91                           'SENSITIVE', 'SEPARATOR', 'SET',
92                           'SHOW', 'SMALLINT', 'SONAME',
93                           'SPATIAL', 'SPECIFIC', 'SQL',
94                           'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING',
95                           'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT',
96                           'SSL', 'STARTING', 'STRAIGHT_JOIN',
97                           'TABLE', 'TERMINATED', 'THEN',
98                           'TINYBLOB', 'TINYINT', 'TINYTEXT',
99                           'TO', 'TRAILING', 'TRIGGER',
100                           'TRUE', 'UNDO', 'UNION',
101                           'UNIQUE', 'UNLOCK', 'UNSIGNED',
102                           'UPDATE', 'USAGE', 'USE',
103                           'USING', 'UTC_DATE', 'UTC_TIME',
104                           'UTC_TIMESTAMP', 'VALUES', 'VARBINARY',
105                           'VARCHAR', 'VARCHARACTER', 'VARYING',
106                           'WHEN', 'WHERE', 'WHILE',
107                           'WITH', 'WRITE', 'X509',
108                           'XOR', 'YEAR_MONTH', 'ZEROFILL'
109                           );
110
111     /**
112      * Obtain DBMS specific SQL code portion needed to declare an text type
113      * field to be used in statements like CREATE TABLE.
114      *
115      * @param array $field  associative array with the name of the properties
116      *      of the field being declared as array indexes. Currently, the types
117      *      of supported field properties are as follows:
118      *
119      *      length
120      *          Integer value that determines the maximum length of the text
121      *          field. If this argument is missing the field should be
122      *          declared to have the longest length allowed by the DBMS.
123      *
124      *      default
125      *          Text value to be used as default for this field.
126      *
127      *      notnull
128      *          Boolean flag that indicates whether this field is constrained
129      *          to not be set to null.
130      *
131      * @return string  DBMS specific SQL code portion that should be used to
132      *      declare the specified field.
133      */
134     public function getNativeDeclaration($field)
135     {
136         if ( ! isset($field['type'])) {
137             throw new Doctrine_DataDict_Exception('Missing column type.');
138         }
139
140         switch ($field['type']) {
141             case 'char':
142                 $length = ( ! empty($field['length'])) ? $field['length'] : false;
143
144                 return $length ? 'CHAR('.$length.')' : 'CHAR(255)';
145             case 'varchar':
146             case 'array':
147             case 'object':
148             case 'string':
149             case 'gzip':
150                 if ( ! isset($field['length'])) {
151                     if (array_key_exists('default', $field)) {
152                         $field['length'] = $this->conn->varchar_max_length;
153                     } else {
154                         $field['length'] = false;
155                     }
156                 }
157
158                 $length = ($field['length'] <= $this->conn->varchar_max_length) ? $field['length'] : false;
159                 $fixed  = (isset($field['fixed'])) ? $field['fixed'] : false;
160
161                 return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
162                     : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
163             case 'clob':
164                 if ( ! empty($field['length'])) {
165                     $length = $field['length'];
166                     if ($length <= 255) {
167                         return 'TINYTEXT';
168                     } elseif ($length <= 65532) {
169                         return 'TEXT';
170                     } elseif ($length <= 16777215) {
171                         return 'MEDIUMTEXT';
172                     }
173                 }
174                 return 'LONGTEXT';
175             case 'blob':
176                 if ( ! empty($field['length'])) {
177                     $length = $field['length'];
178                     if ($length <= 255) {
179                         return 'TINYBLOB';
180                     } elseif ($length <= 65532) {
181                         return 'BLOB';
182                     } elseif ($length <= 16777215) {
183                         return 'MEDIUMBLOB';
184                     }
185                 }
186                 return 'LONGBLOB';
187             case 'enum':
188                 if ($this->conn->getAttribute(Doctrine::ATTR_USE_NATIVE_ENUM)) {
189                     $values = array();
190                     foreach ($field['values'] as $value) {
191                       $values[] = $this->conn->quote($value, 'varchar');
192                     }
193                     return 'ENUM('.implode(', ', $values).')';
194                 }
195                 // fall back to integer
196             case 'integer':
197             case 'int':
198                 if ( ! empty($field['length'])) {
199                     $length = $field['length'];
200                     if ($length <= 1) {
201                         return 'TINYINT';
202                     } elseif ($length == 2) {
203                         return 'SMALLINT';
204                     } elseif ($length == 3) {
205                         return 'MEDIUMINT';
206                     } elseif ($length == 4) {
207                         return 'INT';
208                     } elseif ($length > 4) {
209                         return 'BIGINT';
210                     }
211                 }
212                 return 'INT';
213             case 'boolean':
214                 return 'TINYINT(1)';
215             case 'date':
216                 return 'DATE';
217             case 'time':
218                 return 'TIME';
219             case 'timestamp':
220                 return 'DATETIME';
221             case 'float':
222             case 'double':
223                 return 'DOUBLE';
224             case 'decimal':
225                 $length = !empty($field['length']) ? $field['length'] : 18;
226                 $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine::ATTR_DECIMAL_PLACES);
227                 return 'DECIMAL('.$length.','.$scale.')';
228             case 'bit':
229                 return 'BIT';
230         }
231         throw new Doctrine_DataDict_Exception('Unknown field type \'' . $field['type'] .  '\'.');
232     }
233
234     /**
235      * Maps a native array description of a field to a MDB2 datatype and length
236      *
237      * @param array  $field native field description
238      * @return array containing the various possible types, length, sign, fixed
239      */
240     public function getPortableDeclaration(array $field)
241     {
242         $dbType = strtolower($field['type']);
243         $dbType = strtok($dbType, '(), ');
244         if ($dbType == 'national') {
245             $dbType = strtok('(), ');
246         }
247         if (isset($field['length'])) {
248             $length = $field['length'];
249             $decimal = '';
250         } else {
251             $length = strtok('(), ');
252             $decimal = strtok('(), ');
253         }
254         $type = array();
255         $unsigned = $fixed = null;
256
257         if ( ! isset($field['name'])) {
258             $field['name'] = '';
259         }
260
261         $values = null;
262
263         switch ($dbType) {
264             case 'tinyint':
265                 $type[] = 'integer';
266                 $type[] = 'boolean';
267                 if (preg_match('/^(is|has)/', $field['name'])) {
268                     $type = array_reverse($type);
269                 }
270                 $unsigned = preg_match('/ unsigned/i', $field['type']);
271                 $length = 1;
272             break;
273             case 'smallint':
274                 $type[] = 'integer';
275                 $unsigned = preg_match('/ unsigned/i', $field['type']);
276                 $length = 2;
277             break;
278             case 'mediumint':
279                 $type[] = 'integer';
280                 $unsigned = preg_match('/ unsigned/i', $field['type']);
281                 $length = 3;
282             break;
283             case 'int':
284             case 'integer':
285                 $type[] = 'integer';
286                 $unsigned = preg_match('/ unsigned/i', $field['type']);
287                 $length = 4;
288             break;
289             case 'bigint':
290                 $type[] = 'integer';
291                 $unsigned = preg_match('/ unsigned/i', $field['type']);
292                 $length = 8;
293             break;
294             case 'tinytext':
295             case 'mediumtext':
296             case 'longtext':
297             case 'text':
298             case 'text':
299             case 'varchar':
300                 $fixed = false;
301             case 'string':
302             case 'char':
303                 $type[] = 'string';
304                 if ($length == '1') {
305                     $type[] = 'boolean';
306                     if (preg_match('/^(is|has)/', $field['name'])) {
307                         $type = array_reverse($type);
308                     }
309                 } elseif (strstr($dbType, 'text')) {
310                     $type[] = 'clob';
311                     if ($decimal == 'binary') {
312                         $type[] = 'blob';
313                     }
314                 }
315                 if ($fixed !== false) {
316                     $fixed = true;
317                 }
318             break;
319             case 'enum':
320                 $type[] = 'enum';
321                 preg_match_all('/\'((?:\'\'|[^\'])*)\'/', $field['type'], $matches);
322                 $length = 0;
323                 $fixed = false;
324                 if (is_array($matches)) {
325                     foreach ($matches[1] as &$value) {
326                         $value = str_replace('\'\'', '\'', $value);
327                         $length = max($length, strlen($value));
328                     }
329                     if ($length == '1' && count($matches[1]) == 2) {
330                         $type[] = 'boolean';
331                         if (preg_match('/^(is|has)/', $field['name'])) {
332                             $type = array_reverse($type);
333                         }
334                     } else {
335                         $values = $matches[1];
336                     }
337                 }
338                 $type[] = 'integer';
339                 break;
340             case 'set':
341                 $fixed = false;
342                 $type[] = 'text';
343                 $type[] = 'integer';
344             break;
345             case 'date':
346                 $type[] = 'date';
347                 $length = null;
348             break;
349             case 'datetime':
350             case 'timestamp':
351                 $type[] = 'timestamp';
352                 $length = null;
353             break;
354             case 'time':
355                 $type[] = 'time';
356                 $length = null;
357             break;
358             case 'float':
359             case 'double':
360             case 'real':
361                 $type[] = 'float';
362                 $unsigned = preg_match('/ unsigned/i', $field['type']);
363             break;
364             case 'unknown':
365             case 'decimal':
366             case 'numeric':
367                 $type[] = 'decimal';
368                 $unsigned = preg_match('/ unsigned/i', $field['type']);
369             break;
370             case 'tinyblob':
371             case 'mediumblob':
372             case 'longblob':
373             case 'blob':
374                 $type[] = 'blob';
375                 $length = null;
376             break;
377             case 'year':
378                 $type[] = 'integer';
379                 $type[] = 'date';
380                 $length = null;
381             break;
382             case 'bit':
383                 $type[] = 'bit';
384             break;
385             default:
386                 throw new Doctrine_DataDict_Exception('unknown database attribute type: ' . $dbType);
387         }
388
389         $length = ((int) $length == 0) ? null : (int) $length;
390
391         if ($values === null) {
392             return array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed);
393         } else {
394             return array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed, 'values' => $values);
395         }
396     }
397
398     /**
399      * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
400      * of a field declaration to be used in statements like CREATE TABLE.
401      *
402      * @param string $charset   name of the charset
403      * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET
404      *                 of a field declaration.
405      */
406     public function getCharsetFieldDeclaration($charset)
407     {
408         return 'CHARACTER SET ' . $charset;
409     }
410
411     /**
412      * Obtain DBMS specific SQL code portion needed to set the COLLATION
413      * of a field declaration to be used in statements like CREATE TABLE.
414      *
415      * @param string $collation   name of the collation
416      * @return string  DBMS specific SQL code portion needed to set the COLLATION
417      *                 of a field declaration.
418      */
419     public function getCollationFieldDeclaration($collation)
420     {
421         return 'COLLATE ' . $collation;
422     }
423
424     /**
425      * Obtain DBMS specific SQL code portion needed to declare an integer type
426      * field to be used in statements like CREATE TABLE.
427      *
428      * @param string  $name   name the field to be declared.
429      * @param string  $field  associative array with the name of the properties
430      *                        of the field being declared as array indexes.
431      *                        Currently, the types of supported field
432      *                        properties are as follows:
433      *
434      *                       unsigned
435      *                        Boolean flag that indicates whether the field
436      *                        should be declared as unsigned integer if
437      *                        possible.
438      *
439      *                       default
440      *                        Integer value to be used as default for this
441      *                        field.
442      *
443      *                       notnull
444      *                        Boolean flag that indicates whether this field is
445      *                        constrained to not be set to null.
446      * @return string  DBMS specific SQL code portion that should be used to
447      *                 declare the specified field.
448      */
449     public function getIntegerDeclaration($name, $field)
450     {
451         $default = $autoinc = '';
452         if ( ! empty($field['autoincrement'])) {
453             $autoinc = ' AUTO_INCREMENT';
454         } elseif (array_key_exists('default', $field)) {
455             if ($field['default'] === '') {
456                 $field['default'] = empty($field['notnull']) ? null : 0;
457             }
458             if (is_null($field['default'])) {
459                 $default = ' DEFAULT NULL';
460             } else {
461                 $default = ' DEFAULT '.$this->conn->quote($field['default']);
462             }
463         }
464         /**
465         elseif (empty($field['notnull'])) {
466             $default = ' DEFAULT NULL';
467         }
468         */
469
470         $notnull  = (isset($field['notnull'])  && $field['notnull'])  ? ' NOT NULL' : '';
471         $unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : '';
472
473         $name = $this->conn->quoteIdentifier($name, true);
474
475         return $name . ' ' . $this->getNativeDeclaration($field) . $unsigned . $default . $notnull . $autoinc;
476     }
477 }