1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:
26: 27: 28: 29: 30: 31: 32: 33:
34: class DboSqlite extends DboSource {
35: 36: 37: 38: 39:
40: var $description = "SQLite DBO Driver";
41: 42: 43: 44: 45:
46: var $startQuote = '"';
47: 48: 49: 50: 51:
52: var $endQuote = '"';
53: 54: 55: 56: 57: 58:
59: var $_queryStats = array();
60: 61: 62: 63: 64:
65: var $_baseConfig = array(
66: 'persistent' => true,
67: 'database' => null,
68: 'connect' => 'sqlite_popen'
69: );
70: 71: 72: 73: 74: 75:
76: var $_commands = array(
77: 'begin' => 'BEGIN TRANSACTION',
78: 'commit' => 'COMMIT TRANSACTION',
79: 'rollback' => 'ROLLBACK TRANSACTION'
80: );
81: 82: 83: 84: 85:
86: var $columns = array(
87: 'primary_key' => array('name' => 'integer primary key'),
88: 'string' => array('name' => 'varchar', 'limit' => '255'),
89: 'text' => array('name' => 'text'),
90: 'integer' => array('name' => 'integer', 'limit' => 11, 'formatter' => 'intval'),
91: 'float' => array('name' => 'float', 'formatter' => 'floatval'),
92: 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
93: 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
94: 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
95: 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
96: 'binary' => array('name' => 'blob'),
97: 'boolean' => array('name' => 'boolean')
98: );
99: 100: 101: 102: 103: 104:
105: function connect() {
106: $config = $this->config;
107: $this->connection = $config['connect']($config['database']);
108: $this->connected = is_resource($this->connection);
109:
110: if ($this->connected) {
111: $this->_execute('PRAGMA count_changes = 1;');
112: }
113: return $this->connected;
114: }
115: 116: 117: 118: 119:
120: function enabled() {
121: return extension_loaded('sqlite');
122: }
123: 124: 125: 126: 127:
128: function disconnect() {
129: @sqlite_close($this->connection);
130: $this->connected = false;
131: return $this->connected;
132: }
133: 134: 135: 136: 137: 138:
139: function _execute($sql) {
140: $result = sqlite_query($this->connection, $sql);
141:
142: if (preg_match('/^(INSERT|UPDATE|DELETE)/', $sql)) {
143: $this->resultSet($result);
144: list($this->_queryStats) = $this->fetchResult();
145: }
146: return $result;
147: }
148: 149: 150: 151: 152: 153:
154: function execute($sql) {
155: $result = parent::execute($sql);
156: $this->_queryStats = array();
157: return $result;
158: }
159: 160: 161: 162: 163:
164: function listSources() {
165: $cache = parent::listSources();
166:
167: if ($cache != null) {
168: return $cache;
169: }
170: $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
171:
172: if (empty($result)) {
173: return array();
174: } else {
175: $tables = array();
176: foreach ($result as $table) {
177: $tables[] = $table[0]['name'];
178: }
179: parent::listSources($tables);
180: return $tables;
181: }
182: return array();
183: }
184: 185: 186: 187: 188: 189:
190: function describe(&$model) {
191: $cache = parent::describe($model);
192: if ($cache != null) {
193: return $cache;
194: }
195: $fields = array();
196: $result = $this->fetchAll('PRAGMA table_info(' . $this->fullTableName($model) . ')');
197:
198: foreach ($result as $column) {
199: $fields[$column[0]['name']] = array(
200: 'type' => $this->column($column[0]['type']),
201: 'null' => !$column[0]['notnull'],
202: 'default' => $column[0]['dflt_value'],
203: 'length' => $this->length($column[0]['type'])
204: );
205: if ($column[0]['pk'] == 1) {
206: $colLength = $this->length($column[0]['type']);
207: $fields[$column[0]['name']] = array(
208: 'type' => $fields[$column[0]['name']]['type'],
209: 'null' => false,
210: 'default' => $column[0]['dflt_value'],
211: 'key' => $this->index['PRI'],
212: 'length'=> ($colLength != null) ? $colLength : 11
213: );
214: }
215: }
216:
217: $this->__cacheDescription($model->tablePrefix . $model->table, $fields);
218: return $fields;
219: }
220: 221: 222: 223: 224: 225:
226: function value($data, $column = null, $safe = false) {
227: $parent = parent::value($data, $column, $safe);
228:
229: if ($parent != null) {
230: return $parent;
231: }
232: if ($data === null) {
233: return 'NULL';
234: }
235: if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
236: return "''";
237: }
238: switch ($column) {
239: case 'boolean':
240: $data = $this->boolean((bool)$data);
241: break;
242: case 'integer':
243: case 'float':
244: if ($data === '') {
245: return 'NULL';
246: }
247: default:
248: $data = sqlite_escape_string($data);
249: break;
250: }
251: return "'" . $data . "'";
252: }
253: 254: 255: 256: 257: 258: 259: 260: 261:
262: function update(&$model, $fields = array(), $values = null, $conditions = null) {
263: if (empty($values) && !empty($fields)) {
264: foreach ($fields as $field => $value) {
265: if (strpos($field, $model->alias . '.') !== false) {
266: unset($fields[$field]);
267: $field = str_replace($model->alias . '.', "", $field);
268: $field = str_replace($model->alias . '.', "", $field);
269: $fields[$field] = $value;
270: }
271: }
272: }
273: $result = parent::update($model, $fields, $values, $conditions);
274: return $result;
275: }
276: 277: 278: 279: 280: 281: 282: 283:
284: function truncate($table) {
285: return $this->execute('DELETE From ' . $this->fullTableName($table));
286: }
287: 288: 289: 290: 291:
292: function lastError() {
293: $error = sqlite_last_error($this->connection);
294: if ($error) {
295: return $error.': '.sqlite_error_string($error);
296: }
297: return null;
298: }
299: 300: 301: 302: 303:
304: function lastAffected() {
305: if (!empty($this->_queryStats)) {
306: foreach (array('rows inserted', 'rows updated', 'rows deleted') as $key) {
307: if (array_key_exists($key, $this->_queryStats)) {
308: return $this->_queryStats[$key];
309: }
310: }
311: }
312: return false;
313: }
314: 315: 316: 317: 318: 319:
320: function lastNumRows() {
321: if ($this->hasResult()) {
322: sqlite_num_rows($this->_result);
323: }
324: return false;
325: }
326: 327: 328: 329: 330:
331: function lastInsertId() {
332: return sqlite_last_insert_rowid($this->connection);
333: }
334: 335: 336: 337: 338: 339:
340: function column($real) {
341: if (is_array($real)) {
342: $col = $real['name'];
343: if (isset($real['limit'])) {
344: $col .= '('.$real['limit'].')';
345: }
346: return $col;
347: }
348:
349: $col = strtolower(str_replace(')', '', $real));
350: $limit = null;
351: if (strpos($col, '(') !== false) {
352: list($col, $limit) = explode('(', $col);
353: }
354:
355: if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
356: return $col;
357: }
358: if (strpos($col, 'varchar') !== false) {
359: return 'string';
360: }
361: if (in_array($col, array('blob', 'clob'))) {
362: return 'binary';
363: }
364: if (strpos($col, 'numeric') !== false) {
365: return 'float';
366: }
367: return 'text';
368: }
369: 370: 371: 372: 373:
374: function resultSet(&$results) {
375: $this->results =& $results;
376: $this->map = array();
377: $fieldCount = sqlite_num_fields($results);
378: $index = $j = 0;
379:
380: while ($j < $fieldCount) {
381: $columnName = str_replace('"', '', sqlite_field_name($results, $j));
382:
383: if (strpos($columnName, '.')) {
384: $parts = explode('.', $columnName);
385: $this->map[$index++] = array($parts[0], $parts[1]);
386: } else {
387: $this->map[$index++] = array(0, $columnName);
388: }
389: $j++;
390: }
391: }
392: 393: 394: 395: 396:
397: function fetchResult() {
398: if ($row = sqlite_fetch_array($this->results, SQLITE_ASSOC)) {
399: $resultRow = array();
400: $i = 0;
401:
402: foreach ($row as $index => $field) {
403: if (strpos($index, '.')) {
404: list($table, $column) = explode('.', str_replace('"', '', $index));
405: $resultRow[$table][$column] = $row[$index];
406: } else {
407: $resultRow[0][str_replace('"', '', $index)] = $row[$index];
408: }
409: $i++;
410: }
411: return $resultRow;
412: } else {
413: return false;
414: }
415: }
416: 417: 418: 419: 420: 421: 422:
423: function limit($limit, $offset = null) {
424: if ($limit) {
425: $rt = '';
426: if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
427: $rt = ' LIMIT';
428: }
429: $rt .= ' ' . $limit;
430: if ($offset) {
431: $rt .= ' OFFSET ' . $offset;
432: }
433: return $rt;
434: }
435: return null;
436: }
437: 438: 439: 440: 441: 442: 443:
444: function buildColumn($column) {
445: $name = $type = null;
446: $column = array_merge(array('null' => true), $column);
447: extract($column);
448:
449: if (empty($name) || empty($type)) {
450: trigger_error('Column name or type not defined in schema', E_USER_WARNING);
451: return null;
452: }
453:
454: if (!isset($this->columns[$type])) {
455: trigger_error("Column type {$type} does not exist", E_USER_WARNING);
456: return null;
457: }
458:
459: $real = $this->columns[$type];
460: $out = $this->name($name) . ' ' . $real['name'];
461: if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
462: return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
463: }
464: if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
465: if (isset($column['length'])) {
466: $length = $column['length'];
467: } elseif (isset($column['limit'])) {
468: $length = $column['limit'];
469: } elseif (isset($real['length'])) {
470: $length = $real['length'];
471: } else {
472: $length = $real['limit'];
473: }
474: $out .= '(' . $length . ')';
475: }
476: if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
477: $out .= ' ' . $this->columns['primary_key']['name'];
478: } elseif (isset($column['key']) && $column['key'] == 'primary') {
479: $out .= ' NOT NULL';
480: } elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
481: $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
482: } elseif (isset($column['default'])) {
483: $out .= ' DEFAULT ' . $this->value($column['default'], $type);
484: } elseif (isset($column['null']) && $column['null'] == true) {
485: $out .= ' DEFAULT NULL';
486: } elseif (isset($column['null']) && $column['null'] == false) {
487: $out .= ' NOT NULL';
488: }
489: return $out;
490: }
491: 492: 493: 494: 495:
496: function setEncoding($enc) {
497: if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
498: return false;
499: }
500: return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
501: }
502: 503: 504: 505: 506:
507: function getEncoding() {
508: return $this->fetchRow('PRAGMA encoding');
509: }
510: 511: 512: 513: 514: 515: 516:
517: function buildIndex($indexes, $table = null) {
518: $join = array();
519:
520: foreach ($indexes as $name => $value) {
521:
522: if ($name == 'PRIMARY') {
523: continue;
524: }
525: $out = 'CREATE ';
526:
527: if (!empty($value['unique'])) {
528: $out .= 'UNIQUE ';
529: }
530: if (is_array($value['column'])) {
531: $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
532: } else {
533: $value['column'] = $this->name($value['column']);
534: }
535: $out .= "INDEX {$name} ON {$table}({$value['column']});";
536: $join[] = $out;
537: }
538: return $join;
539: }
540: 541: 542: 543: 544: 545: 546:
547: function index(&$model) {
548: $index = array();
549: $table = $this->fullTableName($model);
550: if ($table) {
551: $indexes = $this->query('PRAGMA index_list(' . $table . ')');
552: $tableInfo = $this->query('PRAGMA table_info(' . $table . ')');
553: foreach ($indexes as $i => $info) {
554: $key = array_pop($info);
555: $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
556: foreach ($keyInfo as $keyCol) {
557: if (!isset($index[$key['name']])) {
558: $col = array();
559: if (preg_match('/autoindex/', $key['name'])) {
560: $key['name'] = 'PRIMARY';
561: }
562: $index[$key['name']]['column'] = $keyCol[0]['name'];
563: $index[$key['name']]['unique'] = intval($key['unique'] == 1);
564: } else {
565: if (!is_array($index[$key['name']]['column'])) {
566: $col[] = $index[$key['name']]['column'];
567: }
568: $col[] = $keyCol[0]['name'];
569: $index[$key['name']]['column'] = $col;
570: }
571: }
572: }
573: }
574: return $index;
575: }
576:
577: 578: 579: 580: 581: 582: 583:
584: function renderStatement($type, $data) {
585: switch (strtolower($type)) {
586: case 'schema':
587: extract($data);
588:
589: foreach (array('columns', 'indexes') as $var) {
590: if (is_array(${$var})) {
591: ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
592: }
593: }
594: return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
595: break;
596: default:
597: return parent::renderStatement($type, $data);
598: break;
599: }
600: }
601: }
602: ?>