📄 dbo_source.php
字号:
<?php/* SVN FILE: $Id: dbo_source.php 7125 2008-06-05 15:06:49Z gwoo $ *//** * Short description for file. * * Long description for file * * PHP versions 4 and 5 * * CakePHP(tm) : Rapid Development Framework <http://www.cakephp.org/> * Copyright 2005-2008, 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 2005-2008, Cake Software Foundation, Inc. * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @package cake * @subpackage cake.cake.libs.model.datasources * @since CakePHP(tm) v 0.10.0.1076 * @version $Revision: 7125 $ * @modifiedby $LastChangedBy: gwoo $ * @lastmodified $Date: 2008-06-05 08:06:49 -0700 (Thu, 05 Jun 2008) $ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */App::import('Core', 'Set');/** * 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";/** * index definition, standard cake, primary, index, unique * * @var array */ var $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');/** * 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 ';/** * Caches fields quoted in DboSource::name() * * @var array */ var $fieldCache = array();/** * Enter description here... * * @var unknown_type */ var $__bypass = false;/** * The set of valid SQL operations usable in a WHERE statement * * @var array */ var $__sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');/** * Index of basic SQL commands * * @var array * @access protected */ var $_commands = array( 'begin' => 'BEGIN', 'commit' => 'COMMIT', 'rollback' => 'ROLLBACK' );/** * Constructor */ function __construct($config = null, $autoConnect = true) { if (!isset($config['prefix'])) { $config['prefix'] = ''; } parent::__construct($config); $this->fullDebug = Configure::read() > 1; if ($autoConnect) { return $this->connect(); } else { return true; } }/** * 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 = array_merge($this->_baseConfig, $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)) { return array_map(array(&$this, 'value'), $data, array_fill(0, count($data), $column)); } elseif (is_object($data)) { if (isset($data->type) && $data->type == 'identifier') { return $this->name($data->value); } } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) { return $data; } else { return null; } }/** * Returns an object to represent a database identifier in a query * * @param string $identifier * @return object An object representing a database identifier to be used in a query */ function identifier($identifier) { $obj = new stdClass(); $obj->type = 'identifier'; $obj->value = $identifier; return $obj; }/** * Returns an object to represent a database expression in a query * * @param string $expression * @return object An object representing a database expression to be used in a query */ function expression($expression) { $obj = new stdClass(); $obj->type = 'expression'; $obj->value = $expression; return $obj; }/** * 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 mixed Resource or object representing the result set, or false on failure */ function execute($sql) { $t = getMicrotime(); $this->_result = $this->_execute($sql); $this->took = round((getMicrotime() - $t) * 1000, 0); $this->affected = $this->lastAffected(); $this->error = $this->lastError(); $this->numRows = $this->lastNumRows(); if (Configure::read() > 1) { $this->logQuery($sql); } if ($this->error) { $this->showQuery($sql); return false; } else { return $this->_result; } }/** * DataSource 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(strtolower($args[0]), 'findby') === 0 || strpos(strtolower($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]; } if (!array_key_exists(0, $params)) { return false; } $c = 0; $query = array(); foreach ($field as $f) { $query[$args[2]->alias . '.' . $f] = $params[$c]; $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 { if (isset($args[1]) && $args[1] === true) { return $this->fetchAll($args[0], true); } else if (isset($args[1]) && !is_array($args[1]) ) { return $this->fetchAll($args[0], false); } else if (isset($args[1]) && is_array($args[1])) { $offset = 0; if (isset($args[2])) { $cache = $args[2]; } else { $cache = true; } $args[1] = array_map(array(&$this, 'value'), $args[1]); return $this->fetchAll(String::insert($args[0], $args[1]), $cache); } } }/** * Returns a row from current resultset as an array * * @return array The fetched row as an array */ function fetchRow($sql = null) { if (!empty($sql) && is_string($sql) && strlen($sql) > 5) { if (!$this->execute($sql)) { return null; } } if (is_resource($this->_result) || is_object($this->_result)) { $this->resultSet($this->_result); $resultRow = $this->fetchResult(); return $resultRow; } else { return null; } }/** * 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 (preg_match('/^\s*select/i', $sql)) { return $this->_queryCache[$sql]; } } if ($this->execute($sql)) { $out = array(); while ($item = $this->fetchRow()) { $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->fetchRow($sql); if (!isset($data[$name]) || empty($data[$name])) { return false; } else { return $data[$name]; } }/** * Returns a quoted name of $data for use in an SQL statement. * Strips fields out of SQL functions before quoting. * * @param string $data * @return string SQL field */ function name($data) { if ($data == '*') { return '*'; } $array = is_array($data); $data = (array)$data; $count = count($data); for($i = 0; $i < $count; $i++) { if ($data[$i] == '*') { continue; } if (strpos($data[$i], '(') !== false && preg_match_all('/([^(]*)\((.*)\)(.*)/', $data[$i], $fields)) { $fields = Set::extract($fields, '{n}.0'); if (!empty($fields[1])) { if (!empty($fields[2])) { $data[$i] = $fields[1] . '(' . $this->name($fields[2]) . ')' . $fields[3]; } else { $data[$i] = $fields[1] . '()' . $fields[3]; } } } $data[$i] = $this->startQuote . str_replace('.', $this->endQuote . '.' . $this->startQuote, $data[$i]) . $this->endQuote; $data[$i] = str_replace($this->startQuote . $this->startQuote, $this->startQuote, $data[$i]); if (strpos($data[$i], ' AS ')) { $data[$i] = str_replace(' AS ', $this->endQuote . ' AS ' . $this->startQuote, $data[$i]); } if (!empty($this->endQuote) && $this->endQuote == $this->startQuote) { if (substr_count($data[$i], $this->endQuote) % 2 == 1) { $data[$i] = trim($data[$i], $this->endQuote); } } if (strpos($data[$i], '*')) { $data[$i] = str_replace($this->endQuote . '*' . $this->endQuote, '*', $data[$i]); } $data[$i] = str_replace($this->endQuote . $this->endQuote, $this->endQuote, $data[$i]); } if (!$array) { return $data[0]; } return $data; }/** * 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);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -