Coverage for Doctrine_DataDict_Pgsql

Back to coverage report

1 <?php
2 /*
3  *  $Id: Pgsql.php 3895 2008-02-27 01:39:51Z guilhermeblanco $
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      Paul Cooper <pgc@ucecom.com>
28  * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
29  * @version     $Revision: 3895 $
30  * @link        www.phpdoctrine.org
31  * @since       1.0
32  */
33 class Doctrine_DataDict_Pgsql extends Doctrine_DataDict
34 {
35     /**
36      * @param array $reservedKeyWords     an array of reserved keywords by pgsql
37      */
38     protected static $reservedKeyWords = array(
39                                         'abort',
40                                         'absolute',
41                                         'access',
42                                         'action',
43                                         'add',
44                                         'after',
45                                         'aggregate',
46                                         'all',
47                                         'alter',
48                                         'analyse',
49                                         'analyze',
50                                         'and',
51                                         'any',
52                                         'as',
53                                         'asc',
54                                         'assertion',
55                                         'assignment',
56                                         'at',
57                                         'authorization',
58                                         'backward',
59                                         'before',
60                                         'begin',
61                                         'between',
62                                         'bigint',
63                                         'binary',
64                                         'bit',
65                                         'boolean',
66                                         'both',
67                                         'by',
68                                         'cache',
69                                         'called',
70                                         'cascade',
71                                         'case',
72                                         'cast',
73                                         'chain',
74                                         'char',
75                                         'character',
76                                         'characteristics',
77                                         'check',
78                                         'checkpoint',
79                                         'class',
80                                         'close',
81                                         'cluster',
82                                         'coalesce',
83                                         'collate',
84                                         'column',
85                                         'comment',
86                                         'commit',
87                                         'committed',
88                                         'constraint',
89                                         'constraints',
90                                         'conversion',
91                                         'convert',
92                                         'copy',
93                                         'create',
94                                         'createdb',
95                                         'createuser',
96                                         'cross',
97                                         'current_date',
98                                         'current_time',
99                                         'current_timestamp',
100                                         'current_user',
101                                         'cursor',
102                                         'cycle',
103                                         'database',
104                                         'day',
105                                         'deallocate',
106                                         'dec',
107                                         'decimal',
108                                         'declare',
109                                         'default',
110                                         'deferrable',
111                                         'deferred',
112                                         'definer',
113                                         'delete',
114                                         'delimiter',
115                                         'delimiters',
116                                         'desc',
117                                         'distinct',
118                                         'do',
119                                         'domain',
120                                         'double',
121                                         'drop',
122                                         'each',
123                                         'else',
124                                         'encoding',
125                                         'encrypted',
126                                         'end',
127                                         'escape',
128                                         'except',
129                                         'exclusive',
130                                         'execute',
131                                         'exists',
132                                         'explain',
133                                         'external',
134                                         'extract',
135                                         'false',
136                                         'fetch',
137                                         'float',
138                                         'for',
139                                         'force',
140                                         'foreign',
141                                         'forward',
142                                         'freeze',
143                                         'from',
144                                         'full',
145                                         'function',
146                                         'get',
147                                         'global',
148                                         'grant',
149                                         'group',
150                                         'handler',
151                                         'having',
152                                         'hour',
153                                         'ilike',
154                                         'immediate',
155                                         'immutable',
156                                         'implicit',
157                                         'in',
158                                         'increment',
159                                         'index',
160                                         'inherits',
161                                         'initially',
162                                         'inner',
163                                         'inout',
164                                         'input',
165                                         'insensitive',
166                                         'insert',
167                                         'instead',
168                                         'int',
169                                         'integer',
170                                         'intersect',
171                                         'interval',
172                                         'into',
173                                         'invoker',
174                                         'is',
175                                         'isnull',
176                                         'isolation',
177                                         'join',
178                                         'key',
179                                         'lancompiler',
180                                         'language',
181                                         'leading',
182                                         'left',
183                                         'level',
184                                         'like',
185                                         'limit',
186                                         'listen',
187                                         'load',
188                                         'local',
189                                         'localtime',
190                                         'localtimestamp',
191                                         'location',
192                                         'lock',
193                                         'match',
194                                         'maxvalue',
195                                         'minute',
196                                         'minvalue',
197                                         'mode',
198                                         'month',
199                                         'move',
200                                         'names',
201                                         'national',
202                                         'natural',
203                                         'nchar',
204                                         'new',
205                                         'next',
206                                         'no',
207                                         'nocreatedb',
208                                         'nocreateuser',
209                                         'none',
210                                         'not',
211                                         'nothing',
212                                         'notify',
213                                         'notnull',
214                                         'null',
215                                         'nullif',
216                                         'numeric',
217                                         'of',
218                                         'off',
219                                         'offset',
220                                         'oids',
221                                         'old',
222                                         'on',
223                                         'only',
224                                         'operator',
225                                         'option',
226                                         'or',
227                                         'order',
228                                         'out',
229                                         'outer',
230                                         'overlaps',
231                                         'overlay',
232                                         'owner',
233                                         'partial',
234                                         'password',
235                                         'path',
236                                         'pendant',
237                                         'placing',
238                                         'position',
239                                         'precision',
240                                         'prepare',
241                                         'primary',
242                                         'prior',
243                                         'privileges',
244                                         'procedural',
245                                         'procedure',
246                                         'read',
247                                         'real',
248                                         'recheck',
249                                         'references',
250                                         'reindex',
251                                         'relative',
252                                         'rename',
253                                         'replace',
254                                         'reset',
255                                         'restrict',
256                                         'returns',
257                                         'revoke',
258                                         'right',
259                                         'rollback',
260                                         'row',
261                                         'rule',
262                                         'schema',
263                                         'scroll',
264                                         'second',
265                                         'security',
266                                         'select',
267                                         'sequence',
268                                         'serializable',
269                                         'session',
270                                         'session_user',
271                                         'set',
272                                         'setof',
273                                         'share',
274                                         'show',
275                                         'similar',
276                                         'simple',
277                                         'smallint',
278                                         'some',
279                                         'stable',
280                                         'start',
281                                         'statement',
282                                         'statistics',
283                                         'stdin',
284                                         'stdout',
285                                         'storage',
286                                         'strict',
287                                         'substring',
288                                         'sysid',
289                                         'table',
290                                         'temp',
291                                         'template',
292                                         'temporary',
293                                         'then',
294                                         'time',
295                                         'timestamp',
296                                         'to',
297                                         'toast',
298                                         'trailing',
299                                         'transaction',
300                                         'treat',
301                                         'trigger',
302                                         'trim',
303                                         'true',
304                                         'truncate',
305                                         'trusted',
306                                         'type',
307                                         'unencrypted',
308                                         'union',
309                                         'unique',
310                                         'unknown',
311                                         'unlisten',
312                                         'until',
313                                         'update',
314                                         'usage',
315                                         'user',
316                                         'using',
317                                         'vacuum',
318                                         'valid',
319                                         'validator',
320                                         'values',
321                                         'varchar',
322                                         'varying',
323                                         'verbose',
324                                         'version',
325                                         'view',
326                                         'volatile',
327                                         'when',
328                                         'where',
329                                         'with',
330                                         'without',
331                                         'work',
332                                         'write',
333                                         'year',
334                                         'zone'
335                                         );
336
337     /**
338      * Obtain DBMS specific SQL code portion needed to declare an text type
339      * field to be used in statements like CREATE TABLE.
340      *
341      * @param array $field  associative array with the name of the properties
342      *      of the field being declared as array indexes. Currently, the types
343      *      of supported field properties are as follows:
344      *
345      *      length
346      *          Integer value that determines the maximum length of the text
347      *          field. If this argument is missing the field should be
348      *          declared to have the longest length allowed by the DBMS.
349      *
350      *      default
351      *          Text value to be used as default for this field.
352      *
353      *      notnull
354      *          Boolean flag that indicates whether this field is constrained
355      *          to not be set to null.
356      *
357      * @return string  DBMS specific SQL code portion that should be used to
358      *      declare the specified field.
359      */
360     public function getNativeDeclaration(array $field)
361     {
362         if ( ! isset($field['type'])) {
363             throw new Doctrine_DataDict_Exception('Missing column type.');
364         }
365         switch ($field['type']) {
366             case 'char':
367             case 'string':
368             case 'array':
369             case 'object':
370             case 'varchar':
371             case 'gzip':
372                 // TODO: what is the maximum VARCHAR length in pgsql ?
373                 $length = (isset($field['length']) && $field['length'] && $field['length'] < 10000) ? $field['length'] : null;
374
375                 $fixed  = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false;
376
377                 return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR('.$this->conn->options['default_text_field_length'].')')
378                     : ($length ? 'VARCHAR(' .$length . ')' : 'TEXT');
379
380             case 'clob':
381                 return 'TEXT';
382             case 'blob':
383                 return 'BYTEA';
384             case 'enum':
385             case 'integer':
386             case 'int':
387                 if ( ! empty($field['autoincrement'])) {
388                     if ( ! empty($field['length'])) {
389                         $length = $field['length'];
390                         if ($length > 4) {
391                             return 'BIGSERIAL';
392                         }
393                     }
394                     return 'SERIAL';
395                 }
396                 if ( ! empty($field['length'])) {
397                     $length = $field['length'];
398                     if ($length <= 2) {
399                         return 'SMALLINT';
400                     } elseif ($length == 3 || $length == 4) {
401                         return 'INT';
402                     } elseif ($length > 4) {
403                         return 'BIGINT';
404                     }
405                 }
406                 return 'INT';
407             case 'boolean':
408                 return 'BOOLEAN';
409             case 'date':
410                 return 'DATE';
411             case 'time':
412                 return 'TIME without time zone';
413             case 'timestamp':
414                 return 'TIMESTAMP without time zone';
415             case 'float':
416             case 'double':
417                 return 'FLOAT';
418             case 'decimal':
419                 $length = !empty($field['length']) ? $field['length'] : 18;
420                 $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine::ATTR_DECIMAL_PLACES);
421                 return 'NUMERIC('.$length.','.$scale.')';
422         }
423         throw new Doctrine_DataDict_Exception('Unknown field type \'' . $field['type'] .  '\'.');
424     }
425
426     /**
427      * Maps a native array description of a field to a portable Doctrine datatype and length
428      *
429      * @param array  $field native field description
430      *
431      * @return array containing the various possible types, length, sign, fixed
432      */
433     public function getPortableDeclaration(array $field)
434     {
435
436         $length = (isset($field['length'])) ? $field['length'] : null;
437         if ($length == '-1' && isset($field['atttypmod'])) {
438             $length = $field['atttypmod'] - 4;
439         }
440         if ((int)$length <= 0) {
441             $length = null;
442         }
443         $type = array();
444         $unsigned = $fixed = null;
445
446         if ( ! isset($field['name'])) {
447             $field['name'] = '';
448         }
449
450         $dbType = strtolower($field['type']);
451
452         switch ($dbType) {
453             case 'smallint':
454             case 'int2':
455                 $type[] = 'integer';
456                 $unsigned = false;
457                 $length = 2;
458                 if ($length == '2') {
459                     $type[] = 'boolean';
460                     if (preg_match('/^(is|has)/', $field['name'])) {
461                         $type = array_reverse($type);
462                     }
463                 }
464                 break;
465             case 'int':
466             case 'int4':
467             case 'integer':
468             case 'serial':
469             case 'serial4':
470                 $type[] = 'integer';
471                 $unsigned = false;
472                 $length = 4;
473                 break;
474             case 'bigint':
475             case 'int8':
476             case 'bigserial':
477             case 'serial8':
478                 $type[] = 'integer';
479                 $unsigned = false;
480                 $length = 8;
481                 break;
482             case 'bool':
483             case 'boolean':
484                 $type[] = 'boolean';
485                 $length = 1;
486                 break;
487             case 'text':
488             case 'varchar':
489             case 'interval':
490             case '_varchar':
491                 $fixed = false;
492             case 'unknown':
493             case 'char':
494             case 'bpchar':
495                 $type[] = 'string';
496                 if ($length == '1') {
497                     $type[] = 'boolean';
498                     if (preg_match('/^(is|has)/', $field['name'])) {
499                         $type = array_reverse($type);
500                     }
501                 } elseif (strstr($dbType, 'text')) {
502                     $type[] = 'clob';
503                 }
504                 if ($fixed !== false) {
505                     $fixed = true;
506                 }
507                 break;
508             case 'date':
509                 $type[] = 'date';
510                 $length = null;
511                 break;
512             case 'datetime':
513             case 'timestamp':
514             case 'timestamptz':
515                 $type[] = 'timestamp';
516                 $length = null;
517                 break;
518             case 'time':
519                 $type[] = 'time';
520                 $length = null;
521                 break;
522             case 'float':
523             case 'float4':
524             case 'float8':
525             case 'double':
526             case 'double precision':
527             case 'real':
528                 $type[] = 'float';
529                 break;
530             case 'decimal':
531             case 'money':
532             case 'numeric':
533                 $type[] = 'decimal';
534                 break;
535             case 'tinyblob':
536             case 'mediumblob':
537             case 'longblob':
538             case 'blob':
539             case 'bytea':
540                 $type[] = 'blob';
541                 $length = null;
542                 break;
543             case 'oid':
544                 $type[] = 'blob';
545                 $type[] = 'clob';
546                 $length = null;
547                 break;
548             case 'year':
549                 $type[] = 'integer';
550                 $type[] = 'date';
551                 $length = null;
552                 break;
553             default:
554                 throw new Doctrine_DataDict_Exception('unknown database attribute type: '.$dbType);
555         }
556
557         return array('type'     => $type,
558                      'length'   => $length,
559                      'unsigned' => $unsigned,
560                      'fixed'    => $fixed);
561     }
562
563     /**
564      * Obtain DBMS specific SQL code portion needed to declare an integer type
565      * field to be used in statements like CREATE TABLE.
566      *
567      * @param string $name name the field to be declared.
568      * @param array $field associative array with the name of the properties
569      *       of the field being declared as array indexes. Currently, the types
570      *       of supported field properties are as follows:
571      *
572      *       unsigned
573      *           Boolean flag that indicates whether the field should be
574      *           declared as unsigned integer if possible.
575      *
576      *       default
577      *           Integer value to be used as default for this field.
578      *
579      *       notnull
580      *           Boolean flag that indicates whether this field is constrained
581      *           to not be set to null.
582      * @return string DBMS specific SQL code portion that should be used to
583      *       declare the specified field.
584      */
585     public function getIntegerDeclaration($name, $field)
586     {
587         /**
588         if ( ! empty($field['unsigned'])) {
589             $this->conn->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
590         }
591         */
592
593         if ( ! empty($field['autoincrement'])) {
594             $name = $this->conn->quoteIdentifier($name, true);
595             return $name . ' ' . $this->getNativeDeclaration($field);
596         }
597
598         $default = '';
599         if (array_key_exists('default', $field)) {
600             if ($field['default'] === '') {
601                 $field['default'] = empty($field['notnull']) ? null : 0;
602             }
603             $default = ' DEFAULT '.$this->conn->quote($field['default'], $field['type']);
604         }
605         /**
606         TODO: is this needed ?
607         elseif (empty($field['notnull'])) {
608             $default = ' DEFAULT NULL';
609         }
610         */
611
612         $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
613         $name = $this->conn->quoteIdentifier($name, true);
614         return $name . ' ' . $this->getNativeDeclaration($field) . $default . $notnull;
615     }
616
617     /**
618      * parseBoolean
619      * parses a literal boolean value and returns
620      * proper sql equivalent
621      *
622      * @param string $value     boolean value to be parsed
623      * @return string           parsed boolean value
624      */
625     public function parseBoolean($value)
626     {
627         return $value;
628     }
629 }