Database should work now. I have introduced some semi-singelton magic in dbo. DboFactory is no longer needed. This is not tested properly, and tests will most likely fail! Follow up soon.

git-svn-id: https://svn.cakephp.org/repo/trunk/cake@274 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
brego 2005-06-23 13:59:02 +00:00
parent 9206b074d3
commit ba139f10bb
5 changed files with 1309 additions and 1212 deletions

View file

@ -19,27 +19,23 @@
* Database configuration class.
* You can specify multiple configurations for production, development and testing.
*/
class DATABASE_CONFIG {
function devel () {
return array(
class DATABASE_CONFIG
{
var $default = array(
'driver' => 'mysql',
'host' => 'localhost',
'login' => 'www',
'password' => '',
'database' => 'project_name'
);
}
function test () {
return array(
var $test = array(
'driver' => 'mysql',
'host' => 'localhost',
'login' => 'www-test',
'password' => '',
'database' => 'project_name-test'
);
}
}
?>

View file

@ -117,14 +117,19 @@ class Controller extends Template
$model_class = Inflector::singularize($this->name);
if (class_exists($model_class) && $this->db && ($this->uses === false))
//Is this needed?
$this->db = DBO::getInstance();
if (class_exists($model_class) && ($this->uses === false))
{
$this->$model_class = new $model_class ();
$this->$model_class = new $model_class();
}
elseif ($this->uses)
{
if (!$this->db)
{
die("Controller::__construct() : ".$this->name." controller needs database access, exiting.");
}
$uses = is_array($this->uses)? $this->uses: array($this->uses);

View file

@ -72,15 +72,14 @@ uses('object');
/**
* Enter description here...
*
*
* @package cake
* @subpackage cake.libs
* @since Cake v 0.2.9
*
*/
class DBO extends Object {
class DBO extends Object
{
/**
/**
* Are we connected to the database?
*
* @var boolean
@ -88,7 +87,7 @@ class DBO extends Object {
*/
var $connected=FALSE;
/**
/**
* Connection configuration.
*
* @var array
@ -96,7 +95,7 @@ class DBO extends Object {
*/
var $config=FALSE;
/**
/**
* Enter description here...
*
* @var boolean
@ -104,7 +103,7 @@ class DBO extends Object {
*/
var $debug=FALSE;
/**
/**
* Enter description here...
*
* @var boolean
@ -112,7 +111,7 @@ class DBO extends Object {
*/
var $fullDebug=FALSE;
/**
/**
* Enter description here...
*
* @var unknown_type
@ -120,7 +119,7 @@ class DBO extends Object {
*/
var $error=NULL;
/**
/**
* String to hold how many rows were affected by the last SQL operation.
*
* @var unknown_type
@ -128,7 +127,7 @@ class DBO extends Object {
*/
var $affected=NULL;
/**
/**
* Number of rows in current resultset
*
* @var int
@ -136,7 +135,7 @@ class DBO extends Object {
*/
var $numRows=NULL;
/**
/**
* Time the last query took
*
* @var unknown_type
@ -144,7 +143,7 @@ class DBO extends Object {
*/
var $took=NULL;
/**
/**
* Enter description here...
*
* @var unknown_type
@ -152,7 +151,7 @@ class DBO extends Object {
*/
var $_conn=NULL;
/**
/**
* Enter description here...
*
* @var unknown_type
@ -160,7 +159,7 @@ class DBO extends Object {
*/
var $_result=NULL;
/**
/**
* Queries count.
*
* @var unknown_type
@ -168,7 +167,7 @@ class DBO extends Object {
*/
var $_queriesCnt=0;
/**
/**
* Total duration of all queries.
*
* @var unknown_type
@ -176,7 +175,7 @@ class DBO extends Object {
*/
var $_queriesTime=NULL;
/**
/**
* Enter description here...
*
* @var unknown_type
@ -184,7 +183,7 @@ class DBO extends Object {
*/
var $_queriesLog=array();
/**
/**
* Maximum number of items in query log, to prevent query log taking over
* too much memory on large amounts of queries -- I we've had problems at
* >6000 queries on one system.
@ -195,49 +194,127 @@ class DBO extends Object {
var $_queriesLogMax=200;
/**
/**
* Constructor. Sets the level of debug for dbo (fullDebug or debug).
*
* @param array $config
* @return unknown
*/
function __construct ($config=NULL) {
function __construct($config=NULL)
{
$this->debug = DEBUG > 0;
$this->fullDebug = DEBUG > 1;
parent::__construct();
return $this->connect($config);
}
/**
/**
* Destructor. Closes connection to the database.
*
*/
function __destructor () {
function __destructor()
{
$this->close();
}
/**
/**
* A semi-singelton. Returns actual instance, or creates a new one with given config.
*
* @param string $config Name of key of $dbConfig array to be used.
* @return mixed
*/
function getInstance($config = null)
{
static $instance;
if (!isset($instance))
{
if ($config == null)
{
return false;
}
$configs = get_class_vars('DATABASE_CONFIG');
$config = $configs[$config];
// special case for AdoDB -- driver name in the form of 'adodb-drivername'
if (preg_match('#^adodb[\-_](.*)$#i', $config['driver'], $res))
{
uses('dbo/dbo_adodb');
$config['driver'] = $res[1];
$instance = array(DBO_AdoDB($config));
}
// special case for PEAR:DB -- driver name in the form of 'pear-drivername'
elseif (preg_match('#^pear[\-_](.*)$#i', $config['driver'], $res))
{
uses('dbo/dbo_pear');
$config['driver'] = $res[1];
$instance = array(new DBO_Pear($config));
}
// regular, Cake-native db drivers
else
{
$db_driver_class = 'DBO_'.$config['driver'];
$db_driver_fn = LIBS.strtolower('dbo'.DS.$db_driver_class.'.php');
if (file_exists($db_driver_fn))
{
uses(strtolower('dbo'.DS.$db_driver_class));
$instance = array(new $db_driver_class($config));
}
else
{
trigger_error(ERROR_UNKNOWN_DATABASE_DRIVER, E_USER_ERROR);
return false;
}
}
}
return $instance[0];
}
/**
* Sets config to use. If there is already a connection, close it first.
*
* @param string $configName Name of the config array key to use.
* @return mixed
*/
function setConfig($config)
{
if ($this->connected === true)
{
$this->close();
}
return $this->getInstance($config);
}
/**
* Returns a string with a USE [databasename] SQL statement.
*
* @param string $db_name Name of database to use
* @return unknown Result of the query
*/
function useDb ($db_name) {
function useDb($db_name)
{
return $this->query("USE {$db_name}");
}
/**
/**
* Disconnects database, kills the connection and says the connection is closed, and if DEBUG is turned on, the log for this object is shown.
*
*/
function close () {
function close ()
{
if ($this->fullDebug) $this->showLog();
$this->disconnect();
$this->_conn = NULL;
$this->connected = false;
}
/**
/**
* 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.
@ -265,18 +342,19 @@ class DBO extends Object {
return array_map('strtolower', $this->tablesList());
}
/**
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return unknown
*/
function rawQuery ($sql) {
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.
@ -299,7 +377,7 @@ class DBO extends Object {
return $this->error? false: $this->_result;
}
/**
/**
* Returns a single row of results from the _last_ SQL query.
*
* @param resource $res
@ -317,25 +395,28 @@ class DBO extends Object {
}
}
/**
/**
* 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) {
function one ($sql)
{
return $this->query($sql)? $this->farr(): false;
}
/**
/**
* Returns an array of all result rows for a given SQL query.
* Returns false if no rows matched.
*
* @param string $sql SQL statement
* @return array Array of resultset rows, or false if no rows matched
*/
function all ($sql) {
if($this->query($sql)) {
function all ($sql)
{
if($this->query($sql))
{
$out=array();
while ($item = $this->farr(null, true))
{
@ -343,50 +424,55 @@ class DBO extends Object {
}
return $out;
}
else {
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) {
function field ($name, $sql)
{
$data = $this->one($sql);
return empty($data[$name])? false: $data[$name];
}
/**
/**
* Checks if the specified table contains any record matching specified SQL
*
* @param string $table Name of table to look in
* @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
* @return boolean True if the table has a matching record, else false
*/
function hasAny($table, $sql) {
function hasAny($table, $sql)
{
$out = $this->one("SELECT COUNT(*) AS count FROM {$table}".($sql? " WHERE {$sql}":""));
return is_array($out)? $out['count']: false;
}
/**
/**
* Checks if it's connected to the database
*
* @return boolean True if the database is connected, else false
*/
function isConnected() {
function isConnected()
{
return $this->connected;
}
/**
/**
* Outputs the contents of the log.
*
* @param boolean $sorted
*/
function showLog($sorted=false) {
function showLog($sorted=false)
{
$log = $sorted?
sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC):
$this->_queriesLog;
@ -394,19 +480,21 @@ class DBO extends Object {
print("<table border=1>\n<tr><th colspan=7>{$this->_queriesCnt} queries took {$this->_queriesTime} ms</th></tr>\n");
print("<tr><td>Nr</td><td>Query</td><td>Error</td><td>Affected</td><td>Num. rows</td><td>Took (ms)</td></tr>\n");
foreach($log AS $k=>$i) {
foreach($log AS $k=>$i)
{
print("<tr><td>".($k+1)."</td><td>{$i['query']}</td><td>{$i['error']}</td><td align='right'>{$i['affected']}</td><td align='right'>{$i['numRows']}</td><td align='right'>{$i['took']}</td></tr>\n");
}
print("</table>\n");
}
/**
/**
* Log given SQL query.
*
* @param string $sql SQL statement
*/
function logQuery($sql) {
function logQuery($sql)
{
$this->_queriesCnt++;
$this->_queriesTime += $this->took;
@ -418,29 +506,35 @@ class DBO extends Object {
'took'=>$this->took
);
if (count($this->_queriesLog) > $this->_queriesLogMax) {
if (count($this->_queriesLog) > $this->_queriesLogMax)
{
array_pop($this->_queriesLog);
}
if ($this->error)
false; // shouldn't we be logging errors somehow?
return false; // shouldn't we be logging errors somehow?
}
/**
/**
* Output information about an SQL query. The SQL statement, number of rows in resultset,
* and execution time in microseconds. If the query fails, and error is output instead.
*
* @param string $sql
*/
function showQuery($sql) {
function showQuery($sql)
{
$error = $this->error;
if (strlen($sql)>200 && !$this->fullDebug)
{
$sql = substr($sql, 0, 200) .'[...]';
}
if ($this->debug || $error) {
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) {
if($error)
{
print("<br /><span style=\"color:Red;text-align:left\"><b>ERROR:</b> {$this->error}</span>");
}
print('</p>');

View file

@ -154,12 +154,12 @@ class Model extends Object
*/
function __construct ($id=false, $table=null, $db=null)
{
global $DB;
$this->db = $db? $db: $DB;
$this->db = $db? $db: DBO::getInstance();
if ($id)
{
$this->id = $id;
}
$table_name = $table? $table: ($this->use_table? $this->use_table: Inflector::tableize(get_class($this)));
$this->useTable ($table_name);

View file

@ -68,13 +68,15 @@ DEBUG? error_reporting(E_ALL): error_reporting(0);
$TIME_START = getMicrotime();
uses('folder', 'dispatcher', 'dbo_factory');
//uses('folder', 'dispatcher', 'dbo_factory');
uses('folder', 'dispatcher', 'dbo');
config('tags', 'database');
if (class_exists('DATABASE_CONFIG'))
{
$DB = DboFactory::make('devel');
$db = DBO::getInstance('default');
//$DB = DboFactory::make('devel');
loadModels();
}