Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/*
3
 *  $Id: Mysql.php 7635 2010-06-08 13:56:17Z 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.doctrine-project.org>.
20
 */
21
 
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: 7635 $
29
 * @link        www.doctrine-project.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 'enum':
146
                if ($this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) {
147
                    $values = array();
148
                    foreach ($field['values'] as $value) {
149
                      $values[] = $this->conn->quote($value, 'varchar');
150
                    }
151
                    return 'ENUM('.implode(', ', $values).')';
152
                } else {
153
                    $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255;
154
                }
155
            case 'set':
156
                if ($this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_SET)) {
157
                    $values = array();
158
                    foreach ($field['values'] as $value) {
159
                        $values[] = $this->conn->quote($value, 'varchar');
160
                    }
161
                    return 'SET('.implode(', ', $values).')';
162
                } else {
163
                    $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255;
164
                }
165
            case 'varchar':
166
            case 'string':
167
            case 'gzip':
168
                if ( ! isset($field['length'])) {
169
                    if (array_key_exists('default', $field)) {
170
                        $field['length'] = $this->conn->varchar_max_length;
171
                    } else {
172
                        $field['length'] = false;
173
                    }
174
                }
175
 
176
                $length = ($field['length'] <= $this->conn->varchar_max_length) ? $field['length'] : false;
177
                $fixed  = (isset($field['fixed'])) ? $field['fixed'] : false;
178
 
179
                return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
180
                    : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
181
            case 'array':
182
            case 'object':
183
            case 'clob':
184
                if ( ! empty($field['length'])) {
185
                    $length = $field['length'];
186
                    if ($length <= 255) {
187
                        return 'TINYTEXT';
188
                    } elseif ($length <= 65532) {
189
                        return 'TEXT';
190
                    } elseif ($length <= 16777215) {
191
                        return 'MEDIUMTEXT';
192
                    }
193
                }
194
                return 'LONGTEXT';
195
            case 'blob':
196
                if ( ! empty($field['length'])) {
197
                    $length = $field['length'];
198
                    if ($length <= 255) {
199
                        return 'TINYBLOB';
200
                    } elseif ($length <= 65532) {
201
                        return 'BLOB';
202
                    } elseif ($length <= 16777215) {
203
                        return 'MEDIUMBLOB';
204
                    }
205
                }
206
                return 'LONGBLOB';
207
            case 'integer':
208
            case 'int':
209
                if ( ! empty($field['length'])) {
210
                    $length = $field['length'];
211
                    if ($length <= 1) {
212
                        return 'TINYINT';
213
                    } elseif ($length == 2) {
214
                        return 'SMALLINT';
215
                    } elseif ($length == 3) {
216
                        return 'MEDIUMINT';
217
                    } elseif ($length == 4) {
218
                        return 'INT';
219
                    } elseif ($length > 4) {
220
                        return 'BIGINT';
221
                    }
222
                }
223
                return 'INT';
224
            case 'boolean':
225
                return 'TINYINT(1)';
226
            case 'date':
227
                return 'DATE';
228
            case 'time':
229
                return 'TIME';
230
            case 'timestamp':
231
                return 'DATETIME';
232
            case 'float':
233
                $length = !empty($field['length']) ? $field['length'] : 18;
234
                $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES);
235
                return 'FLOAT('.$length.', '.$scale.')';
236
            case 'double':
237
                $length = !empty($field['length']) ? $field['length'] : 18;
238
                $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES);
239
                return 'DOUBLE('.$length.', '.$scale.')';
240
            case 'decimal':
241
                $length = !empty($field['length']) ? $field['length'] : 18;
242
                $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES);
243
                return 'DECIMAL('.$length.', '.$scale.')';
244
            case 'bit':
245
                return 'BIT';
246
        }
247
        return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null);
248
    }
249
 
250
    /**
251
     * Maps a native array description of a field to a MDB2 datatype and length
252
     *
253
     * @param array  $field native field description
254
     * @return array containing the various possible types, length, sign, fixed
255
     */
256
    public function getPortableDeclaration(array $field)
257
    {
258
        $dbType = strtolower($field['type']);
259
        $dbType = strtok($dbType, '(), ');
260
        if ($dbType == 'national') {
261
            $dbType = strtok('(), ');
262
        }
263
        if (isset($field['length'])) {
264
            $length = $field['length'];
265
            $decimal = '';
266
        } else {
267
            $length = strtok('(), ');
268
            $decimal = strtok('(), ');
269
            if ( ! $decimal ) {
270
                $decimal = null;
271
            }
272
        }
273
        $type = array();
274
        $unsigned = $fixed = null;
275
 
276
        if ( ! isset($field['name'])) {
277
            $field['name'] = '';
278
        }
279
 
280
        $values = null;
281
        $scale = null;
282
 
283
        switch ($dbType) {
284
            case 'tinyint':
285
                $type[] = 'integer';
286
                $type[] = 'boolean';
287
                if (preg_match('/^(is|has)/', $field['name'])) {
288
                    $type = array_reverse($type);
289
                }
290
                $unsigned = preg_match('/ unsigned/i', $field['type']);
291
                $length = 1;
292
            break;
293
            case 'smallint':
294
                $type[] = 'integer';
295
                $unsigned = preg_match('/ unsigned/i', $field['type']);
296
                $length = 2;
297
            break;
298
            case 'mediumint':
299
                $type[] = 'integer';
300
                $unsigned = preg_match('/ unsigned/i', $field['type']);
301
                $length = 3;
302
            break;
303
            case 'int':
304
            case 'integer':
305
                $type[] = 'integer';
306
                $unsigned = preg_match('/ unsigned/i', $field['type']);
307
                $length = 4;
308
            break;
309
            case 'bigint':
310
                $type[] = 'integer';
311
                $unsigned = preg_match('/ unsigned/i', $field['type']);
312
                $length = 8;
313
            break;
314
            case 'tinytext':
315
            case 'mediumtext':
316
            case 'longtext':
317
            case 'text':
318
            case 'text':
319
            case 'varchar':
320
                $fixed = false;
321
            case 'string':
322
            case 'char':
323
                $type[] = 'string';
324
                if ($length == '1') {
325
                    $type[] = 'boolean';
326
                    if (preg_match('/^(is|has)/', $field['name'])) {
327
                        $type = array_reverse($type);
328
                    }
329
                } elseif (strstr($dbType, 'text')) {
330
                    $type[] = 'clob';
331
                    if ($decimal == 'binary') {
332
                        $type[] = 'blob';
333
                    }
334
                }
335
                if ($fixed !== false) {
336
                    $fixed = true;
337
                }
338
            break;
339
            case 'enum':
340
                $type[] = 'enum';
341
                preg_match_all('/\'((?:\'\'|[^\'])*)\'/', $field['type'], $matches);
342
                $length = 0;
343
                $fixed = false;
344
                if (is_array($matches)) {
345
                    foreach ($matches[1] as &$value) {
346
                        $value = str_replace('\'\'', '\'', $value);
347
                        $length = max($length, strlen($value));
348
                    }
349
                    if ($length == '1' && count($matches[1]) == 2) {
350
                        $type[] = 'boolean';
351
                        if (preg_match('/^(is|has)/', $field['name'])) {
352
                            $type = array_reverse($type);
353
                        }
354
                    }
355
 
356
                    $values = $matches[1];
357
                }
358
                $type[] = 'integer';
359
                break;
360
            case 'set':
361
                $fixed = false;
362
                $type[] = 'text';
363
                $type[] = 'integer';
364
            break;
365
            case 'date':
366
                $type[] = 'date';
367
                $length = null;
368
            break;
369
            case 'datetime':
370
            case 'timestamp':
371
                $type[] = 'timestamp';
372
                $length = null;
373
            break;
374
            case 'time':
375
                $type[] = 'time';
376
                $length = null;
377
            break;
378
            case 'float':
379
            case 'double':
380
            case 'real':
381
                $type[] = 'float';
382
                $unsigned = preg_match('/ unsigned/i', $field['type']);
383
            break;
384
            case 'unknown':
385
            case 'decimal':
386
                if ($decimal !== null) {
387
                    $scale = $decimal;
388
                }
389
            case 'numeric':
390
                $type[] = 'decimal';
391
                $unsigned = preg_match('/ unsigned/i', $field['type']);
392
            break;
393
            case 'tinyblob':
394
            case 'mediumblob':
395
            case 'longblob':
396
            case 'blob':
397
            case 'binary':
398
            case 'varbinary':
399
                $type[] = 'blob';
400
                $length = null;
401
            break;
402
            case 'year':
403
                $type[] = 'integer';
404
                $type[] = 'date';
405
                $length = null;
406
            break;
407
            case 'bit':
408
                $type[] = 'bit';
409
            break;
410
            case 'geometry':
411
            case 'geometrycollection':
412
            case 'point':
413
            case 'multipoint':
414
            case 'linestring':
415
            case 'multilinestring':
416
            case 'polygon':
417
            case 'multipolygon':
418
                $type[] = 'blob';
419
                $length = null;
420
            break;
421
            default:
422
                $type[] = $field['type'];
423
                $length = isset($field['length']) ? $field['length']:null;
424
        }
425
 
426
        $length = ((int) $length == 0) ? null : (int) $length;
427
        $def =  array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed);
428
        if ($values !== null) {
429
            $def['values'] = $values;
430
        }
431
        if ($scale !== null) {
432
            $def['scale'] = $scale;
433
        }
434
        return $def;
435
    }
436
 
437
    /**
438
     * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
439
     * of a field declaration to be used in statements like CREATE TABLE.
440
     *
441
     * @param string $charset   name of the charset
442
     * @return string  DBMS specific SQL code portion needed to set the CHARACTER SET
443
     *                 of a field declaration.
444
     */
445
    public function getCharsetFieldDeclaration($charset)
446
    {
447
        return 'CHARACTER SET ' . $charset;
448
    }
449
 
450
    /**
451
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
452
     * of a field declaration to be used in statements like CREATE TABLE.
453
     *
454
     * @param string $collation   name of the collation
455
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
456
     *                 of a field declaration.
457
     */
458
    public function getCollationFieldDeclaration($collation)
459
    {
460
        return 'COLLATE ' . $collation;
461
    }
462
 
463
    /**
464
     * Obtain DBMS specific SQL code portion needed to declare an integer type
465
     * field to be used in statements like CREATE TABLE.
466
     *
467
     * @param string  $name   name the field to be declared.
468
     * @param string  $field  associative array with the name of the properties
469
     *                        of the field being declared as array indexes.
470
     *                        Currently, the types of supported field
471
     *                        properties are as follows:
472
     *
473
     *                       unsigned
474
     *                        Boolean flag that indicates whether the field
475
     *                        should be declared as unsigned integer if
476
     *                        possible.
477
     *
478
     *                       default
479
     *                        Integer value to be used as default for this
480
     *                        field.
481
     *
482
     *                       notnull
483
     *                        Boolean flag that indicates whether this field is
484
     *                        constrained to not be set to null.
485
     * @return string  DBMS specific SQL code portion that should be used to
486
     *                 declare the specified field.
487
     */
488
    public function getIntegerDeclaration($name, $field)
489
    {
490
        $unique = (isset($field['unique']) && $field['unique']) ? ' UNIQUE' : '';
491
        $default = $autoinc = '';
492
        if ( ! empty($field['autoincrement'])) {
493
            $autoinc = ' AUTO_INCREMENT';
494
        } elseif (array_key_exists('default', $field)) {
495
            if ($field['default'] === '') {
496
                $field['default'] = empty($field['notnull']) ? null : 0;
497
            }
498
 
499
            $default = ' DEFAULT ' . (is_null($field['default'])
500
                ? 'NULL'
501
                : $this->conn->quote($field['default']));
502
        }
503
 
504
        $notnull  = (isset($field['notnull'])  && $field['notnull'])  ? ' NOT NULL' : '';
505
        $unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : '';
506
        $comment  = (isset($field['comment']) && $field['comment'])
507
            ? " COMMENT " . $this->conn->quote($field['comment'], 'text') : '';
508
 
509
        $name = $this->conn->quoteIdentifier($name, true);
510
 
511
        return $name . ' ' . $this->getNativeDeclaration($field) . $unsigned
512
            . $default . $unique . $notnull . $autoinc . $comment;
513
    }
514
}