source: pro-violet-viettel/sourcecode/application/libraries/Doctrine/DBAL/Platforms/SqlitePlatform.php @ 345

Last change on this file since 345 was 345, checked in by quyenla, 11 years ago

collaborator page

File size: 15.3 KB
Line 
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 LGPL. For more information, see
17 * <http://www.doctrine-project.org>.
18 */
19
20namespace Doctrine\DBAL\Platforms;
21
22use 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 */
33class SqlitePlatform extends AbstractPlatform
34{
35    /**
36     * returns the regular expression operator
37     *
38     * @return string
39     * @override
40     */
41    public function getRegexpExpression()
42    {
43        return 'RLIKE';
44    }
45
46    /**
47     * Return string to call a variable with the current timestamp inside an SQL statement
48     * There are three special variables for current date and time.
49     *
50     * @return string       sqlite function as string
51     * @override
52     */
53    public function getNowExpression($type = 'timestamp')
54    {
55        switch ($type) {
56            case 'time':
57                return 'time(\'now\')';
58            case 'date':
59                return 'date(\'now\')';
60            case 'timestamp':
61            default:
62                return 'datetime(\'now\')';
63        }
64    }
65
66    /**
67     * Trim a string, leading/trailing/both and with a given char which defaults to space.
68     *
69     * @param string $str
70     * @param int $pos
71     * @param string $char
72     * @return string
73     */
74    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
75    {
76        $trimFn = '';
77        $trimChar = ($char != false) ? (', ' . $char) : '';
78
79        if ($pos == self::TRIM_LEADING) {
80            $trimFn = 'LTRIM';
81        } else if($pos == self::TRIM_TRAILING) {
82            $trimFn = 'RTRIM';
83        } else {
84            $trimFn = 'TRIM';
85        }
86
87        return $trimFn . '(' . $str . $trimChar . ')';
88    }
89
90    /**
91     * return string to call a function to get a substring inside an SQL statement
92     *
93     * Note: Not SQL92, but common functionality.
94     *
95     * SQLite only supports the 2 parameter variant of this function
96     *
97     * @param string $value         an sql string literal or column name/alias
98     * @param integer $position     where to start the substring portion
99     * @param integer $length       the substring portion length
100     * @return string               SQL substring function with given parameters
101     * @override
102     */
103    public function getSubstringExpression($value, $position, $length = null)
104    {
105        if ($length !== null) {
106            return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
107        }
108        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
109    }
110
111    /**
112     * returns the position of the first occurrence of substring $substr in string $str
113     *
114     * @param string $substr    literal string to find
115     * @param string $str       literal string
116     * @param int    $pos       position to start at, beginning of string by default
117     * @return integer
118     */
119    public function getLocateExpression($str, $substr, $startPos = false)
120    {
121        if ($startPos == false) {
122            return 'LOCATE('.$str.', '.$substr.')';
123        } else {
124            return 'LOCATE('.$str.', '.$substr.', '.$startPos.')';
125        }
126    }
127
128    public function getDateDiffExpression($date1, $date2)
129    {
130        return 'ROUND(JULIANDAY('.$date1 . ')-JULIANDAY('.$date2.'))';
131    }
132
133    public function getDateAddDaysExpression($date, $days)
134    {
135        return "DATE(" . $date . ",'+". $days . " day')";
136    }
137
138    public function getDateSubDaysExpression($date, $days)
139    {
140        return "DATE(" . $date . ",'-". $days . " day')";
141    }
142
143    public function getDateAddMonthExpression($date, $months)
144    {
145        return "DATE(" . $date . ",'+". $months . " month')";
146    }
147
148    public function getDateSubMonthExpression($date, $months)
149    {
150        return "DATE(" . $date . ",'-". $months . " month')";
151    }
152
153    protected function _getTransactionIsolationLevelSQL($level)
154    {
155        switch ($level) {
156            case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
157                return 0;
158            case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
159            case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
160            case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
161                return 1;
162            default:
163                return parent::_getTransactionIsolationLevelSQL($level);
164        }
165    }
166
167    public function getSetTransactionIsolationSQL($level)
168    {
169        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
170    }
171
172    /**
173     * @override
174     */
175    public function prefersIdentityColumns()
176    {
177        return true;
178    }
179
180    /**
181     * @override
182     */
183    public function getBooleanTypeDeclarationSQL(array $field)
184    {
185        return 'BOOLEAN';
186    }
187
188    /**
189     * @override
190     */
191    public function getIntegerTypeDeclarationSQL(array $field)
192    {
193        return $this->_getCommonIntegerTypeDeclarationSQL($field);
194    }
195
196    /**
197     * @override
198     */
199    public function getBigIntTypeDeclarationSQL(array $field)
200    {
201        return $this->_getCommonIntegerTypeDeclarationSQL($field);
202    }
203
204    /**
205     * @override
206     */
207    public function getTinyIntTypeDeclarationSql(array $field)
208    {
209        return $this->_getCommonIntegerTypeDeclarationSQL($field);
210    }
211
212    /**
213     * @override
214     */
215    public function getSmallIntTypeDeclarationSQL(array $field)
216    {
217        return $this->_getCommonIntegerTypeDeclarationSQL($field);
218    }
219
220    /**
221     * @override
222     */
223    public function getMediumIntTypeDeclarationSql(array $field)
224    {
225        return $this->_getCommonIntegerTypeDeclarationSQL($field);
226    }
227
228    /**
229     * @override
230     */
231    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
232    {
233        return 'DATETIME';
234    }
235
236    /**
237     * @override
238     */
239    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
240    {
241        return 'DATE';
242    }
243
244    /**
245     * @override
246     */
247    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
248    {
249        return 'TIME';
250    }
251
252    /**
253     * @override
254     */
255    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
256    {
257        return 'INTEGER';
258    }
259
260    /**
261     * create a new table
262     *
263     * @param string $name   Name of the database that should be created
264     * @param array $fields  Associative array that contains the definition of each field of the new table
265     *                       The indexes of the array entries are the names of the fields of the table an
266     *                       the array entry values are associative arrays like those that are meant to be
267     *                       passed with the field definitions to get[Type]Declaration() functions.
268     *                          array(
269     *                              'id' => array(
270     *                                  'type' => 'integer',
271     *                                  'unsigned' => 1
272     *                                  'notnull' => 1
273     *                                  'default' => 0
274     *                              ),
275     *                              'name' => array(
276     *                                  'type' => 'text',
277     *                                  'length' => 12
278     *                              ),
279     *                              'password' => array(
280     *                                  'type' => 'text',
281     *                                  'length' => 12
282     *                              )
283     *                          );
284     * @param array $options  An associative array of table options:
285     *
286     * @return void
287     * @override
288     */
289    protected function _getCreateTableSQL($name, array $columns, array $options = array())
290    {
291        $name = str_replace(".", "__", $name);
292        $queryFields = $this->getColumnDeclarationListSQL($columns);
293
294        if (isset($options['primary']) && ! empty($options['primary'])) {
295            $keyColumns = array_unique(array_values($options['primary']));
296            $keyColumns = array_map(array($this, 'quoteIdentifier'), $keyColumns);
297            $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
298        }
299
300        $query[] = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
301
302        if (isset($options['indexes']) && ! empty($options['indexes'])) {
303            foreach ($options['indexes'] as $index => $indexDef) {
304                $query[] = $this->getCreateIndexSQL($indexDef, $name);
305            }
306        }
307        if (isset($options['unique']) && ! empty($options['unique'])) {
308            foreach ($options['unique'] as $index => $indexDef) {
309                $query[] = $this->getCreateIndexSQL($indexDef, $name);
310            }
311        }
312        return $query;
313    }
314
315    /**
316     * {@inheritdoc}
317     */
318    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
319    {
320        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
321                : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
322    }
323
324    public function getClobTypeDeclarationSQL(array $field)
325    {
326        return 'CLOB';
327    }
328
329    public function getListTableConstraintsSQL($table)
330    {
331        $table = str_replace(".", "__", $table);
332        return "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = '$table' AND sql NOT NULL ORDER BY name";
333    }
334
335    public function getListTableColumnsSQL($table, $currentDatabase = null)
336    {
337        $table = str_replace(".", "__", $table);
338        return "PRAGMA table_info($table)";
339    }
340
341    public function getListTableIndexesSQL($table, $currentDatabase = null)
342    {
343        $table = str_replace(".", "__", $table);
344        return "PRAGMA index_list($table)";
345    }
346
347    public function getListTablesSQL()
348    {
349        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
350             . "UNION ALL SELECT name FROM sqlite_temp_master "
351             . "WHERE type = 'table' ORDER BY name";
352    }
353
354    public function getListViewsSQL($database)
355    {
356        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
357    }
358
359    public function getCreateViewSQL($name, $sql)
360    {
361        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
362    }
363
364    public function getDropViewSQL($name)
365    {
366        return 'DROP VIEW '. $name;
367    }
368
369    /**
370     * SQLite does support foreign key constraints, but only in CREATE TABLE statements...
371     * This really limits their usefulness and requires SQLite specific handling, so
372     * we simply say that SQLite does NOT support foreign keys for now...
373     *
374     * @return boolean FALSE
375     * @override
376     */
377    public function supportsForeignKeyConstraints()
378    {
379        return false;
380    }
381
382    public function supportsAlterTable()
383    {
384        return false;
385    }
386
387    public function supportsIdentityColumns()
388    {
389        return true;
390    }
391
392    /**
393     * Get the platform name for this instance
394     *
395     * @return string
396     */
397    public function getName()
398    {
399        return 'sqlite';
400    }
401
402    /**
403     * @inheritdoc
404     */
405    public function getTruncateTableSQL($tableName, $cascade = false)
406    {
407        $tableName = str_replace(".", "__", $tableName);
408        return 'DELETE FROM '.$tableName;
409    }
410
411    /**
412     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction()
413     *
414     * @param  int|float $value
415     * @return float
416     */
417    static public function udfSqrt($value)
418    {
419        return sqrt($value);
420    }
421
422    /**
423     * User-defined function for Sqlite that implements MOD(a, b)
424     */
425    static public function udfMod($a, $b)
426    {
427        return ($a % $b);
428    }
429
430    /**
431     * @param string $str
432     * @param string $substr
433     * @param int $offset
434     */
435    static public function udfLocate($str, $substr, $offset = 0)
436    {
437        $pos = strpos($str, $substr, $offset);
438        if ($pos !== false) {
439            return $pos+1;
440        }
441        return 0;
442    }
443
444    public function getForUpdateSql()
445    {
446        return '';
447    }
448
449    protected function initializeDoctrineTypeMappings()
450    {
451        $this->doctrineTypeMapping = array(
452            'boolean'          => 'boolean',
453            'tinyint'          => 'boolean',
454            'smallint'         => 'smallint',
455            'mediumint'        => 'integer',
456            'int'              => 'integer',
457            'integer'          => 'integer',
458            'serial'           => 'integer',
459            'bigint'           => 'bigint',
460            'bigserial'        => 'bigint',
461            'clob'             => 'text',
462            'tinytext'         => 'text',
463            'mediumtext'       => 'text',
464            'longtext'         => 'text',
465            'text'             => 'text',
466            'varchar'          => 'string',
467            'longvarchar'      => 'string',
468            'varchar2'         => 'string',
469            'nvarchar'         => 'string',
470            'image'            => 'string',
471            'ntext'            => 'string',
472            'char'             => 'string',
473            'date'             => 'date',
474            'datetime'         => 'datetime',
475            'timestamp'        => 'datetime',
476            'time'             => 'time',
477            'float'            => 'float',
478            'double'           => 'float',
479            'double precision' => 'float',
480            'real'             => 'float',
481            'decimal'          => 'decimal',
482            'numeric'          => 'decimal',
483            'blob'             => 'blob',
484        );
485    }
486
487    protected function getReservedKeywordsClass()
488    {
489        return 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords';
490    }
491
492    /**
493     * Gets the SQL Snippet used to declare a BLOB column type.
494     */
495    public function getBlobTypeDeclarationSQL(array $field)
496    {
497        return 'BLOB';
498    }
499
500    public function getTemporaryTableName($tableName)
501    {
502        $tableName = str_replace(".", "__", $tableName);
503        return $tableName;
504    }
505
506    /**
507     * Sqlite Platform emulates schema by underscoring each dot and generating tables
508     * into the default database.
509     *
510     * This hack is implemented to be able to use SQLite as testdriver when
511     * using schema supporting databases.
512     *
513     * @return bool
514     */
515    public function canEmulateSchemas()
516    {
517        return true;
518    }
519}
Note: See TracBrowser for help on using the repository browser.