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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 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
    • Network
      • Email
      • Http
    • Routing
      • 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('class' => $e->getMessage()));
117:         }
118:         return $this->connected;
119:     }
120: 
121: /**
122:  * Check whether the SQLite extension is installed/loaded
123:  *
124:  * @return boolean
125:  */
126:     public function enabled() {
127:         return in_array('sqlite', PDO::getAvailableDrivers());
128:     }
129: 
130: /**
131:  * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
132:  *
133:  * @param mixed $data
134:  * @return array Array of table names in the database
135:  */
136:     public function listSources($data = null) {
137:         $cache = parent::listSources();
138:         if ($cache != null) {
139:             return $cache;
140:         }
141: 
142:         $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
143: 
144:         if (!$result || empty($result)) {
145:             return array();
146:         } else {
147:             $tables = array();
148:             foreach ($result as $table) {
149:                 $tables[] = $table[0]['name'];
150:             }
151:             parent::listSources($tables);
152:             return $tables;
153:         }
154:     }
155: 
156: /**
157:  * Returns an array of the fields in given table name.
158:  *
159:  * @param Model|string $model Either the model or table name you want described.
160:  * @return array Fields in table. Keys are name and type
161:  */
162:     public function describe($model) {
163:         $table = $this->fullTableName($model, false, false);
164:         $cache = parent::describe($table);
165:         if ($cache != null) {
166:             return $cache;
167:         }
168:         $fields = array();
169:         $result = $this->_execute(
170:             'PRAGMA table_info(' . $this->value($table, 'string') . ')'
171:         );
172: 
173:         foreach ($result as $column) {
174:             $column = (array)$column;
175:             $default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
176: 
177:             $fields[$column['name']] = array(
178:                 'type' => $this->column($column['type']),
179:                 'null' => !$column['notnull'],
180:                 'default' => $default,
181:                 'length' => $this->length($column['type'])
182:             );
183:             if ($column['pk'] == 1) {
184:                 $fields[$column['name']]['key'] = $this->index['PRI'];
185:                 $fields[$column['name']]['null'] = false;
186:                 if (empty($fields[$column['name']]['length'])) {
187:                     $fields[$column['name']]['length'] = 11;
188:                 }
189:             }
190:         }
191: 
192:         $result->closeCursor();
193:         $this->_cacheDescription($table, $fields);
194:         return $fields;
195:     }
196: 
197: /**
198:  * Generates and executes an SQL UPDATE statement for given model, fields, and values.
199:  *
200:  * @param Model $model
201:  * @param array $fields
202:  * @param array $values
203:  * @param mixed $conditions
204:  * @return array
205:  */
206:     public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
207:         if (empty($values) && !empty($fields)) {
208:             foreach ($fields as $field => $value) {
209:                 if (strpos($field, $model->alias . '.') !== false) {
210:                     unset($fields[$field]);
211:                     $field = str_replace($model->alias . '.', "", $field);
212:                     $field = str_replace($model->alias . '.', "", $field);
213:                     $fields[$field] = $value;
214:                 }
215:             }
216:         }
217:         return parent::update($model, $fields, $values, $conditions);
218:     }
219: 
220: /**
221:  * Deletes all the records in a table and resets the count of the auto-incrementing
222:  * primary key, where applicable.
223:  *
224:  * @param mixed $table A string or model class representing the table to be truncated
225:  * @return boolean  SQL TRUNCATE TABLE statement, false if not applicable.
226:  */
227:     public function truncate($table) {
228:         $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
229:         return $this->execute('DELETE FROM ' . $this->fullTableName($table));
230:     }
231: 
232: /**
233:  * Converts database-layer column types to basic types
234:  *
235:  * @param string $real Real database-layer column type (i.e. "varchar(255)")
236:  * @return string Abstract column type (i.e. "string")
237:  */
238:     public function column($real) {
239:         if (is_array($real)) {
240:             $col = $real['name'];
241:             if (isset($real['limit'])) {
242:                 $col .= '(' . $real['limit'] . ')';
243:             }
244:             return $col;
245:         }
246: 
247:         $col = strtolower(str_replace(')', '', $real));
248:         $limit = null;
249:         @list($col, $limit) = explode('(', $col);
250: 
251:         if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
252:             return $col;
253:         }
254:         if (strpos($col, 'char') !== false) {
255:             return 'string';
256:         }
257:         if (in_array($col, array('blob', 'clob'))) {
258:             return 'binary';
259:         }
260:         if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
261:             return 'float';
262:         }
263:         return 'text';
264:     }
265: 
266: /**
267:  * Generate ResultSet
268:  *
269:  * @param mixed $results
270:  * @return void
271:  */
272:     public function resultSet($results) {
273:         $this->results = $results;
274:         $this->map = array();
275:         $numFields = $results->columnCount();
276:         $index = 0;
277:         $j = 0;
278: 
279:         //PDO::getColumnMeta is experimental and does not work with sqlite3,
280:         //  so try to figure it out based on the querystring
281:         $querystring = $results->queryString;
282:         if (stripos($querystring, 'SELECT') === 0) {
283:             $last = strripos($querystring, 'FROM');
284:             if ($last !== false) {
285:                 $selectpart = substr($querystring, 7, $last - 8);
286:                 $selects = String::tokenize($selectpart, ',', '(', ')');
287:             }
288:         } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
289:             $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
290:         } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
291:             $selects = array('seq', 'name', 'unique');
292:         } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
293:             $selects = array('seqno', 'cid', 'name');
294:         }
295:         while ($j < $numFields) {
296:             if (!isset($selects[$j])) {
297:                 $j++;
298:                 continue;
299:             }
300:             if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
301:                  $columnName = trim($matches[1], '"');
302:             } else {
303:                 $columnName = trim(str_replace('"', '', $selects[$j]));
304:             }
305: 
306:             if (strpos($selects[$j], 'DISTINCT') === 0) {
307:                 $columnName = str_ireplace('DISTINCT', '', $columnName);
308:             }
309: 
310:             $metaType = false;
311:             try {
312:                 $metaData = (array)$results->getColumnMeta($j);
313:                 if (!empty($metaData['sqlite:decl_type'])) {
314:                     $metaType = trim($metaData['sqlite:decl_type']);
315:                 }
316:             } catch (Exception $e) {
317:             }
318: 
319:             if (strpos($columnName, '.')) {
320:                 $parts = explode('.', $columnName);
321:                 $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
322:             } else {
323:                 $this->map[$index++] = array(0, $columnName, $metaType);
324:             }
325:             $j++;
326:         }
327:     }
328: 
329: /**
330:  * Fetches the next row from the current result set
331:  *
332:  * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
333:  */
334:     public function fetchResult() {
335:         if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
336:             $resultRow = array();
337:             foreach ($this->map as $col => $meta) {
338:                 list($table, $column, $type) = $meta;
339:                 $resultRow[$table][$column] = $row[$col];
340:                 if ($type == 'boolean' && !is_null($row[$col])) {
341:                     $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
342:                 }
343:             }
344:             return $resultRow;
345:         } else {
346:             $this->_result->closeCursor();
347:             return false;
348:         }
349:     }
350: 
351: /**
352:  * Returns a limit statement in the correct format for the particular database.
353:  *
354:  * @param integer $limit Limit of results returned
355:  * @param integer $offset Offset from which to start results
356:  * @return string SQL limit/offset statement
357:  */
358:     public function limit($limit, $offset = null) {
359:         if ($limit) {
360:             $rt = '';
361:             if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
362:                 $rt = ' LIMIT';
363:             }
364:             $rt .= ' ' . $limit;
365:             if ($offset) {
366:                 $rt .= ' OFFSET ' . $offset;
367:             }
368:             return $rt;
369:         }
370:         return null;
371:     }
372: 
373: /**
374:  * Generate a database-native column schema string
375:  *
376:  * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
377:  *    where options can be 'default', 'length', or 'key'.
378:  * @return string
379:  */
380:     public function buildColumn($column) {
381:         $name = $type = null;
382:         $column = array_merge(array('null' => true), $column);
383:         extract($column);
384: 
385:         if (empty($name) || empty($type)) {
386:             trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
387:             return null;
388:         }
389: 
390:         if (!isset($this->columns[$type])) {
391:             trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
392:             return null;
393:         }
394: 
395:         if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
396:             return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
397:         }
398:         return parent::buildColumn($column);
399:     }
400: 
401: /**
402:  * Sets the database encoding
403:  *
404:  * @param string $enc Database encoding
405:  * @return boolean
406:  */
407:     public function setEncoding($enc) {
408:         if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
409:             return false;
410:         }
411:         return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
412:     }
413: 
414: /**
415:  * Gets the database encoding
416:  *
417:  * @return string The database encoding
418:  */
419:     public function getEncoding() {
420:         return $this->fetchRow('PRAGMA encoding');
421:     }
422: 
423: /**
424:  * Removes redundant primary key indexes, as they are handled in the column def of the key.
425:  *
426:  * @param array $indexes
427:  * @param string $table
428:  * @return string
429:  */
430:     public function buildIndex($indexes, $table = null) {
431:         $join = array();
432: 
433:         $table = str_replace('"', '', $table);
434:         list($dbname, $table) = explode('.', $table);
435:         $dbname = $this->name($dbname);
436: 
437:         foreach ($indexes as $name => $value) {
438: 
439:             if ($name == 'PRIMARY') {
440:                 continue;
441:             }
442:             $out = 'CREATE ';
443: 
444:             if (!empty($value['unique'])) {
445:                 $out .= 'UNIQUE ';
446:             }
447:             if (is_array($value['column'])) {
448:                 $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
449:             } else {
450:                 $value['column'] = $this->name($value['column']);
451:             }
452:             $t = trim($table, '"');
453:             $indexname = $this->name($t . '_' . $name);
454:             $table = $this->name($table);
455:             $out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
456:             $join[] = $out;
457:         }
458:         return $join;
459:     }
460: 
461: /**
462:  * Overrides DboSource::index to handle SQLite index introspection
463:  * Returns an array of the indexes in given table name.
464:  *
465:  * @param string $model Name of model to inspect
466:  * @return array Fields in table. Keys are column and unique
467:  */
468:     public function index($model) {
469:         $index = array();
470:         $table = $this->fullTableName($model, false, false);
471:         if ($table) {
472:             $indexes = $this->query('PRAGMA index_list(' . $table . ')');
473: 
474:             if (is_bool($indexes)) {
475:                 return array();
476:             }
477:             foreach ($indexes as $i => $info) {
478:                 $key = array_pop($info);
479:                 $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
480:                 foreach ($keyInfo as $keyCol) {
481:                     if (!isset($index[$key['name']])) {
482:                         $col = array();
483:                         if (preg_match('/autoindex/', $key['name'])) {
484:                             $key['name'] = 'PRIMARY';
485:                         }
486:                         $index[$key['name']]['column'] = $keyCol[0]['name'];
487:                         $index[$key['name']]['unique'] = intval($key['unique'] == 1);
488:                     } else {
489:                         if (!is_array($index[$key['name']]['column'])) {
490:                             $col[] = $index[$key['name']]['column'];
491:                         }
492:                         $col[] = $keyCol[0]['name'];
493:                         $index[$key['name']]['column'] = $col;
494:                     }
495:                 }
496:             }
497:         }
498:         return $index;
499:     }
500: 
501: /**
502:  * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
503:  *
504:  * @param string $type
505:  * @param array $data
506:  * @return string
507:  */
508:     public function renderStatement($type, $data) {
509:         switch (strtolower($type)) {
510:             case 'schema':
511:                 extract($data);
512:                 if (is_array($columns)) {
513:                     $columns = "\t" . join(",\n\t", array_filter($columns));
514:                 }
515:                 if (is_array($indexes)) {
516:                     $indexes = "\t" . join("\n\t", array_filter($indexes));
517:                 }
518:                 return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
519:             break;
520:             default:
521:                 return parent::renderStatement($type, $data);
522:             break;
523:         }
524:     }
525: 
526: /**
527:  * PDO deals in objects, not resources, so overload accordingly.
528:  *
529:  * @return boolean
530:  */
531:     public function hasResult() {
532:         return is_object($this->_result);
533:     }
534: 
535: /**
536:  * Generate a "drop table" statement for the given Schema object
537:  *
538:  * @param CakeSchema $schema An instance of a subclass of CakeSchema
539:  * @param string $table Optional.  If specified only the table name given will be generated.
540:  *   Otherwise, all tables defined in the schema are generated.
541:  * @return string
542:  */
543:     public function dropSchema(CakeSchema $schema, $table = null) {
544:         $out = '';
545:         foreach ($schema->tables as $curTable => $columns) {
546:             if (!$table || $table == $curTable) {
547:                 $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
548:             }
549:         }
550:         return $out;
551:     }
552: 
553: /**
554:  * Gets the schema name
555:  *
556:  * @return string The schema name
557:  */
558:     public function getSchemaName() {
559:         return "main"; // Sqlite Datasource does not support multidb
560:     }
561: 
562: }
563: 
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