00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035 class DboSqlite extends DboSource {
00036
00037
00038
00039
00040
00041 var $description = "SQLite DBO Driver";
00042
00043
00044
00045
00046
00047 var $startQuote = '"';
00048
00049
00050
00051
00052
00053 var $endQuote = '"';
00054
00055
00056
00057
00058
00059
00060 var $_queryStats = array();
00061
00062
00063
00064
00065
00066 var $_baseConfig = array(
00067 'persistent' => true,
00068 'database' => null,
00069 'connect' => 'sqlite_popen'
00070 );
00071
00072
00073
00074
00075
00076
00077 var $_commands = array(
00078 'begin' => 'BEGIN TRANSACTION',
00079 'commit' => 'COMMIT TRANSACTION',
00080 'rollback' => 'ROLLBACK TRANSACTION'
00081 );
00082
00083
00084
00085
00086
00087 var $columns = array(
00088 'primary_key' => array('name' => 'integer primary key'),
00089 'string' => array('name' => 'varchar', 'limit' => '255'),
00090 'text' => array('name' => 'text'),
00091 'integer' => array('name' => 'integer', 'limit' => 11, 'formatter' => 'intval'),
00092 'float' => array('name' => 'float', 'formatter' => 'floatval'),
00093 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00094 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00095 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
00096 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
00097 'binary' => array('name' => 'blob'),
00098 'boolean' => array('name' => 'boolean')
00099 );
00100
00101
00102
00103
00104
00105
00106 function connect() {
00107 $config = $this->config;
00108 $this->connection = $config['connect']($config['database']);
00109 $this->connected = is_resource($this->connection);
00110
00111 if ($this->connected) {
00112 $this->_execute('PRAGMA count_changes = 1;');
00113 }
00114 return $this->connected;
00115 }
00116
00117
00118
00119
00120
00121 function disconnect() {
00122 @sqlite_close($this->connection);
00123 $this->connected = false;
00124 return $this->connected;
00125 }
00126
00127
00128
00129
00130
00131
00132 function _execute($sql) {
00133 $result = sqlite_query($this->connection, $sql);
00134
00135 if (preg_match('/^(INSERT|UPDATE|DELETE)/', $sql)) {
00136 $this->resultSet($result);
00137 list($this->_queryStats) = $this->fetchResult();
00138 }
00139 return $result;
00140 }
00141
00142
00143
00144
00145
00146
00147 function execute($sql) {
00148 $result = parent::execute($sql);
00149 $this->_queryStats = array();
00150 return $result;
00151 }
00152
00153
00154
00155
00156
00157 function listSources() {
00158 $cache = parent::listSources();
00159
00160 if ($cache != null) {
00161 return $cache;
00162 }
00163 $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
00164
00165 if (empty($result)) {
00166 return array();
00167 } else {
00168 $tables = array();
00169 foreach ($result as $table) {
00170 $tables[] = $table[0]['name'];
00171 }
00172 parent::listSources($tables);
00173 return $tables;
00174 }
00175 return array();
00176 }
00177
00178
00179
00180
00181
00182
00183 function describe(&$model) {
00184 $cache = parent::describe($model);
00185 if ($cache != null) {
00186 return $cache;
00187 }
00188 $fields = array();
00189 $result = $this->fetchAll('PRAGMA table_info(' . $this->fullTableName($model) . ')');
00190
00191 foreach ($result as $column) {
00192 $fields[$column[0]['name']] = array(
00193 'type' => $this->column($column[0]['type']),
00194 'null' => !$column[0]['notnull'],
00195 'default' => $column[0]['dflt_value'],
00196 'length' => $this->length($column[0]['type'])
00197 );
00198 if ($column[0]['pk'] == 1) {
00199 $colLength = $this->length($column[0]['type']);
00200 $fields[$column[0]['name']] = array(
00201 'type' => $fields[$column[0]['name']]['type'],
00202 'null' => false,
00203 'default' => $column[0]['dflt_value'],
00204 'key' => $this->index['PRI'],
00205 'length'=> ($colLength != null) ? $colLength : 11
00206 );
00207 }
00208 }
00209
00210 $this->__cacheDescription($model->tablePrefix . $model->table, $fields);
00211 return $fields;
00212 }
00213
00214
00215
00216
00217
00218
00219 function value($data, $column = null, $safe = false) {
00220 $parent = parent::value($data, $column, $safe);
00221
00222 if ($parent != null) {
00223 return $parent;
00224 }
00225 if ($data === null) {
00226 return 'NULL';
00227 }
00228 if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
00229 return "''";
00230 }
00231 switch ($column) {
00232 case 'boolean':
00233 $data = $this->boolean((bool)$data);
00234 break;
00235 case 'integer':
00236 case 'float':
00237 if ($data === '') {
00238 return 'NULL';
00239 }
00240 default:
00241 $data = sqlite_escape_string($data);
00242 break;
00243 }
00244 return "'" . $data . "'";
00245 }
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255 function update(&$model, $fields = array(), $values = null, $conditions = null) {
00256 if (empty($values) && !empty($fields)) {
00257 foreach ($fields as $field => $value) {
00258 if (strpos($field, $model->alias . '.') !== false) {
00259 unset($fields[$field]);
00260 $field = str_replace($model->alias . '.', "", $field);
00261 $field = str_replace($model->alias . '.', "", $field);
00262 $fields[$field] = $value;
00263 }
00264 }
00265 }
00266 $result = parent::update($model, $fields, $values, $conditions);
00267 return $result;
00268 }
00269
00270
00271
00272
00273
00274
00275
00276
00277 function truncate($table) {
00278 return $this->execute('DELETE From ' . $this->fullTableName($table));
00279 }
00280
00281
00282
00283
00284
00285 function lastError() {
00286 $error = sqlite_last_error($this->connection);
00287 if ($error) {
00288 return $error.': '.sqlite_error_string($error);
00289 }
00290 return null;
00291 }
00292
00293
00294
00295
00296
00297 function lastAffected() {
00298 if (!empty($this->_queryStats)) {
00299 foreach (array('rows inserted', 'rows updated', 'rows deleted') as $key) {
00300 if (array_key_exists($key, $this->_queryStats)) {
00301 return $this->_queryStats[$key];
00302 }
00303 }
00304 }
00305 return false;
00306 }
00307
00308
00309
00310
00311
00312
00313 function lastNumRows() {
00314 if ($this->hasResult()) {
00315 sqlite_num_rows($this->_result);
00316 }
00317 return false;
00318 }
00319
00320
00321
00322
00323
00324 function lastInsertId() {
00325 return sqlite_last_insert_rowid($this->connection);
00326 }
00327
00328
00329
00330
00331
00332
00333 function column($real) {
00334 if (is_array($real)) {
00335 $col = $real['name'];
00336 if (isset($real['limit'])) {
00337 $col .= '('.$real['limit'].')';
00338 }
00339 return $col;
00340 }
00341
00342 $col = strtolower(str_replace(')', '', $real));
00343 $limit = null;
00344 if (strpos($col, '(') !== false) {
00345 list($col, $limit) = explode('(', $col);
00346 }
00347
00348 if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
00349 return $col;
00350 }
00351 if (strpos($col, 'varchar') !== false) {
00352 return 'string';
00353 }
00354 if (in_array($col, array('blob', 'clob'))) {
00355 return 'binary';
00356 }
00357 if (strpos($col, 'numeric') !== false) {
00358 return 'float';
00359 }
00360 return 'text';
00361 }
00362
00363
00364
00365
00366
00367 function resultSet(&$results) {
00368 $this->results =& $results;
00369 $this->map = array();
00370 $fieldCount = sqlite_num_fields($results);
00371 $index = $j = 0;
00372
00373 while ($j < $fieldCount) {
00374 $columnName = str_replace('"', '', sqlite_field_name($results, $j));
00375
00376 if (strpos($columnName, '.')) {
00377 $parts = explode('.', $columnName);
00378 $this->map[$index++] = array($parts[0], $parts[1]);
00379 } else {
00380 $this->map[$index++] = array(0, $columnName);
00381 }
00382 $j++;
00383 }
00384 }
00385
00386
00387
00388
00389
00390 function fetchResult() {
00391 if ($row = sqlite_fetch_array($this->results, SQLITE_ASSOC)) {
00392 $resultRow = array();
00393 $i = 0;
00394
00395 foreach ($row as $index => $field) {
00396 if (strpos($index, '.')) {
00397 list($table, $column) = explode('.', str_replace('"', '', $index));
00398 $resultRow[$table][$column] = $row[$index];
00399 } else {
00400 $resultRow[0][str_replace('"', '', $index)] = $row[$index];
00401 }
00402 $i++;
00403 }
00404 return $resultRow;
00405 } else {
00406 return false;
00407 }
00408 }
00409
00410
00411
00412
00413
00414
00415
00416 function limit($limit, $offset = null) {
00417 if ($limit) {
00418 $rt = '';
00419 if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
00420 $rt = ' LIMIT';
00421 }
00422 $rt .= ' ' . $limit;
00423 if ($offset) {
00424 $rt .= ' OFFSET ' . $offset;
00425 }
00426 return $rt;
00427 }
00428 return null;
00429 }
00430
00431
00432
00433
00434
00435
00436
00437 function buildColumn($column) {
00438 $name = $type = null;
00439 $column = array_merge(array('null' => true), $column);
00440 extract($column);
00441
00442 if (empty($name) || empty($type)) {
00443 trigger_error('Column name or type not defined in schema', E_USER_WARNING);
00444 return null;
00445 }
00446
00447 if (!isset($this->columns[$type])) {
00448 trigger_error("Column type {$type} does not exist", E_USER_WARNING);
00449 return null;
00450 }
00451
00452 $real = $this->columns[$type];
00453 $out = $this->name($name) . ' ' . $real['name'];
00454 if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
00455 return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
00456 }
00457 if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
00458 if (isset($column['length'])) {
00459 $length = $column['length'];
00460 } elseif (isset($column['limit'])) {
00461 $length = $column['limit'];
00462 } elseif (isset($real['length'])) {
00463 $length = $real['length'];
00464 } else {
00465 $length = $real['limit'];
00466 }
00467 $out .= '(' . $length . ')';
00468 }
00469 if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
00470 $out .= ' ' . $this->columns['primary_key']['name'];
00471 } elseif (isset($column['key']) && $column['key'] == 'primary') {
00472 $out .= ' NOT NULL';
00473 } elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
00474 $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
00475 } elseif (isset($column['default'])) {
00476 $out .= ' DEFAULT ' . $this->value($column['default'], $type);
00477 } elseif (isset($column['null']) && $column['null'] == true) {
00478 $out .= ' DEFAULT NULL';
00479 } elseif (isset($column['null']) && $column['null'] == false) {
00480 $out .= ' NOT NULL';
00481 }
00482 return $out;
00483 }
00484
00485
00486
00487
00488
00489 function setEncoding($enc) {
00490 if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
00491 return false;
00492 }
00493 return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
00494 }
00495
00496
00497
00498
00499
00500 function getEncoding() {
00501 return $this->fetchRow('PRAGMA encoding');
00502 }
00503
00504
00505
00506
00507
00508
00509
00510 function buildIndex($indexes, $table = null) {
00511 $join = array();
00512
00513 foreach ($indexes as $name => $value) {
00514
00515 if ($name == 'PRIMARY') {
00516 continue;
00517 }
00518 $out = 'CREATE ';
00519
00520 if (!empty($value['unique'])) {
00521 $out .= 'UNIQUE ';
00522 }
00523 if (is_array($value['column'])) {
00524 $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
00525 } else {
00526 $value['column'] = $this->name($value['column']);
00527 }
00528 $out .= "INDEX {$name} ON {$table}({$value['column']});";
00529 $join[] = $out;
00530 }
00531 return $join;
00532 }
00533
00534
00535
00536
00537
00538
00539
00540 function index(&$model) {
00541 $index = array();
00542 $table = $this->fullTableName($model);
00543 if ($table) {
00544 $indexes = $this->query('PRAGMA index_list(' . $table . ')');
00545 $tableInfo = $this->query('PRAGMA table_info(' . $table . ')');
00546 foreach ($indexes as $i => $info) {
00547 $key = array_pop($info);
00548 $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
00549 foreach ($keyInfo as $keyCol) {
00550 if (!isset($index[$key['name']])) {
00551 $col = array();
00552 if (preg_match('/autoindex/', $key['name'])) {
00553 $key['name'] = 'PRIMARY';
00554 }
00555 $index[$key['name']]['column'] = $keyCol[0]['name'];
00556 $index[$key['name']]['unique'] = intval($key['unique'] == 1);
00557 } else {
00558 if (!is_array($index[$key['name']]['column'])) {
00559 $col[] = $index[$key['name']]['column'];
00560 }
00561 $col[] = $keyCol[0]['name'];
00562 $index[$key['name']]['column'] = $col;
00563 }
00564 }
00565 }
00566 }
00567 return $index;
00568 }
00569
00570
00571
00572
00573
00574
00575
00576
00577 function renderStatement($type, $data) {
00578 switch (strtolower($type)) {
00579 case 'schema':
00580 extract($data);
00581
00582 foreach (array('columns', 'indexes') as $var) {
00583 if (is_array(${$var})) {
00584 ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
00585 }
00586 }
00587 return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
00588 break;
00589 default:
00590 return parent::renderStatement($type, $data);
00591 break;
00592 }
00593 }
00594 }
00595 ?>