1
0
mirror of https://github.com/dg/dibi.git synced 2025-07-30 19:00:13 +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
* @package dibi
* @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', '<'))
@@ -108,7 +108,8 @@ class dibi
* @var string|NULL
*/
static public $logFile;
static public $logMode = 'w';
static public $logMode = 'a';
static public $errorMode;
/**
* Enable/disable debug mode
@@ -137,7 +138,8 @@ class dibi
*
* @param array|string connection parameters
* @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')
{
@@ -147,7 +149,7 @@ class dibi
// config['driver'] is required
if (empty($config['driver']))
return new DibiException('Driver is not specified.');
throw new DibiException('Driver is not specified.');
// include dibi driver
$className = "Dibi$config[driver]Driver";
@@ -155,38 +157,15 @@ class dibi
include_once dirname(__FILE__) . "/drivers/$config[driver].php";
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); */
$conn = call_user_func(array($className, 'connect'), $config);
self::$conn = self::$registry[$name] = call_user_func(array($className, 'connect'), $config);
// optionally log to file
// 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;
dibi::log("Successfully connected to DB '$config[driver]'");
}
@@ -209,6 +188,9 @@ class dibi
*/
static public function getConnection()
{
if (!self::$conn)
throw new DibiException('Dibi is not connected to database');
return self::$conn;
}
@@ -223,11 +205,10 @@ class dibi
static public function activate($name)
{
if (!isset(self::$registry[$name]))
return FALSE;
throw new DibiException("There is no connection named '$name'.");
// change active connection
self::$conn = self::$registry[$name];
return TRUE;
}
@@ -239,39 +220,31 @@ class dibi
* Generates and executes SQL query
*
* @param array|mixed one or more arguments
* @return int|DibiResult|Exception
* @return int|DibiResult
* @throw DibiException
*/
static public function query($args)
{
if (!self::$conn) return new DibiException('Dibi is not connected to DB'); // is connected?
$conn = self::getConnection();
// receive arguments
if (!is_array($args))
$args = func_get_args();
// and generate SQL
$trans = new DibiTranslator(self::$conn, self::$substs);
$trans = new DibiTranslator($conn, self::$substs);
self::$sql = $trans->translate($args);
if (is_error(self::$sql)) return self::$sql; // reraise the exception
// execute SQL
$timer = -microtime(true);
$res = self::$conn->query(self::$sql);
$res = $conn->query(self::$sql);
$timer += microtime(true);
if (is_error($res)) {
// optionally debug on display
if (self::$debug) {
echo '[dibi error] ' . $res->getMessage();
self::dump(self::$sql);
}
// todo: log all errors!
self::$error = $res;
} else {
self::$error = FALSE;
}
// todo:
self::$error = is_error($res) ? $res : FALSE;
// optionally log to file
// optional log to file
if (self::$logFile != NULL)
{
if (is_error($res))
@@ -281,14 +254,11 @@ class dibi
else
$msg = 'OK';
$f = fopen(self::$logFile, 'a');
fwrite($f,
self::$sql
dibi::log(self::$sql
. ";\r\n-- Result: $msg"
. "\r\n-- Takes: " . sprintf('%0.3f', $timer * 1000) . ' ms'
. "\r\n\r\n"
);
fclose($f);
}
return $res;
@@ -306,14 +276,12 @@ class dibi
*/
static public function test($args)
{
if (!self::$conn) return FALSE; // is connected?
// receive arguments
if (!is_array($args))
$args = func_get_args();
// and generate SQL
$trans = new DibiTranslator(self::$conn, self::$substs);
$trans = new DibiTranslator(self::getConnection(), self::$substs);
$sql = $trans->translate($args);
$dump = TRUE; // !!!
if ($dump) {
@@ -334,7 +302,7 @@ class dibi
*/
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()
{
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

View File

@@ -42,11 +42,12 @@ class DibiMySqlDriver extends DibiDriver {
/**
* Driver factory
* @throw DibiException
*/
public static function connect($config)
{
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)
if (!isset($config[$var])) $config[$var] = NULL;
@@ -73,7 +74,7 @@ class DibiMySqlDriver extends DibiDriver {
if (!is_resource($conn))
return new DibiException("Connecting error", array(
throw new DibiException("Connecting error", array(
'message' => mysql_error() ? mysql_error() : $php_errormsg,
'code' => mysql_errno(),
));
@@ -87,7 +88,7 @@ class DibiMySqlDriver extends DibiDriver {
if (!empty($config['database'])) {
if (!@mysql_select_db($config['database'], $conn))
return new DibiException("Connecting error", array(
throw new DibiException("Connecting error", array(
'message' => mysql_error($conn),
'code' => mysql_errno($conn),
));

View File

@@ -44,7 +44,7 @@ class DibiMySqliDriver extends DibiDriver {
public static function connect($config)
{
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';
@@ -54,7 +54,7 @@ class DibiMySqliDriver extends DibiDriver {
$conn = @mysqli_connect($config['host'], $config['username'], $config['password'], $config['database'], $config['port']);
if (!$conn)
return new DibiException("Connecting error", array(
throw new DibiException("Connecting error", array(
'message' => mysqli_connect_error(),
'code' => mysqli_connect_errno(),
));

View File

@@ -43,13 +43,13 @@ class DibiOdbcDriver extends DibiDriver {
public static function connect($config)
{
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']))
return new DibiException("Username must be specified");
throw new DibiException("Username must be specified");
if (!isset($config['password']))
return new DibiException("Password must be specified");
throw new DibiException("Password must be specified");
if (empty($config['persistent']))
$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']);
if (!is_resource($conn))
return new DibiException("Connecting error", array(
throw new DibiException("Connecting error", array(
'message' => odbc_errormsg(),
'code' => odbc_error(),
));

View File

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

View File

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

View File

@@ -53,7 +53,7 @@ abstract class DibiDriver
* @param array connect configuration
* @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']))
$message = "$message: $info[message]";
/*
if (isset($info['sql']))
$message .= "\n[SQL] $info[sql]";
*/
/* experimental */
dibi::log($message);
if (dibi::$debug) {
echo '[dibi error] ' . $message;
if (isset($info['sql'])) dibi::dump($info['sql']);
}
parent::__construct($message);
}
public function getSql()
{
return $this->info['sql'];
return @$this->info['sql'];
}

View File

@@ -2,12 +2,19 @@
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
$state = dibi::connect(array(
dibi::connect(array(
'driver' => 'mysql',
'host' => 'localhost',
'username' => 'root',
@@ -44,7 +51,6 @@ dibi::connect(array(
// check status
if (!dibi::isConnected()) {
echo 'dibi::isConnected(): Not connected';
echo "<br>\n";
} else {
echo 'Connected';
}

View File

@@ -7,7 +7,7 @@ dibi::$debug = true;
// mysql
dibi::connect(array(
'driver' => 'mysqli',
'driver' => 'mysql',
'host' => 'localhost',
'username' => 'root',
'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');

View File

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