1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17:
18:
19: App::uses('DboSource', 'Model/Datasource');
20: App::uses('CakeText', 'Utility');
21:
22: 23: 24: 25: 26: 27: 28:
29: class Sqlite extends DboSource {
30:
31: 32: 33: 34: 35:
36: public $description = "SQLite DBO Driver";
37:
38: 39: 40: 41: 42:
43: public $startQuote = '"';
44:
45: 46: 47: 48: 49:
50: public $endQuote = '"';
51:
52: 53: 54: 55: 56:
57: protected $_baseConfig = array(
58: 'persistent' => false,
59: 'database' => null,
60: 'flags' => array()
61: );
62:
63: 64: 65: 66: 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: 86: 87: 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: 104: 105: 106: 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: 128: 129: 130:
131: public function enabled() {
132: return in_array('sqlite', PDO::getAvailableDrivers());
133: }
134:
135: 136: 137: 138: 139: 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: 163: 164: 165: 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 ($column['pk'] == 1) {
189: $fields[$column['name']]['key'] = $this->index['PRI'];
190: $fields[$column['name']]['null'] = false;
191: if (empty($fields[$column['name']]['length'])) {
192: $fields[$column['name']]['length'] = 11;
193: }
194: }
195: }
196:
197: $result->closeCursor();
198: $this->_cacheDescription($table, $fields);
199: return $fields;
200: }
201:
202: 203: 204: 205: 206: 207: 208: 209: 210:
211: public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
212: if (empty($values) && !empty($fields)) {
213: foreach ($fields as $field => $value) {
214: if (strpos($field, $model->alias . '.') !== false) {
215: unset($fields[$field]);
216: $field = str_replace($model->alias . '.', "", $field);
217: $field = str_replace($model->alias . '.', "", $field);
218: $fields[$field] = $value;
219: }
220: }
221: }
222: return parent::update($model, $fields, $values, $conditions);
223: }
224:
225: 226: 227: 228: 229: 230: 231:
232: public function truncate($table) {
233: if (in_array('sqlite_sequence', $this->listSources())) {
234: $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
235: }
236: return $this->execute('DELETE FROM ' . $this->fullTableName($table));
237: }
238:
239: 240: 241: 242: 243: 244:
245: public function column($real) {
246: if (is_array($real)) {
247: $col = $real['name'];
248: if (isset($real['limit'])) {
249: $col .= '(' . $real['limit'] . ')';
250: }
251: return $col;
252: }
253:
254: $col = strtolower(str_replace(')', '', $real));
255: if (strpos($col, '(') !== false) {
256: list($col) = explode('(', $col);
257: }
258:
259: $standard = array(
260: 'text',
261: 'integer',
262: 'float',
263: 'boolean',
264: 'timestamp',
265: 'date',
266: 'datetime',
267: 'time'
268: );
269: if (in_array($col, $standard)) {
270: return $col;
271: }
272: if ($col === 'bigint') {
273: return 'biginteger';
274: }
275: if (strpos($col, 'char') !== false) {
276: return 'string';
277: }
278: if (in_array($col, array('blob', 'clob'))) {
279: return 'binary';
280: }
281: if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
282: return 'decimal';
283: }
284: return 'text';
285: }
286:
287: 288: 289: 290: 291: 292:
293: public function resultSet($results) {
294: $this->results = $results;
295: $this->map = array();
296: $numFields = $results->columnCount();
297: $index = 0;
298: $j = 0;
299:
300:
301:
302: $querystring = $results->queryString;
303: if (stripos($querystring, 'SELECT') === 0 && stripos($querystring, 'FROM') > 0) {
304: $selectpart = substr($querystring, 7);
305: $selects = array();
306: foreach (CakeText::tokenize($selectpart, ',', '(', ')') as $part) {
307: $fromPos = stripos($part, ' FROM ');
308: if ($fromPos !== false) {
309: $selects[] = trim(substr($part, 0, $fromPos));
310: break;
311: }
312: $selects[] = $part;
313: }
314: } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
315: $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
316: } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
317: $selects = array('seq', 'name', 'unique');
318: } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
319: $selects = array('seqno', 'cid', 'name');
320: }
321: while ($j < $numFields) {
322: if (!isset($selects[$j])) {
323: $j++;
324: continue;
325: }
326: if (preg_match('/\bAS(?!.*\bAS\b)\s+(.*)/i', $selects[$j], $matches)) {
327: $columnName = trim($matches[1], '"');
328: } else {
329: $columnName = trim(str_replace('"', '', $selects[$j]));
330: }
331:
332: if (strpos($selects[$j], 'DISTINCT') === 0) {
333: $columnName = str_ireplace('DISTINCT', '', $columnName);
334: }
335:
336: $metaType = false;
337: try {
338: $metaData = (array)$results->getColumnMeta($j);
339: if (!empty($metaData['sqlite:decl_type'])) {
340: $metaType = trim($metaData['sqlite:decl_type']);
341: }
342: } catch (Exception $e) {
343: }
344:
345: if (strpos($columnName, '.')) {
346: $parts = explode('.', $columnName);
347: $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
348: } else {
349: $this->map[$index++] = array(0, $columnName, $metaType);
350: }
351: $j++;
352: }
353: }
354:
355: 356: 357: 358: 359:
360: public function fetchResult() {
361: if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
362: $resultRow = array();
363: foreach ($this->map as $col => $meta) {
364: list($table, $column, $type) = $meta;
365: $resultRow[$table][$column] = $row[$col];
366: if ($type === 'boolean' && $row[$col] !== null) {
367: $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
368: }
369: }
370: return $resultRow;
371: }
372: $this->_result->closeCursor();
373: return false;
374: }
375:
376: 377: 378: 379: 380: 381: 382:
383: public function limit($limit, $offset = null) {
384: if ($limit) {
385: $rt = sprintf(' LIMIT %u', $limit);
386: if ($offset) {
387: $rt .= sprintf(' OFFSET %u', $offset);
388: }
389: return $rt;
390: }
391: return null;
392: }
393:
394: 395: 396: 397: 398: 399: 400:
401: public function buildColumn($column) {
402: $name = $type = null;
403: $column += array('null' => true);
404: extract($column);
405:
406: if (empty($name) || empty($type)) {
407: trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
408: return null;
409: }
410:
411: if (!isset($this->columns[$type])) {
412: trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
413: return null;
414: }
415:
416: $isPrimary = (isset($column['key']) && $column['key'] === 'primary');
417: if ($isPrimary && $type === 'integer') {
418: return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
419: }
420: $out = parent::buildColumn($column);
421: if ($isPrimary && $type === 'biginteger') {
422: $replacement = 'PRIMARY KEY';
423: if ($column['null'] === false) {
424: $replacement = 'NOT NULL ' . $replacement;
425: }
426: return str_replace($this->columns['primary_key']['name'], $replacement, $out);
427: }
428: return $out;
429: }
430:
431: 432: 433: 434: 435: 436:
437: public function setEncoding($enc) {
438: if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
439: return false;
440: }
441: return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
442: }
443:
444: 445: 446: 447: 448:
449: public function getEncoding() {
450: return $this->fetchRow('PRAGMA encoding');
451: }
452:
453: 454: 455: 456: 457: 458: 459:
460: public function buildIndex($indexes, $table = null) {
461: $join = array();
462:
463: $table = str_replace('"', '', $table);
464: list($dbname, $table) = explode('.', $table);
465: $dbname = $this->name($dbname);
466:
467: foreach ($indexes as $name => $value) {
468:
469: if ($name === 'PRIMARY') {
470: continue;
471: }
472: $out = 'CREATE ';
473:
474: if (!empty($value['unique'])) {
475: $out .= 'UNIQUE ';
476: }
477: if (is_array($value['column'])) {
478: $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
479: } else {
480: $value['column'] = $this->name($value['column']);
481: }
482: $t = trim($table, '"');
483: $indexname = $this->name($t . '_' . $name);
484: $table = $this->name($table);
485: $out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
486: $join[] = $out;
487: }
488: return $join;
489: }
490:
491: 492: 493: 494: 495: 496: 497:
498: public function index($model) {
499: $index = array();
500: $table = $this->fullTableName($model, false, false);
501: if ($table) {
502: $indexes = $this->query('PRAGMA index_list(' . $table . ')');
503:
504: if (is_bool($indexes)) {
505: return array();
506: }
507: foreach ($indexes as $info) {
508: $key = array_pop($info);
509: $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
510: foreach ($keyInfo as $keyCol) {
511: if (!isset($index[$key['name']])) {
512: $col = array();
513: if (preg_match('/autoindex/', $key['name'])) {
514: $key['name'] = 'PRIMARY';
515: }
516: $index[$key['name']]['column'] = $keyCol[0]['name'];
517: $index[$key['name']]['unique'] = (int)$key['unique'] === 1;
518: } else {
519: if (!is_array($index[$key['name']]['column'])) {
520: $col[] = $index[$key['name']]['column'];
521: }
522: $col[] = $keyCol[0]['name'];
523: $index[$key['name']]['column'] = $col;
524: }
525: }
526: }
527: }
528: return $index;
529: }
530:
531: 532: 533: 534: 535: 536: 537:
538: public function renderStatement($type, $data) {
539: switch (strtolower($type)) {
540: case 'schema':
541: extract($data);
542: if (is_array($columns)) {
543: $columns = "\t" . implode(",\n\t", array_filter($columns));
544: }
545: if (is_array($indexes)) {
546: $indexes = "\t" . implode("\n\t", array_filter($indexes));
547: }
548: return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
549: default:
550: return parent::renderStatement($type, $data);
551: }
552: }
553:
554: 555: 556: 557: 558:
559: public function hasResult() {
560: return is_object($this->_result);
561: }
562:
563: 564: 565: 566: 567: 568:
569: protected function _dropTable($table) {
570: return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
571: }
572:
573: 574: 575: 576: 577:
578: public function getSchemaName() {
579: return "main";
580: }
581:
582: 583: 584: 585: 586:
587: public function nestedTransactionSupported() {
588: return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
589: }
590:
591: }
592: