CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.9 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.9
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • Mysql
  • Postgres
  • Sqlite
  • Sqlserver
  1: <?php
  2: /**
  3:  * SQLite layer for DBO
  4:  *
  5:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7:  *
  8:  * Licensed under The MIT License
  9:  * For full copyright and license information, please see the LICENSE.txt
 10:  * Redistributions of files must retain the above copyright notice.
 11:  *
 12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 13:  * @link          http://cakephp.org CakePHP(tm) Project
 14:  * @package       Cake.Model.Datasource.Database
 15:  * @since         CakePHP(tm) v 0.9.0
 16:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 17:  */
 18: 
 19: App::uses('DboSource', 'Model/Datasource');
 20: App::uses('CakeText', 'Utility');
 21: 
 22: /**
 23:  * DBO implementation for the SQLite3 DBMS.
 24:  *
 25:  * A DboSource adapter for SQLite 3 using PDO
 26:  *
 27:  * @package       Cake.Model.Datasource.Database
 28:  */
 29: class Sqlite extends DboSource {
 30: 
 31: /**
 32:  * Datasource Description
 33:  *
 34:  * @var string
 35:  */
 36:     public $description = "SQLite DBO Driver";
 37: 
 38: /**
 39:  * Quote Start
 40:  *
 41:  * @var string
 42:  */
 43:     public $startQuote = '"';
 44: 
 45: /**
 46:  * Quote End
 47:  *
 48:  * @var string
 49:  */
 50:     public $endQuote = '"';
 51: 
 52: /**
 53:  * Base configuration settings for SQLite3 driver
 54:  *
 55:  * @var array
 56:  */
 57:     protected $_baseConfig = array(
 58:         'persistent' => false,
 59:         'database' => null,
 60:         'flags' => array()
 61:     );
 62: 
 63: /**
 64:  * SQLite3 column definition
 65:  *
 66:  * @var array
 67:  */
 68:     public $columns = array(
 69:         'primary_key' => array('name' => 'integer primary key autoincrement'),
 70:         'string' => array('name' => 'varchar', 'limit' => '255'),
 71:         'text' => array('name' => 'text'),
 72:         'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
 73:         'biginteger' => array('name' => 'bigint', 'limit' => 20),
 74:         'float' => array('name' => 'float', 'formatter' => 'floatval'),
 75:         'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
 76:         'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
 77:         'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
 78:         'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
 79:         'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
 80:         'binary' => array('name' => 'blob'),
 81:         'boolean' => array('name' => 'boolean')
 82:     );
 83: 
 84: /**
 85:  * List of engine specific additional field parameters used on table creating
 86:  *
 87:  * @var array
 88:  */
 89:     public $fieldParameters = array(
 90:         'collate' => array(
 91:             'value' => 'COLLATE',
 92:             'quote' => false,
 93:             'join' => ' ',
 94:             'column' => 'Collate',
 95:             'position' => 'afterDefault',
 96:             'options' => array(
 97:                 'BINARY', 'NOCASE', 'RTRIM'
 98:             )
 99:         ),
100:     );
101: 
102: /**
103:  * Connects to the database using config['database'] as a filename.
104:  *
105:  * @return bool
106:  * @throws MissingConnectionException
107:  */
108:     public function connect() {
109:         $config = $this->config;
110:         $flags = $config['flags'] + array(
111:             PDO::ATTR_PERSISTENT => $config['persistent'],
112:             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
113:         );
114:         try {
115:             $this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags);
116:             $this->connected = true;
117:         } catch(PDOException $e) {
118:             throw new MissingConnectionException(array(
119:                 'class' => get_class($this),
120:                 'message' => $e->getMessage()
121:             ));
122:         }
123:         return $this->connected;
124:     }
125: 
126: /**
127:  * Check whether the SQLite extension is installed/loaded
128:  *
129:  * @return bool
130:  */
131:     public function enabled() {
132:         return in_array('sqlite', PDO::getAvailableDrivers());
133:     }
134: 
135: /**
136:  * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
137:  *
138:  * @param mixed $data Unused.
139:  * @return array Array of table names in the database
140:  */
141:     public function listSources($data = null) {
142:         $cache = parent::listSources();
143:         if ($cache) {
144:             return $cache;
145:         }
146: 
147:         $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
148: 
149:         if (!$result || empty($result)) {
150:             return array();
151:         }
152: 
153:         $tables = array();
154:         foreach ($result as $table) {
155:             $tables[] = $table[0]['name'];
156:         }
157:         parent::listSources($tables);
158:         return $tables;
159:     }
160: 
161: /**
162:  * Returns an array of the fields in given table name.
163:  *
164:  * @param Model|string $model Either the model or table name you want described.
165:  * @return array Fields in table. Keys are name and type
166:  */
167:     public function describe($model) {
168:         $table = $this->fullTableName($model, false, false);
169:         $cache = parent::describe($table);
170:         if ($cache) {
171:             return $cache;
172:         }
173:         $fields = array();
174:         $result = $this->_execute(
175:             'PRAGMA table_info(' . $this->value($table, 'string') . ')'
176:         );
177: 
178:         foreach ($result as $column) {
179:             $column = (array)$column;
180:             $default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
181: 
182:             $fields[$column['name']] = array(
183:                 'type' => $this->column($column['type']),
184:                 'null' => !$column['notnull'],
185:                 'default' => $default,
186:                 'length' => $this->length($column['type'])
187:             );
188:             if (in_array($fields[$column['name']]['type'], array('timestamp', 'datetime')) && strtoupper($fields[$column['name']]['default']) === 'CURRENT_TIMESTAMP') {
189:                 $fields[$column['name']]['default'] = null;
190:             }
191:             if ($column['pk'] == 1) {
192:                 $fields[$column['name']]['key'] = $this->index['PRI'];
193:                 $fields[$column['name']]['null'] = false;
194:                 if (empty($fields[$column['name']]['length'])) {
195:                     $fields[$column['name']]['length'] = 11;
196:                 }
197:             }
198:         }
199: 
200:         $result->closeCursor();
201:         $this->_cacheDescription($table, $fields);
202:         return $fields;
203:     }
204: 
205: /**
206:  * Generates and executes an SQL UPDATE statement for given model, fields, and values.
207:  *
208:  * @param Model $model The model instance to update.
209:  * @param array $fields The fields to update.
210:  * @param array $values The values to set columns to.
211:  * @param mixed $conditions array of conditions to use.
212:  * @return array
213:  */
214:     public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
215:         if (empty($values) && !empty($fields)) {
216:             foreach ($fields as $field => $value) {
217:                 if (strpos($field, $model->alias . '.') !== false) {
218:                     unset($fields[$field]);
219:                     $field = str_replace($model->alias . '.', "", $field);
220:                     $field = str_replace($model->alias . '.', "", $field);
221:                     $fields[$field] = $value;
222:                 }
223:             }
224:         }
225:         return parent::update($model, $fields, $values, $conditions);
226:     }
227: 
228: /**
229:  * Deletes all the records in a table and resets the count of the auto-incrementing
230:  * primary key, where applicable.
231:  *
232:  * @param string|Model $table A string or model class representing the table to be truncated
233:  * @return bool SQL TRUNCATE TABLE statement, false if not applicable.
234:  */
235:     public function truncate($table) {
236:         if (in_array('sqlite_sequence', $this->listSources())) {
237:             $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
238:         }
239:         return $this->execute('DELETE FROM ' . $this->fullTableName($table));
240:     }
241: 
242: /**
243:  * Converts database-layer column types to basic types
244:  *
245:  * @param string $real Real database-layer column type (i.e. "varchar(255)")
246:  * @return string Abstract column type (i.e. "string")
247:  */
248:     public function column($real) {
249:         if (is_array($real)) {
250:             $col = $real['name'];
251:             if (isset($real['limit'])) {
252:                 $col .= '(' . $real['limit'] . ')';
253:             }
254:             return $col;
255:         }
256: 
257:         $col = strtolower(str_replace(')', '', $real));
258:         if (strpos($col, '(') !== false) {
259:             list($col) = explode('(', $col);
260:         }
261: 
262:         $standard = array(
263:             'text',
264:             'integer',
265:             'float',
266:             'boolean',
267:             'timestamp',
268:             'date',
269:             'datetime',
270:             'time'
271:         );
272:         if (in_array($col, $standard)) {
273:             return $col;
274:         }
275:         if ($col === 'bigint') {
276:             return 'biginteger';
277:         }
278:         if (strpos($col, 'char') !== false) {
279:             return 'string';
280:         }
281:         if (in_array($col, array('blob', 'clob'))) {
282:             return 'binary';
283:         }
284:         if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
285:             return 'decimal';
286:         }
287:         return 'text';
288:     }
289: 
290: /**
291:  * Generate ResultSet
292:  *
293:  * @param mixed $results The results to modify.
294:  * @return void
295:  */
296:     public function resultSet($results) {
297:         $this->results = $results;
298:         $this->map = array();
299:         $numFields = $results->columnCount();
300:         $index = 0;
301:         $j = 0;
302: 
303:         // PDO::getColumnMeta is experimental and does not work with sqlite3,
304:         // so try to figure it out based on the querystring
305:         $querystring = $results->queryString;
306:         if (stripos($querystring, 'SELECT') === 0 && stripos($querystring, 'FROM') > 0) {
307:             $selectpart = substr($querystring, 7);
308:             $selects = array();
309:             foreach (CakeText::tokenize($selectpart, ',', '(', ')') as $part) {
310:                 $fromPos = stripos($part, ' FROM ');
311:                 if ($fromPos !== false) {
312:                     $selects[] = trim(substr($part, 0, $fromPos));
313:                     break;
314:                 }
315:                 $selects[] = $part;
316:             }
317:         } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
318:             $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
319:         } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
320:             $selects = array('seq', 'name', 'unique');
321:         } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
322:             $selects = array('seqno', 'cid', 'name');
323:         }
324:         while ($j < $numFields) {
325:             if (!isset($selects[$j])) {
326:                 $j++;
327:                 continue;
328:             }
329:             if (preg_match('/\bAS(?!.*\bAS\b)\s+(.*)/i', $selects[$j], $matches)) {
330:                 $columnName = trim($matches[1], '"');
331:             } else {
332:                 $columnName = trim(str_replace('"', '', $selects[$j]));
333:             }
334: 
335:             if (strpos($selects[$j], 'DISTINCT') === 0) {
336:                 $columnName = str_ireplace('DISTINCT', '', $columnName);
337:             }
338: 
339:             $metaType = false;
340:             try {
341:                 $metaData = (array)$results->getColumnMeta($j);
342:                 if (!empty($metaData['sqlite:decl_type'])) {
343:                     $metaType = trim($metaData['sqlite:decl_type']);
344:                 }
345:             } catch (Exception $e) {
346:             }
347: 
348:             if (strpos($columnName, '.')) {
349:                 $parts = explode('.', $columnName);
350:                 $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
351:             } else {
352:                 $this->map[$index++] = array(0, $columnName, $metaType);
353:             }
354:             $j++;
355:         }
356:     }
357: 
358: /**
359:  * Fetches the next row from the current result set
360:  *
361:  * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
362:  */
363:     public function fetchResult() {
364:         if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
365:             $resultRow = array();
366:             foreach ($this->map as $col => $meta) {
367:                 list($table, $column, $type) = $meta;
368:                 $resultRow[$table][$column] = $row[$col];
369:                 if ($type === 'boolean' && $row[$col] !== null) {
370:                     $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
371:                 }
372:             }
373:             return $resultRow;
374:         }
375:         $this->_result->closeCursor();
376:         return false;
377:     }
378: 
379: /**
380:  * Returns a limit statement in the correct format for the particular database.
381:  *
382:  * @param int $limit Limit of results returned
383:  * @param int $offset Offset from which to start results
384:  * @return string SQL limit/offset statement
385:  */
386:     public function limit($limit, $offset = null) {
387:         if ($limit) {
388:             $rt = sprintf(' LIMIT %u', $limit);
389:             if ($offset) {
390:                 $rt .= sprintf(' OFFSET %u', $offset);
391:             }
392:             return $rt;
393:         }
394:         return null;
395:     }
396: 
397: /**
398:  * Generate a database-native column schema string
399:  *
400:  * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
401:  *    where options can be 'default', 'length', or 'key'.
402:  * @return string
403:  */
404:     public function buildColumn($column) {
405:         $name = $type = null;
406:         $column += array('null' => true);
407:         extract($column);
408: 
409:         if (empty($name) || empty($type)) {
410:             trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
411:             return null;
412:         }
413: 
414:         if (!isset($this->columns[$type])) {
415:             trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
416:             return null;
417:         }
418: 
419:         $isPrimary = (isset($column['key']) && $column['key'] === 'primary');
420:         if ($isPrimary && $type === 'integer') {
421:             return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
422:         }
423:         $out = parent::buildColumn($column);
424:         if ($isPrimary && $type === 'biginteger') {
425:             $replacement = 'PRIMARY KEY';
426:             if ($column['null'] === false) {
427:                 $replacement = 'NOT NULL ' . $replacement;
428:             }
429:             return str_replace($this->columns['primary_key']['name'], $replacement, $out);
430:         }
431:         return $out;
432:     }
433: 
434: /**
435:  * Sets the database encoding
436:  *
437:  * @param string $enc Database encoding
438:  * @return bool
439:  */
440:     public function setEncoding($enc) {
441:         if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
442:             return false;
443:         }
444:         return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
445:     }
446: 
447: /**
448:  * Gets the database encoding
449:  *
450:  * @return string The database encoding
451:  */
452:     public function getEncoding() {
453:         return $this->fetchRow('PRAGMA encoding');
454:     }
455: 
456: /**
457:  * Removes redundant primary key indexes, as they are handled in the column def of the key.
458:  *
459:  * @param array $indexes The indexes to build.
460:  * @param string $table The table name.
461:  * @return string The completed index.
462:  */
463:     public function buildIndex($indexes, $table = null) {
464:         $join = array();
465: 
466:         $table = str_replace('"', '', $table);
467:         list($dbname, $table) = explode('.', $table);
468:         $dbname = $this->name($dbname);
469: 
470:         foreach ($indexes as $name => $value) {
471: 
472:             if ($name === 'PRIMARY') {
473:                 continue;
474:             }
475:             $out = 'CREATE ';
476: 
477:             if (!empty($value['unique'])) {
478:                 $out .= 'UNIQUE ';
479:             }
480:             if (is_array($value['column'])) {
481:                 $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
482:             } else {
483:                 $value['column'] = $this->name($value['column']);
484:             }
485:             $t = trim($table, '"');
486:             $indexname = $this->name($t . '_' . $name);
487:             $table = $this->name($table);
488:             $out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
489:             $join[] = $out;
490:         }
491:         return $join;
492:     }
493: 
494: /**
495:  * Overrides DboSource::index to handle SQLite index introspection
496:  * Returns an array of the indexes in given table name.
497:  *
498:  * @param string $model Name of model to inspect
499:  * @return array Fields in table. Keys are column and unique
500:  */
501:     public function index($model) {
502:         $index = array();
503:         $table = $this->fullTableName($model, false, false);
504:         if ($table) {
505:             $indexes = $this->query('PRAGMA index_list(' . $table . ')');
506: 
507:             if (is_bool($indexes)) {
508:                 return array();
509:             }
510:             foreach ($indexes as $info) {
511:                 $key = array_pop($info);
512:                 $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
513:                 foreach ($keyInfo as $keyCol) {
514:                     if (!isset($index[$key['name']])) {
515:                         $col = array();
516:                         if (preg_match('/autoindex/', $key['name'])) {
517:                             $key['name'] = 'PRIMARY';
518:                         }
519:                         $index[$key['name']]['column'] = $keyCol[0]['name'];
520:                         $index[$key['name']]['unique'] = (int)$key['unique'] === 1;
521:                     } else {
522:                         if (!is_array($index[$key['name']]['column'])) {
523:                             $col[] = $index[$key['name']]['column'];
524:                         }
525:                         $col[] = $keyCol[0]['name'];
526:                         $index[$key['name']]['column'] = $col;
527:                     }
528:                 }
529:             }
530:         }
531:         return $index;
532:     }
533: 
534: /**
535:  * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
536:  *
537:  * @param string $type The type of statement being rendered.
538:  * @param array $data The data to convert to SQL.
539:  * @return string
540:  */
541:     public function renderStatement($type, $data) {
542:         switch (strtolower($type)) {
543:             case 'schema':
544:                 extract($data);
545:                 if (is_array($columns)) {
546:                     $columns = "\t" . implode(",\n\t", array_filter($columns));
547:                 }
548:                 if (is_array($indexes)) {
549:                     $indexes = "\t" . implode("\n\t", array_filter($indexes));
550:                 }
551:                 return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
552:             default:
553:                 return parent::renderStatement($type, $data);
554:         }
555:     }
556: 
557: /**
558:  * PDO deals in objects, not resources, so overload accordingly.
559:  *
560:  * @return bool
561:  */
562:     public function hasResult() {
563:         return is_object($this->_result);
564:     }
565: 
566: /**
567:  * Generate a "drop table" statement for the given table
568:  *
569:  * @param type $table Name of the table to drop
570:  * @return string Drop table SQL statement
571:  */
572:     protected function _dropTable($table) {
573:         return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
574:     }
575: 
576: /**
577:  * Gets the schema name
578:  *
579:  * @return string The schema name
580:  */
581:     public function getSchemaName() {
582:         return "main"; // Sqlite Datasource does not support multidb
583:     }
584: 
585: /**
586:  * Check if the server support nested transactions
587:  *
588:  * @return bool
589:  */
590:     public function nestedTransactionSupported() {
591:         return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
592:     }
593: 
594: }
595: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs