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:
69: public $columns = array(
70: 'primary_key' => array('name' => 'integer primary key autoincrement'),
71: 'string' => array('name' => 'varchar', 'limit' => '255'),
72: 'text' => array('name' => 'text'),
73: 'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
74: 'smallinteger' => array('name' => 'smallint', 'limit' => null, 'formatter' => 'intval'),
75: 'tinyinteger' => array('name' => 'tinyint', 'limit' => null, 'formatter' => 'intval'),
76: 'biginteger' => array('name' => 'bigint', 'limit' => 20),
77: 'float' => array('name' => 'float', 'formatter' => 'floatval'),
78: 'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
79: 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
80: 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
81: 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
82: 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
83: 'binary' => array('name' => 'blob'),
84: 'boolean' => array('name' => 'boolean')
85: );
86:
87: 88: 89: 90: 91:
92: public $fieldParameters = array(
93: 'collate' => array(
94: 'value' => 'COLLATE',
95: 'quote' => false,
96: 'join' => ' ',
97: 'column' => 'Collate',
98: 'position' => 'afterDefault',
99: 'options' => array(
100: 'BINARY', 'NOCASE', 'RTRIM'
101: )
102: ),
103: );
104:
105: 106: 107: 108: 109: 110:
111: public function connect() {
112: $config = $this->config;
113: $flags = $config['flags'] + array(
114: PDO::ATTR_PERSISTENT => $config['persistent'],
115: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
116: );
117: try {
118: $this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags);
119: $this->connected = true;
120: } catch(PDOException $e) {
121: throw new MissingConnectionException(array(
122: 'class' => get_class($this),
123: 'message' => $e->getMessage()
124: ));
125: }
126: return $this->connected;
127: }
128:
129: 130: 131: 132: 133:
134: public function enabled() {
135: return in_array('sqlite', PDO::getAvailableDrivers());
136: }
137:
138: 139: 140: 141: 142: 143:
144: public function listSources($data = null) {
145: $cache = parent::listSources();
146: if ($cache) {
147: return $cache;
148: }
149:
150: $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
151:
152: if (!$result || empty($result)) {
153: return array();
154: }
155:
156: $tables = array();
157: foreach ($result as $table) {
158: $tables[] = $table[0]['name'];
159: }
160: parent::listSources($tables);
161: return $tables;
162: }
163:
164: 165: 166: 167: 168: 169:
170: public function describe($model) {
171: $table = $this->fullTableName($model, false, false);
172: $cache = parent::describe($table);
173: if ($cache) {
174: return $cache;
175: }
176: $fields = array();
177: $result = $this->_execute(
178: 'PRAGMA table_info(' . $this->value($table, 'string') . ')'
179: );
180:
181: foreach ($result as $column) {
182: $default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
183:
184: $fields[$column['name']] = array(
185: 'type' => $this->column($column['type']),
186: 'null' => !$column['notnull'],
187: 'default' => $default,
188: 'length' => $this->length($column['type'])
189: );
190: if (in_array($fields[$column['name']]['type'], array('timestamp', 'datetime')) && strtoupper($fields[$column['name']]['default']) === 'CURRENT_TIMESTAMP') {
191: $fields[$column['name']]['default'] = null;
192: }
193: if ($column['pk'] == 1) {
194: $fields[$column['name']]['key'] = $this->index['PRI'];
195: $fields[$column['name']]['null'] = false;
196: if (empty($fields[$column['name']]['length'])) {
197: $fields[$column['name']]['length'] = 11;
198: }
199: }
200: }
201:
202: $result->closeCursor();
203: $this->_cacheDescription($table, $fields);
204: return $fields;
205: }
206:
207: 208: 209: 210: 211: 212: 213: 214: 215:
216: public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
217: if (empty($values) && !empty($fields)) {
218: foreach ($fields as $field => $value) {
219: if (strpos($field, $model->alias . '.') !== false) {
220: unset($fields[$field]);
221: $field = str_replace($model->alias . '.', "", $field);
222: $field = str_replace($model->alias . '.', "", $field);
223: $fields[$field] = $value;
224: }
225: }
226: }
227: return parent::update($model, $fields, $values, $conditions);
228: }
229:
230: 231: 232: 233: 234: 235: 236:
237: public function truncate($table) {
238: if (in_array('sqlite_sequence', $this->listSources())) {
239: $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
240: }
241: return $this->execute('DELETE FROM ' . $this->fullTableName($table));
242: }
243:
244: 245: 246: 247: 248: 249:
250: public function column($real) {
251: if (is_array($real)) {
252: $col = $real['name'];
253: if (isset($real['limit'])) {
254: $col .= '(' . $real['limit'] . ')';
255: }
256: return $col;
257: }
258:
259: $col = strtolower(str_replace(')', '', $real));
260: if (strpos($col, '(') !== false) {
261: list($col) = explode('(', $col);
262: }
263:
264: $standard = array(
265: 'text',
266: 'integer',
267: 'float',
268: 'boolean',
269: 'timestamp',
270: 'date',
271: 'datetime',
272: 'time'
273: );
274: if (in_array($col, $standard)) {
275: return $col;
276: }
277: if ($col === 'tinyint') {
278: return 'tinyinteger';
279: }
280: if ($col === 'smallint') {
281: return 'smallinteger';
282: }
283: if ($col === 'bigint') {
284: return 'biginteger';
285: }
286: if (strpos($col, 'char') !== false) {
287: return 'string';
288: }
289: if (in_array($col, array('blob', 'clob'))) {
290: return 'binary';
291: }
292: if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
293: return 'decimal';
294: }
295: return 'text';
296: }
297:
298: 299: 300: 301: 302: 303:
304: public function resultSet($results) {
305: $this->results = $results;
306: $this->map = array();
307: $numFields = $results->columnCount();
308: $index = 0;
309: $j = 0;
310:
311:
312:
313: $querystring = $results->queryString;
314: if (stripos($querystring, 'SELECT') === 0 && stripos($querystring, 'FROM') > 0) {
315: $selectpart = substr($querystring, 7);
316: $selects = array();
317: foreach (CakeText::tokenize($selectpart, ',', '(', ')') as $part) {
318: $fromPos = stripos($part, ' FROM ');
319: if ($fromPos !== false) {
320: $selects[] = trim(substr($part, 0, $fromPos));
321: break;
322: }
323: $selects[] = $part;
324: }
325: } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
326: $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
327: } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
328: $selects = array('seq', 'name', 'unique');
329: } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
330: $selects = array('seqno', 'cid', 'name');
331: }
332: while ($j < $numFields) {
333: if (!isset($selects[$j])) {
334: $j++;
335: continue;
336: }
337: if (preg_match('/\bAS(?!.*\bAS\b)\s+(.*)/i', $selects[$j], $matches)) {
338: $columnName = trim($matches[1], '"');
339: } else {
340: $columnName = trim(str_replace('"', '', $selects[$j]));
341: }
342:
343: if (strpos($selects[$j], 'DISTINCT') === 0) {
344: $columnName = str_ireplace('DISTINCT', '', $columnName);
345: }
346:
347: $metaType = false;
348: try {
349: $metaData = (array)$results->getColumnMeta($j);
350: if (!empty($metaData['sqlite:decl_type'])) {
351: $metaType = trim($metaData['sqlite:decl_type']);
352: }
353: } catch (Exception $e) {
354: }
355:
356: if (strpos($columnName, '.')) {
357: $parts = explode('.', $columnName);
358: $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
359: } else {
360: $this->map[$index++] = array(0, $columnName, $metaType);
361: }
362: $j++;
363: }
364: }
365:
366: 367: 368: 369: 370:
371: public function fetchResult() {
372: if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
373: $resultRow = array();
374: foreach ($this->map as $col => $meta) {
375: list($table, $column, $type) = $meta;
376: $resultRow[$table][$column] = $row[$col];
377: if ($type === 'boolean' && $row[$col] !== null) {
378: $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
379: }
380: }
381: return $resultRow;
382: }
383: $this->_result->closeCursor();
384: return false;
385: }
386:
387: 388: 389: 390: 391: 392: 393:
394: public function limit($limit, $offset = null) {
395: if ($limit) {
396: $rt = sprintf(' LIMIT %u', $limit);
397: if ($offset) {
398: $rt .= sprintf(' OFFSET %u', $offset);
399: }
400: return $rt;
401: }
402: return null;
403: }
404:
405: 406: 407: 408: 409: 410: 411:
412: public function buildColumn($column) {
413: $name = $type = null;
414: $column += array('null' => true);
415: extract($column);
416:
417: if (empty($name) || empty($type)) {
418: trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
419: return null;
420: }
421:
422: if (!isset($this->columns[$type])) {
423: trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
424: return null;
425: }
426:
427: $isPrimary = (isset($column['key']) && $column['key'] === 'primary');
428: if ($isPrimary && $type === 'integer') {
429: return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
430: }
431: $out = parent::buildColumn($column);
432: if ($isPrimary && $type === 'biginteger') {
433: $replacement = 'PRIMARY KEY';
434: if ($column['null'] === false) {
435: $replacement = 'NOT NULL ' . $replacement;
436: }
437: return str_replace($this->columns['primary_key']['name'], $replacement, $out);
438: }
439: return $out;
440: }
441:
442: 443: 444: 445: 446: 447:
448: public function setEncoding($enc) {
449: if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
450: return false;
451: }
452: return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
453: }
454:
455: 456: 457: 458: 459:
460: public function getEncoding() {
461: return $this->fetchRow('PRAGMA encoding');
462: }
463:
464: 465: 466: 467: 468: 469: 470:
471: public function buildIndex($indexes, $table = null) {
472: $join = array();
473:
474: $table = str_replace('"', '', $table);
475: list($dbname, $table) = explode('.', $table);
476: $dbname = $this->name($dbname);
477:
478: foreach ($indexes as $name => $value) {
479:
480: if ($name === 'PRIMARY') {
481: continue;
482: }
483: $out = 'CREATE ';
484:
485: if (!empty($value['unique'])) {
486: $out .= 'UNIQUE ';
487: }
488: if (is_array($value['column'])) {
489: $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
490: } else {
491: $value['column'] = $this->name($value['column']);
492: }
493: $t = trim($table, '"');
494: $indexname = $this->name($t . '_' . $name);
495: $table = $this->name($table);
496: $out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
497: $join[] = $out;
498: }
499: return $join;
500: }
501:
502: 503: 504: 505: 506: 507: 508:
509: public function index($model) {
510: $index = array();
511: $table = $this->fullTableName($model, false, false);
512: if ($table) {
513: $indexes = $this->query('PRAGMA index_list(' . $table . ')');
514:
515: if (is_bool($indexes)) {
516: return array();
517: }
518: foreach ($indexes as $info) {
519: $key = array_pop($info);
520: $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
521: foreach ($keyInfo as $keyCol) {
522: if (!isset($index[$key['name']])) {
523: $col = array();
524: if (preg_match('/autoindex/', $key['name'])) {
525: $key['name'] = 'PRIMARY';
526: }
527: $index[$key['name']]['column'] = $keyCol[0]['name'];
528: $index[$key['name']]['unique'] = (int)$key['unique'] === 1;
529: } else {
530: if (!is_array($index[$key['name']]['column'])) {
531: $col[] = $index[$key['name']]['column'];
532: }
533: $col[] = $keyCol[0]['name'];
534: $index[$key['name']]['column'] = $col;
535: }
536: }
537: }
538: }
539: return $index;
540: }
541:
542: 543: 544: 545: 546: 547: 548:
549: public function renderStatement($type, $data) {
550: switch (strtolower($type)) {
551: case 'schema':
552: extract($data);
553: if (is_array($columns)) {
554: $columns = "\t" . implode(",\n\t", array_filter($columns));
555: }
556: if (is_array($indexes)) {
557: $indexes = "\t" . implode("\n\t", array_filter($indexes));
558: }
559: return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
560: default:
561: return parent::renderStatement($type, $data);
562: }
563: }
564:
565: 566: 567: 568: 569:
570: public function hasResult() {
571: return is_object($this->_result);
572: }
573:
574: 575: 576: 577: 578: 579:
580: protected function _dropTable($table) {
581: return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
582: }
583:
584: 585: 586: 587: 588:
589: public function getSchemaName() {
590: return "main";
591: }
592:
593: 594: 595: 596: 597:
598: public function nestedTransactionSupported() {
599: return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
600: }
601:
602: 603: 604: 605: 606: 607: 608: 609:
610: public function getLockingHint($mode) {
611: return null;
612: }
613: }
614: