Rajout de doctrine/orm
[zf2.biz/galerie.git] / vendor / doctrine / dbal / lib / Doctrine / DBAL / Platforms / SqlitePlatform.php
1 <?php
2 /*
3  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14  *
15  * This software consists of voluntary contributions made by many individuals
16  * and is licensed under the MIT license. For more information, see
17  * <http://www.doctrine-project.org>.
18  */
19
20 namespace Doctrine\DBAL\Platforms;
21
22 use Doctrine\DBAL\DBALException;
23
24 /**
25  * The SqlitePlatform class describes the specifics and dialects of the SQLite
26  * database platform.
27  *
28  * @since 2.0
29  * @author Roman Borschel <roman@code-factory.org>
30  * @author Benjamin Eberlei <kontakt@beberlei.de>
31  * @todo Rename: SQLitePlatform
32  */
33 class SqlitePlatform extends AbstractPlatform
34 {
35     /**
36      * {@inheritDoc}
37      */
38     public function getRegexpExpression()
39     {
40         return 'RLIKE';
41     }
42
43     /**
44      * {@inheritDoc}
45      */
46     public function getNowExpression($type = 'timestamp')
47     {
48         switch ($type) {
49             case 'time':
50                 return 'time(\'now\')';
51             case 'date':
52                 return 'date(\'now\')';
53             case 'timestamp':
54             default:
55                 return 'datetime(\'now\')';
56         }
57     }
58
59     /**
60      * {@inheritDoc}
61      */
62     public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
63     {
64         $trimChar = ($char != false) ? (', ' . $char) : '';
65
66         switch ($pos) {
67             case self::TRIM_LEADING:
68                 $trimFn = 'LTRIM';
69                 break;
70
71             case self::TRIM_TRAILING:
72                 $trimFn = 'RTRIM';
73                 break;
74
75             default:
76                 $trimFn = 'TRIM';
77         }
78
79         return $trimFn . '(' . $str . $trimChar . ')';
80     }
81
82     /**
83      * {@inheritDoc}
84      *
85      * SQLite only supports the 2 parameter variant of this function
86      */
87     public function getSubstringExpression($value, $position, $length = null)
88     {
89         if ($length !== null) {
90             return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
91         }
92
93         return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
94     }
95
96     /**
97      * {@inheritDoc}
98      */
99     public function getLocateExpression($str, $substr, $startPos = false)
100     {
101         if ($startPos == false) {
102             return 'LOCATE('.$str.', '.$substr.')';
103         }
104
105         return 'LOCATE('.$str.', '.$substr.', '.$startPos.')';
106     }
107
108     /**
109      * {@inheritDoc}
110      */
111     public function getDateDiffExpression($date1, $date2)
112     {
113         return 'ROUND(JULIANDAY('.$date1 . ')-JULIANDAY('.$date2.'))';
114     }
115
116     /**
117      * {@inheritDoc}
118      */
119     public function getDateAddDaysExpression($date, $days)
120     {
121         return "DATE(" . $date . ",'+". $days . " day')";
122     }
123
124     /**
125      * {@inheritDoc}
126      */
127     public function getDateSubDaysExpression($date, $days)
128     {
129         return "DATE(" . $date . ",'-". $days . " day')";
130     }
131
132     /**
133      * {@inheritDoc}
134      */
135     public function getDateAddMonthExpression($date, $months)
136     {
137         return "DATE(" . $date . ",'+". $months . " month')";
138     }
139
140     /**
141      * {@inheritDoc}
142      */
143     public function getDateSubMonthExpression($date, $months)
144     {
145         return "DATE(" . $date . ",'-". $months . " month')";
146     }
147
148     /**
149      * {@inheritDoc}
150      */
151     protected function _getTransactionIsolationLevelSQL($level)
152     {
153         switch ($level) {
154             case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
155                 return 0;
156             case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
157             case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
158             case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
159                 return 1;
160             default:
161                 return parent::_getTransactionIsolationLevelSQL($level);
162         }
163     }
164
165     /**
166      * {@inheritDoc}
167      */
168     public function getSetTransactionIsolationSQL($level)
169     {
170         return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
171     }
172
173     /**
174      * {@inheritDoc}
175      */
176     public function prefersIdentityColumns()
177     {
178         return true;
179     }
180
181     /**
182      * {@inheritDoc}
183      */
184     public function getBooleanTypeDeclarationSQL(array $field)
185     {
186         return 'BOOLEAN';
187     }
188
189     /**
190      * {@inheritDoc}
191      */
192     public function getIntegerTypeDeclarationSQL(array $field)
193     {
194         return $this->_getCommonIntegerTypeDeclarationSQL($field);
195     }
196
197     /**
198      * {@inheritDoc}
199      */
200     public function getBigIntTypeDeclarationSQL(array $field)
201     {
202         return $this->_getCommonIntegerTypeDeclarationSQL($field);
203     }
204
205     /**
206      * {@inheritDoc}
207      */
208     public function getTinyIntTypeDeclarationSql(array $field)
209     {
210         return $this->_getCommonIntegerTypeDeclarationSQL($field);
211     }
212
213     /**
214      * {@inheritDoc}
215      */
216     public function getSmallIntTypeDeclarationSQL(array $field)
217     {
218         return $this->_getCommonIntegerTypeDeclarationSQL($field);
219     }
220
221     /**
222      * {@inheritDoc}
223      */
224     public function getMediumIntTypeDeclarationSql(array $field)
225     {
226         return $this->_getCommonIntegerTypeDeclarationSQL($field);
227     }
228
229     /**
230      * {@inheritDoc}
231      */
232     public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
233     {
234         return 'DATETIME';
235     }
236
237     /**
238      * {@inheritDoc}
239      */
240     public function getDateTypeDeclarationSQL(array $fieldDeclaration)
241     {
242         return 'DATE';
243     }
244
245     /**
246      * {@inheritDoc}
247      */
248     public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
249     {
250         return 'TIME';
251     }
252
253     /**
254      * {@inheritDoc}
255      */
256     protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
257     {
258         return 'INTEGER';
259     }
260
261     /**
262      * {@inheritDoc}
263      */
264     protected function _getCreateTableSQL($name, array $columns, array $options = array())
265     {
266         $name = str_replace(".", "__", $name);
267         $queryFields = $this->getColumnDeclarationListSQL($columns);
268
269         if (isset($options['primary']) && ! empty($options['primary'])) {
270             $keyColumns = array_unique(array_values($options['primary']));
271             $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
272         }
273
274         $query[] = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
275
276         if (isset($options['indexes']) && ! empty($options['indexes'])) {
277             foreach ($options['indexes'] as $index => $indexDef) {
278                 $query[] = $this->getCreateIndexSQL($indexDef, $name);
279             }
280         }
281
282         if (isset($options['unique']) && ! empty($options['unique'])) {
283             foreach ($options['unique'] as $index => $indexDef) {
284                 $query[] = $this->getCreateIndexSQL($indexDef, $name);
285             }
286         }
287
288         return $query;
289     }
290
291     /**
292      * {@inheritDoc}
293      */
294     protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
295     {
296         return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
297                 : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
298     }
299
300     /**
301      * {@inheritDoc}
302      */
303     public function getClobTypeDeclarationSQL(array $field)
304     {
305         return 'CLOB';
306     }
307
308     public function getListTableConstraintsSQL($table)
309     {
310         $table = str_replace(".", "__", $table);
311
312         return "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = '$table' AND sql NOT NULL ORDER BY name";
313     }
314
315     public function getListTableColumnsSQL($table, $currentDatabase = null)
316     {
317         $table = str_replace(".", "__", $table);
318
319         return "PRAGMA table_info($table)";
320     }
321
322     /**
323      * {@inheritDoc}
324      */
325     public function getListTableIndexesSQL($table, $currentDatabase = null)
326     {
327         $table = str_replace(".", "__", $table);
328
329         return "PRAGMA index_list($table)";
330     }
331
332     public function getListTablesSQL()
333     {
334         return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
335              . "UNION ALL SELECT name FROM sqlite_temp_master "
336              . "WHERE type = 'table' ORDER BY name";
337     }
338
339     /**
340      * {@inheritDoc}
341      */
342     public function getListViewsSQL($database)
343     {
344         return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
345     }
346
347     public function getCreateViewSQL($name, $sql)
348     {
349         return 'CREATE VIEW ' . $name . ' AS ' . $sql;
350     }
351
352     public function getDropViewSQL($name)
353     {
354         return 'DROP VIEW '. $name;
355     }
356
357     /**
358      * {@inheritDoc}
359      *
360      * SQLite does support foreign key constraints, but only in CREATE TABLE statements...
361      * This really limits their usefulness and requires SQLite specific handling, so
362      * we simply say that SQLite does NOT support foreign keys for now...
363      */
364     public function supportsForeignKeyConstraints()
365     {
366         return false;
367     }
368
369     /**
370      * {@inheritDoc}
371      */
372     public function supportsAlterTable()
373     {
374         return false;
375     }
376
377     /**
378      * {@inheritDoc}
379      */
380     public function supportsIdentityColumns()
381     {
382         return true;
383     }
384
385     /**
386      * {@inheritDoc}
387      */
388     public function getName()
389     {
390         return 'sqlite';
391     }
392
393     /**
394      * {@inheritDoc}
395      */
396     public function getTruncateTableSQL($tableName, $cascade = false)
397     {
398         $tableName = str_replace(".", "__", $tableName);
399         return 'DELETE FROM '.$tableName;
400     }
401
402     /**
403      * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction()
404      *
405      * @param  int|float $value
406      *
407      * @return float
408      */
409     static public function udfSqrt($value)
410     {
411         return sqrt($value);
412     }
413
414     /**
415      * User-defined function for Sqlite that implements MOD(a, b)
416      *
417      * @param integer $a
418      * @param integer $b
419      *
420      * @return integer
421      */
422     static public function udfMod($a, $b)
423     {
424         return ($a % $b);
425     }
426
427     /**
428      * @param string $str
429      * @param string $substr
430      * @param integer $offset
431      *
432      * @return integer
433      */
434     static public function udfLocate($str, $substr, $offset = 0)
435     {
436         $pos = strpos($str, $substr, $offset);
437         if ($pos !== false) {
438             return $pos+1;
439         }
440
441         return 0;
442     }
443
444     public function getForUpdateSql()
445     {
446         return '';
447     }
448
449     /**
450      * {@inheritDoc}
451      */
452     protected function initializeDoctrineTypeMappings()
453     {
454         $this->doctrineTypeMapping = array(
455             'boolean'          => 'boolean',
456             'tinyint'          => 'boolean',
457             'smallint'         => 'smallint',
458             'mediumint'        => 'integer',
459             'int'              => 'integer',
460             'integer'          => 'integer',
461             'serial'           => 'integer',
462             'bigint'           => 'bigint',
463             'bigserial'        => 'bigint',
464             'clob'             => 'text',
465             'tinytext'         => 'text',
466             'mediumtext'       => 'text',
467             'longtext'         => 'text',
468             'text'             => 'text',
469             'varchar'          => 'string',
470             'longvarchar'      => 'string',
471             'varchar2'         => 'string',
472             'nvarchar'         => 'string',
473             'image'            => 'string',
474             'ntext'            => 'string',
475             'char'             => 'string',
476             'date'             => 'date',
477             'datetime'         => 'datetime',
478             'timestamp'        => 'datetime',
479             'time'             => 'time',
480             'float'            => 'float',
481             'double'           => 'float',
482             'double precision' => 'float',
483             'real'             => 'float',
484             'decimal'          => 'decimal',
485             'numeric'          => 'decimal',
486             'blob'             => 'blob',
487         );
488     }
489
490     /**
491      * {@inheritDoc}
492      */
493     protected function getReservedKeywordsClass()
494     {
495         return 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords';
496     }
497
498     /**
499      * {@inheritDoc}
500      */
501     public function getBlobTypeDeclarationSQL(array $field)
502     {
503         return 'BLOB';
504     }
505
506     /**
507      * {@inheritDoc}
508      */
509     public function getTemporaryTableName($tableName)
510     {
511         $tableName = str_replace(".", "__", $tableName);
512
513         return $tableName;
514     }
515
516     /**
517      * {@inheritDoc}
518      *
519      * Sqlite Platform emulates schema by underscoring each dot and generating tables
520      * into the default database.
521      *
522      * This hack is implemented to be able to use SQLite as testdriver when
523      * using schema supporting databases.
524      */
525     public function canEmulateSchemas()
526     {
527         return true;
528     }
529 }