1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-04 05:07:36 +02:00

throwing exception on connect

This commit is contained in:
David Grudl
2006-11-13 06:32:16 +00:00
parent 11b294be44
commit f447a03c96
11 changed files with 78 additions and 92 deletions

View File

@@ -14,11 +14,11 @@
* @license GNU GENERAL PUBLIC LICENSE v2 * @license GNU GENERAL PUBLIC LICENSE v2
* @package dibi * @package dibi
* @category Database * @category Database
* @version 0.6c $Revision$ $Date$ * @version 0.6d $Revision$ $Date$
*/ */
define('DIBI', 'Version 0.6c $Revision$'); define('DIBI', 'Version 0.6d $Revision$');
if (version_compare(PHP_VERSION , '5.0.3', '<')) if (version_compare(PHP_VERSION , '5.0.3', '<'))
@@ -108,7 +108,8 @@ class dibi
* @var string|NULL * @var string|NULL
*/ */
static public $logFile; static public $logFile;
static public $logMode = 'w'; static public $logMode = 'a';
static public $errorMode;
/** /**
* Enable/disable debug mode * Enable/disable debug mode
@@ -137,7 +138,8 @@ class dibi
* *
* @param array|string connection parameters * @param array|string connection parameters
* @param string connection name * @param string connection name
* @return bool|object TRUE on success, FALSE or Exception on failure * @return void
* @throw DibiException
*/ */
static public function connect($config, $name = '1') static public function connect($config, $name = '1')
{ {
@@ -147,7 +149,7 @@ class dibi
// config['driver'] is required // config['driver'] is required
if (empty($config['driver'])) if (empty($config['driver']))
return new DibiException('Driver is not specified.'); throw new DibiException('Driver is not specified.');
// include dibi driver // include dibi driver
$className = "Dibi$config[driver]Driver"; $className = "Dibi$config[driver]Driver";
@@ -155,38 +157,15 @@ class dibi
include_once dirname(__FILE__) . "/drivers/$config[driver].php"; include_once dirname(__FILE__) . "/drivers/$config[driver].php";
if (!class_exists($className)) if (!class_exists($className))
return new DibiException("Unable to create instance of dibi driver class '$className'."); throw new DibiException("Unable to create instance of dibi driver class '$className'.");
} }
// create connection object // create connection object and store in list
/** like $conn = $className::connect($config); */ /** like $conn = $className::connect($config); */
$conn = call_user_func(array($className, 'connect'), $config); self::$conn = self::$registry[$name] = call_user_func(array($className, 'connect'), $config);
// optionally log to file dibi::log("Successfully connected to DB '$config[driver]'");
// todo: log other exceptions!
if (self::$logFile != NULL && self::$logMode) {
if (is_error($conn))
$msg = "Can't connect to DB '$config[driver]': ".$conn->getMessage();
else
$msg = "Successfully connected to DB '$config[driver]'";
$f = fopen(self::$logFile, self::$logMode);
fwrite($f, "$msg\r\n\r\n");
fclose($f);
}
if (is_error($conn)) {
// optionally debug on display
if (self::$debug) echo '[dibi error] ' . $conn->getMessage();
return $conn; // reraise the exception
}
// store connection in list
self::$conn = self::$registry[$name] = $conn;
return TRUE;
} }
@@ -209,6 +188,9 @@ class dibi
*/ */
static public function getConnection() static public function getConnection()
{ {
if (!self::$conn)
throw new DibiException('Dibi is not connected to database');
return self::$conn; return self::$conn;
} }
@@ -223,11 +205,10 @@ class dibi
static public function activate($name) static public function activate($name)
{ {
if (!isset(self::$registry[$name])) if (!isset(self::$registry[$name]))
return FALSE; throw new DibiException("There is no connection named '$name'.");
// change active connection // change active connection
self::$conn = self::$registry[$name]; self::$conn = self::$registry[$name];
return TRUE;
} }
@@ -239,39 +220,31 @@ class dibi
* Generates and executes SQL query * Generates and executes SQL query
* *
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return int|DibiResult|Exception * @return int|DibiResult
* @throw DibiException
*/ */
static public function query($args) static public function query($args)
{ {
if (!self::$conn) return new DibiException('Dibi is not connected to DB'); // is connected? $conn = self::getConnection();
// receive arguments // receive arguments
if (!is_array($args)) if (!is_array($args))
$args = func_get_args(); $args = func_get_args();
// and generate SQL // and generate SQL
$trans = new DibiTranslator(self::$conn, self::$substs); $trans = new DibiTranslator($conn, self::$substs);
self::$sql = $trans->translate($args); self::$sql = $trans->translate($args);
if (is_error(self::$sql)) return self::$sql; // reraise the exception if (is_error(self::$sql)) return self::$sql; // reraise the exception
// execute SQL // execute SQL
$timer = -microtime(true); $timer = -microtime(true);
$res = self::$conn->query(self::$sql); $res = $conn->query(self::$sql);
$timer += microtime(true); $timer += microtime(true);
if (is_error($res)) { // todo:
// optionally debug on display self::$error = is_error($res) ? $res : FALSE;
if (self::$debug) {
echo '[dibi error] ' . $res->getMessage();
self::dump(self::$sql);
}
// todo: log all errors!
self::$error = $res;
} else {
self::$error = FALSE;
}
// optionally log to file // optional log to file
if (self::$logFile != NULL) if (self::$logFile != NULL)
{ {
if (is_error($res)) if (is_error($res))
@@ -281,14 +254,11 @@ class dibi
else else
$msg = 'OK'; $msg = 'OK';
$f = fopen(self::$logFile, 'a'); dibi::log(self::$sql
fwrite($f,
self::$sql
. ";\r\n-- Result: $msg" . ";\r\n-- Result: $msg"
. "\r\n-- Takes: " . sprintf('%0.3f', $timer * 1000) . ' ms' . "\r\n-- Takes: " . sprintf('%0.3f', $timer * 1000) . ' ms'
. "\r\n\r\n" . "\r\n\r\n"
); );
fclose($f);
} }
return $res; return $res;
@@ -306,14 +276,12 @@ class dibi
*/ */
static public function test($args) static public function test($args)
{ {
if (!self::$conn) return FALSE; // is connected?
// receive arguments // receive arguments
if (!is_array($args)) if (!is_array($args))
$args = func_get_args(); $args = func_get_args();
// and generate SQL // and generate SQL
$trans = new DibiTranslator(self::$conn, self::$substs); $trans = new DibiTranslator(self::getConnection(), self::$substs);
$sql = $trans->translate($args); $sql = $trans->translate($args);
$dump = TRUE; // !!! $dump = TRUE; // !!!
if ($dump) { if ($dump) {
@@ -334,7 +302,7 @@ class dibi
*/ */
static public function insertId() static public function insertId()
{ {
return self::$conn ? self::$conn->insertId() : FALSE; return self::getConnection()->insertId();
} }
@@ -346,7 +314,7 @@ class dibi
*/ */
static public function affectedRows() static public function affectedRows()
{ {
return self::$conn ? self::$conn->affectedRows() : FALSE; return self::getConnection()->affectedRows();
} }
@@ -449,6 +417,18 @@ class dibi
} }
/**
* Error logging
* EXPERIMENTAL
*/
static public function log($message)
{
if (self::$logFile == NULL || self::$logMode == NULL) return;
$f = fopen(self::$logFile, self::$logMode);
fwrite($f, $message. "\r\n\r\n");
fclose($f);
}
} // class dibi } // class dibi

View File

@@ -42,11 +42,12 @@ class DibiMySqlDriver extends DibiDriver {
/** /**
* Driver factory * Driver factory
* @throw DibiException
*/ */
public static function connect($config) public static function connect($config)
{ {
if (!extension_loaded('mysql')) if (!extension_loaded('mysql'))
return new DibiException("PHP extension 'mysql' is not loaded"); throw new DibiException("PHP extension 'mysql' is not loaded");
foreach (array('username', 'password', 'protocol') as $var) foreach (array('username', 'password', 'protocol') as $var)
if (!isset($config[$var])) $config[$var] = NULL; if (!isset($config[$var])) $config[$var] = NULL;
@@ -73,7 +74,7 @@ class DibiMySqlDriver extends DibiDriver {
if (!is_resource($conn)) if (!is_resource($conn))
return new DibiException("Connecting error", array( throw new DibiException("Connecting error", array(
'message' => mysql_error() ? mysql_error() : $php_errormsg, 'message' => mysql_error() ? mysql_error() : $php_errormsg,
'code' => mysql_errno(), 'code' => mysql_errno(),
)); ));
@@ -87,7 +88,7 @@ class DibiMySqlDriver extends DibiDriver {
if (!empty($config['database'])) { if (!empty($config['database'])) {
if (!@mysql_select_db($config['database'], $conn)) if (!@mysql_select_db($config['database'], $conn))
return new DibiException("Connecting error", array( throw new DibiException("Connecting error", array(
'message' => mysql_error($conn), 'message' => mysql_error($conn),
'code' => mysql_errno($conn), 'code' => mysql_errno($conn),
)); ));

View File

@@ -44,7 +44,7 @@ class DibiMySqliDriver extends DibiDriver {
public static function connect($config) public static function connect($config)
{ {
if (!extension_loaded('mysqli')) if (!extension_loaded('mysqli'))
return new DibiException("PHP extension 'mysqli' is not loaded"); throw new DibiException("PHP extension 'mysqli' is not loaded");
if (empty($config['host'])) $config['host'] = 'localhost'; if (empty($config['host'])) $config['host'] = 'localhost';
@@ -54,7 +54,7 @@ class DibiMySqliDriver extends DibiDriver {
$conn = @mysqli_connect($config['host'], $config['username'], $config['password'], $config['database'], $config['port']); $conn = @mysqli_connect($config['host'], $config['username'], $config['password'], $config['database'], $config['port']);
if (!$conn) if (!$conn)
return new DibiException("Connecting error", array( throw new DibiException("Connecting error", array(
'message' => mysqli_connect_error(), 'message' => mysqli_connect_error(),
'code' => mysqli_connect_errno(), 'code' => mysqli_connect_errno(),
)); ));

View File

@@ -43,13 +43,13 @@ class DibiOdbcDriver extends DibiDriver {
public static function connect($config) public static function connect($config)
{ {
if (!extension_loaded('odbc')) if (!extension_loaded('odbc'))
return new DibiException("PHP extension 'odbc' is not loaded"); throw new DibiException("PHP extension 'odbc' is not loaded");
if (!isset($config['username'])) if (!isset($config['username']))
return new DibiException("Username must be specified"); throw new DibiException("Username must be specified");
if (!isset($config['password'])) if (!isset($config['password']))
return new DibiException("Password must be specified"); throw new DibiException("Password must be specified");
if (empty($config['persistent'])) if (empty($config['persistent']))
$conn = @odbc_connect($config['database'], $config['username'], $config['password']); $conn = @odbc_connect($config['database'], $config['username'], $config['password']);
@@ -57,7 +57,7 @@ class DibiOdbcDriver extends DibiDriver {
$conn = @odbc_pconnect($config['database'], $config['username'], $config['password']); $conn = @odbc_pconnect($config['database'], $config['username'], $config['password']);
if (!is_resource($conn)) if (!is_resource($conn))
return new DibiException("Connecting error", array( throw new DibiException("Connecting error", array(
'message' => odbc_errormsg(), 'message' => odbc_errormsg(),
'code' => odbc_error(), 'code' => odbc_error(),
)); ));

View File

@@ -43,10 +43,10 @@ class DibiPostgreDriver extends DibiDriver {
public static function connect($config) public static function connect($config)
{ {
if (!extension_loaded('pgsql')) if (!extension_loaded('pgsql'))
return new DibiException("PHP extension 'pgsql' is not loaded"); throw new DibiException("PHP extension 'pgsql' is not loaded");
if (empty($config['string'])) if (empty($config['string']))
return new DibiException("Connection string must be specified"); throw new DibiException("Connection string must be specified");
if (empty($config['type'])) $config['type'] = NULL; if (empty($config['type'])) $config['type'] = NULL;
@@ -57,7 +57,7 @@ class DibiPostgreDriver extends DibiDriver {
$conn = @pg_pconnect($config['string'], $config['type']); $conn = @pg_pconnect($config['string'], $config['type']);
if (!is_resource($conn)) if (!is_resource($conn))
return new DibiException("Connecting error", array( throw new DibiException("Connecting error", array(
'message' => pg_last_error(), 'message' => pg_last_error(),
)); ));

View File

@@ -44,10 +44,10 @@ class DibiSqliteDriver extends DibiDriver {
public static function connect($config) public static function connect($config)
{ {
if (!extension_loaded('sqlite')) if (!extension_loaded('sqlite'))
return new DibiException("PHP extension 'sqlite' is not loaded"); throw new DibiException("PHP extension 'sqlite' is not loaded");
if (empty($config['database'])) if (empty($config['database']))
return new DibiException("Database must be specified"); throw new DibiException("Database must be specified");
if (!isset($config['mode'])) if (!isset($config['mode']))
$config['mode'] = 0666; $config['mode'] = 0666;
@@ -59,7 +59,7 @@ class DibiSqliteDriver extends DibiDriver {
$conn = @sqlite_popen($config['database'], $config['mode'], $errorMsg); $conn = @sqlite_popen($config['database'], $config['mode'], $errorMsg);
if (!$conn) if (!$conn)
return new DibiException("Connecting error", array( throw new DibiException("Connecting error", array(
'message' => $errorMsg, 'message' => $errorMsg,
)); ));
@@ -136,7 +136,7 @@ class DibiSqliteDriver extends DibiDriver {
public function quoteName($value) public function quoteName($value)
{ {
return $value; return '[' . $value . ']';
} }

View File

@@ -53,7 +53,7 @@ abstract class DibiDriver
* @param array connect configuration * @param array connect configuration
* @return bool|object DibiDriver object on success, FALSE or Exception on failure * @return bool|object DibiDriver object on success, FALSE or Exception on failure
*/ */
abstract static public function connect($config); /*abstract PHP 5.2*/ static public function connect($config) {}

View File

@@ -37,18 +37,21 @@ class DibiException extends Exception
if (isset($info['message'])) if (isset($info['message']))
$message = "$message: $info[message]"; $message = "$message: $info[message]";
/*
if (isset($info['sql'])) /* experimental */
$message .= "\n[SQL] $info[sql]"; dibi::log($message);
*/ if (dibi::$debug) {
echo '[dibi error] ' . $message;
if (isset($info['sql'])) dibi::dump($info['sql']);
}
parent::__construct($message); parent::__construct($message);
} }
public function getSql() public function getSql()
{ {
return $this->info['sql']; return @$this->info['sql'];
} }

View File

@@ -2,12 +2,19 @@
require_once '../dibi/dibi.php'; require_once '../dibi/dibi.php';
// connects using DSN
$state = dibi::connect('driver=mysql&host=localhost&username=root&password=xxx&database=test&charset=utf8'); try {
// connects using DSN
dibi::connect('driver=mysql&host=localhost&username=root&password=xxx&database=test&charset=utf8');
} catch (DibiException $e) {
echo "DibiException: " . $e->getMessage();
die();
}
// connects to mysql // connects to mysql
$state = dibi::connect(array( dibi::connect(array(
'driver' => 'mysql', 'driver' => 'mysql',
'host' => 'localhost', 'host' => 'localhost',
'username' => 'root', 'username' => 'root',
@@ -44,7 +51,6 @@ dibi::connect(array(
// check status // check status
if (!dibi::isConnected()) { if (!dibi::isConnected()) {
echo 'dibi::isConnected(): Not connected'; echo 'dibi::isConnected(): Not connected';
echo "<br>\n";
} else { } else {
echo 'Connected'; echo 'Connected';
} }

View File

@@ -7,7 +7,7 @@ dibi::$debug = true;
// mysql // mysql
dibi::connect(array( dibi::connect(array(
'driver' => 'mysqli', 'driver' => 'mysql',
'host' => 'localhost', 'host' => 'localhost',
'username' => 'root', 'username' => 'root',
'password' => 'xxx', // change to real password! 'password' => 'xxx', // change to real password!
@@ -16,10 +16,6 @@ dibi::connect(array(
)); ));
if (!dibi::isConnected())
die('Not connected');
$res = dibi::query('SELECT * FROM table'); $res = dibi::query('SELECT * FROM table');

View File

@@ -1 +1 @@
Dibi Version 0.6c Dibi Version 0.6d