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.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 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

Classes

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