1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18:
19:
20: App::uses('DboSource', 'Model/Datasource');
21: App::uses('String', 'Utility');
22:
23: 24: 25: 26: 27: 28: 29:
30: class Sqlite extends DboSource {
31:
32: 33: 34: 35: 36:
37: public $description = "SQLite DBO Driver";
38:
39: 40: 41: 42: 43:
44: public $startQuote = '"';
45:
46: 47: 48: 49: 50:
51: public $endQuote = '"';
52:
53: 54: 55: 56: 57:
58: protected $_baseConfig = array(
59: 'persistent' => false,
60: 'database' => null
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: '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: 84: 85: 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: 102: 103: 104: 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: 126: 127: 128:
129: public function enabled() {
130: return in_array('sqlite', PDO::getAvailableDrivers());
131: }
132:
133: 134: 135: 136: 137: 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: 161: 162: 163: 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: 202: 203: 204: 205: 206: 207: 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: 225: 226: 227: 228: 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: 237: 238: 239: 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: 273: 274: 275: 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:
285:
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: 336: 337: 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: 358: 359: 360: 361: 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: 380: 381: 382: 383: 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: 408: 409: 410: 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: 421: 422: 423:
424: public function getEncoding() {
425: return $this->fetchRow('PRAGMA encoding');
426: }
427:
428: 429: 430: 431: 432: 433: 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: 468: 469: 470: 471: 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: 508: 509: 510: 511: 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: 531: 532: 533:
534: public function hasResult() {
535: return is_object($this->_result);
536: }
537:
538: 539: 540: 541: 542: 543: 544: 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: 558: 559: 560:
561: public function getSchemaName() {
562: return "main";
563: }
564:
565: 566: 567: 568: 569:
570: public function nestedTransactionSupported() {
571: return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
572: }
573:
574: }
575: