SqlitePlatform.php 14.7 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

22
use Doctrine\DBAL\DBALException;
23

24
/**
25 26
 * The SqlitePlatform class describes the specifics and dialects of the SQLite
 * 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
{
    /**
     * returns the regular expression operator
     *
     * @return string
     * @override
     */
    public function getRegexpExpression()
    {
        return 'RLIKE';
    }

    /**
     * Return string to call a variable with the current timestamp inside an SQL statement
     * There are three special variables for current date and time.
     *
     * @return string       sqlite function as string
     * @override
     */
    public function getNowExpression($type = 'timestamp')
    {
        switch ($type) {
            case 'time':
                return 'time(\'now\')';
            case 'date':
                return 'date(\'now\')';
            case 'timestamp':
            default:
                return 'datetime(\'now\')';
        }
    }

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    /**
     * Trim a string, leading/trailing/both and with a given char which defaults to space.
     *
     * @param string $str
     * @param int $pos
     * @param string $char
     * @return string
     */
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
    {
        $trimFn = '';
        $trimChar = ($char != false) ? (', ' . $char) : '';

        if ($pos == self::TRIM_LEADING) {
            $trimFn = 'LTRIM';
        } else if($pos == self::TRIM_TRAILING) {
            $trimFn = 'RTRIM';
        } else {
            $trimFn = 'TRIM';
        }

        return $trimFn . '(' . $str . $trimChar . ')';
    }

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    /**
     * return string to call a function to get a substring inside an SQL statement
     *
     * Note: Not SQL92, but common functionality.
     *
     * SQLite only supports the 2 parameter variant of this function
     *
     * @param string $value         an sql string literal or column name/alias
     * @param integer $position     where to start the substring portion
     * @param integer $length       the substring portion length
     * @return string               SQL substring function with given parameters
     * @override
     */
    public function getSubstringExpression($value, $position, $length = null)
    {
        if ($length !== null) {
            return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
        }
        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
    }

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    /**
     * returns the position of the first occurrence of substring $substr in string $str
     *
     * @param string $substr    literal string to find
     * @param string $str       literal string
     * @param int    $pos       position to start at, beginning of string by default
     * @return integer
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE('.$str.', '.$substr.')';
        } else {
            return 'LOCATE('.$str.', '.$substr.', '.$startPos.')';
        }
    }

128 129 130 131 132 133 134
    public function getDateDiffExpression($date1, $date2)
    {
        return 'ROUND(JULIANDAY('.$date1 . ')-JULIANDAY('.$date2.'))';
    }

    public function getDateAddDaysExpression($date, $days)
    {
Benjamin Eberlei's avatar
Benjamin Eberlei committed
135
        return "DATE(" . $date . ",'+". $days . " day')";
136 137 138 139
    }

    public function getDateSubDaysExpression($date, $days)
    {
140
        return "DATE(" . $date . ",'-". $days . " day')";
141 142 143 144
    }

    public function getDateAddMonthExpression($date, $months)
    {
145
        return "DATE(" . $date . ",'+". $months . " month')";
146 147 148 149
    }

    public function getDateSubMonthExpression($date, $months)
    {
150
        return "DATE(" . $date . ",'-". $months . " month')";
151 152
    }

153
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
154 155
    {
        switch ($level) {
156
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
romanb's avatar
romanb committed
157
                return 0;
158 159 160
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
            case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
            case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
romanb's avatar
romanb committed
161 162
                return 1;
            default:
163
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
164 165
        }
    }
166

167
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
168
    {
169
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
170
    }
171

172 173 174
    /** 
     * @override 
     */
175 176
    public function prefersIdentityColumns()
    {
177 178
        return true;
    }
179 180 181 182
    
    /** 
     * @override 
     */
183
    public function getBooleanTypeDeclarationSQL(array $field)
184 185 186
    {
        return 'BOOLEAN';
    }
187

188 189 190
    /** 
     * @override 
     */
191
    public function getIntegerTypeDeclarationSQL(array $field)
192
    {
193
        return $this->_getCommonIntegerTypeDeclarationSQL($field);
194 195
    }

196 197 198
    /** 
     * @override 
     */
199
    public function getBigIntTypeDeclarationSQL(array $field)
200
    {
201
        return $this->_getCommonIntegerTypeDeclarationSQL($field);
202 203
    }

204 205 206
    /** 
     * @override 
     */
207 208
    public function getTinyIntTypeDeclarationSql(array $field)
    {
209
        return $this->_getCommonIntegerTypeDeclarationSQL($field);
210 211
    }

212 213 214
    /** 
     * @override 
     */
215
    public function getSmallIntTypeDeclarationSQL(array $field)
216
    {
217
        return $this->_getCommonIntegerTypeDeclarationSQL($field);
218 219
    }

220 221 222
    /** 
     * @override 
     */
223 224
    public function getMediumIntTypeDeclarationSql(array $field)
    {
225
        return $this->_getCommonIntegerTypeDeclarationSQL($field);
226 227
    }

228 229 230
    /** 
     * @override 
     */
231
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
232 233 234
    {
        return 'DATETIME';
    }
235 236 237 238
    
    /**
     * @override
     */
239
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
240 241 242
    {
        return 'DATE';
    }
243

244 245 246
    /**
     * @override
     */
247
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
248 249 250 251
    {
        return 'TIME';
    }

252 253 254
    /** 
     * @override 
     */
255
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
256
    {
257 258
        $autoinc = ! empty($columnDef['autoincrement']) ? ' AUTOINCREMENT' : '';
        $pk = ! empty($columnDef['primary']) && ! empty($autoinc) ? ' PRIMARY KEY' : '';
259

260
        return 'INTEGER' . $pk . $autoinc;
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    }

    /**
     * create a new table
     *
     * @param string $name   Name of the database that should be created
     * @param array $fields  Associative array that contains the definition of each field of the new table
     *                       The indexes of the array entries are the names of the fields of the table an
     *                       the array entry values are associative arrays like those that are meant to be
     *                       passed with the field definitions to get[Type]Declaration() functions.
     *                          array(
     *                              'id' => array(
     *                                  'type' => 'integer',
     *                                  'unsigned' => 1
     *                                  'notnull' => 1
     *                                  'default' => 0
     *                              ),
     *                              'name' => array(
     *                                  'type' => 'text',
     *                                  'length' => 12
     *                              ),
     *                              'password' => array(
     *                                  'type' => 'text',
     *                                  'length' => 12
     *                              )
     *                          );
     * @param array $options  An associative array of table options:
     *
     * @return void
     * @override
     */
292
    protected function _getCreateTableSQL($name, array $columns, array $options = array())
293
    {
294
        $queryFields = $this->getColumnDeclarationListSQL($columns);
295 296

        $autoinc = false;
297
        foreach($columns as $field) {
298
            if (isset($field['autoincrement']) && $field['autoincrement']) {
299 300 301 302 303
                $autoinc = true;
                break;
            }
        }

304
        if ( ! $autoinc && isset($options['primary']) && ! empty($options['primary'])) {
305
            $keyColumns = array_unique(array_values($options['primary']));
romanb's avatar
romanb committed
306
            $keyColumns = array_map(array($this, 'quoteIdentifier'), $keyColumns);
307 308 309
            $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
        }

310
        $query[] = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
311 312

        if (isset($options['indexes']) && ! empty($options['indexes'])) {
313
            foreach ($options['indexes'] as $index => $indexDef) {
314
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
315 316 317 318
            }
        }
        if (isset($options['unique']) && ! empty($options['unique'])) {
            foreach ($options['unique'] as $index => $indexDef) {
319
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
320 321 322 323 324 325 326 327
            }
        }
        return $query;
    }

    /**
     * {@inheritdoc}
     */
328
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
329 330 331 332
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
                : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
    }
333
    
334
    public function getClobTypeDeclarationSQL(array $field)
335 336 337
    {
        return 'CLOB';
    }
338

339
    public function getListTableConstraintsSQL($table)
340
    {
341
        return "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = '$table' AND sql NOT NULL ORDER BY name";
342 343
    }

344
    public function getListTableColumnsSQL($table, $currentDatabase = null)
345 346 347 348
    {
        return "PRAGMA table_info($table)";
    }

349
    public function getListTableIndexesSQL($table, $currentDatabase = null)
350 351 352 353
    {
        return "PRAGMA index_list($table)";
    }

354
    public function getListTablesSQL()
355 356 357 358 359 360
    {
        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' "
             . "UNION ALL SELECT name FROM sqlite_temp_master "
             . "WHERE type = 'table' ORDER BY name";
    }

361
    public function getListViewsSQL($database)
362 363 364 365
    {
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
    }

366
    public function getCreateViewSQL($name, $sql)
367 368 369 370
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

371
    public function getDropViewSQL($name)
372 373 374 375
    {
        return 'DROP VIEW '. $name;
    }

376 377 378 379 380
    /**
     * SQLite does support foreign key constraints, but only in CREATE TABLE statements...
     * This really limits their usefulness and requires SQLite specific handling, so
     * we simply say that SQLite does NOT support foreign keys for now...
     *
381
     * @return boolean FALSE
382 383 384 385 386 387
     * @override
     */
    public function supportsForeignKeyConstraints()
    {
        return false;
    }
388

389 390 391 392 393
    public function supportsAlterTable()
    {
        return false;
    }

394 395 396 397 398
    public function supportsIdentityColumns()
    {
        return true;
    }

399 400 401 402 403 404 405 406 407
    /**
     * Get the platform name for this instance
     *
     * @return string
     */
    public function getName()
    {
        return 'sqlite';
    }
408 409 410 411

    /**
     * @inheritdoc
     */
412
    public function getTruncateTableSQL($tableName, $cascade = false)
413 414 415
    {
        return 'DELETE FROM '.$tableName;
    }
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

    /**
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction()
     *
     * @param  int|float $value
     * @return float
     */
    static public function udfSqrt($value)
    {
        return sqrt($value);
    }

    /**
     * User-defined function for Sqlite that implements MOD(a, b)
     */
    static public function udfMod($a, $b)
    {
        return ($a % $b);
    }
435 436 437 438 439 440 441 442 443 444 445 446 447 448

    /**
     * @param string $str
     * @param string $substr
     * @param int $offset
     */
    static public function udfLocate($str, $substr, $offset = 0)
    {
        $pos = strpos($str, $substr, $offset);
        if ($pos !== false) {
            return $pos+1;
        }
        return 0;
    }
449 450 451 452 453

    public function getForUpdateSql()
    {
        return '';
    }
454 455 456 457

    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
            'boolean'          => 'boolean',
            'tinyint'          => 'boolean',
            'smallint'         => 'smallint',
            'mediumint'        => 'integer',
            'int'              => 'integer',
            'integer'          => 'integer',
            'serial'           => 'integer',
            'bigint'           => 'bigint',
            'bigserial'        => 'bigint',
            'clob'             => 'text',
            'tinytext'         => 'text',
            'mediumtext'       => 'text',
            'longtext'         => 'text',
            'text'             => 'text',
            'varchar'          => 'string',
473
            'longvarchar'      => 'string',
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
            'varchar2'         => 'string',
            'nvarchar'         => 'string',
            'image'            => 'string',
            'ntext'            => 'string',
            'char'             => 'string',
            'date'             => 'date',
            'datetime'         => 'datetime',
            'timestamp'        => 'datetime',
            'time'             => 'time',
            'float'            => 'float',
            'double'           => 'float',
            'double precision' => 'float',
            'real'             => 'float',
            'decimal'          => 'decimal',
            'numeric'          => 'decimal',
489 490
        );
    }
491 492 493 494 495
    
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords';
    }
496
}