dbo_sqlite.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: dbo_sqlite.php 8184 2009-06-02 03:03:51Z mark_story $ */
00003 /**
00004  * SQLite layer for DBO
00005  *
00006  * Long description for file
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
00011  * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00012  *
00013  * Licensed under The MIT License
00014  * Redistributions of files must retain the above copyright notice.
00015  *
00016  * @filesource
00017  * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00018  * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00019  * @package       cake
00020  * @subpackage    cake.cake.libs.model.datasources.dbo
00021  * @since         CakePHP(tm) v 0.9.0
00022  * @version       $Revision: 8184 $
00023  * @modifiedby    $LastChangedBy: mark_story $
00024  * @lastmodified  $Date: 2009-06-01 23:03:51 -0400 (Mon, 01 Jun 2009) $
00025  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
00026  */
00027 /**
00028  * DBO implementation for the SQLite DBMS.
00029  *
00030  * Long description for class
00031  *
00032  * @package       cake
00033  * @subpackage    cake.cake.libs.model.datasources.dbo
00034  */
00035 class DboSqlite extends DboSource {
00036 /**
00037  * Enter description here...
00038  *
00039  * @var unknown_type
00040  */
00041     var $description = "SQLite DBO Driver";
00042 /**
00043  * Opening quote for quoted identifiers
00044  *
00045  * @var string
00046  */
00047     var $startQuote = '"';
00048 /**
00049  * Closing quote for quoted identifiers
00050  *
00051  * @var string
00052  */
00053     var $endQuote = '"';
00054 /**
00055  * Keeps the transaction statistics of CREATE/UPDATE/DELETE queries
00056  *
00057  * @var array
00058  * @access protected
00059  */
00060     var $_queryStats = array();
00061 /**
00062  * Base configuration settings for SQLite driver
00063  *
00064  * @var array
00065  */
00066     var $_baseConfig = array(
00067         'persistent' => true,
00068         'database' => null,
00069         'connect' => 'sqlite_popen'
00070     );
00071 /**
00072  * Index of basic SQL commands
00073  *
00074  * @var array
00075  * @access protected
00076  */
00077     var $_commands = array(
00078         'begin'    => 'BEGIN TRANSACTION',
00079         'commit'   => 'COMMIT TRANSACTION',
00080         'rollback' => 'ROLLBACK TRANSACTION'
00081     );
00082 /**
00083  * SQLite column definition
00084  *
00085  * @var array
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  * Connects to the database using config['database'] as a filename.
00102  *
00103  * @param array $config Configuration array for connecting
00104  * @return mixed
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  * Disconnects from database.
00118  *
00119  * @return boolean True if the database could be disconnected, else false
00120  */
00121     function disconnect() {
00122         @sqlite_close($this->connection);
00123         $this->connected = false;
00124         return $this->connected;
00125     }
00126 /**
00127  * Executes given SQL statement.
00128  *
00129  * @param string $sql SQL statement
00130  * @return resource Result resource identifier
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  * Overrides DboSource::execute() to correctly handle query statistics
00143  *
00144  * @param string $sql
00145  * @return unknown
00146  */
00147     function execute($sql) {
00148         $result = parent::execute($sql);
00149         $this->_queryStats = array();
00150         return $result;
00151     }
00152 /**
00153  * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
00154  *
00155  * @return array Array of tablenames in the database
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  * Returns an array of the fields in given table name.
00179  *
00180  * @param string $tableName Name of database table to inspect
00181  * @return array Fields in table. Keys are name and type
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  * Returns a quoted and escaped string of $data for use in an SQL statement.
00215  *
00216  * @param string $data String to be prepared for use in an SQL statement
00217  * @return string Quoted and escaped
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  * Generates and executes an SQL UPDATE statement for given model, fields, and values.
00248  *
00249  * @param Model $model
00250  * @param array $fields
00251  * @param array $values
00252  * @param mixed $conditions
00253  * @return array
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  * Deletes all the records in a table and resets the count of the auto-incrementing
00271  * primary key, where applicable.
00272  *
00273  * @param mixed $table A string or model class representing the table to be truncated
00274  * @return boolean  SQL TRUNCATE TABLE statement, false if not applicable.
00275  * @access public
00276  */
00277     function truncate($table) {
00278         return $this->execute('DELETE From ' . $this->fullTableName($table));
00279     }
00280 /**
00281  * Returns a formatted error message from previous database operation.
00282  *
00283  * @return string Error message
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  * Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
00294  *
00295  * @return integer Number of affected rows
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  * Returns number of rows in previous resultset. If no previous resultset exists,
00309  * this returns false.
00310  *
00311  * @return integer Number of rows in resultset
00312  */
00313     function lastNumRows() {
00314         if ($this->hasResult()) {
00315             sqlite_num_rows($this->_result);
00316         }
00317         return false;
00318     }
00319 /**
00320  * Returns the ID generated from the previous INSERT operation.
00321  *
00322  * @return int
00323  */
00324     function lastInsertId() {
00325         return sqlite_last_insert_rowid($this->connection);
00326     }
00327 /**
00328  * Converts database-layer column types to basic types
00329  *
00330  * @param string $real Real database-layer column type (i.e. "varchar(255)")
00331  * @return string Abstract column type (i.e. "string")
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  * Enter description here...
00364  *
00365  * @param unknown_type $results
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  * Fetches the next row from the current result set
00387  *
00388  * @return unknown
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  * Returns a limit statement in the correct format for the particular database.
00411  *
00412  * @param integer $limit Limit of results returned
00413  * @param integer $offset Offset from which to start results
00414  * @return string SQL limit/offset statement
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  * Generate a database-native column schema string
00432  *
00433  * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
00434  *                      where options can be 'default', 'length', or 'key'.
00435  * @return string
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  * Sets the database encoding
00486  *
00487  * @param string $enc Database encoding
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  * Gets the database encoding
00497  *
00498  * @return string The database encoding
00499  */
00500     function getEncoding() {
00501         return $this->fetchRow('PRAGMA encoding');
00502     }
00503 /**
00504  * Removes redundant primary key indexes, as they are handled in the column def of the key.
00505  *
00506  * @param array $indexes
00507  * @param string $table
00508  * @return string
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  * Overrides DboSource::index to handle SQLite indexe introspection
00535  * Returns an array of the indexes in given table name.
00536  *
00537  * @param string $model Name of model to inspect
00538  * @return array Fields in table. Keys are column and unique
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  * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
00572  *
00573  * @param string $type
00574  * @param array $data
00575  * @return string
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 ?>

Generated on Sun Nov 22 00:30:53 2009 for CakePHP 1.2.x.x (v1.2.4.8284) by doxygen 1.4.7