📄 dbo_source.php.svn-base
字号:
<?php/* SVN FILE: $Id: dbo_source.php 4202 2006-12-25 12:06:13Z phpnut $ *//** * Short description for file. * * Long description for file * * PHP versions 4 and 5 * * CakePHP : Rapid Development Framework <http://www.cakephp.org/> * Copyright (c) 2006, Cake Software Foundation, Inc. * 1785 E. Sahara Avenue, Suite 490-204 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2006, Cake Software Foundation, Inc. * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project * @package cake * @subpackage cake.cake.libs.model.datasources * @since CakePHP v 0.10.0.1076 * @version $Revision: 4202 $ * @modifiedby $LastChangedBy: phpnut $ * @lastmodified $Date: 2006-12-25 06:06:13 -0600 (Mon, 25 Dec 2006) $ * @license http://www.opensource.org/licenses/mit-license.php The MIT License *//** * DboSource * * Creates DBO-descendant objects from a given db connection configuration * * @package cake * @subpackage cake.cake.libs.model.datasources */class DboSource extends DataSource {/** * Description string for this Database Data Source. * * @var unknown_type */ var $description = "Database Data Source";/** * Enter description here... * * @var unknown_type */ var $__bypass = false;/** * Enter description here... * * @var array */ var $__assocJoins = null;/** * Enter description here... * * @var unknown_type */ var $startQuote = null;/** * Enter description here... * * @var unknown_type */ var $endQuote = null;/** * Enter description here... * * @var unknown_type */ var $alias = 'AS ';/** * Enter description here... * * @var unknown_type */ var $goofyLimit = false;/** * Constructor */ function __construct($config = null) { $this->debug = Configure::read() > 0; $this->fullDebug = Configure::read() > 1; parent::__construct($config); return $this->connect(); }/** * Reconnects to database server with optional new settings * * @param array $config An array defining the new configuration settings * @return boolean True on success, false on failure */ function reconnect($config = null) { $this->disconnect(); if ($config != null) { $this->config = am($this->_baseConfig, $this->config, $config); } return $this->connect(); }/** * Prepares a value, or an array of values for database queries by quoting and escaping them. * * @param mixed $data A value or an array of values to prepare. * @return mixed Prepared value or array of values. */ function value($data, $column = null) { if (is_array($data)) { $out = array(); $keys = array_keys($data); $count = count($data); for($i = 0; $i < $count; $i++) { $out[$keys[$i]] = $this->value($data[$keys[$i]]); } return $out; } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'))) { return $data; } else { return null; } }/** * Caches/returns cached results for child instances * * @return array */ function listSources($data = null) { if ($this->__sources != null) { return $this->__sources; } if (Configure::read() > 0) { $expires = "+30 seconds"; } else { $expires = "+999 days"; } if ($data != null) { $data = serialize($data); } $filename = ConnectionManager::getSourceName($this) . '_' . $this->config['database'] . '_list'; $new = cache('models' . DS . $filename, $data, $expires); if ($new != null) { $new = unserialize($new); $this->__sources = $new; } return $new; }/** * Convenience method for DboSource::listSources(). * * @return array */ function sources() { $return = array_map('strtolower', $this->listSources()); return $return; }/** * SQL Query abstraction * * @return resource Result resource identifier */ function query() { $args = func_get_args(); $fields = null; $order = null; $limit = null; $page = null; $recursive = null; if (count($args) == 1) { return $this->fetchAll($args[0]); } elseif (count($args) > 1 && (strpos(low($args[0]), 'findby') === 0 || strpos(low($args[0]), 'findallby') === 0)) { $params = $args[1]; if (strpos(strtolower($args[0]), 'findby') === 0) { $all = false; $field = Inflector::underscore(preg_replace('/findBy/i', '', $args[0])); } else { $all = true; $field = Inflector::underscore(preg_replace('/findAllBy/i', '', $args[0])); } $or = (strpos($field, '_or_') !== false); if ($or) { $field = explode('_or_', $field); } else { $field = explode('_and_', $field); } $off = count($field) - 1; if (isset($params[1 + $off])) { $fields = $params[1 + $off]; } if (isset($params[2 + $off])) { $order = $params[2 + $off]; } $c = 0; $query = array(); foreach ($field as $f) { $query[$args[2]->name . '.' . $f] = '= ' . $params[$c++]; } if ($or) { $query = array('OR' => $query); } if ($all) { if (isset($params[3 + $off])) { $limit = $params[3 + $off]; } if (isset($params[4 + $off])) { $page = $params[4 + $off]; } if (isset($params[5 + $off])) { $recursive = $params[5 + $off]; } return $args[2]->findAll($query, $fields, $order, $limit, $page, $recursive); } else { if (isset($params[3 + $off])) { $recursive = $params[3 + $off]; } return $args[2]->find($query, $fields, $order, $recursive); } } else { return $this->fetchAll($args[0], false); } }/** * Executes given SQL statement. * * @param string $sql SQL statement * @return unknown */ function rawQuery($sql) { $this->took = $this->error = $this->numRows = false; return $this->execute($sql); }/** * Queries the database with given SQL statement, and obtains some metadata about the result * (rows affected, timing, any errors, number of rows in resultset). The query is also logged. * If DEBUG is set, the log is shown all the time, else it is only shown on errors. * * @param string $sql * @return unknown */ function execute($sql) { $t = getMicrotime(); $this->_result = $this->_execute($sql); $this->affected = $this->lastAffected(); $this->took = round((getMicrotime() - $t) * 1000, 0); $this->error = $this->lastError(); $this->numRows = $this->lastNumRows($this->_result); if($this->fullDebug) { $this->logQuery($sql); } if ($this->error) { return false; } else { return $this->_result; } }/** * Returns a row from given resultset as an array . * * @param bool $assoc Associative array only, or both? * @return array The fetched row as an array */ function fetchRow($assoc = false) { if (is_resource($this->_result)) { $this->resultSet($this->_result); $resultRow = $this->fetchResult(); return $resultRow; } else { return null; } }/** * Returns a single row of results from the _last_ SQL query. * * @param resource $res * @return array A single row of results */ function fetchArray($assoc = false) { if ($assoc === false) { return $this->fetchRow(); } else { return $this->fetchRow($assoc); } }/** * Returns a single row of results for a _given_ SQL query. * * @param string $sql SQL statement * @return array A single row of results */ function one($sql) { if ($this->execute($sql)) { return $this->fetchArray(); } return false; }/** * Returns an array of all result rows for a given SQL query. * Returns false if no rows matched. * * @param string $sql SQL statement * @param boolean $cache Enables returning/storing cached query results * @return array Array of resultset rows, or false if no rows matched */ function fetchAll($sql, $cache = true, $modelName = null) { if ($cache && isset($this->_queryCache[$sql])) { if (strpos(trim(strtolower($sql)), 'select') !== false) { return $this->_queryCache[$sql]; } } if ($this->execute($sql)) { $out = array(); while($item = $this->fetchArray(true)) { $out[] = $item; } if ($cache) { if (strpos(trim(strtolower($sql)), 'select') !== false) { $this->_queryCache[$sql] = $out; } } return $out; } else { return false; } }/** * Returns a single field of the first of query results for a given SQL query, or false if empty. * * @param string $name Name of the field * @param string $sql SQL query * @return unknown */ function field($name, $sql) { $data = $this->one($sql); if (empty($data[$name])) { return false; } else { return $data[$name]; } }/** * Checks if it's connected to the database * * @return boolean True if the database is connected, else false */ function isConnected() { return $this->connected; }/** * Outputs the contents of the queries log. * * @param boolean $sorted */ function showLog($sorted = false) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } if ($this->_queriesCnt > 1) { $text = 'queries'; } else { $text = 'query'; } if (php_sapi_name() != 'cli') { print ("<table id=\"cakeSqlLog\" cellspacing=\"0\" border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n"); print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n"); foreach($log as $k => $i) { print ("<tr><td>" . ($k + 1) . "</td><td>{$i['query']}</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n"); } print ("</table>\n"); } else { foreach($log as $k => $i) { print (($k + 1) . ". {$i['query']} {$i['error']}\n"); } } }/** * Log given SQL query. * * @param string $sql SQL statement * @todo: Add hook to log errors instead of returning false */ function logQuery($sql) { $this->_queriesCnt++; $this->_queriesTime += $this->took; $this->_queriesLog[] = array('query' => $sql, 'error' => $this->error, 'affected' => $this->affected, 'numRows' => $this->numRows, 'took' => $this->took ); if (count($this->_queriesLog) > $this->_queriesLogMax) { array_pop($this->_queriesLog); } if ($this->error) { return false; } }/** * Output information about an SQL query. The SQL statement, number of rows in resultset, * and execution time in microseconds. If the query fails, an error is output instead. * * @param string $sql Query to show information on. */ function showQuery($sql) { $error = $this->error; if (strlen($sql) > 200 && !$this->fullDebug) { $sql = substr($sql, 0, 200) . '[...]'; } if ($this->debug || $error) { print ("<p style = \"text-align:left\"><b>Query:</b> {$sql} <small>[Aff:{$this->affected} Num:{$this->numRows} Took:{$this->took}ms]</small>"); if ($error) { print ("<br /><span style = \"color:Red;text-align:left\"><b>ERROR:</b> {$this->error}</span>"); } print ('</p>'); } }/** * Gets full table name including prefix * * @param mixed $model * @param boolean $quote * @return string Full quoted table name */ function fullTableName($model, $quote = true) { if (is_object($model)) { $table = $model->table; if ($model->tablePrefix != null && !empty($model->tablePrefix)) { $table = $model->tablePrefix . $table; } } elseif (isset($this->config['prefix'])) { $table = $this->config['prefix'] . strval($model); } else { $table = strval($model); } if ($quote) { return $this->name($table); } return $table; }/** * The "C" in CRUD * * @param Model $model * @param array $fields * @param array $values * @return boolean Success */ function create(&$model, $fields = null, $values = null) { $fieldInsert = array(); $valueInsert = array(); if ($fields == null) { unset($fields, $values); $fields = array_keys($model->data); $values = array_values($model->data); } $count = count($fields); for ($i = 0; $i < $count; $i++) { $fieldInsert[] = $this->name($fields[$i]); } $count = count($values); for ($i = 0; $i < $count; $i++) { $set = $this->value($values[$i], $model->getColumnType($fields[$i])); if ($set === "''") { unset ($fieldInsert[$i]); } else { $valueInsert[] = $set; } } if ($this->execute('INSERT INTO ' . $this->fullTableName($model) . ' (' . join(',', $fieldInsert). ') VALUES (' . join(',', $valueInsert) . ')')) { return true; } return false; }/** * The "R" in CRUD * * @param Model $model * @param array $queryData * @param integer $recursive Number of levels of association * @return unknown */ function read(&$model, $queryData = array(), $recursive = null) { $this->__scrubQueryData($queryData); $null = null; $array = array(); $linkedModels = array(); $this->__bypass = false; $this->__assocJoins = null; if (!is_null($recursive)) { $_recursive = $model->recursive; $model->recursive = $recursive; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -