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('class' => $e->getMessage()));
117: }
118: return $this->connected;
119: }
120:
121: 122: 123: 124: 125:
126: public function enabled() {
127: return in_array('sqlite', PDO::getAvailableDrivers());
128: }
129:
130: 131: 132: 133: 134: 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: 158: 159: 160: 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: 199: 200: 201: 202: 203: 204: 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: 222: 223: 224: 225: 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: 234: 235: 236: 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: 268: 269: 270: 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:
280:
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: 331: 332: 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: 353: 354: 355: 356: 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: 375: 376: 377: 378: 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: 403: 404: 405: 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: 416: 417: 418:
419: public function getEncoding() {
420: return $this->fetchRow('PRAGMA encoding');
421: }
422:
423: 424: 425: 426: 427: 428: 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: 463: 464: 465: 466: 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: 503: 504: 505: 506: 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: 528: 529: 530:
531: public function hasResult() {
532: return is_object($this->_result);
533: }
534:
535: 536: 537: 538: 539: 540: 541: 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: 555: 556: 557:
558: public function getSchemaName() {
559: return "main";
560: }
561:
562: }
563: